Example usage for javax.xml.stream XMLEventReader nextEvent

List of usage examples for javax.xml.stream XMLEventReader nextEvent

Introduction

In this page you can find the example usage for javax.xml.stream XMLEventReader nextEvent.

Prototype

public XMLEvent nextEvent() throws XMLStreamException;

Source Link

Document

Gets the next XMLEvent.

Usage

From source file:edu.unc.lib.dl.services.TripleStoreManagerMulgaraImpl.java

/**
 * @param query/*w  w w  . j  a va2  s.co  m*/
 *           an ITQL command
 * @return the message returned by Mulgara
 * @throws RemoteException
 *            for communication failure
 */
public String storeCommand(String query) {
    String result = null;
    String response = this.sendTQL(query);
    if (response != null) {
        StringReader sr = new StringReader(response);
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        XMLEventReader r = null;
        try {
            boolean inMessage = false;
            StringBuffer message = new StringBuffer();
            r = factory.createXMLEventReader(sr);
            while (r.hasNext()) {
                XMLEvent e = r.nextEvent();
                if (e.isStartElement()) {
                    StartElement s = e.asStartElement();
                    if ("message".equals(s.getName().getLocalPart())) {
                        inMessage = true;
                    }
                } else if (e.isEndElement()) {
                    EndElement end = e.asEndElement();
                    if ("message".equals(end.getName().getLocalPart())) {
                        inMessage = false;
                    }
                } else if (inMessage && e.isCharacters()) {
                    message.append(e.asCharacters().getData());
                }
            }
            result = message.toString();
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } finally {
            if (r != null) {
                try {
                    r.close();
                } catch (Exception ignored) {
                    log.error(ignored);
                }
            }

        }
        sr.close();
    }
    return result;
}

From source file:jenkins.plugins.livingdoc.XmlReportReader.java

public XmlReportReader parse(FilePath fileReport) throws IOException {

    this.name = getFilenameWithoutExtension(fileReport);

    InputStreamReader fileReader = null;
    XMLEventReader xmlEventReader = null;

    try {//  w  ww .  j  ava  2s .c o  m
        fileReader = new InputStreamReader(new FileInputStream(new File(fileReport.toURI())),
                Charset.forName("UTF-8"));
        xmlEventReader = XIF.createXMLEventReader(fileReader);

        while (xmlEventReader.hasNext()) {
            final XMLEvent event = xmlEventReader.nextEvent();

            if (event.isStartElement()) {
                final String localPart = event.asStartElement().getName().getLocalPart();

                if (localPart.equals("external-link")) {
                    this.externalLink = readString(xmlEventReader.nextEvent());
                    continue;
                }

                if (localPart.equals("success")) {
                    int success = readInteger(xmlEventReader.nextEvent());
                    this.statistics.setSuccess(success);
                    continue;
                }

                if (localPart.equals("failure")) {
                    int failure = readInteger(xmlEventReader.nextEvent());
                    this.statistics.setFailure(failure);
                    continue;
                }

                if (localPart.equals("error")) {
                    int error = readInteger(xmlEventReader.nextEvent());
                    this.statistics.setError(error);
                    continue;
                }

                if (localPart.equals("ignored")) {
                    int ignored = readInteger(xmlEventReader.nextEvent());
                    this.statistics.setIgnored(ignored);
                    continue;
                }

                if (localPart.equals("total")) {
                    int total = readInteger(xmlEventReader.nextEvent());
                    this.timeStatistics.setTotal(total);
                    continue;
                }

                if (localPart.equals("execution")) {
                    int execution = readInteger(xmlEventReader.nextEvent());
                    this.timeStatistics.setExecution(execution);
                    continue;
                }

                if (localPart.equals("results")) {
                    this.results = readString(xmlEventReader.nextEvent());
                }

                if (localPart.equals("global-exception")) {
                    this.globalException = readString(xmlEventReader.nextEvent());
                }
            }
        }
    } catch (XMLStreamException | InterruptedException ex) {
        throw new IOException(String.format("Cannot read xml report file %s", fileReport), ex);
    } finally {
        IOUtils.closeQuietly(fileReader);
        closeQuietly(xmlEventReader);
    }

    return this;
}

From source file:HTTPChunkLocator.java

/**
 * parses a chunk info part/*from   w  w  w . ja v  a2 s  . c o m*/
 * <p/>
 * <pre>
 *  <chunk_list>
 *    <chunk offset="0" chunk_size="67108864">
 *      <map>
 *        <copy ip_addr="10.10.2.200" name="vistasn1" snid="1" vid="1" />
 *        <copy ip_addr="10.10.2.201" name="vistasn2" snid="2" vid="3" />
 *     </map>
 *    </chunk>
 *  </chunk_list>
 * </pre>
 */
private List<ChunkLocation> parseChunks(final XMLEventReader reader, final long fileSizeInBytes)
        throws XMLStreamException, IOException {
    long offset = -1;
    long length = -1;
    final List<ChunkLocation> locations = new ArrayList<ChunkLocation>(5);
    final List<StorageNodeInfo> sninfo = new ArrayList<StorageNodeInfo>();
    final List<Integer> volumeIds = new ArrayList<Integer>();
    while (reader.hasNext()) {
        final XMLEvent nextEvent = reader.nextEvent();
        if (!(nextEvent instanceof StartElement)) {
            continue;
        }
        final StartElement start = (StartElement) nextEvent;
        if (CHUNK_ID.equals(start.getName().getLocalPart())) {
            if (sninfo.size() > 0) {
                final ChunkInfo chunkInfo = new ChunkInfo(offset, length, volumeIds.toArray(new Integer[0]));
                locations.add(
                        new ChunkLocation(sninfo.toArray(new StorageNodeInfo[0]), chunkInfo, fileSizeInBytes));
                sninfo.clear();
                volumeIds.clear();
            }
            offset = Long.parseLong(get(start, Q_OFFSET));
            length = Long.parseLong(get(start, Q_CHUNK_SIZE));

        } else if (COPY_ID.equals(start.getName().getLocalPart())) {
            final InetAddress ip = InetAddress.getByName(get(start, Q_IP_ADDR));
            final int vid = Integer.parseInt(get(start, Q_VID));
            final String name = get(start, Q_NAME);
            sninfo.add(new StorageNodeInfo(name, ip.getHostAddress(), true, true));
            volumeIds.add(Integer.valueOf(vid));

        }
    }
    if (sninfo.size() > 0) {
        final ChunkInfo chunkInfo = new ChunkInfo(offset, length, volumeIds.toArray(new Integer[0]));
        locations.add(new ChunkLocation(sninfo.toArray(new StorageNodeInfo[0]), chunkInfo, fileSizeInBytes));
    }
    return locations;
}

From source file:edu.jhu.hlt.concrete.ingesters.bolt.BoltForumPostIngester.java

private int handleLink(final XMLEventReader rdr) throws XMLStreamException {
    // Links have a start element, characters, and end element.
    // Alternatively, they have a start and end element.
    XMLEvent linkContent = rdr.nextEvent();
    if (linkContent.isEndElement())
        return linkContent.getLocation().getCharacterOffset();
    else if (linkContent.isCharacters())
        // Skip end of link.
        return rdr.nextEvent().getLocation().getCharacterOffset();
    else//from  ww w .  j  av a 2 s.  c o m
        throw new RuntimeException("Characters did not follow link.");
}

From source file:edu.jhu.hlt.concrete.ingesters.webposts.WebPostIngester.java

private Section handleBeginning(final XMLEventReader rdr, final String content, final Communication cptr)
        throws XMLStreamException, ConcreteException {
    // The first type is always a document start event. Skip it.
    rdr.nextEvent();

    // The second type is a document block. Skip it.
    rdr.nextEvent();//from   w w  w . j  av  a2  s .  c  o m

    // The third type is a whitespace block. Skip it.
    rdr.nextEvent();

    // The next type is a docid start tag.
    rdr.nextEvent();

    // Text of the docid.
    Characters cc = rdr.nextEvent().asCharacters();
    String idTxt = cc.getData().trim();
    cptr.setId(idTxt);

    // The next part is the docid end element. Skip.
    rdr.nextEvent();

    // Whitespace. Skip.
    rdr.nextEvent();

    // Reader is now pointing at the doctype.
    // XMLEvent doctypeStart = rdr.nextEvent();
    rdr.nextEvent();
    // StartElement dtse = doctypeStart.asStartElement();

    // Doc type content.
    Characters docTypeChars = rdr.nextEvent().asCharacters();
    String docTypeContent = docTypeChars.getData().trim();
    cptr.setType(docTypeContent);

    // Doctype end. Skip.
    rdr.nextEvent();
    // Whitespace. skip.
    rdr.nextEvent();
    // Datetime start.
    rdr.nextEvent();

    // Datetime value.
    Characters dtChars = rdr.nextEvent().asCharacters();
    // TODO: parse this

    String dtValue = dtChars.getData().trim();

    DateTime dt = this.dtf.parseDateTime(dtValue).toDateTime(DateTimeZone.UTC);
    LOGGER.debug("Got DateTime: {}", dt.toString());
    long millis = dt.getMillis();
    cptr.setStartTime(millis / 1000);

    // Datetime end.
    rdr.nextEvent();
    // WS
    rdr.nextEvent();
    // Body begin.
    rdr.nextEvent();
    // WS
    rdr.nextEvent();

    // Headline begin.
    XMLEvent hl = rdr.nextEvent();
    StartElement hlse = hl.asStartElement();
    QName hlqn = hlse.getName();
    final String hlPart = hlqn.getLocalPart();
    LOGGER.debug("QN: {}", hlPart);

    // Headline text.
    Characters hlChars = rdr.nextEvent().asCharacters();
    final int charOff = hlChars.getLocation().getCharacterOffset();
    final int clen = hlChars.getData().length();

    // Construct section, text span, etc.
    final int endTextOffset = charOff + clen;
    final String hlText = content.substring(charOff, endTextOffset);

    SimpleImmutableEntry<Integer, Integer> pads = trimSpacing(hlText);
    TextSpan ts = new TextSpan(charOff + pads.getKey(), endTextOffset - pads.getValue());

    Section s = new Section();
    s.setKind("headline");
    s.setTextSpan(ts);
    List<Integer> intList = new ArrayList<>();
    intList.add(0);
    s.setNumberList(intList);
    return s;
}

From source file:fr.openwide.talendalfresco.rest.client.importer.RestImportFileTest.java

public void login() {
    // create client and configure it
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

    // instantiating a new method and configuring it
    GetMethod method = new GetMethod(restCommandUrlPrefix + "login");
    method.setFollowRedirects(true); // ?
    // Provide custom retry handler is necessary (?)
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] params = new NameValuePair[] { new NameValuePair("username", "admin"),
            new NameValuePair("password", "admin") };
    method.setQueryString(params);//from  ww w. j a  v  a  2s.c om

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody)); // TODO rm

        HashSet<String> defaultElementSet = new HashSet<String>(
                Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE,
                        RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE }));
        HashMap<String, String> elementValueMap = new HashMap<String, String>(6);

        try {
            XMLEventReader xmlReader = XmlHelper.getXMLInputFactory()
                    .createXMLEventReader(new ByteArrayInputStream(responseBody));
            StringBuffer singleLevelTextBuf = null;
            while (xmlReader.hasNext()) {
                XMLEvent event = xmlReader.nextEvent();
                switch (event.getEventType()) {
                case XMLEvent.CHARACTERS:
                case XMLEvent.CDATA:
                    if (singleLevelTextBuf != null) {
                        singleLevelTextBuf.append(event.asCharacters().getData());
                    } // else element not meaningful
                    break;
                case XMLEvent.START_ELEMENT:
                    StartElement startElement = event.asStartElement();
                    String elementName = startElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)
                            // TODO another command specific level
                            || "ticket".equals(elementName)) {
                        // reinit buffer at start of meaningful elements
                        singleLevelTextBuf = new StringBuffer();
                    } else {
                        singleLevelTextBuf = null; // not useful
                    }
                    break;
                case XMLEvent.END_ELEMENT:
                    if (singleLevelTextBuf == null) {
                        break; // element not meaningful
                    }

                    // TODO or merely put it in the map since the element has been tested at start
                    EndElement endElement = event.asEndElement();
                    elementName = endElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)) {
                        String value = singleLevelTextBuf.toString();
                        elementValueMap.put(elementName, value);
                        // TODO test if it is code and it is not OK, break to error handling
                    }
                    // TODO another command specific level
                    else if ("ticket".equals(elementName)) {
                        ticket = singleLevelTextBuf.toString();
                    }
                    // singleLevelTextBuf = new StringBuffer(); // no ! in start
                    break;
                }
            }
        } catch (XMLStreamException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Throwable t) {
            // TODO Auto-generated catch block
            t.printStackTrace();
            //throw t;
        }

        String code = elementValueMap.get(RestConstants.TAG_CODE);
        assertTrue(RestConstants.CODE_OK.equals(code));
        System.out.println("got ticket " + ticket);

    } catch (HttpException e) {
        // TODO
        e.printStackTrace();
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:fr.openwide.talendalfresco.rest.client.importer.RestImportFileTest.java

public void testSingleFileImport() {
    // create client and configure it
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

    // instantiating a new method and configuring it
    PostMethod method = new PostMethod(restCommandUrlPrefix + "import");
    // Provide custom retry handler is necessary (?)
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] params = new NameValuePair[] { new NameValuePair("path", "/app:company_home"),
            new NameValuePair("ticket", ticket) };
    method.setQueryString(params);/*w  w w  . java 2 s.c  om*/

    try {
        //method.setRequestBody(new NameValuePair[] {
        //      new NameValuePair("path", "/app:company_home") });
        FileInputStream acpXmlIs = new FileInputStream(SAMPLE_SINGLE_FILE_PATH);
        InputStreamRequestEntity entity = new InputStreamRequestEntity(acpXmlIs);
        //InputStreamRequestEntity entity = new InputStreamRequestEntity(acpXmlIs, "text/xml; charset=ISO-8859-1");
        method.setRequestEntity(entity);
    } catch (IOException ioex) {
        fail("ACP XML file not found " + ioex.getMessage());
    }

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody)); // TODO rm

        HashSet<String> defaultElementSet = new HashSet<String>(
                Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE,
                        RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE }));
        HashMap<String, String> elementValueMap = new HashMap<String, String>(6);

        try {
            XMLEventReader xmlReader = XmlHelper.getXMLInputFactory()
                    .createXMLEventReader(new ByteArrayInputStream(responseBody));
            StringBuffer singleLevelTextBuf = null;
            while (xmlReader.hasNext()) {
                XMLEvent event = xmlReader.nextEvent();
                switch (event.getEventType()) {
                case XMLEvent.CHARACTERS:
                case XMLEvent.CDATA:
                    if (singleLevelTextBuf != null) {
                        singleLevelTextBuf.append(event.asCharacters().getData());
                    } // else element not meaningful
                    break;
                case XMLEvent.START_ELEMENT:
                    StartElement startElement = event.asStartElement();
                    String elementName = startElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)
                            // TODO another command specific level
                            || "ticket".equals(elementName)) {
                        // reinit buffer at start of meaningful elements
                        singleLevelTextBuf = new StringBuffer();
                    } else {
                        singleLevelTextBuf = null; // not useful
                    }
                    break;
                case XMLEvent.END_ELEMENT:
                    if (singleLevelTextBuf == null) {
                        break; // element not meaningful
                    }

                    // TODO or merely put it in the map since the element has been tested at start
                    EndElement endElement = event.asEndElement();
                    elementName = endElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)) {
                        String value = singleLevelTextBuf.toString();
                        elementValueMap.put(elementName, value);
                        // TODO test if it is code and it is not OK, break to error handling
                    }
                    // TODO another command specific level
                    else if ("ticket".equals(elementName)) {
                        ticket = singleLevelTextBuf.toString();
                    }
                    // singleLevelTextBuf = new StringBuffer(); // no ! in start
                    break;
                }
            }
        } catch (XMLStreamException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Throwable t) {
            // TODO Auto-generated catch block
            t.printStackTrace();
            //throw t;
        }

        String code = elementValueMap.get(RestConstants.TAG_CODE);
        assertTrue(RestConstants.CODE_OK.equals(code));
        System.out.println("got ticket " + ticket);

    } catch (HttpException e) {
        // TODO
        e.printStackTrace();
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:sapience.injectors.stax.inject.ModelBasedStaxStreamInjector.java

/**
 * The actual injection procedure//from ww  w. j  a va2  s  . c  o m
 * @param in the input stream where the XML is coming from (will be closed in the end) 
 * @param out the output stream where we write the annotated XML into (remains open)
 * @param refs a list of references
 * @throws IOException
 */
public void inject(InputStream in, OutputStream out, List<Reference> refs) throws IOException {
    StringBuilder pb;
    XPathElement characters = null;
    int marked;
    interceptingElements = new ArrayList<Reference>();

    try {
        XMLEventReader r = getXMLInputFactory().createXMLEventReader(in);
        XMLEventWriter w = getXMLOutputFactory().createXMLEventWriter(out);

        while (r.hasNext()) {

            XMLEvent e = r.nextEvent();
            switch (e.getEventType()) {

            case XMLEvent.START_ELEMENT:
                StartElement se = (StartElement) e;
                if (super.getNamespaceContext() == null) {
                    super.updateNamespaceContext(se.getNamespaceContext());
                }

                if (references == null) {
                    // process the namespaces in the references
                    references = this.prepareReferences(refs);
                }
                // store location
                col = e.getLocation().getColumnNumber();

                // add to current xpath            
                updateCurrentPath(getGenerator().asXPathElement((StartElement) e));

                System.out.println(getCurrentPath());
                // check if the current xpath is in our list of attribute references
                for (XPathPattern p : references.keySet()) {
                    if (references.get(p) == null)
                        continue;

                    if (p.isAttribute()) {
                        if (getMatcher().matches(p, getCurrentPath())) {
                            se = this.handleAttribute(w, references.get(p), se);
                            references.put(p, null); // removing it would lead to concurrentmodificationexcpetion
                        }
                    }
                }

                w.add(se);
                break;
            case XMLEvent.END_ELEMENT:
                updateCurrentPath(characters);

                // before removing from stack, we check if the current path with added characters is a match (which means we have to add a new element now)
                XPathStack currentPath = getCurrentPath();

                for (XPathPattern p : references.keySet()) {

                    if (references.get(p) == null)
                        continue;

                    if (getMatcher().matches(p, currentPath)) {
                        if (p.isSiblingElement()) {
                            // injection happens below
                            this.interceptingElements.add(references.get(p));

                        } else if (p.isChildElement()) {
                            // we can add it directly
                            w.add(getXMLEventFactory().createSpace("\n"));
                            writeElementIntoStream(w, references.get(p));
                        } else {
                            throw new IOException("Invalid Reference: " + p);
                        }
                        references.put(p, null); // removing it would lead to concurrentmodificationexcpetion
                        //references.remove(p);
                        //break; //otherwise ConcurrentModificationException

                    }

                }

                // clean up
                if (characters != null) {
                    getCurrentPath().pop();
                    characters = null;
                }

                getCurrentPath().pop();
                w.add(e); // do not change position

                // if the intercepting is not null, the preceding element was a match, hence we inject some xml before writing a new element
                if (this.interceptingElements.size() > 0) {
                    // write all references into stream
                    for (Reference ref : this.interceptingElements) {
                        w.add(getXMLEventFactory().createSpace("\n"));
                        writeElementIntoStream(w, ref);
                    }

                    // reset list
                    this.interceptingElements.clear();
                }

                break;
            case XMLEvent.CHARACTERS:
                characters = getGenerator().asXPathElement((Characters) e);
                w.add(e);
                break;

            default:
                w.add(e);
                break;
            }
        }
    } catch (XPathExpressionException e) {
        if (logger.isLoggable(Level.SEVERE)) {
            logger.log(Level.SEVERE, "Not a valid XPath", e);
        }
        throw new IOException(e);

    } catch (XMLStreamException e) {
        if (logger.isLoggable(Level.SEVERE)) {
            logger.log(Level.SEVERE, "Failed to inject. Reason: " + e.getLocalizedMessage(), e);
        }
        throw new IOException(e);
    } finally {
        in.close();
    }

}

From source file:eu.delving.sip.base.Harvestor.java

private String saveRecords(HttpEntity fetchedRecords, XMLEventWriter out)
        throws IOException, XMLStreamException {
    InputStream inputStream = fetchedRecords.getContent();
    XMLEventReader in = inputFactory.createXMLEventReader(new StreamSource(inputStream, "UTF-8"));
    Path path = Path.create();
    StringBuilder tokenBuilder = null;
    StringBuilder errorBuilder = null;
    String tokenValue = null;//  w  w  w. j  ava 2 s. c  o m
    List<XMLEvent> recordEvents = new ArrayList<XMLEvent>();
    boolean finished = false;
    while (!finished) {
        XMLEvent event = in.nextEvent();
        switch (event.getEventType()) {
        case XMLEvent.START_ELEMENT:
            StartElement start = event.asStartElement();
            path = path.child(Tag.element(start.getName().getLocalPart()));
            if (!recordEvents.isEmpty()) {
                recordEvents.add(event);
            } else if (path.equals(RECORD_ROOT)) {
                if (namespaceCollector != null) {
                    namespaceCollector.gatherFrom(start);
                    out.add(eventFactory.createStartElement("", "", HARVEST_TAG, null,
                            namespaceCollector.iterator()));
                    out.add(eventFactory.createCharacters("\n"));
                    namespaceCollector = null;
                }
                recordEvents.add(eventFactory.createCharacters("\n")); // flag that record has started
            } else if (path.equals(RESUMPTION_TOKEN)) {
                tokenBuilder = new StringBuilder();
                tokenValue = null;
            } else if (path.equals(ERROR)) {
                errorBuilder = new StringBuilder();
            } else if (namespaceCollector != null) {
                namespaceCollector.gatherFrom(start);
            }
            break;
        case XMLEvent.END_ELEMENT:
            if (!recordEvents.isEmpty()) {
                if (path.equals(RECORD_ROOT)) {
                    out.add(eventFactory.createStartElement("", "", RECORD_TAG, null, null));
                    for (XMLEvent saved : recordEvents) {
                        out.add(saved);
                    }
                    out.add(eventFactory.createEndElement("", "", RECORD_TAG));
                    out.add(eventFactory.createCharacters("\n"));
                    recordEvents.clear();
                    tokenBuilder = null;
                    recordCount++;
                } else {
                    recordEvents.add(event);
                    recordEvents.add(eventFactory.createCharacters("\n"));
                }
            } else if (path.equals(RESUMPTION_TOKEN) && tokenBuilder != null) {
                tokenValue = tokenBuilder.toString();
                tokenBuilder = null;
            } else if (path.equals(ERROR) && errorBuilder != null) {
                throw new IOException("OAI-PMH Error: " + errorBuilder);
            }
            path = path.parent();
            break;
        case XMLEvent.END_DOCUMENT:
            finished = true;
            break;
        case XMLEvent.CHARACTERS:
        case XMLEvent.CDATA:
            if (!recordEvents.isEmpty()) {
                String string = event.asCharacters().getData().trim();
                if (!string.isEmpty()) {
                    recordEvents.add(eventFactory.createCharacters(string));
                }
            } else if (tokenBuilder != null) {
                tokenBuilder.append(event.asCharacters().getData());
            } else if (errorBuilder != null) {
                errorBuilder.append(event.asCharacters().getData());
            }
            break;
        default:
            if (!recordEvents.isEmpty()) {
                recordEvents.add(event);
            }
            break;
        }
    }
    return tokenValue;
}

From source file:com.aionengine.gameserver.dataholders.loadingutils.XmlMerger.java

/**
 * Read all {@link javax.xml.stream.events.XMLEvent}'s from specified file and write them onto the {@link javax.xml.stream.XMLEventWriter}
 *
 * @param file     File to import/*from w  w  w .  j av a 2 s . c  o  m*/
 * @param skipRoot Skip-root flag
 * @param writer   Destenation writer
 * @throws XMLStreamException    On event reading/writing error.
 * @throws FileNotFoundException if the reading file does not exist,
 *                               is a directory rather than a regular file,
 *                               or for some other reason cannot be opened for
 *                               reading.
 */
private void importFile(File file, boolean skipRoot, XMLEventWriter writer, Properties metadata)
        throws XMLStreamException, IOException {
    logger.debug("Appending file " + file);
    metadata.setProperty(file.getPath(), makeHash(file));

    XMLEventReader reader = null;

    try {
        reader = inputFactory.createXMLEventReader(new FileReader(file));

        QName firstTagQName = null;

        while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();

            // skip start and end of document.
            if (event.isStartDocument() || event.isEndDocument())
                continue;
            // skip all comments.
            if (event instanceof Comment)
                continue;
            // skip white-spaces and all ignoreable white-spaces.
            if (event.isCharacters()) {
                if (event.asCharacters().isWhiteSpace() || event.asCharacters().isIgnorableWhiteSpace())
                    continue;
            }

            // modify root-tag of imported file.
            if (firstTagQName == null && event.isStartElement()) {
                firstTagQName = event.asStartElement().getName();

                if (skipRoot) {
                    continue;
                } else {
                    StartElement old = event.asStartElement();

                    event = eventFactory.createStartElement(old.getName(), old.getAttributes(), null);
                }
            }

            // if root was skipped - skip root end too.
            if (event.isEndElement() && skipRoot && event.asEndElement().getName().equals(firstTagQName))
                continue;

            // finally - write tag
            writer.add(event);
        }
    } finally {
        if (reader != null)
            try {
                reader.close();
            } catch (Exception ignored) {
            }
    }
}