Example usage for javax.xml.stream XMLInputFactory createXMLEventReader

List of usage examples for javax.xml.stream XMLInputFactory createXMLEventReader

Introduction

In this page you can find the example usage for javax.xml.stream XMLInputFactory createXMLEventReader.

Prototype

public abstract XMLEventReader createXMLEventReader(java.io.InputStream stream) throws XMLStreamException;

Source Link

Document

Create a new XMLEventReader from a java.io.InputStream

Usage

From source file:com.predic8.membrane.core.util.SOAPUtil.java

public static boolean isSOAP(XMLInputFactory xmlInputFactory, XOPReconstitutor xopr, Message msg) {
    try {//from   w w  w .  ja v a2s .c o  m
        XMLEventReader parser;
        synchronized (xmlInputFactory) {
            parser = xmlInputFactory.createXMLEventReader(xopr.reconstituteIfNecessary(msg));
        }

        while (parser.hasNext()) {
            XMLEvent event = parser.nextEvent();
            if (event.isStartElement()) {
                QName name = ((StartElement) event).getName();
                return (Constants.SOAP11_NS.equals(name.getNamespaceURI())
                        || Constants.SOAP12_NS.equals(name.getNamespaceURI()))
                        && "Envelope".equals(name.getLocalPart());
            }
        }
    } catch (Exception e) {
        log.warn("Ignoring exception: ", e);
    }
    return false;
}

From source file:com.hazelcast.simulator.probes.probes.ProbesResultXmlReader.java

public static Map<String, Result> read(InputStream inputStream) {
    Map<String, Result> result = new HashMap<String, Result>();
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    try {/*w w w. ja va 2  s  . c o m*/
        XMLEventReader reader = xmlInputFactory.createXMLEventReader(inputStream);
        while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            if (event.isStartElement()) {
                StartElement startElement = event.asStartElement();
                if (PROBES_RESULT.matches(startElement.getName().getLocalPart())) {
                    parseProbesResult(reader, result);
                }
            }
        }
    } catch (XMLStreamException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.predic8.membrane.core.util.SOAPUtil.java

public static boolean isFault(XMLInputFactory xmlInputFactory, XOPReconstitutor xopr, Message msg) {
    int state = 0;
    /*/* ww  w  .j av  a2 s. co  m*/
     * 0: waiting for "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
     * 1: waiting for "<soapenv:Body>" (skipping any "<soapenv:Header>")
     * 2: waiting for "<soapenv:Fault>"
     */
    try {
        XMLEventReader parser;
        synchronized (xmlInputFactory) {
            parser = xmlInputFactory.createXMLEventReader(xopr.reconstituteIfNecessary(msg));
        }

        while (parser.hasNext()) {
            XMLEvent event = parser.nextEvent();
            if (event.isStartElement()) {
                QName name = ((StartElement) event).getName();
                if (!Constants.SOAP11_NS.equals(name.getNamespaceURI())
                        && !Constants.SOAP12_NS.equals(name.getNamespaceURI()))
                    return false;

                if ("Header".equals(name.getLocalPart())) {
                    // skip header
                    int stack = 0;
                    while (parser.hasNext()) {
                        event = parser.nextEvent();
                        if (event.isStartElement())
                            stack++;
                        if (event.isEndElement())
                            if (stack == 0)
                                break;
                            else
                                stack--;
                    }
                    continue;
                }

                String expected;
                switch (state) {
                case 0:
                    expected = "Envelope";
                    break;
                case 1:
                    expected = "Body";
                    break;
                case 2:
                    expected = "Fault";
                    break;
                default:
                    return false;
                }
                if (expected.equals(name.getLocalPart())) {
                    if (state == 2)
                        return true;
                    else
                        state++;
                } else
                    return false;
            }
            if (event.isEndElement())
                return false;
        }
    } catch (Exception e) {
        log.warn("Ignoring exception: ", e);
    }
    return false;
}

From source file:org.psikeds.knowledgebase.xml.impl.XMLParser.java

/**
 * Helper for parsing big XML files using JAXB in combination with StAX.<br>
 * All classes in the specified package can be parsed.<br>
 * <b>Note:</b> The XML reader will not be closed. This must be invoked by
 * the caller afterwards!<br>// www  .j  a  va2 s.  com
 * 
 * @param xml
 *          Reader for XML-Data
 * @param packageName
 *          Name of the package containing the JAXB-Classes,
 *          e.g. org.psikeds.knowledgebase.jaxb
 * @param handler
 *          Callback handler used to process every single found
 *          XML-Element (@see
 *          org.psikeds.knowledgebase.xml.KBParserCallback#handleElement
 *          (java.lang.Object))
 * @param filter
 *          EventFilter used for StAX-Parsing
 * @param numSkipped
 *          Number of Elements to be skipped,
 *          e.g. numSkipped = 1 for skipping the XML-Root-Element.
 * @return Total number of unmarshalled XML-Elements
 * @throws XMLStreamException
 * @throws JAXBException
 */
public static long parseXmlElements(final Reader xml, final String packageName, final KBParserCallback handler,
        final EventFilter filter, final int numSkipped) throws XMLStreamException, JAXBException {

    // init stream reader
    final XMLInputFactory staxFactory = XMLInputFactory.newInstance();
    final XMLEventReader staxReader = staxFactory.createXMLEventReader(xml);
    final XMLEventReader filteredReader = filter == null ? staxReader
            : staxFactory.createFilteredReader(staxReader, filter);

    skipXmlElements(filteredReader, numSkipped);

    // JAXB with specific package
    final JAXBContext jaxbCtx = JAXBContext.newInstance(packageName);
    final Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();

    // parsing und unmarshalling
    long counter = 0;
    while (filteredReader.peek() != null) {
        final Object element = unmarshaller.unmarshal(staxReader);
        handleElement(handler, element);
        counter++;
    }
    return counter;
}

From source file:org.psikeds.knowledgebase.xml.impl.XMLParser.java

/**
 * Helper for parsing big XML files using JAXB in combination with StAX.<br>
 * Only XML-Elements of the specified Top-Level-Class will be parsed.<br>
 * <b>Note:</b> The XML reader will not be closed. This must be invoked by
 * the caller afterwards!<br>//from ww w.java2s.  c o  m
 * 
 * @param xml
 *          Reader for XML-Data
 * @param elementClass
 *          Top-Level-Class used for JAXB-Unmarshalling
 * @param handler
 *          Callback handler used to process every single found XML
 *          element (@see
 *          org.psikeds.knowledgebase.xml.KBParserCallback#handleElement
 *          (java.lang.Object))
 * @param filter
 *          EventFilter used for StAX-Parsing
 * @param numSkipped
 *          Number of Elements to be skipped,
 *          e.g. numSkipped = 1 for skipping the XML-Root-Element.
 * @return Total number of unmarshalled XML-Elements
 * @throws XMLStreamException
 * @throws JAXBException
 */
public static long parseXmlElements(final Reader xml, final Class<?> elemClazz, final KBParserCallback handler,
        final EventFilter filter, final int numSkipped) throws XMLStreamException, JAXBException {

    // init stream reader
    final XMLInputFactory staxFactory = XMLInputFactory.newInstance();
    final XMLEventReader staxReader = staxFactory.createXMLEventReader(xml);
    final XMLEventReader filteredReader = filter == null ? staxReader
            : staxFactory.createFilteredReader(staxReader, filter);

    skipXmlElements(filteredReader, numSkipped);

    // JAXB with specific top-level-class
    final JAXBContext jaxbCtx = JAXBContext.newInstance(elemClazz);
    final Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();

    // parsing und unmarshalling
    long counter = 0;
    while (filteredReader.peek() != null) {
        final Object element = unmarshaller.unmarshal(staxReader, elemClazz);
        handleElement(handler, element);
        counter++;
    }
    return counter;
}

From source file:org.opennms.netmgt.ackd.readers.HypericAckProcessor.java

/**
 * <p>parseHypericAlerts</p>
 *
 * @param reader a {@link java.io.Reader} object.
 * @return a {@link java.util.List} object.
 * @throws javax.xml.bind.JAXBException if any.
 * @throws javax.xml.stream.XMLStreamException if any.
 *///from  ww  w  . j a v a2  s  . c o  m
public static List<HypericAlertStatus> parseHypericAlerts(Reader reader)
        throws JAXBException, XMLStreamException {
    List<HypericAlertStatus> retval = new ArrayList<HypericAlertStatus>();

    // Instantiate a JAXB context to parse the alert status
    JAXBContext context = JAXBContext
            .newInstance(new Class[] { HypericAlertStatuses.class, HypericAlertStatus.class });
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    XMLEventReader xmler = xmlif.createXMLEventReader(reader);
    EventFilter filter = new EventFilter() {
        @Override
        public boolean accept(XMLEvent event) {
            return event.isStartElement();
        }
    };
    XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter);
    // Read up until the beginning of the root element
    StartElement startElement = (StartElement) xmlfer.nextEvent();
    // Fetch the root element name for {@link HypericAlertStatus} objects
    String rootElementName = context.createJAXBIntrospector().getElementName(new HypericAlertStatuses())
            .getLocalPart();
    if (rootElementName.equals(startElement.getName().getLocalPart())) {
        Unmarshaller unmarshaller = context.createUnmarshaller();
        // Use StAX to pull parse the incoming alert statuses
        while (xmlfer.peek() != null) {
            Object object = unmarshaller.unmarshal(xmler);
            if (object instanceof HypericAlertStatus) {
                HypericAlertStatus alertStatus = (HypericAlertStatus) object;
                retval.add(alertStatus);
            }
        }
    } else {
        // Try to pull in the HTTP response to give the user a better idea of what went wrong
        StringBuffer errorContent = new StringBuffer();
        LineNumberReader lineReader = new LineNumberReader(reader);
        try {
            String line;
            while (true) {
                line = lineReader.readLine();
                if (line == null) {
                    break;
                } else {
                    errorContent.append(line.trim());
                }
            }
        } catch (IOException e) {
            errorContent.append("Exception while trying to print out message content: " + e.getMessage());
        }

        // Throw an exception and include the erroneous HTTP response in the exception text
        throw new JAXBException("Found wrong root element in Hyperic XML document, expected: \""
                + rootElementName + "\", found \"" + startElement.getName().getLocalPart() + "\"\n"
                + errorContent.toString());
    }
    return retval;
}

From source file:de.tudarmstadt.ukp.integration.alignment.xml.AlignmentXmlReader.java

public AlignmentXmlReader(File inputLocation) throws IOException {
    fs = null;//  ww w .jav a2s .com
    try {
        fs = new FileInputStream(inputLocation);
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        xmlEventReader = xmlInputFactory.createXMLEventReader(fs);

        JAXBContext context;
        context = JAXBContext.newInstance(XmlMeta.class, Alignments.class);

        unmarshaller = context.createUnmarshaller();
    } catch (JAXBException | XMLStreamException e1) {
        throw new IOException(e1);
    }

}

From source file:StAXEventTreeViewer.java

public void buildTree(DefaultTreeModel treeModel, DefaultMutableTreeNode current, File file)
        throws XMLStreamException, FileNotFoundException {

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader reader = inputFactory.createXMLEventReader(new FileInputStream(file));
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        switch (event.getEventType()) {
        case XMLStreamConstants.START_DOCUMENT:
            StartDocument startDocument = (StartDocument) event;
            DefaultMutableTreeNode version = new DefaultMutableTreeNode(startDocument.getVersion());
            current.add(version);/*from  w ww.j a va2s. c o  m*/

            current.add(new DefaultMutableTreeNode(startDocument.isStandalone()));
            current.add(new DefaultMutableTreeNode(startDocument.standaloneSet()));
            current.add(new DefaultMutableTreeNode(startDocument.encodingSet()));
            current.add(new DefaultMutableTreeNode(startDocument.getCharacterEncodingScheme()));
            break;
        case XMLStreamConstants.START_ELEMENT:
            StartElement startElement = (StartElement) event;
            QName elementName = startElement.getName();

            DefaultMutableTreeNode element = new DefaultMutableTreeNode(elementName.getLocalPart());
            current.add(element);
            current = element;

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

            for (Iterator it = startElement.getAttributes(); it.hasNext();) {
                Attribute attr = (Attribute) it.next();
                DefaultMutableTreeNode attribute = new DefaultMutableTreeNode("Attribute (name="
                        + attr.getName().getLocalPart() + ",value=" + attr.getValue() + "')");
                String attURI = attr.getName().getNamespaceURI();
                if (!attURI.equals("")) {
                    String attPrefix = attr.getName().getPrefix();
                    if (attPrefix.equals("")) {
                        attPrefix = "[None]";
                    }
                    attribute.add(new DefaultMutableTreeNode("prefix = " + attPrefix + ", URI = " + attURI));
                }
                current.add(attribute);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            current = (DefaultMutableTreeNode) current.getParent();
            break;
        case XMLStreamConstants.CHARACTERS:
            Characters characters = (Characters) event;
            if (!characters.isIgnorableWhiteSpace() && !characters.isWhiteSpace()) {
                String data = characters.getData();
                if (data.length() != 0) {
                    current.add(new DefaultMutableTreeNode(characters.getData()));
                }
            }
            break;
        case XMLStreamConstants.DTD:
            DTD dtde = (DTD) event;
            current.add(new DefaultMutableTreeNode(dtde.getDocumentTypeDeclaration()));
        default:
            System.out.println(event.getClass().getName());
        }
    }
}

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

public XMLEventReaderWrapper(final InputStream stream) throws Exception {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty(XMLInputFactory.IS_VALIDATING, false);
    factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);

    this.wrapped = factory.createXMLEventReader(new ByteArrayInputStream(
            (XMLEventReaderWrapper.CONTENT_STAG + IOUtils.toString(stream) + XMLEventReaderWrapper.CONTENT_ETAG)
                    .getBytes()));//w  w w . j  ava 2 s  . c  o m

    init(wrapped);
}

From source file:edu.uci.ics.jung.io.graphml.GraphMLReader2.java

/**
 * Verifies the object state and initializes this reader. All transformer
 * properties must be set and be non-null or a <code>GraphReaderException
 * </code> will be thrown. This method may be called more than once.
 * Successive calls will have no effect.
 *
 * @throws edu.uci.ics.jung.io.GraphIOException thrown if an error occurred.
 */// ww w . j av  a  2  s .  co  m
public void init() throws GraphIOException {

    try {

        if (!initialized) {

            // Create the event reader.
            XMLInputFactory factory = XMLInputFactory.newInstance();
            xmlEventReader = factory.createXMLEventReader(fileReader);
            xmlEventReader = factory.createFilteredReader(xmlEventReader, new GraphMLEventFilter());

            initialized = true;
        }

    } catch (Exception e) {
        ExceptionConverter.convert(e);
    }
}