Example usage for javax.xml.stream XMLStreamReader next

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

Introduction

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

Prototype

public int next() throws XMLStreamException;

Source Link

Document

Get next parsing event - a processor may return all contiguous character data in a single chunk, or it may split it into several chunks.

Usage

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());
                }// w w  w  .  j av a2s . c  om
            }
        }
    }
    return res;
}

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

protected String getTagContent(XMLStreamReader reader) throws XMLStreamException {
    String value = null;/*  ww  w . ja v  a 2  s  .  c o m*/
    String tagLocalName = reader.getLocalName();
    while (reader.hasNext() && !((reader.getEventType() == XMLStreamConstants.END_ELEMENT)
            && tagLocalName.equals(reader.getLocalName()))) {
        reader.next();
        if (reader.getEventType() == XMLStreamConstants.CHARACTERS) {
            value = reader.getText();
        }
    }
    // empty tag
    if (!reader.hasNext()) {
        throw new XMLStreamException("End element for " + tagLocalName + " not found");
    }
    return value;
}

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 ww.  j  a  v  a  2  s . com
        if (event == CHARACTERS) {
            return in.getText();
        }
    }
    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  ww  . j a va2 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:com.qcadoo.model.internal.classconverter.ModelXmlToClassConverterImpl.java

private void defineClasses(final Map<String, CtClass> ctClasses, final InputStream stream)
        throws XMLStreamException, ModelXmlCompilingException, NotFoundException {
    XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);

    while (reader.hasNext() && reader.next() > 0) {
        if (isTagStarted(reader, TAG_MODEL)) {
            String pluginIdentifier = getPluginIdentifier(reader);
            String modelName = getStringAttribute(reader, L_NAME);
            String className = ClassNameUtils.getFullyQualifiedClassName(pluginIdentifier, modelName);

            if (ctClasses.containsKey(className)) {
                parse(reader, ctClasses.get(className), pluginIdentifier);
            }//from   w  w w .  j a va2 s.c  o m
        }
    }

    reader.close();
}

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.
 *//*www. ja va2  s  . c om*/
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 Map<String, JobDetailsBean> parseJobDetailBeans(InputStream stream) throws XMLStreamException {
    Map<String, JobDetailsBean> res = new TreeMap<String, JobDetailsBean>();
    XMLStreamReader parser = factory.createXMLStreamReader(stream);
    while (parser.hasNext()) {
        int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (parser.hasName()) {
                if (parser.getLocalName().equals("job_status")) {
                    // one job status
                    JobDetailsBean detail = new JobDetailsBean();
                    Map<String, String> jobParams = new HashMap<String, String>();
                    Map<String, String> results = new HashMap<String, String>();
                    int innerEvent = parser.next();
                    while (true) {
                        if (innerEvent == XMLStreamConstants.END_ELEMENT
                                && parser.getLocalName().equals("job_status")) {
                            break;
                        }/*from www .  ja va2  s .c  om*/

                        if (innerEvent == XMLStreamConstants.START_ELEMENT && parser.hasName()) {
                            // single tag
                            if (parser.getLocalName().equals("job_name")) {
                                detail.setJobTitle(parser.getElementText());
                            } else if (parser.getLocalName().equals("user")) {
                                detail.setUserName(parser.getElementText());
                            } else if (parser.getLocalName().equals("algorithm")) {
                                detail.setAlgorithmName(parser.getElementText());
                            } else if (parser.getLocalName().equals("job_id")) {
                                detail.setJobId(parser.getElementText());
                            } else if (parser.getLocalName().equals("date")) {
                                detail.setLastUpdatedDate(parser.getElementText());
                            }

                            // parameters
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.ONEPARAM)) {
                                String name, value;
                                name = value = "";
                                for (int i = 0; i < 3; i++) {
                                    if (parser.getAttributeName(i).toString().equals("name"))
                                        name = parser.getAttributeValue(i);
                                    if (parser.getAttributeName(i).toString().equals("value"))
                                        value = parser.getAttributeValue(i);
                                }
                                jobParams.put(name, value);
                            }

                            // status
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.STATUS)) {
                                String status = parser.getAttributeValue(0);
                                detail.setJobStatus(status);
                            }

                            // results
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.RESULT)) {
                                String name = parser.getAttributeValue(0);
                                String value = parser.getElementText();
                                results.put(name, value);
                            }

                            // message
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.MESSAGE)) {
                                detail.setMessage(parser.getElementText());
                            }

                            // saved or unsaved
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.SAVEDORNOT)) {
                                detail.setJobSavedStr(parser.getElementText());
                            }
                        }
                        innerEvent = parser.next();
                    }
                    detail.setJobParams(jobParams);
                    detail.setResults(results);
                    res.put(detail.getJobId(), detail);
                }
            }
        }
    }
    return res;
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizer.java

/**
 * Loads configuration from XML file, overriding the properties.
 *///from  www.java2  s.com
private void loadXMLConfiguration(InputStream xmlConfigurationStream)
        throws ConfigException, XMLStreamException {
    assert xmlConfigurationStream != null;
    final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    final XMLStreamReader reader = inputFactory.createXMLStreamReader(xmlConfigurationStream);

    boolean config = false;
    Module module = null;
    while (reader.hasNext()) {
        final int event = reader.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT: {
            String name = reader.getLocalName();
            if (name.equals("config")) {
                config = true;
                break;
            }

            if (config && name.equals("module")) {
                if (reader.getAttributeCount() == 1) {
                    final String attributeName = reader.getAttributeLocalName(0);
                    final String attributeValue = reader.getAttributeValue(0);

                    if (attributeName.equals("name") && attributeValue != null) {
                        String fullyQualified = Settings.class.getPackage().getName() + ".modules."
                                + attributeValue;
                        try {
                            Class<?> moduleClass = Class.forName(fullyQualified);
                            module = (Module) moduleClass.newInstance();
                        } catch (InstantiationException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot instantiate module " + attributeValue, ex);
                        } catch (IllegalAccessException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot access module " + attributeValue, ex);
                        } catch (ClassNotFoundException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot load module " + attributeValue, ex);
                        }
                    }
                }
            }

            if (config && name.equals("property")) {
                if (reader.getAttributeCount() == 1) {
                    final String attributeName = reader.getAttributeLocalName(0);
                    final String attributeValue = reader.getAttributeValue(0);

                    if (attributeName.equals("name") && attributeValue != null) {
                        if (module == null) {
                            if (Settings.isProperty(attributeValue)) {
                                Settings.setProperty(attributeValue, reader.getElementText());
                            } else {
                                throw new ConfigException("configuration not valid\n"
                                        + "Tried to override non-existing global property " + attributeValue);
                            }
                        } else {
                            if (module.isProperty(attributeValue)) {
                                module.setProperty(attributeValue, reader.getElementText());
                            } else {
                                throw new ConfigException("configuration not valid\n"
                                        + "configuration tried to override non-existing property "
                                        + attributeValue);
                            }
                        }
                    }
                }
            }

            break;
        }
        case XMLStreamConstants.END_ELEMENT: {
            if (config && reader.getLocalName().equals("module")) {
                addModule(module);

                module = null;
            }

            if (config && reader.getLocalName().equals("config")) {
                config = false;
            }
        }
        }
    }
}

From source file:net.solarnetwork.util.JavaBeanXmlSerializer.java

/**
 * Parse XML into a simple Map structure.
 * /*from  w ww.ja  v  a 2  s.c  om*/
 * @param in
 *        the input stream to parse
 * @return a Map of the XML
 */
public Map<String, Object> parseXml(InputStream in) {
    Deque<Map<String, Object>> stack = new LinkedList<Map<String, Object>>();
    Map<String, Object> result = null;
    XMLStreamReader reader = startParse(in);
    try {
        int eventType;
        boolean parsing = true;
        while (parsing) {
            eventType = reader.next();
            switch (eventType) {
            case XMLStreamConstants.END_DOCUMENT:
                parsing = false;
                break;

            case XMLStreamConstants.START_ELEMENT:
                String name = reader.getLocalName();
                if (stack.isEmpty()) {
                    result = new LinkedHashMap<String, Object>();
                    stack.push(result);
                } else {
                    Map<String, Object> el = new LinkedHashMap<String, Object>();
                    putMapValue(stack.peek(), name, el);
                    stack.push(el);
                }
                parseElement(stack.peek(), reader);
                break;

            case XMLStreamConstants.END_ELEMENT:
                stack.pop();
                break;

            }
        }
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    } finally {
        endParse(reader);
    }
    return result;
}

From source file:dk.statsbiblioteket.util.xml.XMLStepperTest.java

public void testGetSubXML_DoubleContent() throws XMLStreamException {
    final String XML = "<field><content foo=\"bar\"/><content foo=\"zoo\"/></field>";
    final String EXPECTED = "<content foo=\"bar\"></content><content foo=\"zoo\"></content>";

    XMLStreamReader in = xmlFactory.createXMLStreamReader(new StringReader(XML));
    in.next();
    String piped = XMLStepper.getSubXML(in, false, true);
    assertEquals("The output should contain the inner XML", EXPECTED, piped);
}