Example usage for javax.xml.stream XMLStreamConstants END_ELEMENT

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

Introduction

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

Prototype

int END_ELEMENT

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

Click Source Link

Document

Indicates an event is an end element

Usage

From source file:net.cloudkit.enterprises.ws.SuperPassQueryTest.java

public static String parsingReceiptData(String responseData) throws XMLStreamException {
    StringBuilder dataBuilder = new StringBuilder("");
    XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(responseData));
    try {/*from   ww w. ja va2s.  c o  m*/
        int event = reader.getEventType();
        while (true) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:

                if (reader.getName().toString().equals("TradeName")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                // System.out.println(reader.getName());
                if (reader.getName().toString().equals("SeqNo")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                // BillNo
                if (reader.getName().toString().equals("EntryId")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                if (reader.getName().toString().equals("IEFlag")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                // ??
                if (reader.getName().toString().equals("IEDate")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                if (reader.getName().toString().equals("TradeMode")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                if (reader.getName().toString().equals("Status")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                if (reader.getName().toString().equals("RetExplain")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                // NoticeDate
                // CustomsCode
                break;
            case XMLStreamConstants.END_ELEMENT:
                // System.out.println("End Element:" + r.getName());
                break;
            }
            if (!reader.hasNext())
                break;
            event = reader.next();
        }
    } finally {
        reader.close();
    }
    dataBuilder.append("\n");
    return dataBuilder.toString();
}

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

public static Map.Entry<Integer, XmlElement> getAtomElement(final XMLEventReader reader,
        final XMLEventWriter discarded, final String name,
        final Collection<Map.Entry<String, String>> filterAttrs, final int initialDepth, final int minDepth,
        final int maxDepth, final boolean filterInOr) throws Exception {

    int depth = initialDepth;
    StartElement start = null;//  w  ww. j  a  v a 2  s  .  co m

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

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

            if ((StringUtils.isBlank(name)
                    || name.trim().equals(event.asStartElement().getName().getLocalPart()))
                    && (minDepth < 0 || minDepth <= depth) && (maxDepth < 0 || maxDepth >= depth)) {

                boolean match = filterAttrs == null || filterAttrs.isEmpty() || !filterInOr;

                for (Map.Entry<String, String> filterAttr : filterAttrs == null
                        ? Collections.<Map.Entry<String, String>>emptySet()
                        : 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) {
                    start = event.asStartElement();
                }
            }

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

        if (start == null) {
            if (discarded != null) {
                discarded.add(event);
            }
        }
    }

    if (start == null) {
        throw new Exception(String.format("Could not find an element named '%s'", name));
    }

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

From source file:edu.harvard.iq.dvn.core.analysis.NetworkDataServiceBean.java

private void processGraph(XMLStreamReader xmlr, NetworkDataFile ndf) throws XMLStreamException {
    for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (xmlr.getLocalName().equals("node")) {
                Long caseQuantity = ndf.getVertexDataTable().getCaseQuantity();
                if (caseQuantity == null) {
                    caseQuantity = new Long(0);
                }//from   w  w w.j a  v a 2s . c  o  m
                caseQuantity++;
                ndf.getVertexDataTable().setCaseQuantity(caseQuantity);
            } else if (xmlr.getLocalName().equals("edge")) {
                Long caseQuantity = ndf.getEdgeDataTable().getCaseQuantity();
                if (caseQuantity == null) {
                    caseQuantity = new Long(0);
                }
                caseQuantity++;
                ndf.getEdgeDataTable().setCaseQuantity(caseQuantity);
            }
        } else if (event == XMLStreamConstants.END_ELEMENT) {
            if (xmlr.getLocalName().equals("graph")) {
                ndf.getEdgeDataTable()
                        .setVarQuantity(new Long(ndf.getEdgeDataTable().getDataVariables().size()));
                ndf.getVertexDataTable()
                        .setVarQuantity(new Long(ndf.getVertexDataTable().getDataVariables().size()));
                return;
            }
        }
    }
}

From source file:net.solarnetwork.util.JavaBeanXmlSerializer.java

/**
 * Parse XML into a simple Map structure.
 * //from   www . j  a v  a  2  s .  c o m
 * @param in
 *        the input stream to parse
 * @return a Map of the XML
 */
public Map<String, Object> parseXml(InputStream in) {
    Deque<Map<String, Object>> stack = new LinkedList<Map<String, Object>>();
    Map<String, Object> result = null;
    XMLStreamReader reader = startParse(in);
    try {
        int eventType;
        boolean parsing = true;
        while (parsing) {
            eventType = reader.next();
            switch (eventType) {
            case XMLStreamConstants.END_DOCUMENT:
                parsing = false;
                break;

            case XMLStreamConstants.START_ELEMENT:
                String name = reader.getLocalName();
                if (stack.isEmpty()) {
                    result = new LinkedHashMap<String, Object>();
                    stack.push(result);
                } else {
                    Map<String, Object> el = new LinkedHashMap<String, Object>();
                    putMapValue(stack.peek(), name, el);
                    stack.push(el);
                }
                parseElement(stack.peek(), reader);
                break;

            case XMLStreamConstants.END_ELEMENT:
                stack.pop();
                break;

            }
        }
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    } finally {
        endParse(reader);
    }
    return result;
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.ddi.DDIFileReader.java

private void processCodeBook(XMLStreamReader xmlr, SDIOMetadata smd) throws XMLStreamException {

    for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (xmlr.getLocalName().equals("fileDscr")) {
                processFileDscr(xmlr, smd);
            } else if (xmlr.getLocalName().equals("dataDscr")) {
                processDataDscr(xmlr, smd);
            } else {
                throw new XMLStreamException("Unsupported DDI Element:" + xmlr.getLocalName());
            }/*from   www .j a va2s  . c  om*/
        } else if (event == XMLStreamConstants.END_ELEMENT) {
            if (xmlr.getLocalName().equals("codeBook")) {
                dbgLog.info("processed codeBook section;");
                return;
            } else {
                throw new XMLStreamException(
                        "Mismatched DDI Formatting: </codeBook> expected, found " + xmlr.getLocalName());
            }
        }
    }

}

From source file:de.codesourcery.eve.skills.util.XMLMapper.java

public <T> Collection<T> read(Class<T> clasz, IFieldConverters converters, InputStream instream)
        throws XMLStreamException, IOException, IllegalArgumentException, InstantiationException,
        IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {

    final Collection<T> result = new ArrayList<T>();

    try {/*from   w w w.j  a  v  a 2  s .c  o  m*/

        final BeanDescription desc = createBeanDescription(clasz);

        /* 
         * Create inverse mapping attribute name -> field. 
         */
        final Map<String, Field> inverseMapping = new HashMap<String, Field>();

        if (!this.propertyNameMappings.isEmpty()) {

            // key = property name  / value = attribute name
            for (Map.Entry<String, String> propToAttribute : this.propertyNameMappings.entrySet()) {
                inverseMapping.put(propToAttribute.getValue(), desc.getFieldByName(propToAttribute.getKey()));
            }

        } else { // create default mappings
            for (Field f : desc.getFields()) {
                inverseMapping.put(f.getName(), f);
            }
        }

        final int fieldCount = desc.getFields().size();

        final XMLInputFactory factory = XMLInputFactory.newInstance();
        final XMLStreamReader parser = factory.createXMLStreamReader(instream);

        boolean inRow = false;

        final Constructor<T> constructor = clasz.getConstructor(new Class<?>[0]);

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                if ("row".equals(parser.getLocalName())) { // parse row
                    if (inRow) {
                        throw new XMLStreamException("Found nested <row> tag ?", parser.getLocation());
                    }
                    inRow = true;

                    final T bean = constructor.newInstance(new Object[0]);
                    for (int i = 0; i < fieldCount; i++) {
                        final String attrName = parser.getAttributeLocalName(i);
                        final String attrValue = parser.getAttributeValue(i);
                        final Field field = inverseMapping.get(attrName);

                        if (!NIL.equals(attrValue)) {
                            final Object fieldValue = converters.getConverter(field)
                                    .toObject(fromAttributeValue(attrValue), field.getType());
                            field.set(bean, fieldValue);
                        } else {
                            field.set(bean, null);
                        }

                    }
                    result.add(bean);
                }
                break;

            case XMLStreamConstants.END_ELEMENT:
                if ("row".equals(parser.getLocalName())) { // parse row
                    if (!inRow) {
                        throw new XMLStreamException("Found </row> tag without start tag at ",
                                parser.getLocation());
                    }
                    inRow = false;
                }
                break;

            }
        }
    } finally {
        instream.close();
    }

    return result;
}

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   w w  w.  j ava  2s .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.microsoft.windowsazure.services.table.client.AtomPubParser.java

/**
 * Reserved for internal use. Reads the properties of an entity from the stream into a map of property names to
 * typed values. Reads the entity data as an AtomPub Entry Resource from the specified {@link XMLStreamReader} into
 * a map of <code>String</code> property names to {@link EntityProperty} data typed values.
 * /*from www  .  jav  a2 s  .  co  m*/
 * @param xmlr
 *            The <code>XMLStreamReader</code> to read the data from.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @return
 *         A <code>java.util.HashMap</code> containing a map of <code>String</code> property names to
 *         {@link EntityProperty} data typed values found in the entity data.
 * @throws XMLStreamException
 *             if an error occurs accessing the stream.
 * @throws ParseException
 *             if an error occurs converting the input to a particular data type.
 */
protected static HashMap<String, EntityProperty> readProperties(final XMLStreamReader xmlr,
        final OperationContext opContext) throws XMLStreamException, ParseException {
    int eventType = xmlr.getEventType();
    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.PROPERTIES);
    final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>();

    while (xmlr.hasNext()) {
        eventType = xmlr.next();
        if (eventType == XMLStreamConstants.CHARACTERS) {
            xmlr.getText();
            continue;
        }

        if (eventType == XMLStreamConstants.START_ELEMENT
                && xmlr.getNamespaceURI().equals(ODataConstants.DATA_SERVICES_NS)) {
            final String key = xmlr.getLocalName();
            String val = Constants.EMPTY_STRING;
            String edmType = null;

            if (xmlr.getAttributeCount() > 0) {
                edmType = xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE);
            }

            // move to chars
            eventType = xmlr.next();

            if (eventType == XMLStreamConstants.CHARACTERS) {
                val = xmlr.getText();

                // end element
                eventType = xmlr.next();
            }

            xmlr.require(XMLStreamConstants.END_ELEMENT, null, key);

            final EntityProperty newProp = new EntityProperty(val, EdmType.parse(edmType));
            properties.put(key, newProp);
        } else if (eventType == XMLStreamConstants.END_ELEMENT && xmlr.getName().toString()
                .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) {
            // End read properties
            break;
        }
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.PROPERTIES);
    return properties;
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.ddi.DDIFileReader.java

private void processFileDscr(XMLStreamReader xmlr, SDIOMetadata smd) throws XMLStreamException {

    for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (xmlr.getLocalName().equals("fileTxt")) {
                processFileTxt(xmlr, smd);
            } else if (xmlr.getLocalName().equals("notes")) {
                // ignore, at least for now.
                // (the only notes in our fileDscr sections are those with
                // the UNFs and original file information, i.e., things we
                // supply during ingest -- so there's no reason for us to
                // be interested in what's in them; we may, however want to
                // treat is as an error when any notes are encountered
                // during TAB+DDI ingest. -- TBD)
            } else {
                throw new XMLStreamException(
                        "Unsupported DDI Element: codeBook/fileDscr/" + xmlr.getLocalName());
            }//from   w  w w . j a va2  s  .c o  m
        } else if (event == XMLStreamConstants.END_ELEMENT) {// </codeBook>
            if (xmlr.getLocalName().equals("fileDscr")) {
                return;
            } else if (xmlr.getLocalName().equals("notes")) {
                // continue;
            } else {
                throw new XMLStreamException(
                        "Mismatched DDI Formatting: </fileDscr> expected, found " + xmlr.getLocalName());
            }
        }
    }
}

From source file:act.installer.pubchem.PubchemParser.java

/**
 * Incrementally parses a stream of XML events from a PubChem file, extracting the next available PC-Compound entry
 * as a Chemical object./*  ww  w .j  a v a  2s.c  om*/
 * @param eventReader The xml event reader we are parsing the XML from
 * @return The constructed chemical
 * @throws XMLStreamException
 * @throws XPathExpressionException
 */
public Chemical extractNextChemicalFromXMLStream(XMLEventReader eventReader)
        throws XMLStreamException, JaxenException {
    Document bufferDoc = null;
    Element currentElement = null;
    StringBuilder textBuffer = null;
    /* With help from
     * http://stackoverflow.com/questions/7998733/loading-local-chunks-in-dom-while-parsing-a-large-xml-file-in-sax-java
     */
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();

        switch (event.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
            String eventName = event.asStartElement().getName().getLocalPart();
            if (COMPOUND_DOC_TAG.equals(eventName)) {
                // Create a new document if we've found the start of a compound object.
                bufferDoc = documentBuilder.newDocument();
                currentElement = bufferDoc.createElement(eventName);
                bufferDoc.appendChild(currentElement);
            } else if (currentElement != null) { // Wait until we've found a compound entry to start slurping up data.
                // Create a new child element and push down the current pointer when we find a new node.
                Element newElement = bufferDoc.createElement(eventName);
                currentElement.appendChild(newElement);
                currentElement = newElement;
            } // If we aren't in a PC-Compound tree, we just let the elements pass by.
            break;

        case XMLStreamConstants.CHARACTERS:
            if (currentElement == null) { // Ignore this event if we're not in a PC-Compound tree.
                continue;
            }

            Characters chars = event.asCharacters();
            // Ignore only whitespace strings, which just inflate the size of the DOM.  Text coalescing makes this safe.
            if (chars.isWhiteSpace()) {
                continue;
            }

            // Rely on the XMLEventStream to coalesce consecutive text events.
            Text textNode = bufferDoc.createTextNode(chars.getData());
            currentElement.appendChild(textNode);
            break;

        case XMLStreamConstants.END_ELEMENT:
            if (currentElement == null) { // Ignore this event if we're not in a PC-Compound tree.
                continue;
            }

            eventName = event.asEndElement().getName().getLocalPart();
            Node parentNode = currentElement.getParentNode();
            if (parentNode instanceof Element) {
                currentElement = (Element) parentNode;
            } else if (parentNode instanceof Document && eventName.equals(COMPOUND_DOC_TAG)) {
                // We're back at the top of the node stack!  Convert the buffered document into a Chemical.
                PubchemEntry entry = extractPCCompoundFeatures(bufferDoc);
                if (entry != null) {
                    return entry.asChemical();
                } else {
                    // Skip this entry if we can't process it correctly by resetting the world and continuing on.
                    bufferDoc = null;
                    currentElement = null;
                }
            } else {
                // This should not happen, but is here as a sanity check.
                throw new RuntimeException(String.format("Parent of XML element %s is of type %d, not Element",
                        currentElement.getTagName(), parentNode.getNodeType()));
            }
            break;

        // TODO: do we care about attributes or other XML structures?
        }
    }

    // Return null when we run out of chemicals, just like readLine().
    return null;
}