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:babel.content.pages.PageVersion.java

public void unpersist(XMLStreamReader reader) throws XMLStreamException {
    String elemTag;//from w w  w  .  j  ava 2s. c  o  m
    String elemAttrib;

    m_verProps.clear();
    ;
    m_contentMeta.clear();
    m_parseMeta.clear();
    m_outLinks = null;
    m_content = new String();

    while (true) {
        int event = reader.next();

        if (event == XMLStreamConstants.END_ELEMENT
                && XML_TAG_PAGEVERSION.equals(reader.getName().toString())) {
            break;
        }

        if (event == XMLStreamConstants.START_ELEMENT) {
            elemTag = reader.getName().toString();
            elemAttrib = reader.getAttributeValue(0);

            if ("MetaData".equals(elemTag)) {
                if ("VersionProperties".equals(elemAttrib)) {
                    m_verProps.unpersist(reader);
                } else if ("ContentMetadata".equals(elemAttrib)) {
                    m_contentMeta.unpersist(reader);
                } else if ("ParseMetadata".equals(elemAttrib)) {
                    m_parseMeta.unpersist(reader);
                }
            } else if (XML_TAG_CONTENT.equals(elemTag)) {
                //m_content = new String(Base64.decodeBase64(reader.getElementText().getBytes()));
                m_content = reader.getElementText();
            }

            //TODO: Not reading the out links
        }
    }
}

From source file:davmail.exchange.dav.ExchangeDavMethod.java

protected void handleMultiValuedProperty(XMLStreamReader reader, MultiStatusResponse multiStatusResponse)
        throws XMLStreamException {
    String tagLocalName = reader.getLocalName();
    Namespace namespace = Namespace.getNamespace(reader.getNamespaceURI());
    ArrayList<String> values = new ArrayList<String>();
    while (reader.hasNext() && !XMLStreamUtil.isEndTag(reader, tagLocalName)) {
        reader.next();
        if (XMLStreamUtil.isStartTag(reader)) {
            String tagContent = getTagContent(reader);
            if (tagContent != null) {
                values.add(tagContent);//ww w  .  jav a2s .co  m
            }
        }
    }
    multiStatusResponse.add(new DefaultDavProperty(tagLocalName, values, namespace));
}

From source file:com.ikanow.infinit.e.harvest.extraction.document.file.XmlToMetadataParser.java

/**
 * Parses XML and returns a new feed with the resulting HashMap as Metadata
 * @param reader XMLStreamReader using Stax to avoid out of memory errors
 * @return List of Feeds with their Metadata set
 *///from w w w. j a  va  2  s  .co m
public List<DocumentPojo> parseDocument(XMLStreamReader reader) throws XMLStreamException {
    DocumentPojo doc = new DocumentPojo();
    List<DocumentPojo> docList = new ArrayList<DocumentPojo>();
    boolean justIgnored = false;
    boolean hitIdentifier = false;

    while (reader.hasNext()) {
        int eventCode = reader.next();

        switch (eventCode) {
        case (XMLStreamReader.START_ELEMENT): {
            String tagName = reader.getLocalName();

            if (null == levelOneFields || levelOneFields.size() == 0) {
                levelOneFields = new ArrayList<String>();
                levelOneFields.add(tagName);
                doc = new DocumentPojo();
                sb.delete(0, sb.length());
                justIgnored = false;
            } else if (levelOneFields.contains(tagName)) {
                sb.delete(0, sb.length());
                doc = new DocumentPojo();
                justIgnored = false;
            } else if ((null != ignoreFields) && ignoreFields.contains(tagName)) {
                justIgnored = true;
            } else {
                if (this.bPreserveCase) {
                    sb.append("<").append(tagName).append(">");
                } else {
                    sb.append("<").append(tagName.toLowerCase()).append(">");
                }
                justIgnored = false;
            }
            hitIdentifier = tagName.equalsIgnoreCase(PKElement);

            if (!justIgnored && (null != this.AttributePrefix)) { // otherwise ignore attributes anyway
                int nAttributes = reader.getAttributeCount();
                StringBuffer sb2 = new StringBuffer();
                for (int i = 0; i < nAttributes; ++i) {
                    sb2.setLength(0);
                    sb.append('<');

                    sb2.append(this.AttributePrefix);
                    if (this.bPreserveCase) {
                        sb2.append(reader.getAttributeLocalName(i).toLowerCase());
                    } else {
                        sb2.append(reader.getAttributeLocalName(i));
                    }
                    sb2.append('>');

                    sb.append(sb2);
                    sb.append("<![CDATA[").append(reader.getAttributeValue(i).trim()).append("]]>");
                    sb.append("</").append(sb2);
                }
            }
        }
            break;

        case (XMLStreamReader.CHARACTERS): {
            if (reader.getText().trim().length() > 0 && justIgnored == false)
                sb.append("<![CDATA[").append(reader.getText().trim()).append("]]>");
            if (hitIdentifier) {
                String tValue = reader.getText().trim();
                if (null != XmlSourceName) {
                    if (tValue.length() > 0) {
                        doc.setUrl(XmlSourceName + tValue);
                    }
                }
            }
        }
            break;
        case (XMLStreamReader.END_ELEMENT): {
            hitIdentifier = !reader.getLocalName().equalsIgnoreCase(PKElement);
            if ((null != ignoreFields) && !ignoreFields.contains(reader.getLocalName())) {
                if (levelOneFields.contains(reader.getLocalName())) {
                    JSONObject json;
                    try {
                        json = XML.toJSONObject(sb.toString());
                        for (String names : JSONObject.getNames(json)) {
                            JSONObject rec = null;
                            JSONArray jarray = null;

                            try {
                                jarray = json.getJSONArray(names);
                                doc.addToMetadata(names, handleJsonArray(jarray, false));
                            } catch (JSONException e) {
                                try {
                                    rec = json.getJSONObject(names);
                                    doc.addToMetadata(names, convertJsonObjectToLinkedHashMap(rec));
                                } catch (JSONException e2) {
                                    try {
                                        Object[] val = { json.getString(names) };
                                        doc.addToMetadata(names, val);
                                    } catch (JSONException e1) {
                                        e1.printStackTrace();
                                    }
                                }
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    sb.delete(0, sb.length());
                    docList.add(doc);
                } else {
                    if (this.bPreserveCase) {
                        sb.append("</").append(reader.getLocalName()).append(">");
                    } else {
                        sb.append("</").append(reader.getLocalName().toLowerCase()).append(">");
                    }

                }
            }
        } // (end case)
            break;
        } // (end switch)
    }
    return docList;
}

From source file:hudson.plugins.report.jck.parsers.JtregReportParser.java

private List<Test> parseTestsuites(XMLStreamReader in) throws Exception {
    List<Test> r = new ArrayList<>();
    String ignored = "com.google.security.wycheproof.OpenJDKAllTests";
    while (in.hasNext()) {
        int event = in.next();
        if (event == START_ELEMENT && TESTSUITE.equals(in.getLocalName())) {
            JtregBackwardCompatibileSuite suite = parseTestSuite(in);
            if (ignored.equals(suite.name)) {
                System.out.println("Skipping ignored suite : " + ignored);
            } else {
                r.addAll(suite.getTests());
            }/*from ww w.j ava2  s. c  o m*/
        }
    }
    return r;
}

From source file:com.qcadoo.model.internal.classconverter.ModelXmlToClassConverterImpl.java

private Map<String, CtClass> createClasses(final Map<String, Class<?>> existingClasses,
        final InputStream stream) throws XMLStreamException {
    XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
    Map<String, CtClass> ctClasses = new HashMap<String, CtClass>();

    while (reader.hasNext() && reader.next() > 0) {
        if (isTagStarted(reader, TAG_MODEL)) {
            String pluginIdentifier = getPluginIdentifier(reader);
            String modelName = getStringAttribute(reader, L_NAME);
            String className = ClassNameUtils.getFullyQualifiedClassName(pluginIdentifier, modelName);

            if (existingClasses.containsKey(className)) {
                LOG.info("Class " + className + " already exists, skipping");
            } else {
                LOG.info("Creating class " + className);
                ctClasses.put(className, classPool.makeClass(className));
            }/*from  ww w  . j  a  v  a2s .  c  o m*/

            break;
        }
    }

    reader.close();

    return ctClasses;
}

From source file:com.qcadoo.model.internal.classconverter.ModelXmlToClassConverterImpl.java

private Map<String, Class<?>> findExistingClasses(final InputStream stream) throws XMLStreamException {
    XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
    Map<String, Class<?>> existingClasses = new HashMap<String, Class<?>>();

    while (reader.hasNext() && reader.next() > 0) {
        if (isTagStarted(reader, TAG_MODEL)) {
            String pluginIdentifier = getPluginIdentifier(reader);
            String modelName = getStringAttribute(reader, L_NAME);
            String className = ClassNameUtils.getFullyQualifiedClassName(pluginIdentifier, modelName);

            try {
                existingClasses.put(className, classLoader.loadClass(className));
                LOG.info("Class " + className + " already exists, skipping");
            } catch (ClassNotFoundException e) {
                LOG.info("Class " + className + " not found, will be generated");
            }//from  w w w.j  a va  2 s  .co  m

            break;
        }
    }

    reader.close();

    return existingClasses;
}

From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java

private List<String> getPackageNamesFromGuvnor() {
    List<String> packages = new ArrayList<String>();
    String packagesURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain()
            + "/rest/packages/";
    try {/*from  w  w  w .  ja va 2 s. co m*/
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = factory.createXMLStreamReader(getInputStreamForURL(packagesURL, "GET"));
        while (reader.hasNext()) {
            if (reader.next() == XMLStreamReader.START_ELEMENT) {
                if ("title".equals(reader.getLocalName())) {
                    String pname = reader.getElementText();
                    if (!pname.equalsIgnoreCase("Packages")) {
                        packages.add(pname);
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error("Error retriving packages from guvnor: " + e.getMessage());
    }
    return packages;
}

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  ww  w  .j  ava  2s  .c om*/

        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.microsoft.windowsazure.storage.table.TableParser.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.
 * // w  w  w .j ava2  s  . c  om
 * @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.
 */
private static HashMap<String, EntityProperty> readAtomProperties(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:com.prowidesoftware.swift.io.parser.MxParser.java

/**
 * Takes an xml with an MX message and detects the specific message type
 * parsing just the namespace from the Document element. If the Document
 * element is not present, or without the namespace or if the namespace url
 * contains invalid content it will return null.
 * <br><br>// w  w w  . ja v  a2s.  co  m
 * Example of a recognizable Document element:<br>
 * <Doc:Document xmlns:Doc="urn:swift:xsd:camt.003.001.04" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 * <br>
 * The implementation is intended to be lightweight and efficient, based on {@link javax.xml.stream.XMLStreamReader} 
 *
 * @return id with the detected MX message type or null if it cannot be determined.
 * @since 7.7
 */
public MxId detectMessage() {
    if (StringUtils.isBlank(this.buffer)) {
        log.log(Level.SEVERE, "cannot detect message from null or empty content");
        return null;
    }
    final javax.xml.stream.XMLInputFactory xif = javax.xml.stream.XMLInputFactory.newInstance();
    try {
        final javax.xml.stream.XMLStreamReader reader = xif
                .createXMLStreamReader(new StringReader(this.buffer));
        while (reader.hasNext()) {
            int event = reader.next();
            if (javax.xml.stream.XMLStreamConstants.START_ELEMENT == event
                    && reader.getLocalName().equals(DOCUMENT_LOCALNAME)) {
                if (reader.getNamespaceCount() > 0) {
                    //log.finest("ELEMENT START: " + reader.getLocalName() + " , namespace count is: " + reader.getNamespaceCount());
                    for (int nsIndex = 0; nsIndex < reader.getNamespaceCount(); nsIndex++) {
                        final String nsPrefix = StringUtils.trimToNull(reader.getNamespacePrefix(nsIndex));
                        final String elementPrefix = StringUtils.trimToNull(reader.getPrefix());
                        if (StringUtils.equals(nsPrefix, elementPrefix)) {
                            String nsId = reader.getNamespaceURI(nsIndex);
                            //log.finest("\tNamepsace prefix: " + nsPrefix + " associated with URI " + nsId);
                            return new MxId(nsId);
                        }
                    }
                }
            }
        }
    } catch (final Exception e) {
        log.log(Level.SEVERE, "error while detecting message", e);
    }
    return null;
}