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:net.di2e.ecdr.libs.result.relevance.TextParser.java

/**
 * Given xml as a string, this method will parse out element text and CDATA text. It separates
 * each by one space character.//from www. j  a  va 2  s  .c  o m
 *
 * @param xmlData
 *            XML as a {@code String}
 * @return parsed CDATA and element text
 */
protected static String parseTextFrom(String xmlData) {

    StringBuilder builder = new StringBuilder();

    XMLStreamReader xmlStreamReader;

    try {
        // xml parser does not handle leading whitespace
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(xmlData));

        while (xmlStreamReader.hasNext()) {
            int event = xmlStreamReader.next();

            if (event == XMLStreamConstants.CHARACTERS || event == XMLStreamConstants.CDATA) {

                String text = xmlStreamReader.getText();

                if (StringUtils.isNotBlank(text)) {
                    builder.append(" " + text.trim());
                }

            }
            if (event == XMLStreamConstants.START_ELEMENT) {
                for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) {

                    String text = xmlStreamReader.getAttributeValue(i);

                    if (StringUtils.isNotBlank(text)) {
                        builder.append(" " + text.trim());
                    }
                }
            }
        }
    } catch (XMLStreamException e1) {
        LOGGER.warn("Failure occurred in parsing the xml data (" + xmlData
                + "). No data has been stored or indexed.", e1);
    }

    return builder.toString();
}

From source file:Main.java

/**
 * Advance the reader to the next element after start element and return true. 
 * Return false if next start element is not found
 * @param reader a XMLStreamReader/*from  w ww . j a  v  a  2 s .  c  o m*/
 * @param startElement Name of the start element.
 * @return True when successfully advanced the reader.
 * @throws XMLStreamException Exception when reading from the XMLStreamReader fails.
 */
public static boolean advanceToAfterStartElement(XMLStreamReader reader, String startElement)
        throws XMLStreamException {
    while (!(reader.getEventType() == XMLStreamConstants.START_ELEMENT && reader.hasName()
            && reader.getLocalName().equalsIgnoreCase(startElement))) {
        //String name = (reader.hasName()? reader.getLocalName() : "");
        if (reader.hasNext()) {
            reader.next();
        } else {
            // reach the end of elements in reader. Not found.
            return false;
        }
    }
    // found the startElement. Consume that start element also
    if (reader.hasNext()) {
        reader.next();
        return true;
    }

    return false;
}

From source file:com.rockhoppertech.music.midi.js.xml.ModeFactoryXMLHelper.java

/**
 * Read modes.xml and create {@code Scale instances} from those definitions.
 *//*from   w w  w .ja va 2 s. c om*/
public static void init() {
    List<Integer> intervals = null;
    Scale currentMode = null;
    String tagContent = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader reader = null;
    try {
        reader = factory.createXMLStreamReader(ClassLoader.getSystemResourceAsStream("modes.xml"));
    } catch (XMLStreamException e) {
        e.printStackTrace();
        return;
    }

    try {
        while (reader.hasNext()) {
            int event = reader.next();

            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                String el = reader.getLocalName();
                logger.debug("start element '{}'", el);
                if ("mode".equals(el)) {
                    currentMode = new Scale();
                    intervals = new ArrayList<>();
                }
                if ("modes".equals(el)) {
                    modeList = new ArrayList<>();
                }
                break;

            case XMLStreamConstants.CHARACTERS:
                tagContent = reader.getText().trim();
                logger.debug("tagcontent '{}'", tagContent);
                break;

            case XMLStreamConstants.END_ELEMENT:
                switch (reader.getLocalName()) {
                case "mode":
                    // wow. both guava and commmons to get an int[] array
                    Integer[] array = FluentIterable.from(intervals).toArray(Integer.class);
                    // same as Integer[] array = intervals.toArray(new
                    // Integer[intervals.size()]);
                    int[] a = ArrayUtils.toPrimitive(array);
                    currentMode.setIntervals(a);
                    modeList.add(currentMode);
                    ScaleFactory.registerScale(currentMode);
                    break;
                case "interval":
                    logger.debug("interval '{}'", tagContent);
                    logger.debug("intervals '{}'", intervals);
                    intervals.add(Integer.parseInt(tagContent));
                    break;
                case "name":
                    currentMode.setName(tagContent);
                    break;
                }
                break;

            case XMLStreamConstants.START_DOCUMENT:
                modeList = new ArrayList<>();
                intervals = new ArrayList<>();
                break;
            }
        }
    } catch (XMLStreamException e) {
        logger.error(e.getLocalizedMessage(), e);
        e.printStackTrace();
    }

    logger.debug("mode list \n{}", modeList);
}

From source file:io.cloudslang.content.xml.utils.XmlUtils.java

/**
 * Returns the Namespaces context from an xml.
 *
 * @param xmlString   xml as string//from   w w  w  .  j a  va2s. com
 * @param xmlFilePath path to xml file
 * @return the Namespaces context from an xml.
 * @throws IOException        file reading exception
 * @throws XMLStreamException parsing exception
 */
public static NamespaceContext getNamespaceContext(String xmlString, String xmlFilePath) throws Exception {
    InputStream inputXML = getStream(xmlString, xmlFilePath);
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader reader = inputFactory.createXMLStreamReader(inputXML);
    Map<String, String> namespaces = new HashMap<>();
    while (reader.hasNext()) {
        int evt = reader.next();
        if (evt == XMLStreamConstants.START_ELEMENT) {
            QName qName = reader.getName();
            if (qName != null) {
                if (qName.getPrefix() != null && qName.getPrefix().compareTo("") != 0)
                    namespaces.put(qName.getPrefix(), qName.getNamespaceURI());
            }
        }
    }
    return new SimpleNamespaceContext(namespaces);
}

From source file:MDRevealer.ResistanceTests.java

private static ArrayList<HashMap<String, String>> parse_test(File rt_input)
        throws XMLStreamException, FileNotFoundException {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader xsr = xif.createXMLStreamReader(new FileInputStream(rt_input));
    ArrayList<HashMap<String, String>> test = new ArrayList<HashMap<String, String>>();
    HashMap<String, String> hm = new HashMap<String, String>();
    String key = "null";
    while (xsr.hasNext() == true) {

        int constant = xsr.next();

        switch (constant) {
        case XMLStreamConstants.START_ELEMENT:
            key = xsr.getLocalName();//w w w. j a va  2  s  .  c  o m
            if (xsr.getAttributeCount() > 0) {
                for (int i = 0; i < xsr.getAttributeCount(); i++) {
                    hm.put(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i));
                }
                test.add(hm);
                hm = new HashMap<String, String>();
            }
            break;
        case XMLStreamConstants.CHARACTERS:
            if (!xsr.isWhiteSpace()) {
                hm.put(key, xsr.getText());
                test.add(hm);
            }
            hm = new HashMap<String, String>();
            break;
        case XMLStreamConstants.END_ELEMENT:
            if (xsr.getLocalName().equals("condition")) {
                hm.put("condition_over", "true");
                test.add(hm);
                hm = new HashMap<String, String>();
            }
            break;
        }
    }
    return test;
}

From source file:edu.stanford.cfuller.colocalization3d.correction.Correction.java

/**
 * Reads a stored correction from disk.//from w  ww . j  a v a2  s .c  o m
 * 
 * @param filename                  The name of the file containing the Correction that was previously written to disk.
 * @return                          The Correction contained in the file.
 * @throws java.io.IOException      if the Correction cannot be successfully read.
 * @throws ClassNotFoundException   if the file does not contain a Correction.
 */
public static Correction readFromDisk(String filename) throws java.io.IOException, ClassNotFoundException {

    File f = new File(filename);

    FileReader fr = new FileReader(f);

    XMLStreamReader xsr = null;
    String encBinData = null;

    try {
        xsr = XMLInputFactory.newFactory().createXMLStreamReader(fr);

        while (xsr.hasNext()) {

            int event = xsr.next();

            if (event != XMLStreamReader.START_ELEMENT)
                continue;

            if (xsr.hasName() && xsr.getLocalName() == BINARY_DATA_ELEMENT) {

                encBinData = xsr.getElementText();

                break;

            }

        }
    } catch (XMLStreamException e) {
        java.util.logging.Logger.getLogger(LOG_NAME)
                .severe("Exception encountered while reading XML correction: " + e.getMessage());
    }
    byte[] binData = (new HexBinaryAdapter()).unmarshal(encBinData);

    ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(binData));

    Object o = oi.readObject();

    return (Correction) o;

}

From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.java

/**
 * Reserved for internal use. Parses the operation response as a collection of entities. Reads entity data from the
 * specified input stream using the specified class type and optionally projects each entity result with the
 * specified resolver into an {@link ODataPayload} containing a collection of {@link TableResult} objects. .
 * //  w  ww . ja va2s . com
 * @param inStream
 *            The <code>InputStream</code> to read the data to parse from.
 * @param clazzType
 *            The class type <code>T</code> implementing {@link TableEntity} for the entities returned. Set to
 *            <code>null</code> to ignore the returned entities and copy only response properties into the
 *            {@link TableResult} objects.
 * @param resolver
 *            An {@link EntityResolver} instance to project the entities into instances of type <code>R</code>. Set
 *            to <code>null</code> to return the entities as instances of the class type <code>T</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @return
 *         An {@link ODataPayload} containing a collection of {@link TableResult} objects with the parsed operation
 *         response.
 * 
 * @throws XMLStreamException
 *             if an error occurs while accessing the stream.
 * @throws ParseException
 *             if an error occurs while parsing the stream.
 * @throws InstantiationException
 *             if an error occurs while constructing the result.
 * @throws IllegalAccessException
 *             if an error occurs in reflection while parsing the result.
 * @throws StorageException
 *             if a storage service error occurs.
 */
@SuppressWarnings("unchecked")
protected static <T extends TableEntity, R> ODataPayload<?> parseResponse(final InputStream inStream,
        final Class<T> clazzType, final EntityResolver<R> resolver, final OperationContext opContext)
        throws XMLStreamException, ParseException, InstantiationException, IllegalAccessException,
        StorageException {
    ODataPayload<T> corePayload = null;
    ODataPayload<R> resolvedPayload = null;
    ODataPayload<?> commonPayload = null;

    if (resolver != null) {
        resolvedPayload = new ODataPayload<R>();
        commonPayload = resolvedPayload;
    } else {
        corePayload = new ODataPayload<T>();
        commonPayload = corePayload;
    }

    final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(inStream);
    int eventType = xmlr.getEventType();
    xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null);
    eventType = xmlr.next();

    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.FEED);
    // skip feed chars
    eventType = xmlr.next();

    while (xmlr.hasNext()) {
        eventType = xmlr.next();

        if (eventType == XMLStreamConstants.CHARACTERS) {
            xmlr.getText();
            continue;
        }

        final String name = xmlr.getName().toString();

        if (eventType == XMLStreamConstants.START_ELEMENT) {
            if (name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.ENTRY)) {
                final TableResult res = parseEntity(xmlr, clazzType, resolver, opContext);
                if (corePayload != null) {
                    corePayload.tableResults.add(res);
                }

                if (resolver != null) {
                    resolvedPayload.results.add((R) res.getResult());
                } else {
                    corePayload.results.add((T) res.getResult());
                }
            }
        } else if (eventType == XMLStreamConstants.END_ELEMENT
                && name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.FEED)) {
            break;
        }
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.FEED);
    return commonPayload;
}

From source file:com.microsoft.tfs.core.memento.XMLMemento.java

/**
 * Reads an {@link XMLMemento} from the next XML element in the given given
 * {@link InputStream} in the encoding specified as
 * {@link #DEFAULT_ENCODING}./* www  . j  a v  a 2 s .  c o m*/
 *
 * @param inputStream
 *        the {@link InputStream} read to read the {@link XMLMemento} from
 *        (must not be <code>null</code>)
 * @param encoding
 *        the encoding to use when reading the {@link InputStream},
 *        <code>null</code> to use the default encoding (
 *        {@link #DEFAULT_ENCODING})
 * @return a Memento modeled as the first Element in the document.
 * @throws MementoException
 *         if an error prevented the creation of the Memento.
 */
public static XMLMemento read(final InputStream inputStream, final String encoding) throws MementoException {
    Check.notNull(inputStream, "inputStream"); //$NON-NLS-1$

    try {
        final XMLStreamReader reader = StaxFactoryProvider.getXMLInputFactory(true)
                .createXMLStreamReader(inputStream, (encoding != null) ? encoding : DEFAULT_ENCODING);

        XMLMemento memento = null;
        String localName;
        int event;

        do {
            event = reader.next();

            if (event == XMLStreamConstants.START_ELEMENT) {
                localName = reader.getLocalName();

                memento = new XMLMemento(localName);
                memento.readFromElement(reader);
            }
        } while (event != XMLStreamConstants.END_ELEMENT && event != XMLStreamConstants.END_DOCUMENT);

        reader.close();

        return memento;
    } catch (final XMLStreamException e) {
        log.error("Error reading", e); //$NON-NLS-1$
        throw new MementoException(e);
    }
}

From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.java

/**
 * Reserved for internal use. Parses the operation response as an entity. Reads entity data from the specified
 * <code>XMLStreamReader</code> using the specified class type and optionally projects the entity result with the
 * specified resolver into a {@link TableResult} object.
 * //from  w  w  w.  j  av  a  2  s .co m
 * @param xmlr
 *            The <code>XMLStreamReader</code> to read the data to parse from.
 * @param httpStatusCode
 *            The HTTP status code returned with the operation response.
 * @param clazzType
 *            The class type <code>T</code> implementing {@link TableEntity} for the entity returned. Set to
 *            <code>null</code> to ignore the returned entity and copy only response properties into the
 *            {@link TableResult} object.
 * @param resolver
 *            An {@link EntityResolver} instance to project the entity into an instance of type <code>R</code>. Set
 *            to <code>null</code> to return the entitys as instance of the class type <code>T</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @return
 *         A {@link TableResult} object with the parsed operation response.
 * 
 * @throws XMLStreamException
 *             if an error occurs while accessing the stream.
 * @throws ParseException
 *             if an error occurs while parsing the stream.
 * @throws InstantiationException
 *             if an error occurs while constructing the result.
 * @throws IllegalAccessException
 *             if an error occurs in reflection while parsing the result.
 * @throws StorageException
 *             if a storage service error occurs.
 */
protected static <T extends TableEntity, R> TableResult parseSingleOpResponse(final XMLStreamReader xmlr,
        final int httpStatusCode, final Class<T> clazzType, final EntityResolver<R> resolver,
        final OperationContext opContext) throws XMLStreamException, ParseException, InstantiationException,
        IllegalAccessException, StorageException {
    xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null);
    xmlr.next();

    final TableResult res = parseEntity(xmlr, clazzType, resolver, opContext);
    res.setHttpStatusCode(httpStatusCode);
    return res;
}

From source file:sdmx.net.service.nomis.NOMISRESTServiceRegistry.java

public static List<NOMISGeography> parseGeography(InputStream in, String cubeId, String cubeName)
        throws XMLStreamException {
    List<NOMISGeography> geogList = new ArrayList<NOMISGeography>();
    String tagContent = null;//from   w  w  w. ja v a2 s.c  o m
    XMLInputFactory factory = XMLInputFactory.newInstance();

    XMLStreamReader reader = factory.createXMLStreamReader(in);
    int state = 0;
    String lastLang = null;
    while (reader.hasNext()) {
        int event = reader.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            if (reader.getLocalName().equals("Type")) {
                NOMISGeography geog = new NOMISGeography();
                geog.setCubeId(cubeId);
                geog.setCubeName(cubeName);
                geog.setGeography(reader.getAttributeValue("", "value"));
                geog.setGeographyName(reader.getAttributeValue("", "name"));
                geogList.add(geog);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            break;
        }
    }
    return geogList;
}