Example usage for javax.xml.stream XMLStreamConstants START_ELEMENT

List of usage examples for javax.xml.stream XMLStreamConstants START_ELEMENT

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamConstants START_ELEMENT.

Prototype

int START_ELEMENT

To view the source code for javax.xml.stream XMLStreamConstants START_ELEMENT.

Click Source Link

Document

Indicates an event is a start element

Usage

From source file:org.apache.axiom.om.util.OMXMLStreamReaderValidator.java

/**
 * Dump the current event of the delegate.
 *//*from  w w  w  .  jav  a 2s.  co  m*/
protected void logParserState() {
    if (IS_ADV_DEBUG_ENABLED) {
        int currentEvent = delegate.getEventType();

        switch (currentEvent) {
        case XMLStreamConstants.START_ELEMENT:
            log.trace("START_ELEMENT: ");
            log.trace("  QName: " + delegate.getName());
            break;
        case XMLStreamConstants.START_DOCUMENT:
            log.trace("START_DOCUMENT: ");
            break;
        case XMLStreamConstants.CHARACTERS:
            log.trace("CHARACTERS: ");
            log.trace("[" + delegate.getText() + "]");
            break;
        case XMLStreamConstants.CDATA:
            log.trace("CDATA: ");
            log.trace("[" + delegate.getText() + "]");
            break;
        case XMLStreamConstants.END_ELEMENT:
            log.trace("END_ELEMENT: ");
            log.trace("  QName: " + delegate.getName());
            break;
        case XMLStreamConstants.END_DOCUMENT:
            log.trace("END_DOCUMENT: ");
            break;
        case XMLStreamConstants.SPACE:
            log.trace("SPACE: ");
            log.trace("[" + delegate.getText() + "]");
            break;
        case XMLStreamConstants.COMMENT:
            log.trace("COMMENT: ");
            log.trace("[" + delegate.getText() + "]");
            break;
        case XMLStreamConstants.DTD:
            log.trace("DTD: ");
            log.trace("[" + delegate.getText() + "]");
            break;
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            log.trace("PROCESSING_INSTRUCTION: ");
            log.trace("   [" + delegate.getPITarget() + "][" + delegate.getPIData() + "]");
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            log.trace("ENTITY_REFERENCE: ");
            log.trace("    " + delegate.getLocalName() + "[" + delegate.getText() + "]");
            break;
        default:
            log.trace("UNKNOWN_STATE: " + currentEvent);

        }
    }
}

From source file:org.apache.axiom.util.stax.debug.XMLStreamReaderValidator.java

private void trackEvent(int event) throws XMLStreamException {
    logParserState();/* w ww .j av a2s.c om*/

    // Make sure that the start element and end element events match.
    // Mismatched events are a key indication that the delegate stream reader is 
    // broken or corrupted.
    switch (event) {
    case XMLStreamConstants.START_ELEMENT:
        stack.push(super.getName());
        break;
    case XMLStreamConstants.END_ELEMENT:
        QName delegateQName = super.getName();
        if (stack.isEmpty()) {
            reportMismatchedEndElement(null, delegateQName);
        } else {
            QName expectedQName = (QName) stack.pop();

            if (!expectedQName.equals(delegateQName)) {
                reportMismatchedEndElement(expectedQName, delegateQName);
            }
        }
        break;

    default:

    }
}

From source file:org.apache.axiom.util.stax.debug.XMLStreamReaderValidator.java

/**
 * Dump the current event of the delegate.
 *//*from   w w w.  j a  va2s .  c  om*/
protected void logParserState() {
    if (IS_ADV_DEBUG_ENABLED) {
        int currentEvent = super.getEventType();

        switch (currentEvent) {
        case XMLStreamConstants.START_ELEMENT:
            log.trace("START_ELEMENT: ");
            log.trace("  QName: " + super.getName());
            break;
        case XMLStreamConstants.START_DOCUMENT:
            log.trace("START_DOCUMENT: ");
            break;
        case XMLStreamConstants.CHARACTERS:
            log.trace("CHARACTERS: ");
            log.trace("[" + super.getText() + "]");
            break;
        case XMLStreamConstants.CDATA:
            log.trace("CDATA: ");
            log.trace("[" + super.getText() + "]");
            break;
        case XMLStreamConstants.END_ELEMENT:
            log.trace("END_ELEMENT: ");
            log.trace("  QName: " + super.getName());
            break;
        case XMLStreamConstants.END_DOCUMENT:
            log.trace("END_DOCUMENT: ");
            break;
        case XMLStreamConstants.SPACE:
            log.trace("SPACE: ");
            log.trace("[" + super.getText() + "]");
            break;
        case XMLStreamConstants.COMMENT:
            log.trace("COMMENT: ");
            log.trace("[" + super.getText() + "]");
            break;
        case XMLStreamConstants.DTD:
            log.trace("DTD: ");
            log.trace("[" + super.getText() + "]");
            break;
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            log.trace("PROCESSING_INSTRUCTION: ");
            log.trace("   [" + super.getPITarget() + "][" + super.getPIData() + "]");
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            log.trace("ENTITY_REFERENCE: ");
            log.trace("    " + super.getLocalName() + "[" + super.getText() + "]");
            break;
        default:
            log.trace("UNKNOWN_STATE: " + currentEvent);

        }
    }
}

From source file:org.apache.axis2.jaxws.context.listener.ParserInputStreamCustomBuilder.java

private InputStream getPayloadContent(XMLStreamReader parser, ParsedEntityReader entityReader) {
    int event = parser.getEventType();
    //Make sure its start element event.
    if (log.isDebugEnabled()) {
        log.debug("checking if event is START_ELEMENT");
    }/* w  w  w . ja v a2s.com*/
    InputStream parsedStream = null;
    if (event == XMLStreamConstants.START_ELEMENT) {
        if (log.isDebugEnabled()) {
            log.debug("event is START_ELEMENT");
        }
        parsedStream = entityReader.readParsedEntityStream(parser);
        if (parsedStream != null) {
            if (log.isDebugEnabled()) {
                log.debug("Read Parsed EntityStream");
            }
        }
    }
    return parsedStream;
}

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

/**
 * Processes the XML file back into an fsimage.
 *///www .  j  ava  2 s  .  co  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.jackrabbit.oak.benchmark.wikipedia.WikipediaImport.java

public int importWikipedia(Session session) throws Exception {
    long start = System.currentTimeMillis();
    int count = 0;
    int code = 0;

    if (doReport) {
        System.out.format("Importing %s...%n", dump);
    }// ww w .ja v  a2  s . c  om

    String type = "nt:unstructured";
    if (session.getWorkspace().getNodeTypeManager().hasNodeType("oak:Unstructured")) {
        type = "oak:Unstructured";
    }
    Node wikipedia = session.getRootNode().addNode("wikipedia", type);

    int levels = 0;
    if (!flat) {
        // calculate the number of levels needed, based on the rough
        // estimate that the average XML size of a page is about 1kB
        for (long pages = dump.length() / 1024; pages > 256; pages /= 256) {
            levels++;
        }
    }

    String title = null;
    String text = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    StreamSource source;
    if (dump.getName().endsWith(".xml")) {
        source = new StreamSource(dump);
    } else {
        CompressorStreamFactory csf = new CompressorStreamFactory();
        source = new StreamSource(
                csf.createCompressorInputStream(new BufferedInputStream(new FileInputStream(dump))));
    }
    haltImport = false;
    XMLStreamReader reader = factory.createXMLStreamReader(source);
    while (reader.hasNext() && !haltImport) {
        switch (reader.next()) {
        case XMLStreamConstants.START_ELEMENT:
            if ("title".equals(reader.getLocalName())) {
                title = reader.getElementText();
            } else if ("text".equals(reader.getLocalName())) {
                text = reader.getElementText();
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            if ("page".equals(reader.getLocalName())) {
                String name = Text.escapeIllegalJcrChars(title);
                Node parent = wikipedia;
                if (levels > 0) {
                    int n = name.length();
                    for (int i = 0; i < levels; i++) {
                        int hash = name.substring(min(i, n)).hashCode();
                        parent = JcrUtils.getOrAddNode(parent, String.format("%02x", hash & 0xff));
                    }
                }
                Node page = parent.addNode(name);
                page.setProperty("title", title);
                page.setProperty("text", text);
                code += title.hashCode();
                code += text.hashCode();
                count++;
                if (count % 1000 == 0) {
                    batchDone(session, start, count);
                }

                pageAdded(title, text);
            }
            break;
        }
    }

    session.save();

    if (doReport) {
        long millis = System.currentTimeMillis() - start;
        System.out.format("Imported %d pages in %d seconds (%.2fms/page)%n", count, millis / 1000,
                (double) millis / count);
    }

    return code;
}

From source file:org.apache.ode.utils.DOMUtils.java

private static void parse(XMLStreamReader reader, Document doc, Node parent) throws XMLStreamException {
    int event = reader.getEventType();

    while (reader.hasNext()) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            // create element
            Element e = doc.createElementNS(reader.getNamespaceURI(), reader.getLocalName());
            if (reader.getPrefix() != null && reader.getPrefix() != "") {
                e.setPrefix(reader.getPrefix());
            }//from   w w  w . ja  va 2s .  c  o m
            parent.appendChild(e);

            // copy namespaces
            for (int ns = 0; ns < reader.getNamespaceCount(); ns++) {
                String uri = reader.getNamespaceURI(ns);
                String prefix = reader.getNamespacePrefix(ns);
                declare(e, uri, prefix);
            }

            // copy attributes
            for (int att = 0; att < reader.getAttributeCount(); att++) {
                String name = reader.getAttributeLocalName(att);
                String prefix = reader.getAttributePrefix(att);
                if (prefix != null && prefix.length() > 0) {
                    name = prefix + ":" + name;
                }
                Attr attr = doc.createAttributeNS(reader.getAttributeNamespace(att), name);
                attr.setValue(reader.getAttributeValue(att));
                e.setAttributeNode(attr);
            }
            // sub-nodes
            if (reader.hasNext()) {
                reader.next();
                parse(reader, doc, e);
            }
            if (parent instanceof Document) {
                while (reader.hasNext())
                    reader.next();
                return;
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            return;
        case XMLStreamConstants.CHARACTERS:
            if (parent != null) {
                parent.appendChild(doc.createTextNode(reader.getText()));
            }
            break;
        case XMLStreamConstants.COMMENT:
            if (parent != null) {
                parent.appendChild(doc.createComment(reader.getText()));
            }
            break;
        case XMLStreamConstants.CDATA:
            parent.appendChild(doc.createCDATASection(reader.getText()));
            break;
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
            break;
        case XMLStreamConstants.NAMESPACE:
        case XMLStreamConstants.ATTRIBUTE:
            break;
        default:
            break;
        }

        if (reader.hasNext()) {
            event = reader.next();
        }
    }
}

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);/* www.  j a v a  2s.  co 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);/*from  www. j  ava2s . 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  . ja  v a  2 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));
}