Example usage for javax.xml.stream XMLStreamReader hasNext

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

Introduction

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

Prototype

public boolean hasNext() throws XMLStreamException;

Source Link

Document

Returns true if there are more parsing events and false if there are no more events.

Usage

From source file:edu.indiana.d2i.htrc.portal.HTRCAgentClient.java

private Map<String, JobDetailsBean> parseJobDetailBeans(InputStream stream) throws XMLStreamException {
    Map<String, JobDetailsBean> res = new TreeMap<String, JobDetailsBean>();
    XMLStreamReader parser = factory.createXMLStreamReader(stream);
    while (parser.hasNext()) {
        int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (parser.hasName()) {
                if (parser.getLocalName().equals("job_status")) {
                    // one job status
                    JobDetailsBean detail = new JobDetailsBean();
                    Map<String, String> jobParams = new HashMap<String, String>();
                    Map<String, String> results = new HashMap<String, String>();
                    int innerEvent = parser.next();
                    while (true) {
                        if (innerEvent == XMLStreamConstants.END_ELEMENT
                                && parser.getLocalName().equals("job_status")) {
                            break;
                        }// w w w  .  j  ava  2s .  c  o  m

                        if (innerEvent == XMLStreamConstants.START_ELEMENT && parser.hasName()) {
                            // single tag
                            if (parser.getLocalName().equals("job_name")) {
                                detail.setJobTitle(parser.getElementText());
                            } else if (parser.getLocalName().equals("user")) {
                                detail.setUserName(parser.getElementText());
                            } else if (parser.getLocalName().equals("algorithm")) {
                                detail.setAlgorithmName(parser.getElementText());
                            } else if (parser.getLocalName().equals("job_id")) {
                                detail.setJobId(parser.getElementText());
                            } else if (parser.getLocalName().equals("date")) {
                                detail.setLastUpdatedDate(parser.getElementText());
                            }

                            // parameters
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.ONEPARAM)) {
                                String name, value;
                                name = value = "";
                                for (int i = 0; i < 3; i++) {
                                    if (parser.getAttributeName(i).toString().equals("name"))
                                        name = parser.getAttributeValue(i);
                                    if (parser.getAttributeName(i).toString().equals("value"))
                                        value = parser.getAttributeValue(i);
                                }
                                jobParams.put(name, value);
                            }

                            // status
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.STATUS)) {
                                String status = parser.getAttributeValue(0);
                                detail.setJobStatus(status);
                            }

                            // results
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.RESULT)) {
                                String name = parser.getAttributeValue(0);
                                String value = parser.getElementText();
                                results.put(name, value);
                            }

                            // message
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.MESSAGE)) {
                                detail.setMessage(parser.getElementText());
                            }

                            // saved or unsaved
                            if (parser.hasName() && parser.getLocalName().equals(JobDetailsBean.SAVEDORNOT)) {
                                detail.setJobSavedStr(parser.getElementText());
                            }
                        }
                        innerEvent = parser.next();
                    }
                    detail.setJobParams(jobParams);
                    detail.setResults(results);
                    res.put(detail.getJobId(), detail);
                }
            }
        }
    }
    return res;
}

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

private void defineClasses(final Map<String, CtClass> ctClasses, final InputStream stream)
        throws XMLStreamException, ModelXmlCompilingException, NotFoundException {
    XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);

    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 (ctClasses.containsKey(className)) {
                parse(reader, ctClasses.get(className), pluginIdentifier);
            }//from   www  . jav a  2s. co  m
        }
    }

    reader.close();
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizer.java

/**
 * Loads configuration from XML file, overriding the properties.
 *//*from ww w .ja v a2  s . co m*/
private void loadXMLConfiguration(InputStream xmlConfigurationStream)
        throws ConfigException, XMLStreamException {
    assert xmlConfigurationStream != null;
    final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    final XMLStreamReader reader = inputFactory.createXMLStreamReader(xmlConfigurationStream);

    boolean config = false;
    Module module = null;
    while (reader.hasNext()) {
        final int event = reader.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT: {
            String name = reader.getLocalName();
            if (name.equals("config")) {
                config = true;
                break;
            }

            if (config && name.equals("module")) {
                if (reader.getAttributeCount() == 1) {
                    final String attributeName = reader.getAttributeLocalName(0);
                    final String attributeValue = reader.getAttributeValue(0);

                    if (attributeName.equals("name") && attributeValue != null) {
                        String fullyQualified = Settings.class.getPackage().getName() + ".modules."
                                + attributeValue;
                        try {
                            Class<?> moduleClass = Class.forName(fullyQualified);
                            module = (Module) moduleClass.newInstance();
                        } catch (InstantiationException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot instantiate module " + attributeValue, ex);
                        } catch (IllegalAccessException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot access module " + attributeValue, ex);
                        } catch (ClassNotFoundException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot load module " + attributeValue, ex);
                        }
                    }
                }
            }

            if (config && name.equals("property")) {
                if (reader.getAttributeCount() == 1) {
                    final String attributeName = reader.getAttributeLocalName(0);
                    final String attributeValue = reader.getAttributeValue(0);

                    if (attributeName.equals("name") && attributeValue != null) {
                        if (module == null) {
                            if (Settings.isProperty(attributeValue)) {
                                Settings.setProperty(attributeValue, reader.getElementText());
                            } else {
                                throw new ConfigException("configuration not valid\n"
                                        + "Tried to override non-existing global property " + attributeValue);
                            }
                        } else {
                            if (module.isProperty(attributeValue)) {
                                module.setProperty(attributeValue, reader.getElementText());
                            } else {
                                throw new ConfigException("configuration not valid\n"
                                        + "configuration tried to override non-existing property "
                                        + attributeValue);
                            }
                        }
                    }
                }
            }

            break;
        }
        case XMLStreamConstants.END_ELEMENT: {
            if (config && reader.getLocalName().equals("module")) {
                addModule(module);

                module = null;
            }

            if (config && reader.getLocalName().equals("config")) {
                config = false;
            }
        }
        }
    }
}

From source file:at.lame.hellonzb.parser.NzbParser.java

/**
 * This is the constructor of the class.
 * It parses the given XML file.//  w ww .j av  a 2 s. co m
 *
 * @param mainApp The main application object
 * @param file The file name of the nzb file to parse
 * @throws XMLStreamException 
 * @throws IOException 
 */
public NzbParser(HelloNzbCradle mainApp, String file) throws XMLStreamException, IOException, ParseException {
    this.mainApp = mainApp;

    DownloadFile currentFile = null;
    DownloadFileSegment currentSegment = null;
    boolean groupFlag = false;
    boolean segmentFlag = false;

    this.name = file.trim();
    this.name = file.substring(0, file.length() - 4);
    this.downloadFiles = new Vector<DownloadFile>();

    this.origTotalSize = 0;
    this.downloadedBytes = 0;

    // create XML parser
    String string = reformatInputStream(file);
    InputStream in = new ByteArrayInputStream(string.getBytes());
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(in);

    // parse nzb file with a Java XML parser
    while (parser.hasNext()) {
        switch (parser.getEventType()) {
        // parser has reached the end of the xml file
        case XMLStreamConstants.END_DOCUMENT:
            parser.close();
            break;

        // parser has found a new element
        case XMLStreamConstants.START_ELEMENT:
            String elemName = parser.getLocalName().toLowerCase();
            if (elemName.equals("file")) {
                currentFile = newDownloadFile(parser);
                boolean found = false;
                for (DownloadFile dlf : downloadFiles)
                    if (dlf.getFilename().equals(currentFile.getFilename())) {
                        found = true;
                        break;
                    }

                if (!found)
                    downloadFiles.add(currentFile);
            } else if (elemName.equals("group"))
                groupFlag = true;
            else if (elemName.equals("segment")) {
                currentSegment = newDownloadFileSegment(parser, currentFile);
                currentFile.addSegment(currentSegment);
                segmentFlag = true;
            }
            break;

        // end of element
        case XMLStreamConstants.END_ELEMENT:
            groupFlag = false;
            segmentFlag = false;
            break;

        // get the elements value(s)
        case XMLStreamConstants.CHARACTERS:
            if (!parser.isWhiteSpace()) {
                if (groupFlag && (currentFile != null))
                    currentFile.addGroup(parser.getText());
                else if (segmentFlag && (currentSegment != null))
                    currentSegment.setArticleId(parser.getText());
            }
            break;

        // any other parser event?
        default:
            break;
        }

        parser.next();
    }

    checkFileSegments();
    this.origTotalSize = getCurrTotalSize();
}

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  va2 s . c o  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());
            }/* w ww  . ja  v  a2  s  .  c  om*/
        }
    }
    return r;
}

From source file:jp.co.atware.solr.geta.GETAssocComponent.java

/**
 * GETAssoc?????<code>NamedList</code>???????
 * /*from   w w w  .  j av  a 2  s . co  m*/
 * @param inputStream GETAssoc??
 * @return <code>NamedList</code>?
 * @throws FactoryConfigurationError
 * @throws IOException
 */
protected NamedList<Object> convertResult(InputStream inputStream)
        throws FactoryConfigurationError, IOException {
    NamedList<Object> result = new NamedList<Object>();
    LinkedList<NamedList<Object>> stack = new LinkedList<NamedList<Object>>();
    stack.push(result);
    try {
        XMLStreamReader xml = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
        while (xml.hasNext()) {
            switch (xml.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                NamedList<Object> element = new NamedList<Object>();
                stack.peek().add(xml.getName().toString(), element);
                stack.push(element);
                for (int i = 0; i < xml.getAttributeCount(); i++) {
                    String name = xml.getAttributeName(i).toString();
                    String value = xml.getAttributeValue(i);
                    ValueOf valueOf = valueTransMap.get(name);
                    if (valueOf != null) {
                        try {
                            element.add(name, valueOf.toValue(value));
                        } catch (NumberFormatException e) {
                            element.add(name, value);
                        }
                    } else {
                        element.add(name, value);
                    }
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                stack.pop();
                break;
            default:
                break;
            }
            xml.next();

        }
        xml.close();
    } catch (XMLStreamException e) {
        throw new IOException(e);
    }

    LOG.debug(result.toString());
    return result;
}

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 ww .j  a v a 2s .c  o  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: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  w  w w  .j av  a  2 s. 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  ww.  j  a v  a 2s  .c o m

            break;
        }
    }

    reader.close();

    return existingClasses;
}