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:com.clustercontrol.agent.winevent.WinEventMonitor.java

/**
 * XMLStAX???EventLogRecord????/*from  w  ww .  j  a v  a2 s . com*/
 * @param eventXmlStream
 * @return EventLogRecord?
 */
private ArrayList<EventLogRecord> parseEventXML(InputStream eventXmlStream) {
    ArrayList<EventLogRecord> eventlogs = new ArrayList<EventLogRecord>();

    try {
        XMLInputFactory xmlif = XMLInputFactory.newInstance();
        /**
         * OpenJDK7/OracleJDK7??"]"?2?????????????????????????????
         * ?XML?????????OpenJDK7/OracleJDK7???????/??????????
         * URL???????????????
         * 
         * URL
         * http://docs.oracle.com/javase/jp/6/api/javax/xml/stream/XMLStreamReader.html#next()
         */
        String xmlCoalescingKey = "javax.xml.stream.isCoalescing";// TODO JRE???????????????????
        if (m_log.isDebugEnabled()) {
            m_log.debug(xmlCoalescingKey + " = true");
        }
        xmlif.setProperty(xmlCoalescingKey, true);
        XMLStreamReader xmlr = xmlif.createXMLStreamReader(eventXmlStream);

        while (xmlr.hasNext()) {
            switch (xmlr.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                m_log.trace("EventType : XMLStreamConstants.START_ELEMENT");

                String localName = xmlr.getLocalName();
                m_log.trace("local name : " + localName);

                if ("Event".equals(localName)) {
                    EventLogRecord eventlog = new EventLogRecord();
                    eventlogs.add(eventlog);
                    m_log.debug("create new EventLogRecord");
                } else {
                    String attrLocalName = null;
                    String attrValue = null;

                    if (xmlr.getAttributeCount() != 0) {
                        attrLocalName = xmlr.getAttributeLocalName(0);
                        attrValue = xmlr.getAttributeValue(0);
                        m_log.trace("attribute local name : " + attrLocalName);
                        m_log.trace("attribute local value : " + attrValue);
                    }

                    if ("Provider".equals(localName)) {
                        if ("Name".equals(attrLocalName)) {
                            m_log.trace("target value : " + attrValue);

                            EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1);
                            eventlog.setProviderName(attrValue);
                            m_log.debug("set ProviderName : " + eventlog.getProviderName());
                        }
                    }
                    // Get-WinEvent/wevtutil.exe
                    else if ("TimeCreated".equals(localName) && "SystemTime".equals(attrLocalName)) {
                        m_log.trace("target value : " + attrValue);

                        // "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'"???S????????????
                        String formatedDateString = attrValue.replaceAll("\\..*Z", "");
                        m_log.trace("formatted target value : " + formatedDateString);
                        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

                        EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1);
                        ;
                        try {
                            eventlog.setTimeCreated(sdf.parse(formatedDateString));
                        } catch (ParseException e) {
                            // do nothing
                            m_log.error("set TimeCreated Error", e);
                        }
                        m_log.debug("set TimeCreated : " + eventlog.getTimeCreated());
                    }
                    // Get-EventLog
                    if ("TimeGenerated".equals(localName) && "SystemTime".equals(attrLocalName)) {
                        m_log.trace("target value : " + attrValue);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'Z'");
                        sdf.setTimeZone(HinemosTime.getTimeZone());

                        EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1);
                        ;
                        try {
                            eventlog.setTimeCreated(sdf.parse(attrValue));
                        } catch (ParseException e) {
                            // do nothing
                            m_log.error("set TimeCreated Error", e);
                        }
                        m_log.debug("set TimeCreated : " + eventlog.getTimeCreated());
                    } else {
                        targetProperty = localName;
                        m_log.trace("target property : " + targetProperty);
                    }
                }

                break;
            case XMLStreamConstants.SPACE:
            case XMLStreamConstants.CHARACTERS:
                m_log.trace("EventType : XMLStreamConstants.CHARACTERS, length=" + xmlr.getTextLength());
                if (targetProperty != null) {
                    try {
                        EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1);
                        ;
                        if ("EventID".equals(targetProperty)) {
                            eventlog.setId(Integer.parseInt(new String(xmlr.getTextCharacters(),
                                    xmlr.getTextStart(), xmlr.getTextLength())));
                            m_log.debug("set EventID : " + eventlog.getId());
                        }
                        // Get-WinEvent/wevtutil.exe
                        else if ("Level".equals(targetProperty)) {
                            if (eventlog.getLevel() == WinEventConstant.UNDEFINED) {
                                eventlog.setLevel(Integer.parseInt(new String(xmlr.getTextCharacters(),
                                        xmlr.getTextStart(), xmlr.getTextLength())));
                                m_log.debug("set Level : " + eventlog.getLevel());
                            }
                        } else if ("Task".equals(targetProperty)) {
                            if (eventlog.getTask() == WinEventConstant.UNDEFINED) {
                                eventlog.setTask(Integer.parseInt(new String(xmlr.getTextCharacters(),
                                        xmlr.getTextStart(), xmlr.getTextLength())));
                                m_log.debug("set Task : " + eventlog.getTask());
                            }
                        } else if ("Keywords".equals(targetProperty)) {
                            // TODO ????????0x8080000000000000
                            //eventlog.setKeywords(Long.decode(new String(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength())));
                            //m_log.debug("set Keywords : " + eventlog.getKeywords());
                        } else if ("EventRecordId".equals(targetProperty)) {
                            eventlog.setRecordId(Long.parseLong(new String(xmlr.getTextCharacters(),
                                    xmlr.getTextStart(), xmlr.getTextLength())));
                            m_log.debug("set RecordId : " + eventlog.getRecordId());
                        } else if ("Channel".equals(targetProperty)) {
                            eventlog.setLogName(new String(xmlr.getTextCharacters(), xmlr.getTextStart(),
                                    xmlr.getTextLength()));
                            m_log.debug("set LogName : " + eventlog.getLogName());
                        } else if ("Computer".equals(targetProperty)) {
                            eventlog.setMachineName(new String(xmlr.getTextCharacters(), xmlr.getTextStart(),
                                    xmlr.getTextLength()));
                            m_log.debug("set MachineName : " + eventlog.getMachineName());
                        } else if ("Message".equals(targetProperty)) {
                            String message = new String(xmlr.getTextCharacters(), xmlr.getTextStart(),
                                    xmlr.getTextLength());
                            message = message.replaceAll(tmpReturnCode, "\r\n");
                            message = message.replaceAll(tmpLtCode, "<");
                            message = message.replaceAll(tmpGtCode, ">");
                            eventlog.setMessage(message);
                            m_log.debug("set Message : " + eventlog.getMessage());
                        } else if ("Data".equals(targetProperty)) {
                            String data = new String(xmlr.getTextCharacters(), xmlr.getTextStart(),
                                    xmlr.getTextLength());
                            eventlog.getData().add(data);
                            m_log.debug("set Data : " + data);
                        } else {
                            m_log.debug("unknown target property : " + targetProperty);
                        }
                    } catch (NumberFormatException e) {
                        m_log.debug("number parse error", e);
                    }
                }
                targetProperty = null;
                break;
            default: // 
                break;
            }
            xmlr.next();
        }
        xmlr.close();
    } catch (XMLStreamException e) {
        m_log.warn("parseEvent() xmlstream error", e);
    }

    return eventlogs;

}

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

private AlgorithmDetailsBean parseAlgorithmDetailBean(InputStream stream) throws XMLStreamException {
    AlgorithmDetailsBean res = new AlgorithmDetailsBean();
    XMLStreamReader parser = factory.createXMLStreamReader(stream);

    List<AlgorithmDetailsBean.Parameter> parameters = new ArrayList<AlgorithmDetailsBean.Parameter>();
    List<String> authors = new ArrayList<String>();
    while (parser.hasNext()) {
        int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (parser.hasName()) {
                // only parse the info tag!
                if (parser.getLocalName().equals(AlgorithmDetailsBean.NAME)) {
                    res.setName(parser.getElementText());
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.VERSION)) {
                    res.setVersion(parser.getElementText());
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.DESCRIPTION)) {
                    res.setDescription(parser.getElementText());
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.SUPPORTURL)) {
                    res.setSupportUrl(parser.getElementText());
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.PARAMETER)) {
                    AlgorithmDetailsBean.Parameter parameter = new AlgorithmDetailsBean.Parameter();
                    int count = parser.getAttributeCount();
                    for (int i = 0; i < count; i++) {
                        if (parser.getAttributeLocalName(i).equals("required"))
                            parameter.setRequired(Boolean.valueOf(parser.getAttributeValue(i)));
                        if (parser.getAttributeLocalName(i).equals("type"))
                            parameter.setType(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("name"))
                            parameter.setName(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("defaultValue"))
                            parameter.setDefaultValue(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("validation"))
                            parameter.setValidation(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("validationError"))
                            parameter.setValidationError(parser.getAttributeValue(i));
                        if (parser.getAttributeLocalName(i).equals("readOnly"))
                            parameter.setReadOnly(Boolean.parseBoolean(parser.getAttributeValue(i)));
                    }//from   w  w  w  . j a  va 2 s .  com
                    parser.nextTag();
                    if (parser.getLocalName().equals("label"))
                        parameter.setLabel(parser.getElementText());
                    parser.nextTag();
                    if (parser.getLocalName().equals("description"))
                        parameter.setDescription(parser.getElementText());
                    parameters.add(parameter);
                } else if (parser.getLocalName().equals(AlgorithmDetailsBean.AUTHOR)) {
                    int count = parser.getAttributeCount();
                    for (int i = 0; i < count; i++) {
                        if (parser.getAttributeLocalName(i).equals("name"))
                            authors.add(parser.getAttributeValue(i));
                    }
                }
            }
        }
    }
    res.setParameters(parameters);
    res.setAuthors(authors);
    return res;
}

From source file:de.uzk.hki.da.cb.CreatePremisAction.java

/**
 * Accepts a premis.xml file and creates a new xml file for each jhove section  
 * /*from w ww . j a va 2  s .co m*/
 * @author Thomas Kleinke
 * Extract jhove data.
 *
 * @param premisFilePath the premis file path
 * @param outputFolder the output folder
 * @throws XMLStreamException the xML stream exception
 */
public void extractJhoveData(String premisFilePath, String outputFolder) throws XMLStreamException {

    outputFolder += "/premis_output/";

    FileInputStream inputStream = null;

    try {
        inputStream = new FileInputStream(premisFilePath);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Couldn't find file " + premisFilePath, e);
    }

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

    boolean textElement = false;
    boolean jhoveSection = false;
    boolean objectIdentifierValue = false;
    int tab = 0;
    String fileId = "";

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

        switch (event) {

        case XMLStreamConstants.START_ELEMENT:

            if (streamReader.getLocalName().equals("jhove")) {
                jhoveSection = true;
                String outputFilePath = outputFolder + fileId.replace('/', '_').replace('.', '_') + ".xml";
                if (!new File(outputFolder).exists())
                    new File(outputFolder).mkdirs();
                writer = startNewDocument(outputFilePath);
            }

            if (streamReader.getLocalName().equals("objectIdentifierValue"))
                objectIdentifierValue = true;

            if (jhoveSection) {
                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 (objectIdentifierValue) {
                fileId = streamReader.getText();
                objectIdentifierValue = false;
            }

            if (jhoveSection && !streamReader.isWhiteSpace()) {
                writer.writeCharacters(streamReader.getText());
                textElement = true;
            }
            break;

        case XMLStreamConstants.END_ELEMENT:
            if (jhoveSection) {
                tab--;

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

                writer.writeEndElement();
                textElement = false;

                if (streamReader.getLocalName().equals("jhove")) {
                    jhoveSection = false;
                    finalizeDocument();
                }
            }
            break;

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

        default:
            break;
        }
    }
}

From source file:com.widowcrawler.exo.parse.Parser.java

public Sitemap parse(InputStream inputStream) throws XMLStreamException, SitemapParseException {

    final XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream, "utf-8");

    final Sitemap retval = new Sitemap(new HashSet<>());

    final Set<SitemapURL> sitemapURLs = new HashSet<>();
    SitemapURL.Builder urlBuilder = null;
    String urlContent;/*  www .  ja va 2s.  com*/

    reader.getEventType();

    while (reader.hasNext()) {
        switch (state) {
        case START:
            reader.nextTag();

            if (StringUtils.equalsIgnoreCase(reader.getLocalName(), URLSET_TAG_NAME)) {
                state = State.URLSET;
            } else if (StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAPINDEX_TAG_NAME)) {
                state = State.SITEMAPINDEX;
            } else {
                String message = "Invalid root element. Must be either urlset or sitemapindex";
                logger.error(message);
                throw new SitemapParseException(message);
            }

            break;

        case END:
            // consume all end tags
            if (reader.getEventType() != XMLStreamConstants.END_ELEMENT) {
                String message = decorate("There should be only one root element in each sitemap.xml",
                        reader.getLocation());
                logger.error(message);
                throw new SitemapParseException(message);
            }

            reader.next();
            break;

        /////////////////////
        // URLSET Hierarchy
        /////////////////////
        case URLSET:
            // If we're done with the URLs, we're done overall
            if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) {
                state = State.END;
                break;
            }

            // Check that we're entering into a <url> element
            if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), URL_TAG_NAME)) {
                String message = "A <urlset> element can only contain <url> elements. Found: "
                        + reader.getLocalName();
                logger.error(message);
                throw new SitemapParseException(message);
            }

            urlBuilder = new SitemapURL.Builder();
            state = State.URL;
            break;

        case URL:
            reader.nextTag();

            if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
                //logger.info("reader.getLocalName(): " + reader.getLocalName());
                switch (StringUtils.lowerCase(reader.getLocalName())) {
                case LOC_TAG_NAME:
                    state = State.URL_PROP_LOC;
                    break;
                case LASTMOD_TAG_NAME:
                    state = State.URL_PROP_LASTMOD;
                    break;
                case CHANGEFREQ_TAG_NAME:
                    state = State.URL_PROP_CHANGEFREQ;
                    break;
                case PRIORITY_TAG_NAME:
                    state = State.URL_PROP_PRIORITY;
                    break;
                case MOBILE_TAG_NAME:
                    state = State.URL_PROP_MOBILE;
                    break;
                default:
                    String message = "Unexpected tag in url: " + reader.getLocalName();
                    logger.error(message);
                    throw new SitemapParseException(message);
                }
            } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
                // we're done collecting the data for this URL
                assert urlBuilder != null;
                sitemapURLs.add(urlBuilder.build());
                urlBuilder = new SitemapURL.Builder();
                state = State.URLSET;
            }
            break;

        case URL_PROP_LOC:
            urlContent = reader.getElementText();

            try {
                assert urlBuilder != null;
                urlBuilder.withLocation(new URL(StringUtils.trimToNull(urlContent)));

            } catch (MalformedURLException ex) {
                String message = String.format("Malformed URL found: %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);
            }
            state = State.URL;
            break;

        case URL_PROP_LASTMOD:
            assert urlBuilder != null;
            urlBuilder.withLastModified(DateTime.parse(reader.getElementText()));
            state = State.URL;
            break;

        case URL_PROP_CHANGEFREQ:
            assert urlBuilder != null;
            urlBuilder.withChangeFrequency(ChangeFreq.valueOf(StringUtils.upperCase(reader.getElementText())));
            state = State.URL;
            break;

        case URL_PROP_PRIORITY:
            assert urlBuilder != null;
            urlBuilder.withPriority(Double.valueOf(reader.getElementText()));
            state = State.URL;
            break;

        case URL_PROP_MOBILE:
            assert urlBuilder != null;
            urlBuilder.withIsMobileContent(true);
            // consume until "end tag" of self-closing tag
            // Also works if someone puts content in
            reader.getElementText();
            state = State.URL;
            break;

        ///////////////////////////
        // SITEMAPINDEX Hierarchy
        ///////////////////////////
        case SITEMAPINDEX:
            // If we're done with all the Sitemaps, we're done overall
            if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) {
                state = State.END;
                break;
            }

            state = State.SITEMAP;
            break;

        case SITEMAP:
            if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAP_TAG_NAME)) {
                throw new SitemapParseException("A <sitemapindex> element can only contain <sitemap> elements");
            }

            reader.nextTag();

            if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
                switch (StringUtils.lowerCase(reader.getLocalName())) {
                case LOC_TAG_NAME:
                    state = State.URL_PROP_LOC;
                    break;
                case LASTMOD_TAG_NAME:
                    state = State.URL_PROP_LASTMOD;
                    break;
                default:
                    throw new SitemapParseException("Unexpected tag in sitemap: " + reader.getLocalName());
                }
            } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
                // we're done collecting the data for this URL
                assert urlBuilder != null;
                sitemapURLs.add(urlBuilder.build());
                urlBuilder = new SitemapURL.Builder();
                state = State.URLSET;
            }

        case SITEMAP_PROP_LOC:
            urlContent = reader.getElementText();

            try {
                URL sitemapURL = new URL(StringUtils.trimToNull(urlContent));

                Sitemap temp = Retry.retry(() -> {
                    try {
                        return Exo.parse(sitemapURL.toString());
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                });

                retval.merge(temp);

            } catch (MalformedURLException ex) {
                String message = String.format("Malformed URL found: %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);

            } catch (InterruptedException e) {
                logger.warn("Thread interrupted while (re)trying");
                Thread.currentThread().interrupt();

            } catch (RetryFailedException e) {
                String message = String.format("Failed to retrieve sitemap of sitemap index at %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);
            }

            state = State.URL;
            break;

        case SITEMAP_PROP_LASTMOD:
            // Do nothing with this data for now
            reader.getElementText();
            break;
        }

        //System.out.println(state);
    }

    return retval.merge(new Sitemap(sitemapURLs));
}

From source file:com.pocketsoap.salesforce.soap.ChatterClient.java

private <T> T makeSoapRequest(String serverUrl, RequestEntity req, ResponseParser<T> respParser)
        throws XMLStreamException, IOException {
    PostMethod post = new PostMethod(serverUrl);
    post.addRequestHeader("SOAPAction", "\"\"");
    post.setRequestEntity(req);/*from w  w  w .j av  a2 s  . co m*/

    HttpClient http = new HttpClient();
    int sc = http.executeMethod(post);
    if (sc != 200 && sc != 500)
        throw new IOException("request to " + serverUrl + " returned unexpected HTTP status code of " + sc
                + ", check configuration.");

    XMLInputFactory f = XMLInputFactory.newInstance();
    f.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);

    XMLStreamReader rdr = f.createXMLStreamReader(post.getResponseBodyAsStream());
    rdr.require(XMLStreamReader.START_DOCUMENT, null, null);
    rdr.nextTag();
    rdr.require(XMLStreamReader.START_ELEMENT, SOAP_NS, "Envelope");
    rdr.nextTag();
    // TODO, should handle a Header appearing in the response.
    rdr.require(XMLStreamReader.START_ELEMENT, SOAP_NS, "Body");
    rdr.nextTag();
    if (rdr.getLocalName().equals("Fault")) {
        throw handleSoapFault(rdr);
    }
    try {
        T response = respParser.parse(rdr);
        while (rdr.hasNext())
            rdr.next();
        return response;
    } finally {
        try {
            rdr.close();
        } finally {
            post.releaseConnection();
        }
    }
}

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

/**
 * Test status of testcase is determined from its child tags( <skipped>, <failure>, <error> ).
 * If it doesn't contain any of these tags, test is considered passed. If it contains both failure and error tags,
 * test status is set to error./*from w ww  . j ava2  s.c  o  m*/
 */

private JtregBackwardCompatibileTest parseTestcase(XMLStreamReader in) throws Exception {

    final String testName = findAttributeValue(in, "name");
    final String className = findAttributeValue(in, "classname");

    TestStatus status = TestStatus.PASSED;

    String failureOutput = "";
    String stdOutput = "";
    String sysErrOutput = "";
    String message = "";
    StringBuilder errOutput = new StringBuilder();

    while (in.hasNext()) {
        int event = in.next();
        if (event == START_ELEMENT && FAILURE.equals(in.getLocalName())) {
            final String lEmessage = findAttributeValue(in, "message");
            if (lEmessage != null) {
                message = lEmessage;
            }
            failureOutput = captureCharacters(in, FAILURE);
            if (status != TestStatus.ERROR) {
                status = TestStatus.FAILED;
            }
            continue;
        }
        if (event == START_ELEMENT && SYSTEMOUT.equals(in.getLocalName())) {
            stdOutput = captureCharacters(in, SYSTEMOUT);
            continue;
        }
        if (event == START_ELEMENT && SYSTEMERR.equals(in.getLocalName())) {
            sysErrOutput = captureCharacters(in, SYSTEMERR);
            continue;
        }
        if (event == START_ELEMENT && SKIPPED.equals(in.getLocalName())) {
            status = TestStatus.NOT_RUN;
            continue;
        }
        if (event == START_ELEMENT && ERROR.equals(in.getLocalName())) {
            status = TestStatus.ERROR;
            errOutput.append(captureCharacters(in, ERROR)).append('\n');
            continue;
        }
        if (event == END_ELEMENT && TESTCASE.equals(in.getLocalName())) {
            break;
        }
    }

    //order imortant! see revalidateTests
    List<TestOutput> outputs = Arrays.asList(new TestOutput(SYSTEMOUT, stdOutput),
            new TestOutput(SYSTEMERR, sysErrOutput));

    return new JtregBackwardCompatibileTest(className, status, message, outputs, testName, failureOutput,
            errOutput.toString());
}

From source file:com.liferay.portal.util.LocalizationImpl.java

private void _copyNonExempt(XMLStreamReader xmlStreamReader, XMLStreamWriter xmlStreamWriter,
        String exemptLanguageId, String defaultLanguageId, boolean cdata) throws XMLStreamException {

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

        if (event == XMLStreamConstants.START_ELEMENT) {
            String languageId = xmlStreamReader.getAttributeValue(null, _LANGUAGE_ID);

            if (Validator.isNull(languageId)) {
                languageId = defaultLanguageId;
            }//from  w ww  .ja  v a2s. com

            if (!languageId.equals(exemptLanguageId)) {
                xmlStreamWriter.writeStartElement(xmlStreamReader.getLocalName());
                xmlStreamWriter.writeAttribute(_LANGUAGE_ID, languageId);

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

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

                        String text = xmlStreamReader.getText();

                        if (cdata) {
                            xmlStreamWriter.writeCData(text);
                        } else {
                            xmlStreamWriter.writeCharacters(xmlStreamReader.getText());
                        }

                        break;
                    } else if (event == XMLStreamConstants.END_ELEMENT) {
                        break;
                    }
                }

                xmlStreamWriter.writeEndElement();
            }
        } else if (event == XMLStreamConstants.END_DOCUMENT) {
            break;
        }
    }
}

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

private InputTransformer getInputTransformer(InputStream inputStream) {
    XMLStreamReader xmlStreamReader = null;
    try {/*  w w w  .j  av a  2 s .co 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.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Parses the operation response as an entity. Parses the result returned in the
 * specified stream in AtomPub format into a {@link TableResult} containing an entity of the specified class type
 * projected using the specified resolver.
 * //from w w w .jav a  2 s  .c  o m
 * @param xmlr
 *            An <code>XMLStreamReader</code> on the input stream.
 * @param clazzType
 *            The class type <code>T</code> implementing {@link TableEntity} for the entity returned. Set to
 *            <code>null</code> to ignore the returned entity and copy only response properties into the
 *            {@link TableResult} object.
 * @param resolver
 *            An {@link EntityResolver} instance to project the entity into an instance of type <code>R</code>. Set
 *            to <code>null</code> to return the entity as an instance of the class type <code>T</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @return
 *         A {@link TableResult} containing the parsed entity result of the operation.
 * 
 * @throws XMLStreamException
 *             if an error occurs while accessing the stream.
 * @throws ParseException
 *             if an error occurs while parsing the stream.
 * @throws InstantiationException
 *             if an error occurs while constructing the result.
 * @throws IllegalAccessException
 *             if an error occurs in reflection while parsing the result.
 * @throws StorageException
 *             if a storage service error occurs.
 */
private static <T extends TableEntity, R> TableResult parseAtomEntity(final XMLStreamReader xmlr,
        final Class<T> clazzType, final EntityResolver<R> resolver, final OperationContext opContext)
        throws XMLStreamException, ParseException, InstantiationException, IllegalAccessException,
        StorageException {
    int eventType = xmlr.getEventType();
    final TableResult res = new TableResult();

    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.ENTRY);

    String etag = StringEscapeUtils.unescapeHtml4(
            xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.ETAG));

    res.setEtag(etag);

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

        final String name = xmlr.getName().toString();

        if (eventType == XMLStreamConstants.START_ELEMENT) {
            if (name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.ID)) {
                Utility.readElementFromXMLReader(xmlr, ODataConstants.ID);
            } else if (name
                    .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) {
                // Do read properties
                if (resolver == null && clazzType == null) {
                    return res;
                } else {
                    res.setProperties(readAtomProperties(xmlr, opContext));
                    break;
                }
            }
        }
    }

    // Move to end Content
    eventType = xmlr.next();
    if (eventType == XMLStreamConstants.CHARACTERS) {
        eventType = xmlr.next();
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.CONTENT);

    eventType = xmlr.next();
    if (eventType == XMLStreamConstants.CHARACTERS) {
        eventType = xmlr.next();
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.ENTRY);

    String rowKey = null;
    String partitionKey = null;
    Date timestamp = null;

    // Remove core properties from map and set individually
    EntityProperty tempProp = res.getProperties().remove(TableConstants.PARTITION_KEY);
    if (tempProp != null) {
        partitionKey = tempProp.getValueAsString();
    }

    tempProp = res.getProperties().remove(TableConstants.ROW_KEY);
    if (tempProp != null) {
        rowKey = tempProp.getValueAsString();
    }

    tempProp = res.getProperties().remove(TableConstants.TIMESTAMP);
    if (tempProp != null) {
        timestamp = tempProp.getValueAsDate();
    }

    if (resolver != null) {
        // Call resolver
        res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag()));
    } else if (clazzType != null) {
        // Generate new entity and return
        final T entity = clazzType.newInstance();
        entity.setEtag(res.getEtag());

        entity.setPartitionKey(partitionKey);
        entity.setRowKey(rowKey);
        entity.setTimestamp(timestamp);

        entity.readEntity(res.getProperties(), opContext);

        res.setResult(entity);
    }

    return res;
}

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