Example usage for javax.xml.stream XMLEventReader nextEvent

List of usage examples for javax.xml.stream XMLEventReader nextEvent

Introduction

In this page you can find the example usage for javax.xml.stream XMLEventReader nextEvent.

Prototype

public XMLEvent nextEvent() throws XMLStreamException;

Source Link

Document

Gets the next XMLEvent.

Usage

From source file:corpus.sinhala.crawler.blog.rss.RSSFeedParser.java

public String getBlogId() {
    Feed feed = null;//from   w w  w  .jav  a2  s.c o m
    String atomId = "";
    try {
        // First create a new XMLInputFactory
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        // Setup a new eventReader
        InputStream in = read();
        XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
        // Read the XML document
        int location = -1;
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (event.isStartElement()) {
                String localPart = event.asStartElement().getName().getLocalPart();
                //System.out.println(localPart);
                switch (localPart) {

                case CHANNEL:
                    event = eventReader.nextEvent();
                    atomId = getCharacterData(event, eventReader);
                    //System.out.println("Atom Id "+atomId );
                    return atomId.split("-")[1];
                }
            }
        }
    } catch (XMLStreamException e) {

        throw new RuntimeException(e);
    }

    return null;
}

From source file:com.predic8.membrane.core.multipart.XOPReconstitutor.java

private byte[] fillInXOPParts(InputStream inputStream, HashMap<String, Part> parts)
        throws XMLStreamException, FactoryConfigurationError {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(baos);

    try {// w w  w  . jav  a 2  s  .com
        XMLEventReader parser = createEventReaderFromStream(inputStream);

        boolean xopIncludeOpen = false;

        while (parser.hasNext()) {
            XMLEvent event = parser.nextEvent();

            if (event instanceof StartElement) {
                StartElement start = (StartElement) event;
                if (XOP_NAMESPACE_URI.equals(start.getName().getNamespaceURI())
                        && start.getName().getLocalPart().equals("Include")) {
                    String href = start.getAttributeByName(new QName("href")).getValue();

                    if (href.startsWith("cid:"))
                        href = href.substring(4);

                    Part p = parts.get("<" + href + ">");
                    if (p == null)
                        throw new RuntimeException("Did not find multipart with id " + href);

                    writer.add(p.asXMLEvent());
                    xopIncludeOpen = true;
                    continue;
                }
            } else if (event instanceof EndElement) {
                EndElement start = (EndElement) event;
                if (XOP_NAMESPACE_URI.equals(start.getName().getNamespaceURI())
                        && start.getName().getLocalPart().equals("Include") && xopIncludeOpen) {
                    xopIncludeOpen = false;
                    continue;
                }
            }

            writer.add(event);
        }
        writer.flush();
    } catch (XMLStreamException e) {
        log.warn("Received not-wellformed XML.");
        return null;
    }
    return baos.toByteArray();
}

From source file:fr.openwide.talendalfresco.rest.client.ClientCommandBase.java

public final void handleResponse(XMLEventReader xmlReader) throws XMLStreamException {
    // Read the response body and parse it
    while (xmlReader.hasNext()) {
        XMLEvent event = xmlReader.nextEvent();

        if (isInCommandResponseContent) {

            // within command content tag case
            switch (event.getEventType()) {
            case XMLEvent.END_ELEMENT:
                commandResponseContentDepth--;
                if (commandResponseContentDepth == -1) {
                    // means the content tag has been closed
                    isInCommandResponseContent = false;
                }//  w w w .j a  v  a2s.  co m
                break;
            case XMLEvent.START_ELEMENT:
                commandResponseContentDepth++;
            }
            // delegate impl of command content tag case
            handleResponseContentEvent(event);

        } else {

            // outside command content tag case
            handleResponseTopLevelEvent(event);
        }
    }

    resultCode = elementValueMap.get(RestConstants.TAG_CODE);
    resultError = elementValueMap.get(RestConstants.TAG_ERROR);
    resultMessage = elementValueMap.get(RestConstants.TAG_MESSAGE);
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

public static XmlElement getAtomElement(final StartElement start, final XMLEventReader reader)
        throws Exception {

    final XmlElement res = new XmlElement();
    res.setStart(start);//from  ww  w.jav  a  2  s .  c  om

    StringWriter content = new StringWriter();

    int depth = 1;

    while (reader.hasNext() && depth > 0) {
        final XMLEvent event = reader.nextEvent();

        if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && start.getName().getLocalPart().equals(event.asStartElement().getName().getLocalPart())) {
            depth++;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && start.getName().getLocalPart().equals(event.asEndElement().getName().getLocalPart())) {
            depth--;
        }

        if (depth == 0) {
            res.setEnd(event.asEndElement());
        } else {
            event.writeAsEncodedUnicode(content);
        }
    }

    content.flush();
    content.close();

    res.setContent(new ByteArrayInputStream(content.toString().getBytes()));

    return res;
}

From source file:com.streamsets.pipeline.lib.salesforce.BulkRecordCreator.java

private Field pullMap(XMLEventReader reader) throws StageException, XMLStreamException {
    LinkedHashMap<String, Field> map = new LinkedHashMap<>();
    String type = null;/*from  ww  w  . jav a  2 s. com*/

    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            if (event.asStartElement().getName().getLocalPart().equals(TYPE)) {
                // Move to content
                event = reader.nextEvent();
                type = event.asCharacters().getData().toLowerCase();
                // Consume closing tag
                reader.nextEvent();
            } else {
                String fieldName = event.asStartElement().getName().getLocalPart();
                Attribute attr = event.asStartElement().getAttributeByName(XSI_TYPE);
                if (attr != null && attr.getValue().equals(S_OBJECT)) {
                    // Element is a nested record
                    map.put(fieldName, pullMap(reader));
                } else {
                    event = reader.nextEvent();
                    if (event.isCharacters()) {
                        // Element is a field value
                        String fieldValue = event.asCharacters().getData();
                        if (type == null) {
                            throw new StageException(Errors.FORCE_38);
                        }
                        com.sforce.soap.partner.Field sfdcField = getFieldMetadata(type, fieldName);

                        Field field = createField(fieldValue, sfdcField);
                        if (conf.createSalesforceNsHeaders) {
                            setHeadersOnField(field, getFieldMetadata(type, fieldName));
                        }

                        map.put(fieldName, field);

                        // Consume closing tag
                        reader.nextEvent();
                    } else if (event.isStartElement()) {
                        // Element is a nested list of records
                        // Advance over <done>, <queryLocator> to record list
                        while (!(event.isStartElement()
                                && event.asStartElement().getName().getLocalPart().equals(RECORDS))) {
                            event = reader.nextEvent();
                        }

                        // Read record list
                        List<Field> recordList = new ArrayList<>();
                        while (event.isStartElement()
                                && event.asStartElement().getName().getLocalPart().equals(RECORDS)) {
                            recordList.add(pullMap(reader));
                            event = reader.nextEvent();
                        }
                        map.put(fieldName, Field.create(recordList));
                    }
                }
            }
        } else if (event.isEndElement()) {
            // Done with record
            return Field.createListMap(map);
        }
    }

    throw new StageException(Errors.FORCE_39);
}

From source file:com.streamsets.pipeline.lib.xml.StreamingXmlParser.java

XMLEvent read(XMLEventReader reader) throws XMLStreamException {
    skipIgnorable(reader);
    return reader.nextEvent();
}

From source file:com.predic8.membrane.core.interceptor.rest.REST2SOAPInterceptor.java

private String getRootElementNamespace(InputStream stream) {
    try {/*from ww  w .  jav  a2s. co  m*/
        XMLEventReader xer = XMLInputFactory.newFactory().createXMLEventReader(stream);
        while (xer.hasNext()) {
            XMLEvent event = xer.nextEvent();
            if (event.isStartElement())
                return event.asStartElement().getName().getNamespaceURI();
        }
    } catch (XMLStreamException e) {
        log.error("Could not determine root element namespace for check whether namespace is SOAP 1.2.", e);
    }
    return null;
}

From source file:com.predic8.membrane.core.interceptor.schemavalidation.SchematronValidator.java

@Override
public Outcome validateMessage(Exchange exc, Message msg, String source) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {/*from   w w w  .jav a2s .c o m*/
        Transformer transformer = transformers.take();
        try {
            transformer.transform(new StreamSource(xopr.reconstituteIfNecessary(msg)), new StreamResult(baos));
        } finally {
            transformers.put(transformer);
        }

        byte[] result = baos.toByteArray();

        // check for errors
        XMLEventReader parser;
        synchronized (xmlInputFactory) {
            parser = xmlInputFactory.createXMLEventReader(new ByteArrayInputStream(result));
        }
        while (parser.hasNext()) {
            XMLEvent event = parser.nextEvent();
            if (event.isStartElement()) {
                StartElement startElement = (StartElement) event;
                if (startElement.getName().getLocalPart().equals("failed-assert")) {
                    setErrorMessage(exc, new String(result, UTF_8_CHARSET), false, source);
                    invalid.incrementAndGet();
                    return Outcome.ABORT;
                }
            }
        }

    } catch (TransformerException e) {
        setErrorMessage(exc, e.getMessage(), true, source);
        invalid.incrementAndGet();
        return Outcome.ABORT;
    } catch (Exception e) {
        log.error("", e);
        setErrorMessage(exc, "internal error", true, source);
        invalid.incrementAndGet();
        return Outcome.ABORT;
    }
    valid.incrementAndGet();
    return Outcome.CONTINUE;
}

From source file:org.eclipse.swordfish.core.configuration.xml.XmlToPropertiesTransformerImpl.java

public void loadConfiguration(URL path) {
    Assert.notNull(path);// w w w.  ja va2 s . c o  m
    InputStream inputStream = null;
    try {
        inputStream = path.openStream();
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        LinkedList<String> currentElements = new LinkedList<String>();
        XMLEventReader eventReader = inputFactory.createXMLEventReader(inputStream);
        Map<String, List<String>> props = new HashMap<String, List<String>>();
        // Read the XML document
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (event.isCharacters() && !event.asCharacters().isWhiteSpace()) {
                putElement(props, getQualifiedName(currentElements), event.asCharacters().getData());

            } else if (event.isStartElement()) {
                currentElements.add(event.asStartElement().getName().getLocalPart());
                for (Iterator attrIt = event.asStartElement().getAttributes(); attrIt.hasNext();) {
                    Attribute attribute = (Attribute) attrIt.next();
                    putElement(props, getQualifiedName(currentElements) + "[@" + attribute.getName() + "]",
                            attribute.getValue());

                }
            } else if (event.isAttribute()) {
            } else if (event.isEndElement()) {
                String lastElem = event.asEndElement().getName().getLocalPart();
                if (!currentElements.getLast().equals(lastElem)) {
                    throw new UnsupportedOperationException(lastElem + "," + currentElements.getLast());
                }
                currentElements.removeLast();
            }
        }
        properties = flattenProperties(props);
    } catch (Exception ex) {
        throw new SwordfishException(ex);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:com.streamsets.pipeline.lib.xml.StreamingXmlParser.java

void skipIgnorable(XMLEventReader reader) throws XMLStreamException {
    while (reader.hasNext() && isIgnorable(reader.peek())) {
        reader.nextEvent();
    }//  www . ja  v a 2 s . c  om
}