Example usage for javax.xml.stream XMLStreamReader getEventType

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

Introduction

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

Prototype

public int getEventType();

Source Link

Document

Returns an integer code that indicates the type of the event the cursor is pointing to.

Usage

From source file:com.norconex.collector.http.sitemap.impl.StandardSitemapResolver.java

private void parseLocation(InputStream is, HttpClient httpClient, SitemapURLAdder sitemapURLAdder,
        Set<String> resolvedLocations, String location) throws XMLStreamException {

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    inputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
    XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is);
    ParseState parseState = new ParseState();

    String locationDir = StringUtils.substringBeforeLast(location, "/");
    int event = xmlReader.getEventType();
    while (true) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            String tag = xmlReader.getLocalName();
            parseStartElement(parseState, tag);
            break;
        case XMLStreamConstants.CHARACTERS:
            String value = xmlReader.getText();
            if (parseState.sitemapIndex && parseState.loc) {
                resolveLocation(value, httpClient, sitemapURLAdder, resolvedLocations);
                parseState.loc = false;//from  w w w  .  j av a 2 s.  c o m
            } else if (parseState.baseURL != null) {
                parseCharacters(parseState, value);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            tag = xmlReader.getLocalName();
            parseEndElement(sitemapURLAdder, parseState, locationDir, tag);
            break;
        }
        if (!xmlReader.hasNext()) {
            break;
        }
        event = xmlReader.next();
    }
}

From source file:hudson.model.ExternalRun.java

/**
 * Instead of performing a build, accept the log and the return code from a
 * remote machine.//  w ww. j a va2s . c o  m
 *
 * <p> The format of the XML is:
 *
 * <pre><xmp>
 * <run>
 *  <log>...console output...</log>
 *  <result>exit code</result>
 * </run>
 * </xmp></pre>
 */
@SuppressWarnings({ "Since15" })
public void acceptRemoteSubmission(final Reader in) throws IOException {
    final long[] duration = new long[1];
    run(new Runner() {
        private String elementText(XMLStreamReader r) throws XMLStreamException {
            StringBuilder buf = new StringBuilder();
            while (true) {
                int type = r.next();
                if (type == CHARACTERS || type == CDATA) {
                    buf.append(r.getTextCharacters(), r.getTextStart(), r.getTextLength());
                } else {
                    return buf.toString();
                }
            }
        }

        public Result run(BuildListener listener) throws Exception {
            PrintStream logger = null;
            try {
                logger = new PrintStream(new DecodingStream(listener.getLogger()));

                XMLInputFactory xif = XMLInputFactory.newInstance();
                XMLStreamReader p = xif.createXMLStreamReader(in);

                p.nextTag(); // get to the <run>
                p.nextTag(); // get to the <log>

                charset = p.getAttributeValue(null, "content-encoding");
                while (p.next() != END_ELEMENT) {
                    int type = p.getEventType();
                    if (type == CHARACTERS || type == CDATA) {
                        logger.print(p.getText());
                    }
                }
                p.nextTag(); // get to <result>

                Result r = Integer.parseInt(elementText(p)) == 0 ? Result.SUCCESS : Result.FAILURE;

                p.nextTag(); // get to <duration> (optional)
                if (p.getEventType() == START_ELEMENT && p.getLocalName().equals("duration")) {
                    duration[0] = Long.parseLong(elementText(p));
                }

                return r;
            } finally {
                IOUtils.closeQuietly(logger);
            }
        }

        public void post(BuildListener listener) {
            // do nothing
        }

        public void cleanUp(BuildListener listener) {
            // do nothing
        }
    });

    if (duration[0] != 0) {
        super.duration = duration[0];
        // save the updated duration
        save();
    }
}

From source file:com.norconex.collector.http.sitemap.impl.DefaultSitemapResolver.java

private void parseLocation(InputStream is, DefaultHttpClient httpClient, SitemapURLStore sitemapURLStore,
        Set<String> resolvedLocations, String location) throws XMLStreamException {

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    inputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
    XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is);
    ParseState parseState = new ParseState();

    String locationDir = StringUtils.substringBeforeLast(location, "/");
    int event = xmlReader.getEventType();
    while (true) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            String tag = xmlReader.getLocalName();
            parseStartElement(parseState, tag);
            break;
        case XMLStreamConstants.CHARACTERS:
            String value = xmlReader.getText();
            if (parseState.sitemapIndex && parseState.loc) {
                resolveLocation(value, httpClient, sitemapURLStore, resolvedLocations);
                parseState.loc = false;//  w  w  w .j av a  2 s  .  c om
            } else if (parseState.baseURL != null) {
                parseCharacters(parseState, value);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            tag = xmlReader.getLocalName();
            parseEndElement(sitemapURLStore, parseState, locationDir, tag);
            break;
        }
        if (!xmlReader.hasNext()) {
            break;
        }
        event = xmlReader.next();
    }
}

From source file:com.hp.mqm.clt.XmlProcessorTest.java

private void assertXml(List<TestResult> expectedTestResults, Set<XmlElement> expectedElements, File xmlFile)
        throws FileNotFoundException, XMLStreamException {
    FileInputStream fis = new FileInputStream(xmlFile);
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    xmlInputFactory.setProperty("javax.xml.stream.isCoalescing", true);
    XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(fis);

    boolean isFirstEvent = true;
    while (xmlStreamReader.hasNext()) {
        if (!isFirstEvent) {
            xmlStreamReader.next();//from   w w  w . j  ava  2s . c  o m
        } else {
            isFirstEvent = false;
        }

        if (xmlStreamReader.getEventType() == XMLStreamReader.START_ELEMENT) {
            String localName = xmlStreamReader.getLocalName();
            if ("taxonomy".equals(localName)) {
                assertElement(localName, false, xmlStreamReader, expectedElements);
            } else if ("test_field".equals(localName)) {
                assertElement(localName, false, xmlStreamReader, expectedElements);
            } else if ("product_area_ref".equals(localName)) {
                assertElement(localName, true, xmlStreamReader, expectedElements);
            } else if ("backlog_item_ref".equals(localName)) {
                assertElement(localName, true, xmlStreamReader, expectedElements);
            } else if ("release_ref".equals(localName)) {
                assertElement(localName, true, xmlStreamReader, expectedElements);
            } else if ("test_run".equals(localName)) {
                assertXmlTest(xmlStreamReader, expectedTestResults);
            }
        }
    }
    xmlStreamReader.close();
    IOUtils.closeQuietly(fis);
    Assert.assertTrue(expectedElements.isEmpty());
    Assert.assertTrue(expectedTestResults.isEmpty());
}

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

/**
 * This is the constructor of the class.
 * It parses the given XML file./*from w  w  w .  j  a va  2s .  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.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  .  j  a  v a  2 s  . com
 * @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:jp.co.atware.solr.geta.GETAssocComponent.java

/**
 * GETAssoc?????<code>NamedList</code>???????
 * //  w  ww  . j  a v  a 2  s. c o 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.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;/*from w  ww.j av  a 2  s  .  c  om*/

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

/**
 * XMLStAX???EventLogRecord????/*w w w .ja va  2 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:dk.statsbiblioteket.util.xml.XMLStepperTest.java

public void testPipePositionOnIgnoredFail() throws XMLStreamException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    XMLStreamWriter out = xmlOutFactory.createXMLStreamWriter(os);
    XMLStreamReader in = xmlFactory.createXMLStreamReader(new StringReader(SAMPLE));
    assertTrue("The first 'bar' should be findable", XMLStepper.findTagStart(in, "bar"));
    XMLStepper.pipeXML(in, out, false); // until first </bar>
    assertEquals(/*  ww  w  .  jav  a 2  s.c o m*/
            "The reader should be positioned at a character tag (newline) but was positioned at "
                    + XMLUtil.eventID2String(in.getEventType()),
            XMLStreamConstants.CHARACTERS, in.getEventType());
}