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:com.predic8.membrane.integration.ProxyRuleTest.java

@Test
public void testReadRuleFromByteBuffer() throws Exception {
    ProxyRule rule2 = new ProxyRule();
    rule2.setRouter(router);//from w  ww .j ava 2 s .c  o  m

    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader reader = factory.createXMLStreamReader((new ByteArrayInputStream(buffer)), Constants.UTF_8);

    while (reader.next() != XMLStreamReader.START_ELEMENT)
        ;

    rule2.parse(reader);

    assertEquals(8888, rule2.getKey().getPort());
    assertEquals("Rule 1", rule2.getName());
    assertNull(rule2.getLocalHost());
    assertEquals(true, rule2.isInboundTLS());
    assertFalse(rule2.isOutboundTLS());

    List<Interceptor> inters = rule2.getInterceptors();
    assertFalse(inters.isEmpty());
    assertTrue(inters.size() == 2);
    inters.get(0).getId().equals("roundRobinBalancer");
    inters.get(1).getId().equals("accessControlInterceptor");

    assertEquals(true, rule2.isBlockResponse());
    assertFalse(rule2.isBlockRequest());
}

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

protected void move2RootElementIfNeeded(XMLStreamReader token) throws XMLStreamException {
    if (token.getEventType() == XMLStreamReader.START_DOCUMENT) {
        while (!token.isStartElement()) {
            token.next();
        }/* ww  w  .j  a v  a  2 s . co  m*/
    }

}

From source file:StAXStreamTreeViewer.java

private void parseRestOfDocument(XMLStreamReader reader, DefaultMutableTreeNode current)
        throws XMLStreamException {

    while (reader.hasNext()) {
        int type = reader.next();
        switch (type) {
        case XMLStreamConstants.START_ELEMENT:

            DefaultMutableTreeNode element = new DefaultMutableTreeNode(reader.getLocalName());
            current.add(element);//www .j  a v a2 s.  c o  m
            current = element;

            if (reader.getNamespaceURI() != null) {
                String prefix = reader.getPrefix();
                if (prefix == null) {
                    prefix = "[None]";
                }
                DefaultMutableTreeNode namespace = new DefaultMutableTreeNode(
                        "prefix = '" + prefix + "', URI = '" + reader.getNamespaceURI() + "'");
                current.add(namespace);
            }

            if (reader.getAttributeCount() > 0) {
                for (int i = 0; i < reader.getAttributeCount(); i++) {
                    DefaultMutableTreeNode attribute = new DefaultMutableTreeNode(
                            "Attribute (name = '" + reader.getAttributeLocalName(i) + "', value = '"
                                    + reader.getAttributeValue(i) + "')");
                    String attURI = reader.getAttributeNamespace(i);
                    if (attURI != null) {
                        String attPrefix = reader.getAttributePrefix(i);
                        if (attPrefix == null || attPrefix.equals("")) {
                            attPrefix = "[None]";
                        }
                        DefaultMutableTreeNode attNamespace = new DefaultMutableTreeNode(
                                "prefix=" + attPrefix + ",URI=" + attURI);
                        attribute.add(attNamespace);
                    }
                    current.add(attribute);
                }
            }

            break;
        case XMLStreamConstants.END_ELEMENT:
            current = (DefaultMutableTreeNode) current.getParent();
            break;
        case XMLStreamConstants.CHARACTERS:
            if (!reader.isWhiteSpace()) {
                DefaultMutableTreeNode data = new DefaultMutableTreeNode("CD:" + reader.getText());
                current.add(data);
            }
            break;
        case XMLStreamConstants.DTD:
            DefaultMutableTreeNode dtd = new DefaultMutableTreeNode("DTD:" + reader.getText());
            current.add(dtd);
            break;
        case XMLStreamConstants.SPACE:
            break;
        case XMLStreamConstants.COMMENT:
            DefaultMutableTreeNode comment = new DefaultMutableTreeNode(reader.getText());
            current.add(comment);
            break;
        default:
            System.out.println(type);
        }
    }
}

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.
 * /* w w  w. java2s .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. ja va 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:com.flexive.chemistry.webdav.TextDocumentResource.java

protected void processXmlProperties(InputStream in) {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    try {//w  ww  .  ja  v a 2  s . c  om
        final XMLStreamReader parser = factory.createXMLStreamReader(in);
        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                if ("property".equals(parser.getLocalName())) {
                    processProperty(parser);
                } else if ("name".equals(parser.getLocalName())) {
                    processName(parser);
                }

            }
        }
    } catch (XMLStreamException e) {
        throw new RuntimeException("Failed to replace content: " + e.getMessage(), e);
    }
}

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

/**
 * Needed to resolve interceptor IDs into interceptor beans
 *//*from   ww w.j  a  v  a2  s  .  co m*/

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: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.//  w ww .  ja  v a 2s .c  o m
 * @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.cedarsoft.serialization.stax.mate.StaxMateSerializerTest.java

License:asdf

@Nonnull
@Override//  w ww  . j av  a  2 s.c  om
protected AbstractStaxMateSerializer<String> getSerializer() {
    return new AbstractStaxMateSerializer<String>("aString", "http://www.lang.java/String",
            new VersionRange(new Version(1, 5, 3), new Version(1, 5, 3))) {
        @Override
        public void serialize(@Nonnull SMOutputElement serializeTo, @Nonnull String object,
                @Nonnull Version formatVersion) throws XMLStreamException {
            assert isVersionWritable(formatVersion);
            serializeTo.addCharacters(object);
        }

        @Override
        @Nonnull
        public String deserialize(@Nonnull XMLStreamReader deserializeFrom, @Nonnull Version formatVersion)
                throws XMLStreamException {
            assert isVersionReadable(formatVersion);
            deserializeFrom.next();
            String text = deserializeFrom.getText();
            closeTag(deserializeFrom);
            return text;
        }
    };
}

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 w w w .jav a  2 s .  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;
}