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:com.microsoft.windowsazure.services.table.client.AtomPubParser.java

/**
 * Reserved for internal use. Parses the operation response as an entity. Parses the result returned in the
 * specified stream in AtomPub format into a {@link TableResult} containing an entity of the specified class type
 * projected using the specified resolver.
 * //from   w w w  .java  2 s. c om
 * @param xmlr
 *            An <code>XMLStreamReader</code> on the input stream.
 * @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 entity as an 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} containing the parsed entity result of the operation.
 * 
 * @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 parseEntity(final XMLStreamReader xmlr,
        final Class<T> clazzType, final EntityResolver<R> resolver, final OperationContext opContext)
        throws XMLStreamException, ParseException, InstantiationException, IllegalAccessException,
        StorageException {
    int eventType = xmlr.getEventType();
    final TableResult res = new TableResult();

    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.ENTRY);

    res.setEtag(StringEscapeUtils.unescapeHtml4(
            xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.ETAG)));

    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.ID)) {
                res.setId(Utility.readElementFromXMLReader(xmlr, ODataConstants.ID));
            } else if (name
                    .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) {
                // Do read properties
                if (resolver == null && clazzType == null) {
                    return res;
                } else {
                    res.setProperties(readProperties(xmlr, opContext));
                    break;
                }
            }
        }
    }

    // Move to end Content
    eventType = xmlr.next();
    if (eventType == XMLStreamConstants.CHARACTERS) {
        eventType = xmlr.next();
    }
    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.CONTENT);

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

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.ENTRY);

    String rowKey = null;
    String partitionKey = null;
    Date timestamp = null;

    // Remove core properties from map and set individually
    EntityProperty tempProp = res.getProperties().get(TableConstants.PARTITION_KEY);
    if (tempProp != null) {
        res.getProperties().remove(TableConstants.PARTITION_KEY);
        partitionKey = tempProp.getValueAsString();
    }

    tempProp = res.getProperties().get(TableConstants.ROW_KEY);
    if (tempProp != null) {
        res.getProperties().remove(TableConstants.ROW_KEY);
        rowKey = tempProp.getValueAsString();
    }

    tempProp = res.getProperties().get(TableConstants.TIMESTAMP);
    if (tempProp != null) {
        res.getProperties().remove(TableConstants.TIMESTAMP);
        timestamp = tempProp.getValueAsDate();
    }

    if (resolver != null) {
        // Call resolver
        res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag()));
    } else if (clazzType != null) {
        // Generate new entity and return
        final T entity = clazzType.newInstance();
        entity.setEtag(res.getEtag());

        entity.setPartitionKey(partitionKey);
        entity.setRowKey(rowKey);
        entity.setTimestamp(timestamp);

        entity.readEntity(res.getProperties(), opContext);

        res.setResult(entity);
    }

    return res;
}

From source file:com.predic8.membrane.core.interceptor.balancer.XMLElementSessionIdExtractor.java

@Override
public String getSessionId(Message msg) throws Exception {
    if (!msg.isXML()) {
        log.debug("Didn't search a XML element in none XML message.");
        return null;
    }/*from w  w w .j  a  v  a 2 s  .c om*/

    log.debug("searching for sessionid");

    fac.setProperty("javax.xml.stream.isNamespaceAware", namespace != null);
    XMLStreamReader reader = new FixedStreamReader(
            fac.createXMLStreamReader(msg.getBodyAsStreamDecoded(), msg.getCharset()));
    while (reader.hasNext()) {
        reader.next();
        if (isSessionIdElement(reader)) {
            log.debug("sessionid element found");
            return reader.getElementText();
        }

    }

    log.debug("no sessionid element found");
    return null;
}

From source file:eionet.webq.converter.XmlSchemaExtractor.java

/**
 * Extracts {@code @xsi:noNamespaceSchemaLocation} or {@code @xsi:schemaLocation} attribute value from xml root element.
 *
 * @param source source to be searched.//from  ww w. j  a v a 2 s .  c  om
 * @return {@code @xsi:noNamespaceSchemaLocation} or {@code @xsi:schemaLocation} attribute value, default {@code null}
 */
public String extractXmlSchema(byte[] source) {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    ByteArrayInputStream bais = new ByteArrayInputStream(source);
    XMLStreamReader xmlStreamReader = null;
    try {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(bais);
        while (xmlStreamReader.hasNext()) {
            if (xmlStreamReader.next() == START_ELEMENT) {
                return StringUtils.defaultString(
                        parseNoNamespaceSchemaLocation(xmlStreamReader.getAttributeValue(XSI_NAMESPACE_URI,
                                "noNamespaceSchemaLocation")),
                        parseSchemaLocation(
                                xmlStreamReader.getAttributeValue(XSI_NAMESPACE_URI, "schemaLocation")));
            }
        }
    } catch (Exception e) {
        LOGGER.warn("exception thrown during extracting xml schema", e);
    } finally {
        IOUtils.closeQuietly(bais);
        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (XMLStreamException e) {
                LOGGER.warn("unable to close xml stream", e);
            }
        }
    }
    return null;
}

From source file:com.predic8.membrane.core.config.AbstractXmlElement.java

/**
 * Needed to resolve interceptor IDs into interceptor beans
 *///from w  w  w. j av a 2  s .com

public XMLElement parse(XMLStreamReader token) throws Exception {
    move2RootElementIfNeeded(token);
    log.debug("<" + token.getLocalName() + ">");
    parseAttributes(token);
    while (token.hasNext()) {
        token.next();
        if (token.isStartElement()) {
            parseChildren(token, token.getName().getLocalPart());
        } else if (token.isCharacters()) {
            parseCharacters(token);
        } else if (token.isEndElement()) {
            log.debug("</" + token.getLocalName() + ">");
            break;
        }
    }
    doAfterParsing();
    return this;
}

From source file:wiki.link.LinkImporter.java

public boolean readXML(String filename) {

    //System.exit(1);
    //MAKE BLOODY SURE YOU HAVE SOME HOURS.
    DbConnector dbc = new DbConnector("localhost");
    dbc.jdbcTemplate.update("TRUNCATE links;");
    try {/*w  w w .j  a  va2s .c  om*/
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader xsr = xif.createXMLStreamReader(new FileInputStream(filename));

        long n = 0;
        List<Doc> toSave = new ArrayList<>();
        while (xsr.hasNext()) {
            xsr.next();
            if (xsr.getEventType() == XMLStreamReader.START_ELEMENT) {
                if (xsr.getLocalName().equals("page")) {
                    long id = -1;
                    String title = null;
                    String text = null;
                    while (xsr.hasNext()) {
                        xsr.next();
                        if (xsr.getEventType() == XMLStreamReader.START_ELEMENT) {
                            if (xsr.getLocalName().equals("id") && id == -1) {
                                id = Long.parseLong(xsr.getElementText());
                            }
                            if (xsr.getLocalName().equals("title")) {
                                title = xsr.getElementText();
                            }
                            if (xsr.getLocalName().equals("text")) {
                                text = xsr.getElementText();
                            }
                        } else if (xsr.getEventType() == XMLStreamReader.END_ELEMENT
                                && xsr.getLocalName().equals("page")) {
                            break;
                        }
                    }
                    if (id != -1 && title != null && text != null) {
                        Doc wd = new Doc(id, title, text);
                        toSave.add(wd);
                        n++;
                        if (n % 1000 == 0) {
                            insertLinks(toSave, dbc);
                            //                                WikiDoc.insertAll(toSave, dbc);
                            System.out.println(n);
                            toSave.clear();
                        }
                    }
                }
            }
        }
    } catch (IOException | XMLStreamException e) {
        e.printStackTrace();
    }
    return true;
}

From source file:edu.utah.further.mdr.impl.service.uml.XmiParser11Impl.java

/**
 * @param results//w  w w  .ja  v a  2  s . c om
 * @return
 * @throws XMLStreamException 
 * @throws XQException
 */
@Override
protected UmlModel parseResults(final XMLStreamReader results) throws XMLStreamException {
    final UmlModel model = (UmlModel) (new UmlElementBuilder("MODEL_ROOT", "UML Model", ElementType.MODEL)
            .build());

    if (results.hasNext()) {
        final Element dts = getRootElement(results);
        final NodeList elements = dts.getChildNodes();
        for (int i = 0; i < elements.getLength(); i++) {
            try {
                final UmlElement vd = new UmlElementBuilder((Element) elements.item(i)).build();
                model.addChild(vd);
            } catch (final Throwable e) {
                final String message = e.getMessage();
                addMessage(Severity.ERROR,
                        StringUtils.isBlank(message) ? "Failed to build UmlElement: " + e.toString() : message);
            }
        }
    } else {
        addMessage(Severity.ERROR, "xquery did not return a result set");
    }
    return model;
}

From source file:net.bulletin.pdi.xero.step.support.XMLChunkerImpl.java

@Override
public String pullNextXmlChunk() throws KettleException {
    Stack<String> elementStack = xmlChunkerState.getElementStack();
    XMLStreamReader xmlStreamReader = xmlChunkerState.getXmlStreamReader();

    try {/*from   ww w  .j a  va  2 s .  co m*/

        while (xmlStreamReader.hasNext()) {

            switch (xmlStreamReader.next()) {

            case XMLStreamConstants.END_DOCUMENT:
                return null;

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

            case XMLStreamConstants.START_ELEMENT:
                elementStack.push(xmlStreamReader.getLocalName());

                if (actualElementStackHasExpectedElements(xmlChunkerState)) {
                    return pullNextXmlChunkFromTopElementOnStack(xmlChunkerState);
                }

                break;

            }

        }
    } catch (Exception e) {
        throw new KettleException("a problem has arisen reading the xero xml stream", e);
    }

    return null;
}

From source file:edu.utah.further.core.xml.xquery.UTestXQueryServiceBaseX.java

/**
 * Execute a test XQuery document and put the results in a Stream.
 * /*from  w w w .  j  av a 2s.  co  m*/
 * @throws XMLStreamException
 */
@Test
public void executeXQueryIntoStream() throws XMLStreamException {
    final XMLStreamReader result = xQueryService.executeIntoStream(testXQuery, testXmlDocument,
            new HashMap<String, String>());
    assertNotNull(result);

    String elementResult = null;
    while (result.hasNext()) {
        if (result.next() == XMLStreamReader.START_ELEMENT && result.getName().getLocalPart() == "message") {
            elementResult = result.getElementText();
        }
    }

    assertNotNull(elementResult);
    assertThat(elementResult, is("Hello World!"));
}

From source file:edu.indiana.d2i.htrc.io.index.solr.SolrClient.java

private NamedVector parseOneVolume(InputStream content) throws XMLStreamException, IOException {
    //      java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(content));
    //      String line = "";
    //      while ((line = br.readLine()) != null) {
    //         System.out.println(line);
    //      }//www .java  2  s  . c o m
    //      br.close();

    String volumeID = null;
    Vector vector = null;
    XMLStreamReader parser = factory.createXMLStreamReader(content);
    while (parser.hasNext()) {
        int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            String attributeValue = parser.getAttributeValue(null, "name");
            if (attributeValue != null) {
                if (attributeValue.equals(VOLUME_ID)) {
                    volumeID = parser.getElementText();
                    volumeID = pairtree.uncleanId(volumeID);
                } else if (attributeValue.equals(VOLUME_OCR)) {
                    vector = createVector(parser);
                    break;
                }
            }
        }
    }

    NamedVector tv = new NamedVector(vector, volumeID);
    return tv;
}

From source file:com.sazneo.export.file.FileProcessor.java

/**
 * Process the XML file//from   w ww.ja  v a  2  s  . c  om
 */
public void process() {
    try {
        Reader reader = new FileReader(exportFile);
        XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
        XMLStreamReader xmlStreamReader = xmlFactory.createXMLStreamReader(reader);
        boolean fileTag = false;
        String fileName = null;
        Integer fileSize = null;
        while (xmlStreamReader.hasNext()) {
            xmlStreamReader.next();

            if (xmlStreamReader.getEventType() == XMLStreamReader.START_ELEMENT) {
                if ("file".equals(xmlStreamReader.getLocalName())) {
                    fileTag = true;
                    fileName = MessageFormat.format("{0}_{1}", xmlStreamReader.getAttributeValue(null, "id"),
                            xmlStreamReader.getAttributeValue(null, "filename"));
                    fileSize = Integer.parseInt(xmlStreamReader.getAttributeValue(null, "size"));
                    logger.debug(MessageFormat.format("XML contains file with name: {0} and size {1} bytes",
                            fileName, fileSize));
                }
            }

            if (fileTag) {
                if (xmlStreamReader.getEventType() == XMLStreamReader.CHARACTERS) {
                    exportFile(xmlStreamReader.getText(), fileName, fileSize);
                }

                if (xmlStreamReader.getEventType() == XMLStreamReader.END_ELEMENT) {
                    fileSize = null;
                    fileName = null;
                    fileTag = false;
                }
            }
        }
    } catch (FileNotFoundException e) {
        logger.error(MessageFormat.format("Could not find export file:-\n{0}", e));
    } catch (XMLStreamException e) {
        logger.error(MessageFormat.format("Could not parse xml export file:-\n{0}", e));
    }
}