Example usage for javax.xml.stream XMLStreamReader next

List of usage examples for javax.xml.stream XMLStreamReader next

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamReader next.

Prototype

public int next() throws XMLStreamException;

Source Link

Document

Get next parsing event - a processor may return all contiguous character data in a single chunk, or it may split it into several chunks.

Usage

From source file:ddf.catalog.source.opensearch.OpenSearchSource.java

private InputTransformer getInputTransformer(InputStream inputStream) {
    XMLStreamReader xmlStreamReader = null;
    try {/*ww  w.  j a v a2s .c o  m*/
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(inputStream);
        while (xmlStreamReader.hasNext()) {
            int next = xmlStreamReader.next();
            if (next == XMLStreamConstants.START_ELEMENT) {
                String namespaceUri = xmlStreamReader.getNamespaceURI();
                InputTransformer transformerReference = lookupTransformerReference(namespaceUri);
                if (transformerReference != null) {
                    return transformerReference;
                }
            }
        }
    } catch (XMLStreamException | InvalidSyntaxException e) {
        LOGGER.error("Failed to parse transformer namespace", e);
    } finally {
        try {
            if (xmlStreamReader != null) {
                xmlStreamReader.close();
            }
        } catch (XMLStreamException e) {
            LOGGER.error("failed to close namespace reader", e);
        }
    }
    return null;
}

From source file:com.rapidminer.gui.properties.OperatorPropertyPanel.java

/**
 * Starts a progress thread which parses the parameter descriptions for the provided operator ,
 * cleans the {@link #parameterDescriptionCache}, and stores parsed descriptions in the
 * {@link #parameterDescriptionCache}./*from   www  .j  a v  a 2s . c  o  m*/
 */
private void parseParameterDescriptions(final Operator operator) {
    parameterDescriptionCache.clear();
    URL documentationURL = OperatorDocumentationBrowser.getDocResourcePath(operator);
    if (documentationURL != null) {
        try (InputStream documentationStream = documentationURL.openStream()) {
            XMLStreamReader reader = XML_STREAM_FACTORY.createXMLStreamReader(documentationStream);
            String parameterKey = null;

            // The builder that stores the parameter description text
            StringBuilder parameterTextBuilder = null;
            boolean inParameters = false;
            while (reader.hasNext()) {
                switch (reader.next()) {
                case XMLStreamReader.START_ELEMENT:
                    if (!inParameters && reader.getLocalName().equals(TAG_PARAMETERS)) {
                        inParameters = true;
                    } else {
                        AttributesImpl attributes = new AttributesImpl();
                        for (int i = 0; i < reader.getAttributeCount(); i++) {
                            attributes.addAttribute("", reader.getAttributeLocalName(i),
                                    reader.getAttributeName(i).toString(), reader.getAttributeType(i),
                                    reader.getAttributeValue(i));
                        }

                        // Check if no parameter was found
                        if (reader.getLocalName().equals(TAG_PARAMETER)) {
                            parameterKey = attributes.getValue(ATTRIBUTE_PARAMETER_KEY);

                            // In case a parameter key was found, create a new string
                            // builder
                            if (parameterKey != null) {
                                parameterTextBuilder = new StringBuilder();
                            }
                        }

                        if (parameterTextBuilder != null) {
                            appendParameterStartTag(reader.getLocalName(), attributes, parameterTextBuilder);
                        }
                    }
                    break;
                case XMLStreamReader.END_ELEMENT:
                    // end parsing when end of parameters element is reached
                    if (reader.getLocalName().equals(TAG_PARAMETERS)) {
                        return;
                    }

                    if (parameterTextBuilder != null) {

                        // otherwise add element to description text
                        parameterTextBuilder.append("</");
                        parameterTextBuilder.append(reader.getLocalName());
                        parameterTextBuilder.append(">");

                        // Store description when parameter element ends
                        if (reader.getLocalName().equals(TAG_PARAMETER)) {
                            final String parameterDescription = parameterTextBuilder.toString();
                            final String key = parameterKey;
                            if (!parameterDescriptionCache.containsKey(parameterKey)) {
                                Source xmlSource = new StreamSource(new StringReader(parameterDescription));
                                try {
                                    String desc = OperatorDocToHtmlConverter.applyXSLTTransformation(xmlSource);
                                    parameterDescriptionCache.put(key, StringEscapeUtils.unescapeHtml(desc));
                                } catch (TransformerException e) {
                                    // ignore
                                }
                            }
                        }
                    }
                    break;
                case XMLStreamReader.CHARACTERS:
                    if (parameterTextBuilder != null) {
                        parameterTextBuilder.append(StringEscapeUtils.escapeHtml(reader.getText()));
                    }
                    break;
                default:
                    // ignore other events
                    break;
                }
            }
        } catch (IOException | XMLStreamException e) {
            // ignore
        }
    }
}

From source file:com.microsoft.tfs.core.memento.XMLMemento.java

/**
 * Reads the current element from the given reader and returns the
 * {@link XMLMemento} read from its data. The {@link XMLStreamReader} must
 * be positioned at {@link XMLStreamConstants#START_ELEMENT}.
 *
 * @param reader/*  w  w w  . j  av a  2 s . c  o  m*/
 *        the reader (must not be <code>null</code>)
 * @return the {@link XMLMemento} read from the stream
 * @throws XMLStreamException
 *         if an error occurred reading from the reader
 */
private synchronized void readFromElement(final XMLStreamReader reader) throws XMLStreamException {
    Check.notNull(reader, "reader"); //$NON-NLS-1$

    /*
     * Read all the attributes from the current element.
     */
    final int attributeCount = reader.getAttributeCount();
    for (int i = 0; i < attributeCount; i++) {
        putString(reader.getAttributeLocalName(i), reader.getAttributeValue(i));
    }

    /*
     * Process child nodes (which may be text or child Mementos).
     */
    String localName;
    int event;
    do {
        event = reader.next();

        if (event == XMLStreamConstants.START_ELEMENT) {
            localName = reader.getLocalName();

            final XMLMemento child = (XMLMemento) createChild(localName);
            child.readFromElement(reader);
        } else if (event == XMLStreamConstants.CHARACTERS) {
            putTextData(reader.getText());
        }
    } while (event != XMLStreamConstants.END_ELEMENT);
}

From source file:ddf.catalog.source.opensearch.impl.OpenSearchSource.java

private InputTransformer getInputTransformer(InputStream inputStream) {
    XMLStreamReader xmlStreamReader = null;
    try {//from  w w w. ja v  a  2 s . c  om
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(inputStream);
        while (xmlStreamReader.hasNext()) {
            int next = xmlStreamReader.next();
            if (next == XMLStreamConstants.START_ELEMENT) {
                String namespaceUri = xmlStreamReader.getNamespaceURI();
                InputTransformer transformerReference = lookupTransformerReference(namespaceUri);
                if (transformerReference != null) {
                    return transformerReference;
                }
            }
        }
    } catch (XMLStreamException | InvalidSyntaxException e) {
        LOGGER.debug("Failed to parse transformer namespace", e);
    } finally {
        try {
            if (xmlStreamReader != null) {
                xmlStreamReader.close();
            }
        } catch (XMLStreamException e) {
            LOGGER.debug("failed to close namespace reader", e);
        }
    }
    return null;
}

From source file:de.uzk.hki.da.model.ObjectPremisXmlWriter.java

/**
 * Integrate jhove data./*from w  ww.j a  va2 s . c om*/
 *
 * @param jhoveFilePath the jhove file path
 * @param tab the tab
 * @throws XMLStreamException the xML stream exception
 * @author Thomas Kleinke
 * @throws FileNotFoundException 
 */
private void integrateJhoveData(String jhoveFilePath, int tab)
        throws XMLStreamException, FileNotFoundException {
    File jhoveFile = new File(jhoveFilePath);
    if (!jhoveFile.exists())
        throw new FileNotFoundException("file does not exist. " + jhoveFile);

    FileInputStream inputStream = null;

    inputStream = new FileInputStream(jhoveFile);

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader streamReader = inputFactory.createXMLStreamReader(inputStream);

    boolean textElement = false;

    while (streamReader.hasNext()) {
        int event = streamReader.next();

        switch (event) {

        case XMLStreamConstants.START_ELEMENT:
            writer.writeDTD("\n");
            indent(tab);
            tab++;

            String prefix = streamReader.getPrefix();

            if (prefix != null && !prefix.equals("")) {
                writer.setPrefix(prefix, streamReader.getNamespaceURI());
                writer.writeStartElement(streamReader.getNamespaceURI(), streamReader.getLocalName());
            } else
                writer.writeStartElement(streamReader.getLocalName());

            for (int i = 0; i < streamReader.getNamespaceCount(); i++)
                writer.writeNamespace(streamReader.getNamespacePrefix(i), streamReader.getNamespaceURI(i));

            for (int i = 0; i < streamReader.getAttributeCount(); i++) {
                QName qname = streamReader.getAttributeName(i);
                String attributeName = qname.getLocalPart();
                String attributePrefix = qname.getPrefix();
                if (attributePrefix != null && !attributePrefix.equals(""))
                    attributeName = attributePrefix + ":" + attributeName;

                writer.writeAttribute(attributeName, streamReader.getAttributeValue(i));
            }

            break;

        case XMLStreamConstants.CHARACTERS:
            if (!streamReader.isWhiteSpace()) {
                writer.writeCharacters(streamReader.getText());
                textElement = true;
            }
            break;

        case XMLStreamConstants.END_ELEMENT:
            tab--;

            if (!textElement) {
                writer.writeDTD("\n");
                indent(tab);
            }

            writer.writeEndElement();
            textElement = false;
            break;

        default:
            break;
        }
    }

    streamReader.close();
    try {
        inputStream.close();
    } catch (IOException e) {
        throw new RuntimeException("Failed to close input stream", e);
    }
}

From source file:com.sun.socialsite.pojos.PropDefinition.java

protected void init(PropDefinition profileDef, InputStream input) throws SocialSiteException {
    try {/*from www .  ja  v  a2  s .  c o  m*/
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader parser = factory.createXMLStreamReader(input);
        String ns = null; // TODO: namespace for ProfileDef

        // hold the current things we're working on
        Map<String, DisplaySectionDefinition> sdefs = new LinkedHashMap<String, DisplaySectionDefinition>();
        Stack<PropertyDefinitionHolder> propertyHolderStack = new Stack<PropertyDefinitionHolder>();
        List<AllowedValue> allowedValues = null;
        PropertyDefinition pdef = null;

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                log.debug("START ELEMENT -- " + parser.getLocalName());

                if ("display-section".equals(parser.getLocalName())) {
                    propertyHolderStack.push(new DisplaySectionDefinition(parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey")));

                } else if ("property".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    pdef = new PropertyDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey"), parser.getAttributeValue(ns, "type"));

                } else if ("object".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    propertyHolderStack.push(new PropertyObjectDefinition(holder.getBasePath(),
                            parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey")));

                } else if ("collection".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    propertyHolderStack.push(new PropertyObjectCollectionDefinition(holder.getBasePath(),
                            parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey")));

                } else if ("allowed-values".equals(parser.getLocalName())) {
                    allowedValues = new ArrayList<AllowedValue>();

                } else if ("value".equals(parser.getLocalName())) {
                    AllowedValue allowedValue = new AllowedValue(parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey"));
                    allowedValues.add(allowedValue);

                } else if ("default-value".equals(parser.getLocalName())) {
                    pdef.setDefaultValue(parser.getText());
                }
                break;

            case XMLStreamConstants.END_ELEMENT:
                log.debug("END ELEMENT -- " + parser.getLocalName());

                if ("display-section".equals(parser.getLocalName())) {
                    DisplaySectionDefinition sdef = (DisplaySectionDefinition) propertyHolderStack.pop();
                    sdefs.put(sdef.getName(), sdef);

                } else if ("property".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyDefinitions().add(pdef);
                    propertyDefs.put(pdef.getName(), pdef);
                    pdef = null;

                } else if ("object".equals(parser.getLocalName())) {
                    PropertyObjectDefinition odef = (PropertyObjectDefinition) propertyHolderStack.pop();
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyObjectDefinitions().add(odef);

                    // add to list of all property object defs
                    propertyObjectDefs.put(odef.getName(), odef);
                    odef = null;

                } else if ("collection".equals(parser.getLocalName())) {
                    PropertyObjectCollectionDefinition cdef = (PropertyObjectCollectionDefinition) propertyHolderStack
                            .pop();
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyObjectCollectionDefinitions().add(cdef);

                    // add to list of all property object defs
                    propertyObjectCollectionDefs.put(cdef.getName(), cdef);
                    cdef = null;

                } else if ("allowed-values".equals(parser.getLocalName())) {
                    pdef.setAllowedValues(allowedValues);
                    allowedValues = null;
                }
                break;

            case XMLStreamConstants.CHARACTERS:
                break;

            case XMLStreamConstants.CDATA:
                break;

            } // end switch
        } // end while

        parser.close();

        profileDef.sectionDefs = sdefs;

    } catch (Exception ex) {
        throw new SocialSiteException("ERROR parsing profile definitions", ex);
    }
}

From source file:ddf.catalog.source.solr.DynamicSchemaResolver.java

/**
 * Given xml as a string, this method will parse out element text and CDATA text. It separates
 * each by one space character./*from  w  w  w .  ja v a  2  s .c  om*/
 *
 * @param xmlDatas List of XML as {@code String}
 * @return parsed CDATA and element text
 */
protected List<String> parseTextFrom(List<Serializable> xmlDatas) {

    StringBuilder builder = new StringBuilder();
    List<String> parsedTexts = new ArrayList<>();
    XMLStreamReader xmlStreamReader = null;
    StringReader sr = null;
    long starttime = System.currentTimeMillis();

    try {
        for (Serializable xmlData : xmlDatas) {
            // xml parser does not handle leading whitespace
            sr = new StringReader(xmlData.toString());
            xmlStreamReader = XML_INPUT_FACTORY.createXMLStreamReader(sr);

            while (xmlStreamReader.hasNext()) {
                int event = xmlStreamReader.next();

                if (event == XMLStreamConstants.CHARACTERS || event == XMLStreamConstants.CDATA) {

                    String text = xmlStreamReader.getText();

                    if (StringUtils.isNotBlank(text)) {
                        builder.append(" ").append(text.trim());
                    }

                }
                if (event == XMLStreamConstants.START_ELEMENT) {
                    for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) {

                        String text = xmlStreamReader.getAttributeValue(i);

                        if (StringUtils.isNotBlank(text)) {
                            builder.append(" ").append(text.trim());
                        }
                    }
                }
            }
            parsedTexts.add(builder.toString());
            builder.setLength(0);
        }
    } catch (XMLStreamException e1) {
        LOGGER.warn("Failure occurred in parsing the xml data. No data has been stored or indexed.", e1);
    } finally {
        IOUtils.closeQuietly(sr);
        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (XMLStreamException e) {
                LOGGER.debug("Exception closing XMLStreamReader", e);
            }
        }
    }
    long endTime = System.currentTimeMillis();

    LOGGER.debug("Parsing took {} ms", endTime - starttime);

    return parsedTexts;
}

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());
            }//  w  w  w  . j a  v a 2  s . 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:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.ddi.DDIFileReader.java

private void processFileTxt(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("dimensns")) {
                processDimensns(xmlr, smd);
            } else if (xmlr.getLocalName().equals("fileType")) {
                // ignore.
            } else {
                throw new XMLStreamException(
                        "Unsupported DDI Element: codeBook/fileDscr/fileTxt/" + xmlr.getLocalName());
            }//ww w  .  j a va 2  s .c o m
        } else if (event == XMLStreamConstants.END_ELEMENT) {
            if (xmlr.getLocalName().equals("fileTxt")) {
                return;
            } else if (xmlr.getLocalName().equals("fileType")) {
                // continue;
            } else {
                throw new XMLStreamException(
                        "Mismatched DDI Formatting: </fileTxt> expected, found " + xmlr.getLocalName());
            }
        }
    }
}

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());
            }/*w w  w.ja v  a2  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());
            }
        }
    }
}