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:org.springmodules.remoting.xmlrpc.stax.AbstractStaxXmlRpcParser.java

/**
 * Creates a new <code>StructMember</code> from the current element being
 * read in the specified <code>StreamReader</code>.
 * //w  w  w  . j  a  v a 2s  .  co m
 * @param reader
 *          the <code>StreamReader</code>.
 * @return the new <code>StructMember</code>.
 * @throws XmlRpcInvalidPayloadException
 *           if the element contains an unknown child. Only one "name" element
 *           and one "value" element are allowed inside an "member" element.
 * @see #parseValueElement(XMLStreamReader)
 */
protected final XmlRpcMember parseMemberElement(XMLStreamReader reader) throws XMLStreamException {
    String name = null;
    XmlRpcElement value = null;

    while (reader.hasNext()) {
        int event = reader.next();
        String localName = null;

        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            localName = reader.getLocalName();

            if (XmlRpcElementNames.NAME.equals(localName)) {
                name = reader.getElementText();

            } else if (XmlRpcElementNames.VALUE.equals(localName)) {
                value = parseValueElement(reader);

            } else {
                XmlRpcParsingUtils.handleUnexpectedElementFound(localName);
            }
            break;

        case XMLStreamConstants.END_ELEMENT:
            localName = reader.getLocalName();

            if (XmlRpcElementNames.MEMBER.equals(localName)) {
                if (!StringUtils.hasText(name)) {
                    throw new XmlRpcInvalidPayloadException("The struct member should have a name");
                }

                return new XmlRpcMember(name, value);
            }
        }
    }

    // we should never reach this point.
    return null;
}

From source file:org.talend.dataprep.schema.xls.streaming.StreamingSheetReader.java

/**
 * Handles a Stream event./*w  w w  . j a  va  2 s. c o m*/
 *
 * @param event
 * @throws SAXException
 */
private void handleEvent(XMLEvent event) throws SAXException {
    if (event.getEventType() == XMLStreamConstants.CHARACTERS) {
        Characters c = event.asCharacters();
        lastContents += c.getData();
    } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
        StartElement startElement = event.asStartElement();
        String tagLocalName = startElement.getName().getLocalPart();

        if ("row".equals(tagLocalName)) {
            Attribute rowIndex = startElement.getAttributeByName(new QName("r"));
            if (firstRowIndex == -1) {
                firstRowIndex = Integer.parseInt(rowIndex.getValue());
            }
            currentRow = new StreamingRow(Integer.parseInt(rowIndex.getValue()) - 1);
        } else if ("cols".equals(tagLocalName)) {
            parsingCols = true;
        } else if ("col".equals(tagLocalName) && parsingCols) {
            colNumber = colNumber + 1;
        } else if ("c".equals(tagLocalName)) {
            Attribute ref = startElement.getAttributeByName(new QName("r"));

            String[] coord = ref.getValue().split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
            currentCell = new StreamingCell(CellReference.convertColStringToIndex(coord[0]),
                    Integer.parseInt(coord[1]) - 1);
            setFormatString(startElement, currentCell);

            Attribute type = startElement.getAttributeByName(new QName("t"));
            if (type != null) {
                currentCell.setType(type.getValue());
            } else {
                currentCell.setType("n");
            }

            Attribute style = startElement.getAttributeByName(new QName("s"));
            if (style != null) {
                String indexStr = style.getValue();
                try {
                    int index = Integer.parseInt(indexStr);
                    currentCell.setCellStyle(stylesTable.getStyleAt(index));
                } catch (NumberFormatException nfe) {
                    LOGGER.warn("Ignoring invalid style index {}", indexStr);
                }
            }
            // we store the dimension as well to revert with this method when cols not found
            // can happen see xlsx attached here https://jira.talendforge.org/browse/TDP-1957
            // <dimension ref="A1:B60"/>
        } else if ("dimension".equals(tagLocalName)) {
            Attribute attribute = startElement.getAttributeByName(new QName("ref"));
            if (attribute != null) {
                this.dimension = attribute.getValue();
            }
        }

        // Clear contents cache
        lastContents = "";
    } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) {
        EndElement endElement = event.asEndElement();
        String tagLocalName = endElement.getName().getLocalPart();

        if ("v".equals(tagLocalName) || "t".equals(tagLocalName)) {
            currentCell.setRawContents(unformattedContents());
            currentCell.setContents(formattedContents());
        } else if ("row".equals(tagLocalName) && currentRow != null) {
            rowCache.add(currentRow);
        } else if ("c".equals(tagLocalName)) {
            currentRow.getCellMap().put(currentCell.getColumnIndex(), currentCell);
        } else if ("cols".equals(tagLocalName)) {
            parsingCols = false;
        }

    }
}

From source file:org.talend.dataprep.schema.xls.XlsUtils.java

/**
 * read workbook xml spec to get non hidden sheets
 *
 * @param inputStream/*w w  w . ja  va  2 s.co  m*/
 * @return
 */
public static List<String> getActiveSheetsFromWorkbookSpec(InputStream inputStream) throws XMLStreamException {
    // If doesn't support mark, wrap up
    if (!inputStream.markSupported()) {
        inputStream = new PushbackInputStream(inputStream, 8);
    }
    XMLStreamReader streamReader = XML_INPUT_FACTORY.createXMLStreamReader(inputStream);
    try {
        /*
         *
         * <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <workbook
         * xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
         * xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"> <fileVersion appName="xl"
         * lastEdited="5" lowestEdited="5" rupBuild="9303" codeName="{8C4F1C90-05EB-6A55-5F09-09C24B55AC0B}"/>
         * <workbookPr codeName="ThisWorkbook" defaultThemeVersion="124226"/> <bookViews> <workbookView xWindow="0"
         * yWindow="732" windowWidth="22980" windowHeight="8868" firstSheet="1" activeTab="8"/> </bookViews>
         * <sheets> <sheet name="formdata" sheetId="4" state="hidden" r:id="rId1"/> <sheet name="MONDAY" sheetId="1"
         * r:id="rId2"/> <sheet name="TUESDAY" sheetId="8" r:id="rId3"/> <sheet name="WEDNESDAY" sheetId="10"
         * r:id="rId4"/> <sheet name="THURSDAY" sheetId="11" r:id="rId5"/> <sheet name="FRIDAY" sheetId="12"
         * r:id="rId6"/> <sheet name="SATURDAY" sheetId="13" r:id="rId7"/> <sheet name="SUNDAY" sheetId="14"
         * r:id="rId8"/> <sheet name="WEEK SUMMARY" sheetId="15" r:id="rId9"/> </sheets>
         *
         */
        // we only want sheets not with state=hidden

        List<String> names = new ArrayList<>();

        while (streamReader.hasNext()) {
            switch (streamReader.next()) {
            case START_ELEMENT:
                if (StringUtils.equals(streamReader.getLocalName(), "sheet")) {
                    Map<String, String> attributesValues = getAttributesNameValue(streamReader);
                    if (!attributesValues.isEmpty()) {
                        String sheetState = attributesValues.get("state");
                        if (!StringUtils.equals(sheetState, "hidden")) {
                            String sheetName = attributesValues.get("name");
                            names.add(sheetName);
                        }
                    }
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                if (StringUtils.equals(streamReader.getLocalName(), "sheets")) {
                    // shortcut to stop parsing
                    return names;
                }
                break;
            default:
                // no op
            }
        }
        return names;
    } finally {
        if (streamReader != null) {
            streamReader.close();
        }
    }
}

From source file:org.tobarsegais.webapp.data.Index.java

public static Index read(String bundle, XMLStreamReader reader) throws XMLStreamException {
    while (reader.hasNext() && !reader.isStartElement()) {
        reader.next();/*from www  .  ja  va  2 s  .  c  o m*/
    }
    if (reader.getEventType() != XMLStreamConstants.START_ELEMENT) {
        throw new IllegalStateException("Expecting a start element");
    }
    if (!"index".equals(reader.getLocalName())) {
        throw new IllegalStateException("Expecting a <index> element, found a <" + reader.getLocalName() + ">");
    }
    List<IndexEntry> entries = new ArrayList<IndexEntry>();
    int depth = 0;
    while (reader.hasNext() && depth >= 0) {
        switch (reader.next()) {
        case XMLStreamConstants.START_ELEMENT:
            if (depth == 0 && "entry".equals(reader.getLocalName())) {
                entries.add(IndexEntry.read(bundle, Collections.<String>emptyList(), reader));
            } else {
                depth++;
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            depth--;
            break;
        }
    }
    return new Index(entries);
}

From source file:org.tobarsegais.webapp.data.Plugin.java

public static Plugin read(XMLStreamReader reader) throws XMLStreamException {
    while (reader.hasNext() && !reader.isStartElement()) {
        reader.next();//from   ww  w .  j  av  a 2  s. c  om
    }
    if (reader.getEventType() != XMLStreamConstants.START_ELEMENT) {
        throw new IllegalStateException("Expecting a start element");
    }
    if (!"plugin".equals(reader.getLocalName())) {
        throw new IllegalStateException("Expecting a <plugin> element");
    }
    String name = reader.getAttributeValue(null, "name");
    String id = reader.getAttributeValue(null, "id");
    String version = reader.getAttributeValue(null, "version");
    String providerName = reader.getAttributeValue(null, "provider-name");
    List<Extension> extensions = new ArrayList<Extension>();
    int depth = 0;
    while (reader.hasNext() && depth >= 0) {
        switch (reader.next()) {
        case XMLStreamConstants.START_ELEMENT:
            if (depth == 0 && "extension".equals(reader.getLocalName())) {
                extensions.add(Extension.read(reader));
            } else {
                depth++;
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            depth--;
            break;
        }
    }
    return new Plugin(name, id, version, providerName, extensions);
}

From source file:org.tobarsegais.webapp.data.Toc.java

public static Toc read(XMLStreamReader reader) throws XMLStreamException {
    while (reader.hasNext() && !reader.isStartElement()) {
        reader.next();/* www .  jav  a2 s  . c om*/
    }
    if (reader.getEventType() != XMLStreamConstants.START_ELEMENT) {
        throw new IllegalStateException("Expecting a start element");
    }
    if (!"toc".equals(reader.getLocalName())) {
        throw new IllegalStateException("Expecting a <toc> element");
    }
    String label = reader.getAttributeValue(null, "label");
    String topic = reader.getAttributeValue(null, "topic");
    List<Topic> topics = new ArrayList<Topic>();
    int depth = 0;
    while (reader.hasNext() && depth >= 0) {
        switch (reader.next()) {
        case XMLStreamConstants.START_ELEMENT:
            if (depth == 0 && "topic".equals(reader.getLocalName())) {
                topics.add(Topic.read(reader));
            } else {
                depth++;
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            depth--;
            break;
        }
    }
    return new Toc(label, topic, topics);
}

From source file:org.ut.biolab.medsavant.client.plugin.AppController.java

public AppDescriptor getDescriptorFromFile(File f) throws PluginVersionException {
    XMLStreamReader reader;//  w w w .  j  av  a 2  s. c o  m

    try {
        JarFile jar = new JarFile(f);
        ZipEntry entry = jar.getEntry("plugin.xml");
        if (entry != null) {
            InputStream entryStream = jar.getInputStream(entry);
            reader = XMLInputFactory.newInstance().createXMLStreamReader(entryStream);
            String className = null;
            String id = null;
            String version = null;
            String sdkVersion = null;
            String name = null;
            String category = AppDescriptor.Category.UTILITY.toString();
            String currentElement = null;
            String currentText = "";
            do {
                switch (reader.next()) {
                case XMLStreamConstants.START_ELEMENT:
                    switch (readElement(reader)) {
                    case PLUGIN:
                        className = readAttribute(reader, AppDescriptor.PluginXMLAttribute.CLASS);

                        //category can be specified as an attribute or <property>.
                        category = readAttribute(reader, AppDescriptor.PluginXMLAttribute.CATEGORY);
                        break;

                    case ATTRIBUTE:
                        if ("sdk-version".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.ID))) {
                            sdkVersion = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                        }
                        break;

                    case PARAMETER:
                        if ("name".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.ID))) {
                            name = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                        }
                        break;

                    case PROPERTY:
                        if ("name".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            name = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (name == null) {
                                currentElement = "name";
                            }
                        }

                        if ("version".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            version = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (version == null) {
                                currentElement = "version";
                            }
                        }

                        if ("sdk-version"
                                .equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            sdkVersion = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (sdkVersion == null) {
                                currentElement = "sdk-version";
                            }
                        }

                        if ("category".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            category = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (category == null) {
                                currentElement = "category";
                            }
                        }

                        break;
                    }
                    break;

                case XMLStreamConstants.CHARACTERS:
                    if (reader.isWhiteSpace()) {
                        break;
                    } else if (currentElement != null) {
                        currentText += reader.getText().trim().replace("\t", "");
                    }
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    if (readElement(reader) == AppDescriptor.PluginXMLElement.PROPERTY) {
                        if (currentElement != null && currentText.length() > 0) {
                            if (currentElement.equals("name")) {
                                name = currentText;
                            } else if (currentElement.equals("sdk-version")) {
                                sdkVersion = currentText;
                            } else if (currentElement.equals("category")) {
                                category = currentText;
                            } else if (currentElement.equals("version")) {
                                version = currentText;
                            }
                        }
                        currentText = "";
                        currentElement = null;
                    }
                    break;

                case XMLStreamConstants.END_DOCUMENT:
                    reader.close();
                    reader = null;
                    break;
                }
            } while (reader != null);

            System.out.println(className + " " + name + " " + version);

            if (className != null && name != null && version != null) {
                return new AppDescriptor(className, version, name, sdkVersion, category, f);
            }
        }
    } catch (Exception x) {
        LOG.error("Error parsing plugin.xml from " + f.getAbsolutePath() + ": " + x);
    }
    throw new PluginVersionException(f.getName() + " did not contain a valid plugin");
}

From source file:tkwatch.Utilities.java

/**
 * Finds the value of the named element, if any, in an XML string. Adapted
 * from Vohra and Vohra, <i>Pro XML Development with Java Technology</i>, p.
 * 47./*w  ww.j  a v  a  2s  .  c o m*/
 * 
 * @param desiredElementName
 *            The name of the element to search for in the XML string.
 * @param xmlString
 *            The XML string to search for an account number.
 * 
 * @return Returns the element value(s) as formatted in the incoming string
 *         (if found) as a <code>Vector<String></code>, <code>null</code>
 *         otherwise.
 */
public static final Vector<String> getValueFromXml(final String desiredElementName, final String xmlString) {
    Vector<String> elementValue = new Vector<String>();
    String elementValueText = null;
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    try {
        String elementName = "";
        StringReader stringReader = new StringReader(xmlString);
        XMLStreamReader reader = inputFactory.createXMLStreamReader(stringReader);
        while (reader.hasNext()) {
            int eventType = reader.getEventType();
            switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                elementName = reader.getLocalName();
                if (elementName.equals(desiredElementName)) {
                    elementValueText = reader.getAttributeValue(0);
                    System.out.println("START_ELEMENT case, element name is " + elementName
                            + ", element value is " + elementValueText);
                }
                break;
            case XMLStreamConstants.ATTRIBUTE:
                elementName = reader.getLocalName();
                if (elementName.equals(desiredElementName)) {
                    elementValueText = reader.getElementText();
                    System.out.println("ATTRIBUTE case, element name is " + elementName + ", element value is "
                            + elementValueText);
                    elementValue.add(elementValueText);
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                elementName = reader.getLocalName();
                if (elementName.equals(desiredElementName)) {
                    System.out.println("END_ELEMENT case, element name is " + elementName
                            + ", element value is " + elementValueText);
                }
                break;
            default:
                elementName = reader.getLocalName();
                if (elementName != null) {
                    if (elementName.equals(desiredElementName)) {
                        System.out.println("default case, element name is " + elementName);
                    }
                }
                break;
            }
            reader.next();
        }
    } catch (XMLStreamException e) {
        TradekingException.handleException(e);
    }
    return (elementValue.isEmpty() ? null : elementValue);
}

From source file:tpt.dbweb.cat.io.TaggedTextXMLReader.java

private Iterator<TaggedText> getIterator(InputStream is, String errorMessageInfo) {

    XMLStreamReader tmpxsr = null;
    try {/*  ww  w  .  j  a  v a2  s  . com*/
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
        xif.setProperty(XMLInputFactory.IS_VALIDATING, false);
        tmpxsr = xif.createXMLStreamReader(is);
    } catch (XMLStreamException | FactoryConfigurationError e) {
        e.printStackTrace();
        return null;
    }

    final XMLStreamReader xsr = tmpxsr;
    return new PeekIterator<TaggedText>() {

        @Override
        protected TaggedText internalNext() {
            ArrayList<TextSpan> openMarks = new ArrayList<>();
            StringBuilder pureTextSB = new StringBuilder();
            ArrayList<TextSpan> marks = new ArrayList<>();
            marks.add(new TextSpan(null, 0, 0));
            TaggedText tt = null;

            try {
                loop: while (xsr.hasNext()) {
                    xsr.next();
                    int event = xsr.getEventType();
                    switch (event) {
                    case XMLStreamConstants.START_ELEMENT:
                        if ("articles".equals(xsr.getLocalName())) {
                        } else if ("article".equals(xsr.getLocalName())) {
                            tt = new TaggedText();
                            for (int i = 0; i < xsr.getAttributeCount(); i++) {
                                if ("id".equals(xsr.getAttributeLocalName(i))) {
                                    tt.id = xsr.getAttributeValue(i);
                                }
                                tt.info().put(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i));
                            }

                        } else if ("mark".equals(xsr.getLocalName())) {
                            TextSpan tr = new TextSpan(null, pureTextSB.length(), pureTextSB.length());
                            for (int i = 0; i < xsr.getAttributeCount(); i++) {
                                tr.info().put(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i));
                            }

                            openMarks.add(tr);
                        } else if ("br".equals(xsr.getLocalName())) {
                            // TODO: how to propagate tags from the input to the output?
                        } else {
                            log.warn("ignore tag " + xsr.getLocalName());
                        }
                        break;
                    case XMLStreamConstants.END_ELEMENT:
                        if ("mark".equals(xsr.getLocalName())) {

                            // search corresponding <mark ...>
                            TextSpan tr = openMarks.remove(openMarks.size() - 1);
                            if (tr == null) {
                                log.warn("markend at " + xsr.getLocation().getCharacterOffset()
                                        + " has no corresponding mark tag");
                                break;
                            }

                            tr.end = pureTextSB.length();
                            marks.add(tr);

                        } else if ("article".equals(xsr.getLocalName())) {
                            tt.text = StringUtils.stripEnd(pureTextSB.toString().trim(), " \t\n");
                            pureTextSB = new StringBuilder();

                            tt.mentions = new ArrayList<>();
                            for (TextSpan mark : marks) {

                                String entity = mark.info().get("entity");
                                if (entity == null) {
                                    entity = mark.info().get("annotation");
                                }
                                if (entity != null) {
                                    EntityMention e = new EntityMention(tt.text, mark.start, mark.end, entity);
                                    String minMention = mark.info().get("min");
                                    String mention = e.getMention();
                                    if (minMention != null && !"".equals(minMention)) {
                                        Pattern p = Pattern.compile(Pattern.quote(minMention));
                                        Matcher m = p.matcher(mention);
                                        if (m.find()) {
                                            TextSpan min = new TextSpan(e.text, e.start + m.start(),
                                                    e.start + m.end());
                                            e.min = min;
                                            if (m.find()) {
                                                log.warn("found " + minMention + " two times in \"" + mention
                                                        + "\"");
                                            }
                                        } else {
                                            String prefix = Utility.findLongestPrefix(mention, minMention);
                                            log.warn("didn't find min mention '" + minMention + "' in text '"
                                                    + mention + "', longest prefix found: '" + prefix
                                                    + "' in article " + tt.id);
                                        }
                                    }

                                    mark.info().remove("min");
                                    mark.info().remove("entity");
                                    if (mark.info().size() > 0) {
                                        e.info().putAll(mark.info());
                                    }
                                    tt.mentions.add(e);
                                }
                            }
                            openMarks.clear();
                            marks.clear();
                            break loop;
                        }
                        break;
                    case XMLStreamConstants.CHARACTERS:
                        String toadd = xsr.getText();
                        if (pureTextSB.length() == 0) {
                            toadd = StringUtils.stripStart(toadd, " \t\n");
                        }
                        if (toadd.contains("thanks")) {
                            log.info("test");
                        }
                        pureTextSB.append(toadd);
                        break;
                    }

                }
            } catch (XMLStreamException e) {
                log.error("{}", errorMessageInfo);
                throw new RuntimeException(e);
            }
            if (tt != null && tt.mentions != null) {
                tt.mentions.sort(null);
            }
            return tt;
        }
    };
}