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:Main.java

/**
 * Copies all events within a <code>StartElement</code> until the matching
 * <code>EndElement</code> is reached. This method assumes that the reader
 * is positioned after the <code>StartElement</code> event, and when the
 * method completes, the stream will be positioned before the 
 * <code>EndElement</code> event, but it will not consume the end tag.
 * /*from www  .  j  av a  2 s  .  c  o  m*/
 * @param reader The event stream to read, positioned after the
 *       <code>StartElement</code>
 * @param consumer The destination for events read from teh stream, or
 *       <code>null</code> to ignore the events completely.
 * @throws XMLStreamException If an error occurs reading events.
 */
public static final void copyElementContent(XMLEventReader reader, XMLEventConsumer consumer)
        throws XMLStreamException {

    if (!reader.hasNext())
        return;

    for (int depth = 1; true;) {

        // peek and see if we're at the end element
        XMLEvent currEvt = reader.peek();
        if (currEvt.isEndElement()) {

            depth--;
            if (depth == 0) {

                break;

            }

        } else if (currEvt.isStartElement()) {

            depth++;

        }

        // consume the event
        currEvt = reader.nextEvent();

        if (consumer != null) {

            consumer.add(currEvt);

        }

    }

}

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

private static void skipXmlElements(final XMLEventReader filteredReader, final int numSkipped)
        throws XMLStreamException {
    for (int idx = 0; idx < numSkipped; idx++) {
        filteredReader.nextEvent();
    }//from  www  . j  av  a 2 s.  c o  m
}

From source file:ch.njol.skript.Updater.java

/**
 * Gets the changelogs and release dates of the newest versions
 * /*from ww  w. j  a  v a  2s .  c o  m*/
 * @param sender
 */
final static void getChangelogs(final CommandSender sender) {
    InputStream in = null;
    InputStreamReader r = null;
    try {
        final URLConnection conn = new URL(RSSURL).openConnection();
        conn.setRequestProperty("User-Agent", "Skript/v" + Skript.getVersion() + " (by Njol)"); // Bukkit returns a 403 (forbidden) if no user agent is set
        in = conn.getInputStream();
        r = new InputStreamReader(in, conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding());
        final XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(r);

        infos.clear();
        VersionInfo current = null;

        outer: while (reader.hasNext()) {
            XMLEvent e = reader.nextEvent();
            if (e.isStartElement()) {
                final String element = e.asStartElement().getName().getLocalPart();
                if (element.equalsIgnoreCase("title")) {
                    final String name = reader.nextEvent().asCharacters().getData().trim();
                    for (final VersionInfo i : infos) {
                        if (name.equals(i.name)) {
                            current = i;
                            continue outer;
                        }
                    }
                    current = null;
                } else if (element.equalsIgnoreCase("description")) {
                    if (current == null)
                        continue;
                    final StringBuilder cl = new StringBuilder();
                    while ((e = reader.nextEvent()).isCharacters())
                        cl.append(e.asCharacters().getData());
                    current.changelog = "- " + StringEscapeUtils.unescapeHtml("" + cl).replace("<br>", "")
                            .replace("<p>", "").replace("</p>", "").replaceAll("\n(?!\n)", "\n- ");
                } else if (element.equalsIgnoreCase("pubDate")) {
                    if (current == null)
                        continue;
                    synchronized (RFC2822) { // to make FindBugs shut up
                        current.date = new Date(
                                RFC2822.parse(reader.nextEvent().asCharacters().getData()).getTime());
                    }
                }
            }
        }
    } catch (final IOException e) {
        stateLock.writeLock().lock();
        try {
            state = UpdateState.CHECK_ERROR;
            error.set(ExceptionUtils.toString(e));
            Skript.error(sender, m_check_error.toString());
        } finally {
            stateLock.writeLock().unlock();
        }
    } catch (final Exception e) {
        Skript.error(sender, m_internal_error.toString());
        Skript.exception(e, "Unexpected error while checking for a new version of Skript");
        stateLock.writeLock().lock();
        try {
            state = UpdateState.CHECK_ERROR;
            error.set(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage());
        } finally {
            stateLock.writeLock().unlock();
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
            }
        }
        if (r != null) {
            try {
                r.close();
            } catch (final IOException e) {
            }
        }
    }
}

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

private static void parseBucket(XMLEventReader reader, StartElement element, LinearHistogram histogram)
        throws XMLStreamException {
    String upperBound = element.getAttributeByName(new QName(LATENCY_DIST_UPPER_BOUND.getName())).getValue();
    String values = element.getAttributeByName(new QName(LATENCY_DIST_VALUES.getName())).getValue();
    histogram.addMultipleValues(Integer.parseInt(upperBound) - 1, Integer.parseInt(values));

    while (reader.hasNext()) {
        XMLEvent xmlEvent = reader.nextEvent();
        if (xmlEvent.isEndElement()) {
            EndElement endElement = xmlEvent.asEndElement();
            if (LATENCY_DIST_BUCKET.getName().equals(endElement.getName().getLocalPart())) {
                return;
            }/*from  w ww  .ja  v  a 2 s  . com*/
        }
    }
    throw new XMLStreamException("Unexpected end of the document");
}

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  w w w.  jav a2s  .  co  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:com.predic8.membrane.core.interceptor.rest.XML2HTTP.java

/**
 * Checks, if the response contains an XML doc with NS {@link Constants#HTTP_NS}.
 * If it does, the HTTP data (uri, method, status, headers, body) is extracted from the doc
 * and set as the response./*from  w  w w. j a v  a  2 s . c o m*/
 *
 * Reverse of {@link com.predic8.membrane.core.http.xml.Request#write(XMLStreamWriter)} and
 * {@link com.predic8.membrane.core.http.xml.Response#write(XMLStreamWriter)}.
 */
public static void unwrapMessageIfNecessary(Message message) {
    if (MimeType.TEXT_XML_UTF8.equals(message.getHeader().getContentType())) {
        try {
            if (message.getBody().getLength() == 0)
                return;

            XMLEventReader parser;
            synchronized (xmlInputFactory) {
                parser = xmlInputFactory.createXMLEventReader(message.getBodyAsStreamDecoded(),
                        message.getCharset());
            }

            /* States:
             * 0 = before root element,
             * 1 = root element has HTTP_NS namespace
             */
            int state = 0;

            boolean keepSourceHeaders = false, foundHeaders = false, foundBody = false;

            while (parser.hasNext()) {
                XMLEvent event = parser.nextEvent();
                switch (state) {
                case 0:
                    if (event.isStartElement()) {
                        QName name = event.asStartElement().getName();
                        if (Constants.HTTP_NS.equals(name.getNamespaceURI())) {
                            state = 1;
                            if ("request".equals(name.getLocalPart())) {
                                Request req = (Request) message;
                                req.setMethod(requireAttribute(event.asStartElement(), "method"));
                                String httpVersion = getAttribute(event.asStartElement(), "http-version");
                                if (httpVersion == null)
                                    httpVersion = "1.1";
                                req.setVersion(httpVersion);
                            }
                        } else {
                            return;
                        }
                    }
                    break;
                case 1:
                    if (event.isStartElement()) {
                        String localName = event.asStartElement().getName().getLocalPart();
                        if ("status".equals(localName)) {
                            Response res = (Response) message;
                            res.setStatusCode(
                                    Integer.parseInt(requireAttribute(event.asStartElement(), "code")));
                            res.setStatusMessage(slurpCharacterData(parser, event.asStartElement()));
                        }
                        if ("uri".equals(localName)) {
                            Request req = (Request) message;
                            req.setUri(requireAttribute(event.asStartElement(), "value"));
                            // uri/... (port,host,path,query) structure is ignored, as value already contains everything
                            slurpXMLData(parser, event.asStartElement());
                        }
                        if ("headers".equals(localName)) {
                            foundHeaders = true;
                            keepSourceHeaders = "true"
                                    .equals(getAttribute(event.asStartElement(), "keepSourceHeaders"));
                        }
                        if ("header".equals(localName)) {
                            String key = requireAttribute(event.asStartElement(), "name");
                            boolean remove = getAttribute(event.asStartElement(), "remove") != null;
                            if (remove && !keepSourceHeaders)
                                throw new XML2HTTPException(
                                        "<headers keepSourceHeaders=\"false\"><header name=\"...\" remove=\"true\"> does not make sense.");
                            message.getHeader().removeFields(key);
                            if (!remove)
                                message.getHeader().add(key,
                                        slurpCharacterData(parser, event.asStartElement()));
                        }
                        if ("body".equals(localName)) {
                            foundBody = true;
                            String type = requireAttribute(event.asStartElement(), "type");
                            if ("plain".equals(type)) {
                                message.setBodyContent(slurpCharacterData(parser, event.asStartElement())
                                        .getBytes(Constants.UTF_8_CHARSET));
                            } else if ("xml".equals(type)) {
                                message.setBodyContent(slurpXMLData(parser, event.asStartElement())
                                        .getBytes(Constants.UTF_8_CHARSET));
                            } else {
                                throw new XML2HTTPException("XML-HTTP doc body type '" + type
                                        + "' is not supported (only 'plain' or 'xml').");
                            }
                        }
                    }
                    break;
                }
            }

            if (!foundHeaders && !keepSourceHeaders)
                message.getHeader().clear();
            if (!foundBody)
                message.setBodyContent(new byte[0]);
        } catch (XMLStreamException e) {
            log.error("", e);
        } catch (XML2HTTPException e) {
            log.error("", e);
        } catch (IOException e) {
            log.error("", e);
        }
    }
}

From source file:de.dfki.km.leech.parser.wikipedia.WikipediaDumpParser.java

/**
 * Reads all next character events from an xmlEventReader and concatenate their data into one String
 * // ww  w  .j a  v a  2s  .c om
 * @param xmlEventReader the xmlEventReader to get the events
 * 
 * @return the data of the character events, concatenated into one String
 * 
 * @throws XMLStreamException
 */
static protected String readNextCharEventsText(XMLEventReader xmlEventReader) throws XMLStreamException {
    StringBuilder strbText = new StringBuilder("");

    while (xmlEventReader.hasNext()) {
        XMLEvent nextEvent = xmlEventReader.peek();
        if (!nextEvent.isCharacters())
            break;

        nextEvent = xmlEventReader.nextEvent();
        strbText.append(nextEvent.asCharacters().getData());
    }

    return strbText.toString();
}

From source file:org.javelin.sws.ext.bind.internal.model.AttributePattern.java

@Override
protected String consumeNonNullString(XMLEventReader eventReader, UnmarshallingContext context)
        throws XMLStreamException {
    return ((Attribute) eventReader.nextEvent()).getValue();
}

From source file:WpRDFFunctionLibrary.java

public static void mergeGpmltoSingleFile(String gpmlLocation) throws IOException, XMLStreamException,
        ParserConfigurationException, SAXException, TransformerException {
    // Based on: http://stackoverflow.com/questions/10759775/how-to-merge-1000-xml-files-into-one-in-java
    //for (int i = 1; i < 8 ; i++) {      
    Writer outputWriter = new FileWriter("/tmp/WpGPML.xml");
    XMLOutputFactory xmlOutFactory = XMLOutputFactory.newFactory();
    XMLEventWriter xmlEventWriter = xmlOutFactory.createXMLEventWriter(outputWriter);
    XMLEventFactory xmlEventFactory = XMLEventFactory.newFactory();

    xmlEventWriter.add(xmlEventFactory.createStartDocument("ISO-8859-1", "1.0"));
    xmlEventWriter.add(xmlEventFactory.createStartElement("", null, "PathwaySet"));
    xmlEventWriter.add(xmlEventFactory.createAttribute("creationData", basicCalls.now()));
    XMLInputFactory xmlInFactory = XMLInputFactory.newFactory();

    File dir = new File(gpmlLocation);

    File[] rootFiles = dir.listFiles();
    //the section below is only in case of analysis sets
    for (File rootFile : rootFiles) {
        String fileName = FilenameUtils.removeExtension(rootFile.getName());
        System.out.println(fileName);
        String[] identifiers = fileName.split("_");
        System.out.println(fileName);
        String wpIdentifier = identifiers[identifiers.length - 2];
        String wpRevision = identifiers[identifiers.length - 1];
        //Pattern pattern = Pattern.compile("_(WP[0-9]+)_([0-9]+).gpml");
        //Matcher matcher = pattern.matcher(fileName);
        //System.out.println(matcher.find());
        //String wpIdentifier = matcher.group(1);
        File tempFile = new File(constants.localAllGPMLCacheDir() + wpIdentifier + "_" + wpRevision + ".gpml");
        //System.out.println(matcher.group(1));
        //String wpRevision = matcher.group(2);
        //System.out.println(matcher.group(2));
        if (!(tempFile.exists())) {
            System.out.println(tempFile.getName());
            Document currentGPML = basicCalls.openXmlFile(rootFile.getPath());
            basicCalls.saveDOMasXML(WpRDFFunctionLibrary.addWpProvenance(currentGPML, wpIdentifier, wpRevision),
                    constants.localCurrentGPMLCache() + tempFile.getName());
        }/*from  w  w w .  j  a  va2s. c  o  m*/
    }

    dir = new File("/tmp/GPML");
    rootFiles = dir.listFiles();
    for (File rootFile : rootFiles) {
        System.out.println(rootFile);
        XMLEventReader xmlEventReader = xmlInFactory.createXMLEventReader(new StreamSource(rootFile));
        XMLEvent event = xmlEventReader.nextEvent();
        // Skip ahead in the input to the opening document element
        try {
            while (event.getEventType() != XMLEvent.START_ELEMENT) {
                event = xmlEventReader.nextEvent();
            }

            do {
                xmlEventWriter.add(event);
                event = xmlEventReader.nextEvent();
            } while (event.getEventType() != XMLEvent.END_DOCUMENT);
            xmlEventReader.close();
        } catch (Exception e) {
            System.out.println("Malformed gpml file");
        }
    }

    xmlEventWriter.add(xmlEventFactory.createEndElement("", null, "PathwaySet"));
    xmlEventWriter.add(xmlEventFactory.createEndDocument());

    xmlEventWriter.close();
    outputWriter.close();
}

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);//w w  w. jav a2 s  .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());
        }
    }
}