Example usage for javax.xml.stream XMLEventWriter flush

List of usage examples for javax.xml.stream XMLEventWriter flush

Introduction

In this page you can find the example usage for javax.xml.stream XMLEventWriter flush.

Prototype

public void flush() throws XMLStreamException;

Source Link

Document

Writes any cached events to the underlying output mechanism

Usage

From source file:Main.java

/**
 * //  w  ww .java 2  s.com
 * @param is
 * @param os
 * @param elementNames
 * @throws XMLStreamException
 * @throws FactoryConfigurationError
 * @throws UnsupportedEncodingException
 */
public static void stripElements(final InputStream is, final OutputStream os,
        final Collection<String> elementNames)
        throws XMLStreamException, UnsupportedEncodingException, FactoryConfigurationError {
    final XMLEventReader xmlEventReader = XMLInputFactory.newInstance()
            .createXMLEventReader(new InputStreamReader(is, Charset.defaultCharset().name()));
    final XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance().createXMLEventWriter(os);

    String elementName = null;

    while (xmlEventReader.peek() != null) {
        final XMLEvent event = (XMLEvent) xmlEventReader.next();

        switch (event.getEventType()) {
        case XMLStreamConstants.START_DOCUMENT:
        case XMLStreamConstants.END_DOCUMENT: {
            // Ignore.
            break;
        }
        case XMLStreamConstants.START_ELEMENT: {
            final StartElement startElement = event.asStartElement();
            final QName name = startElement.getName();

            if (elementNames.contains(name.getLocalPart())) {
                elementName = name.getLocalPart();
            }

            if (elementName == null) {
                xmlEventWriter.add(event);
            }

            break;
        }
        case XMLStreamConstants.END_ELEMENT: {
            final EndElement endElement = event.asEndElement();
            final QName name = endElement.getName();

            if (elementName == null) {
                xmlEventWriter.add(event);
            } else if (elementName.equals(name.getLocalPart())) {
                elementName = null;
            }

            break;
        }
        default: {
            if (elementName == null) {
                xmlEventWriter.add(event);
            }
        }
        }
    }

    xmlEventWriter.flush();
}

From source file:Main.java

/**
 * //from w ww .  jav  a2s  .  c  o m
 * @param elementName
 * @param is
 * @param onlyValues
 * @return Collection
 * @throws XMLStreamException
 * @throws UnsupportedEncodingException
 */
public static Collection<String> getElements(final String elementName, final InputStream is,
        final boolean onlyValues) throws XMLStreamException, UnsupportedEncodingException {
    final Collection<String> elements = new ArrayList<>();
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    final XMLEventReader reader = XMLInputFactory.newInstance()
            .createXMLEventReader(new InputStreamReader(is, Charset.defaultCharset().name()));
    final XMLEventWriter writer = XMLOutputFactory.newInstance()
            .createXMLEventWriter(new OutputStreamWriter(os, Charset.defaultCharset().name()));
    boolean read = false;
    String characters = null;

    while (reader.peek() != null) {
        final XMLEvent event = (XMLEvent) reader.next();

        switch (event.getEventType()) {
        case XMLStreamConstants.START_DOCUMENT:
        case XMLStreamConstants.END_DOCUMENT: {
            // Ignore.
            break;
        }
        case XMLStreamConstants.START_ELEMENT: {
            read = read || elementName.equals(event.asStartElement().getName().getLocalPart());

            if (read && !onlyValues) {
                writer.add(event);
            }

            break;
        }
        case XMLStreamConstants.ATTRIBUTE: {
            if (read && !onlyValues) {
                writer.add(event);
            }
            break;
        }
        case XMLStreamConstants.CHARACTERS: {
            if (read && !onlyValues) {
                writer.add(event);
            }
            characters = event.asCharacters().getData();
            break;
        }
        case XMLStreamConstants.END_ELEMENT: {
            if (read && !onlyValues) {
                writer.add(event);
            }
            if (elementName.equals(event.asEndElement().getName().getLocalPart())) {
                writer.flush();

                if (characters != null) {
                    elements.add(characters);
                }

                os.reset();
                read = false;
            }
            break;
        }
        default: {
            // Ignore
            break;
        }
        }
    }

    return elements;
}

From source file:log4JToXml.xmlToProperties.XmlToLog4jConverterImpl.java

private void addDTDDeclaration(String filename) throws XMLStreamException {
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent dtd = eventFactory//  ww w . ja  va2  s  .c  om
            .createDTD("<!DOCTYPE log4j:configuration SYSTEM \"" + tempDTD.getAbsolutePath() + "\">");

    XMLInputFactory inFactory = XMLInputFactory.newInstance();
    XMLOutputFactory outFactory = XMLOutputFactory.newInstance();

    XMLEventReader reader = inFactory.createXMLEventReader(new StreamSource(filename));
    reader = new DTDReplacer(reader, dtd);
    XMLEventWriter writer = outFactory.createXMLEventWriter(documentStream);
    writer.add(reader);
    writer.flush();

    writer.close();
}

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

@Override
public void run() {
    try {//from   w  w  w  .  j  a v a2 s .c  o m
        if (context.harvestPrefix() == null || context.harvestPrefix().trim().isEmpty()) {
            throw new IllegalArgumentException("Harvest prefix missing");
        }
        new URL(context.harvestUrl()); // throws MalformedUrlException if it is
        OutputStream outputStream = new GZIPOutputStream(new FileOutputStream(dataSet.importedOutput()));
        XMLEventWriter out = outputFactory.createXMLEventWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        out.add(eventFactory.createStartDocument());
        out.add(eventFactory.createCharacters("\n"));
        progressListener.setProgress(recordCount);
        HttpEntity fetchedRecords = fetchFirstEntity();
        String resumptionToken = saveRecords(fetchedRecords, out);
        while (isValidResumptionToken(resumptionToken) && recordCount > 0) {
            EntityUtils.consume(fetchedRecords);
            progressListener.setProgress(recordCount);
            fetchedRecords = fetchNextEntity(resumptionToken);
            resumptionToken = saveRecords(fetchedRecords, out);
            if (!isValidResumptionToken(resumptionToken) && recordCount > 0)
                EntityUtils.consume(fetchedRecords);
        }
        out.add(eventFactory.createEndElement("", "", ENVELOPE_TAG));
        out.add(eventFactory.createCharacters("\n"));
        out.add(eventFactory.createEndDocument());
        out.flush();
        outputStream.close();
    } catch (CancelException e) {
        progressListener.getFeedback().alert("Cancelled harvest of " + context.harvestUrl(), e);
        recordCount = 0;
    } catch (Exception e) {
        progressListener.getFeedback().alert(String.format("Unable to complete harvest of %s because of: %s",
                context.harvestUrl(), e.getMessage()), e);
        recordCount = 0;
    } finally {
        if (recordCount > 0) {
            progressListener.getFeedback().alert(String.format("Harvest of %s successfully fetched %d records",
                    context.harvestUrl(), recordCount));
        } else {
            FileUtils.deleteQuietly(dataSet.importedOutput());
        }
    }
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

@Override
public InputStream setChanges(final InputStream toBeChanged, final Map<String, InputStream> properties)
        throws Exception {
    XMLEventReader reader = getEventReader(toBeChanged);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    XMLEventWriter writer = xof.createXMLEventWriter(bos);

    // ---------------------------------
    // add property changes
    // ---------------------------------
    Map.Entry<Integer, XmlElement> propertyElement = getAtomElement(reader, writer, PROPERTIES, null, 0, 2, 3,
            false);/*from  w w w  .ja v  a2s .c o m*/

    writer.flush();

    ByteArrayOutputStream pbos = new ByteArrayOutputStream();
    OutputStreamWriter pwriter = new OutputStreamWriter(pbos);

    final XMLEventReader propertyReader = propertyElement.getValue().getContentReader();

    try {
        while (true) {
            final XmlElement property = getAtomElement(propertyReader, null, null);
            final String name = property.getStart().getName().getLocalPart();

            if (properties.containsKey(name)) {
                // replace
                final InputStream replacement = properties.get(name);
                properties.remove(property.getStart().getName().getLocalPart());
                pwriter.append(IOUtils.toString(replacement));
                IOUtils.closeQuietly(replacement);
            } else {
                pwriter.append(IOUtils.toString(property.toStream()));
            }
        }
    } catch (Exception ignore) {
        // end
    }

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (!remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(propertyElement.getValue().getStart());
    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    writer.add(propertyElement.getValue().getEnd());

    IOUtils.closeQuietly(pbos);

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    // ---------------------------------
    // add navigationm changes
    // ---------------------------------

    // remove existent links
    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {

        if (remains.getKey().startsWith("[LINK]")) {
            reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

            bos.reset();
            writer = xof.createXMLEventWriter(bos);

            try {
                final String linkName = remains.getKey().substring(remains.getKey().indexOf("]") + 1);

                getAtomElement(reader, writer, LINK, Collections.<Map.Entry<String, String>>singleton(
                        new SimpleEntry<String, String>("title", linkName)), 0, 2, 2, false);

                writer.add(reader);

            } catch (Exception ignore) {
                // ignore
            }

            writer.flush();
            writer.close();
        }
    }

    reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

    bos.reset();
    writer = xof.createXMLEventWriter(bos);

    propertyElement = getAtomElement(reader, writer, CONTENT, null, 0, 2, 2, false);
    writer.flush();

    pbos.reset();
    pwriter = new OutputStreamWriter(pbos);

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    IOUtils.closeQuietly(pbos);

    writer.add(propertyElement.getValue().getStart());
    writer.add(propertyElement.getValue().getContentReader());
    writer.add(propertyElement.getValue().getEnd());

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

public InputStream addAtomInlinecount(final InputStream feed, final int count, final Accept accept)
        throws Exception {
    final XMLEventReader reader = getEventReader(feed);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    final XMLEventWriter writer = xof.createXMLEventWriter(bos);

    try {// w  w w.  j a v  a 2  s  .c om

        final XmlElement feedElement = getAtomElement(reader, writer, "feed");

        writer.add(feedElement.getStart());
        addAtomElement(IOUtils.toInputStream(String.format("<m:count>%d</m:count>", count)), writer);
        writer.add(feedElement.getContentReader());
        writer.add(feedElement.getEnd());

        while (reader.hasNext()) {
            writer.add(reader.nextEvent());
        }

    } finally {
        writer.flush();
        writer.close();
        reader.close();
        IOUtils.closeQuietly(feed);
    }

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:com.predic8.membrane.core.multipart.XOPReconstitutor.java

private byte[] fillInXOPParts(InputStream inputStream, HashMap<String, Part> parts)
        throws XMLStreamException, FactoryConfigurationError {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(baos);

    try {/*from   w  w w  .  jav a  2  s .c o m*/
        XMLEventReader parser = createEventReaderFromStream(inputStream);

        boolean xopIncludeOpen = false;

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

            if (event instanceof StartElement) {
                StartElement start = (StartElement) event;
                if (XOP_NAMESPACE_URI.equals(start.getName().getNamespaceURI())
                        && start.getName().getLocalPart().equals("Include")) {
                    String href = start.getAttributeByName(new QName("href")).getValue();

                    if (href.startsWith("cid:"))
                        href = href.substring(4);

                    Part p = parts.get("<" + href + ">");
                    if (p == null)
                        throw new RuntimeException("Did not find multipart with id " + href);

                    writer.add(p.asXMLEvent());
                    xopIncludeOpen = true;
                    continue;
                }
            } else if (event instanceof EndElement) {
                EndElement start = (EndElement) event;
                if (XOP_NAMESPACE_URI.equals(start.getName().getNamespaceURI())
                        && start.getName().getLocalPart().equals("Include") && xopIncludeOpen) {
                    xopIncludeOpen = false;
                    continue;
                }
            }

            writer.add(event);
        }
        writer.flush();
    } catch (XMLStreamException e) {
        log.warn("Received not-wellformed XML.");
        return null;
    }
    return baos.toByteArray();
}

From source file:com.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java

@Override
protected Collection<Throwable> call(String inputName) throws Exception {

    final CompiledScript compiledScript;
    Unmarshaller unmarshaller;/*from  w  w  w .j  a  va  2  s.c  o  m*/
    Marshaller marshaller;
    try {
        compiledScript = super.compileJavascript();

        JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast");

        unmarshaller = jc.createUnmarshaller();
        marshaller = jc.createMarshaller();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        PrintWriter pw = openFileOrStdoutAsPrintWriter();
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
        XMLEventWriter w = xof.createXMLEventWriter(pw);

        StreamSource src = null;
        if (inputName == null) {
            LOG.info("Reading stdin");
            src = new StreamSource(stdin());
        } else {
            LOG.info("Reading file " + inputName);
            src = new StreamSource(new File(inputName));
        }

        XMLEventReader r = xmlInputFactory.createXMLEventReader(src);

        XMLEventFactory eventFactory = XMLEventFactory.newFactory();

        SimpleBindings bindings = new SimpleBindings();
        while (r.hasNext()) {
            XMLEvent evt = r.peek();
            switch (evt.getEventType()) {
            case XMLEvent.START_ELEMENT: {
                StartElement sE = evt.asStartElement();
                Hit hit = null;
                JAXBElement<Hit> jaxbElement = null;
                if (sE.getName().getLocalPart().equals("Hit")) {
                    jaxbElement = unmarshaller.unmarshal(r, Hit.class);
                    hit = jaxbElement.getValue();
                } else {
                    w.add(r.nextEvent());
                    break;
                }

                if (hit != null) {

                    bindings.put("hit", hit);

                    boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings);

                    if (accept) {
                        marshaller.marshal(jaxbElement, w);
                        w.add(eventFactory.createCharacters("\n"));
                    }
                }

                break;
            }
            case XMLEvent.SPACE:
                break;
            default: {
                w.add(r.nextEvent());
                break;
            }
            }
            r.close();
        }
        w.flush();
        w.close();
        pw.flush();
        pw.close();
        return RETURN_OK;
    } catch (Exception err) {
        return wrapException(err);
    } finally {

    }
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

private InputStream writeFromStartToEndElement(final StartElement element, final XMLEventReader reader,
        final boolean document) throws XMLStreamException {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    final XMLEventWriter writer = xof.createXMLEventWriter(bos);

    final QName name = element.getName();

    if (document) {
        final XMLEventFactory eventFactory = XMLEventFactory.newInstance();
        writer.add(eventFactory.createStartDocument("UTF-8", "1.0"));
        writer.add(element);/*  w ww  .  j  a va  2s.c om*/

        if (element.getAttributeByName(new QName(ATOM_DATASERVICE_NS)) == null) {
            writer.add(eventFactory.createNamespace(ATOM_PROPERTY_PREFIX.substring(0, 1), DATASERVICES_NS));
        }
        if (element.getAttributeByName(new QName(ATOM_METADATA_NS)) == null) {
            writer.add(eventFactory.createNamespace(ATOM_METADATA_PREFIX.substring(0, 1), METADATA_NS));
        }
    } else {
        writer.add(element);
    }

    XMLEvent event = element;

    while (reader.hasNext() && !(event.isEndElement() && name.equals(event.asEndElement().getName()))) {
        event = reader.nextEvent();
        writer.add(event);
    }

    writer.flush();
    writer.close();

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

@Override
protected InputStream replaceLink(final InputStream toBeChanged, final String linkName,
        final InputStream replacement) throws Exception {
    final XMLEventReader reader = getEventReader(toBeChanged);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    final XMLEventWriter writer = xof.createXMLEventWriter(bos);

    final XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent newLine = eventFactory.createSpace("\n");

    try {//from w  ww.  j  av  a 2 s  .c o  m
        final XmlElement linkElement = getAtomElement(reader, writer, LINK,
                Collections.<Map.Entry<String, String>>singletonList(
                        new SimpleEntry<String, String>("title", linkName)));
        writer.add(linkElement.getStart());

        // ------------------------------------------
        // write inline ...
        // ------------------------------------------
        writer.add(newLine);
        writer.add(eventFactory.createStartElement("m", null, "inline"));

        addAtomElement(replacement, writer);

        writer.add(eventFactory.createEndElement("m", null, "inline"));
        writer.add(newLine);
        // ------------------------------------------

        writer.add(linkElement.getEnd());

        writer.add(reader);
        writer.flush();
        writer.close();
    } finally {
        reader.close();
        IOUtils.closeQuietly(toBeChanged);
    }

    return new ByteArrayInputStream(bos.toByteArray());
}