Example usage for javax.xml.stream.events XMLEvent getEventType

List of usage examples for javax.xml.stream.events XMLEvent getEventType

Introduction

In this page you can find the example usage for javax.xml.stream.events XMLEvent getEventType.

Prototype

public int getEventType();

Source Link

Document

Returns an integer code for this event.

Usage

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.OfflineImageReconstructor.java

private void expectTagEnd(String expected) throws IOException {
    XMLEvent ev = expectTag(expected, true);
    if (ev.getEventType() != XMLStreamConstants.END_ELEMENT) {
        throw new IOException("Expected tag end event for " + expected + ", but got: " + ev);
    }//from  w ww . ja  va 2s  .  c  om
    if (!expected.startsWith("[")) {
        String tag = ev.asEndElement().getName().getLocalPart();
        if (!tag.equals(expected)) {
            throw new IOException(
                    "Expected tag end event for " + expected + ", but got tag end event for " + tag);
        }
    }
}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.OfflineImageReconstructor.java

private void loadNodeChildrenHelper(Node parent, String expected, String terminators[]) throws IOException {
    XMLEvent ev = null;
    while (true) {
        try {/*from  www  . j  av a2s . c om*/
            ev = events.peek();
            switch (ev.getEventType()) {
            case XMLEvent.END_ELEMENT:
                if (terminators.length != 0) {
                    return;
                }
                events.nextEvent();
                return;
            case XMLEvent.START_ELEMENT:
                String key = ev.asStartElement().getName().getLocalPart();
                for (String terminator : terminators) {
                    if (terminator.equals(key)) {
                        return;
                    }
                }
                events.nextEvent();
                Node node = new Node();
                parent.addChild(key, node);
                loadNodeChildrenHelper(node, expected, new String[0]);
                break;
            case XMLEvent.CHARACTERS:
                String val = XMLUtils.unmangleXmlString(ev.asCharacters().getData(), true);
                parent.setVal(val);
                events.nextEvent();
                break;
            case XMLEvent.ATTRIBUTE:
                throw new IOException("Unexpected XML event " + ev);
            default:
                // Ignore other event types like comment, etc.
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Skipping XMLEvent " + ev);
                }
                events.nextEvent();
                break;
            }
        } catch (XMLStreamException e) {
            throw new IOException("Expecting " + expected + ", but got XMLStreamException", e);
        }
    }
}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.OfflineImageReconstructor.java

/**
 * Processes the XML file back into an fsimage.
 *//* w w  w.j  ava2s  .  c  o  m*/
private void processXml() throws Exception {
    LOG.debug("Loading <fsimage>.");
    expectTag("fsimage", false);
    // Read the <version> tag.
    readVersion();
    // Write the HDFSIMG1 magic number which begins the fsimage file.
    out.write(FSImageUtil.MAGIC_HEADER);
    // Write a series of fsimage sections.
    sectionStartOffset = FSImageUtil.MAGIC_HEADER.length;
    final HashSet<String> unprocessedSections = new HashSet<>(sections.keySet());
    while (!unprocessedSections.isEmpty()) {
        XMLEvent ev = expectTag("[section header]", true);
        if (ev.getEventType() == XMLStreamConstants.END_ELEMENT) {
            if (ev.asEndElement().getName().getLocalPart().equals("fsimage")) {
                throw new IOException("FSImage XML ended prematurely, without " + "including section(s) "
                        + StringUtils.join(", ", unprocessedSections));
            }
            throw new IOException(
                    "Got unexpected tag end event for " + ev.asEndElement().getName().getLocalPart()
                            + " while looking " + "for section header tag.");
        } else if (ev.getEventType() != XMLStreamConstants.START_ELEMENT) {
            throw new IOException(
                    "Expected section header START_ELEMENT; " + "got event of type " + ev.getEventType());
        }
        String sectionName = ev.asStartElement().getName().getLocalPart();
        if (!unprocessedSections.contains(sectionName)) {
            throw new IOException("Unknown or duplicate section found for " + sectionName);
        }
        SectionProcessor sectionProcessor = sections.get(sectionName);
        if (sectionProcessor == null) {
            throw new IOException("Unknown FSImage section " + sectionName + ".  Valid section names are ["
                    + StringUtils.join(", ", sections.keySet()) + "]");
        }
        unprocessedSections.remove(sectionName);
        sectionProcessor.process();
    }

    // Write the StringTable section to disk.
    // This has to be done after the other sections, since some of them
    // add entries to the string table.
    writeStringTableSection();

    // Write the FileSummary section to disk.
    // This section is always last.
    long prevOffset = out.getCount();
    FileSummary fileSummary = fileSummaryBld.build();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Writing FileSummary: {" + TextFormat.printToString(fileSummary) + "}");
    }
    // Even though the last 4 bytes of the file gives the FileSummary length,
    // we still write a varint first that also contains the length.
    fileSummary.writeDelimitedTo(out);

    // Write the length of the FileSummary section as a fixed-size big
    // endian 4-byte quantity.
    int summaryLen = Ints.checkedCast(out.getCount() - prevOffset);
    byte[] summaryLenBytes = new byte[4];
    ByteBuffer.wrap(summaryLenBytes).asIntBuffer().put(summaryLen);
    out.write(summaryLenBytes);
}

From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

private void skipElement(final StartElement start, final XMLEventReader reader, final XMLEventWriter writer,
        final boolean excludeStart) throws Exception {

    if (!excludeStart) {
        writeEvent(start, writer);//  ww w.ja  va2  s.c  o m
    }

    int depth = 1;
    boolean found = false;

    while (reader.hasNext() && !found) {
        final XMLEvent event = reader.nextEvent();

        writeEvent(event, writer);

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

From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

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

    final XmlElement res = new XmlElement();
    res.setStart(start);/*www. j a  v a 2 s  .com*/

    StringWriter content = new StringWriter();

    int depth = 1;

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

        if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
            depth++;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) {
            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:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

public Map.Entry<Integer, XmlElement> extractElement(final XMLEventReader reader, final XMLEventWriter writer,
        final List<String> path, final Collection<Map.Entry<String, String>> filter, final boolean filterInOr,
        final int startPathPos, final int minPathPos, final int maxPathPos) throws Exception {

    StartElement start = null;//from   w  w  w. j  a v a  2s  . c om
    int searchFor = 0;
    int depth = startPathPos;

    // Current inspected element
    String current = null;

    // set defaults
    final List<String> pathElementNames = path == null ? Collections.<String>emptyList() : path;
    final Collection<Map.Entry<String, String>> filterAttrs = filter == null
            ? Collections.<Map.Entry<String, String>>emptySet()
            : filter;

    while (reader.hasNext() && start == null) {
        final XMLEvent event = reader.nextEvent();

        if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
            depth++;

            if (current != null
                    || ((minPathPos < 0 || minPathPos <= depth) && (maxPathPos < 0 || depth <= maxPathPos))) {
                if (pathElementNames.isEmpty() || pathElementNames.get(searchFor).trim()
                        .equals(event.asStartElement().getName().getLocalPart())) {

                    if (searchFor < pathElementNames.size() - 1) {
                        // path exploring not completed
                        writeEvent(event, writer);
                        current = pathElementNames.get(searchFor).trim();
                        searchFor++;
                    } else {

                        // path exploring completed ... evaluate filter about path element name attribute
                        boolean match = filterAttrs.isEmpty() || !filterInOr;

                        for (Map.Entry<String, String> filterAttr : filterAttrs) {
                            final Attribute attr = event.asStartElement()
                                    .getAttributeByName(new QName(filterAttr.getKey().trim()));

                            if (attr == null || !filterAttr.getValue().trim().equals(attr.getValue())) {
                                match = filterInOr ? match : false;
                            } else {
                                match = filterInOr ? true : match;
                            }
                        }

                        if (match) {
                            // found searched element
                            start = event.asStartElement();
                        } else {
                            skipElement(event.asStartElement(), reader, writer, false);
                            depth--;
                        }
                    }
                } else if (current == null) {
                    writeEvent(event, writer);
                } else {
                    // skip element
                    skipElement(event.asStartElement(), reader, writer, false);
                    depth--;
                }
            } else {
                writeEvent(event, writer);
            }

        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) {
            depth--;

            writeEvent(event, writer);

            if (event.asEndElement().getName().getLocalPart().equals(current)) {
                // back step ....
                searchFor--;
                current = searchFor > 0 ? pathElementNames.get(searchFor - 1).trim() : null;
            }
        } else {
            writeEvent(event, writer);
        }
    }

    if (start == null) {
        throw new NotFoundException();
    }

    return new SimpleEntry<Integer, XmlElement>(Integer.valueOf(depth - 1), getXmlElement(start, reader));
}

From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

@Override
public InputStream selectEntity(final InputStream entity, final String[] propertyNames) throws Exception {
    final XMLEventReader reader = getEventReader(entity);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    final List<String> found = new ArrayList<String>(Arrays.asList(propertyNames));

    boolean inProperties = false;
    boolean writeCurrent = true;
    Boolean writeNext = null;//w w  w .  j  a  v a  2s  . c  o  m
    String currentName = null;

    final List<String> fieldToBeSaved = new ArrayList<String>(Arrays.asList(propertyNames));

    while (reader.hasNext()) {
        final XMLEvent event = reader.nextEvent();
        if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && LINK.equals(event.asStartElement().getName().getLocalPart())
                && !fieldToBeSaved
                        .contains(event.asStartElement().getAttributeByName(new QName("title")).getValue())
                && !"edit".equals(event.asStartElement().getAttributeByName(new QName("rel")).getValue())) {
            writeCurrent = false;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && LINK.equals(event.asEndElement().getName().getLocalPart())) {
            writeNext = true;
        } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && (PROPERTIES).equals(event.asStartElement().getName().getLocalPart())) {
            writeCurrent = true;
            writeNext = false;
            inProperties = true;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && (PROPERTIES).equals(event.asEndElement().getName().getLocalPart())) {
            writeCurrent = true;
        } else if (inProperties) {
            if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
                final String elementName = event.asStartElement().getName().getLocalPart();

                for (String propertyName : propertyNames) {
                    if ((ATOM_PROPERTY_PREFIX + propertyName.trim()).equals(elementName)) {
                        writeCurrent = true;
                        found.remove(propertyName);
                        currentName = propertyName;
                    }
                }

            } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                    && StringUtils.isNotBlank(currentName) && (ATOM_PROPERTY_PREFIX + currentName.trim())
                            .equals(event.asEndElement().getName().getLocalPart())) {
                writeNext = false;
                currentName = null;
            }

        }

        if (writeCurrent) {
            writer.add(event);
        }

        if (writeNext != null) {
            writeCurrent = writeNext;
            writeNext = null;
        }
    }

    writer.flush();
    writer.close();
    reader.close();
    IOUtils.closeQuietly(entity);

    // Do not raise any exception in order to support FC properties as well
    // if (!found.isEmpty()) {
    //     throw new Exception(String.format("Could not find a properties '%s'", found));
    // }

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:org.apache.olingo.fit.utils.XMLUtilities.java

public XMLElement getXmlElement(final StartElement start, final XMLEventReader reader) throws Exception {

    final XMLElement res = new XMLElement();
    res.setStart(start);//from w  w  w .  j av a 2s  . c o m

    final Charset encoding = Charset.forName(org.apache.olingo.commons.api.Constants.UTF8);
    final ByteArrayOutputStream content = new ByteArrayOutputStream();
    final OutputStreamWriter writer = new OutputStreamWriter(content, encoding);

    int depth = 1;

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

        if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
            depth++;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) {
            depth--;
        }

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

    writer.flush();
    writer.close();

    res.setContent(new ByteArrayInputStream(content.toByteArray()));

    return res;
}

From source file:org.apache.olingo.fit.utils.XMLUtilities.java

public Map.Entry<Integer, XMLElement> extractElement(final XMLEventReader reader, final XMLEventWriter writer,
        final List<String> path, final Collection<Map.Entry<String, String>> filter, final boolean filterInOr,
        final int startPathPos, final int minPathPos, final int maxPathPos) throws Exception {

    StartElement start = null;//from  www.j  av a2  s  . c  o  m
    int searchFor = 0;
    int depth = startPathPos;

    // Current inspected element
    String current = null;

    // set defaults
    final List<String> pathElementNames = path == null ? Collections.<String>emptyList() : path;
    final Collection<Map.Entry<String, String>> filterAttrs = filter == null
            ? Collections.<Map.Entry<String, String>>emptySet()
            : filter;

    while (reader.hasNext() && start == null) {
        final XMLEvent event = reader.nextEvent();

        if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
            depth++;

            if (current != null
                    || ((minPathPos < 0 || minPathPos <= depth) && (maxPathPos < 0 || depth <= maxPathPos))) {
                if (pathElementNames.isEmpty() || pathElementNames.get(searchFor).trim()
                        .equals(event.asStartElement().getName().getLocalPart())) {

                    if (searchFor < pathElementNames.size() - 1) {
                        // path exploring not completed
                        writeEvent(event, writer);
                        current = pathElementNames.get(searchFor).trim();
                        searchFor++;
                    } else {

                        // path exploring completed ... evaluate filter about path element name attribute
                        boolean match = filterAttrs.isEmpty() || !filterInOr;

                        for (Map.Entry<String, String> filterAttr : filterAttrs) {
                            final Attribute attr = event.asStartElement()
                                    .getAttributeByName(new QName(filterAttr.getKey().trim()));

                            if (attr == null || !filterAttr.getValue().trim().equals(attr.getValue())) {
                                match = filterInOr ? match : false;
                            } else {
                                match = filterInOr ? true : match;
                            }
                        }

                        if (match) {
                            // found searched element
                            start = event.asStartElement();
                        } else {
                            skipElement(event.asStartElement(), reader, writer, false);
                            depth--;
                        }
                    }
                } else if (current == null) {
                    writeEvent(event, writer);
                } else {
                    // skip element
                    skipElement(event.asStartElement(), reader, writer, false);
                    depth--;
                }
            } else {
                writeEvent(event, writer);
            }

        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) {
            depth--;

            writeEvent(event, writer);

            if (event.asEndElement().getName().getLocalPart().equals(current)) {
                // back step ....
                searchFor--;
                current = searchFor > 0 ? pathElementNames.get(searchFor - 1).trim() : null;
            }
        } else {
            writeEvent(event, writer);
        }
    }

    if (start == null) {
        throw new NotFoundException();
    }

    return new SimpleEntry<Integer, XMLElement>(Integer.valueOf(depth - 1), getXmlElement(start, reader));
}

From source file:org.apache.olingo.fit.utils.XMLUtilities.java

@Override
public InputStream selectEntity(final InputStream entity, final String[] propertyNames) throws Exception {
    final XMLEventReader reader = getEventReader(entity);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    final List<String> found = new ArrayList<String>(Arrays.asList(propertyNames));

    boolean inProperties = false;
    boolean writeCurrent = true;
    Boolean writeNext = null;/*from   w  w  w .  ja v a2 s  .  c o  m*/
    String currentName = null;

    final List<String> fieldToBeSaved = new ArrayList<String>(Arrays.asList(propertyNames));

    while (reader.hasNext()) {
        final XMLEvent event = reader.nextEvent();
        if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && Constants.get(ConstantKey.LINK).equals(event.asStartElement().getName().getLocalPart())
                && !fieldToBeSaved
                        .contains(event.asStartElement().getAttributeByName(new QName("title")).getValue())
                && !"edit".equals(event.asStartElement().getAttributeByName(new QName("rel")).getValue())) {
            writeCurrent = false;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && Constants.get(ConstantKey.LINK).equals(event.asEndElement().getName().getLocalPart())) {
            writeNext = true;
        } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && (Constants.get(ConstantKey.PROPERTIES))
                        .equals(event.asStartElement().getName().getLocalPart())) {
            writeCurrent = true;
            writeNext = false;
            inProperties = true;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && (Constants.get(ConstantKey.PROPERTIES))
                        .equals(event.asEndElement().getName().getLocalPart())) {
            writeCurrent = true;
        } else if (inProperties) {
            if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
                final String elementName = event.asStartElement().getName().getLocalPart();

                for (String propertyName : propertyNames) {
                    if ((Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + propertyName.trim())
                            .equals(elementName)) {
                        writeCurrent = true;
                        found.remove(propertyName);
                        currentName = propertyName;
                    }
                }

            } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                    && StringUtils.isNotBlank(currentName)
                    && (Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + currentName.trim())
                            .equals(event.asEndElement().getName().getLocalPart())) {
                writeNext = false;
                currentName = null;
            }

        }

        if (writeCurrent) {
            writer.add(event);
        }

        if (writeNext != null) {
            writeCurrent = writeNext;
            writeNext = null;
        }
    }

    writer.flush();
    writer.close();
    reader.close();
    IOUtils.closeQuietly(entity);

    // Do not raise any exception in order to support FC properties as well
    // if (!found.isEmpty()) {
    // throw new Exception(String.format("Could not find a properties '%s'", found));
    // }
    return new ByteArrayInputStream(bos.toByteArray());
}