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:org.apache.olingo.fit.utils.XMLUtilities.java

@Override
public InputStream selectEntity(final InputStream entity, final String[] propertyNames) throws Exception {
    final XMLEventReader reader = getEventReader(entity);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    final List<String> found = new ArrayList<String>(Arrays.asList(propertyNames));

    boolean inProperties = false;
    boolean writeCurrent = true;
    Boolean writeNext = null;//from w  w w .  j a  v a  2 s  . co m
    String currentName = null;

    final List<String> fieldToBeSaved = new ArrayList<String>(Arrays.asList(propertyNames));

    while (reader.hasNext()) {
        final XMLEvent event = reader.nextEvent();
        if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && Constants.get(ConstantKey.LINK).equals(event.asStartElement().getName().getLocalPart())
                && !fieldToBeSaved
                        .contains(event.asStartElement().getAttributeByName(new QName("title")).getValue())
                && !"edit".equals(event.asStartElement().getAttributeByName(new QName("rel")).getValue())) {
            writeCurrent = false;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && Constants.get(ConstantKey.LINK).equals(event.asEndElement().getName().getLocalPart())) {
            writeNext = true;
        } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && (Constants.get(ConstantKey.PROPERTIES))
                        .equals(event.asStartElement().getName().getLocalPart())) {
            writeCurrent = true;
            writeNext = false;
            inProperties = true;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && (Constants.get(ConstantKey.PROPERTIES))
                        .equals(event.asEndElement().getName().getLocalPart())) {
            writeCurrent = true;
        } else if (inProperties) {
            if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
                final String elementName = event.asStartElement().getName().getLocalPart();

                for (String propertyName : propertyNames) {
                    if ((Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + propertyName.trim())
                            .equals(elementName)) {
                        writeCurrent = true;
                        found.remove(propertyName);
                        currentName = propertyName;
                    }
                }

            } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                    && StringUtils.isNotBlank(currentName)
                    && (Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + currentName.trim())
                            .equals(event.asEndElement().getName().getLocalPart())) {
                writeNext = false;
                currentName = null;
            }

        }

        if (writeCurrent) {
            writer.add(event);
        }

        if (writeNext != null) {
            writeCurrent = writeNext;
            writeNext = null;
        }
    }

    writer.flush();
    writer.close();
    reader.close();
    IOUtils.closeQuietly(entity);

    // Do not raise any exception in order to support FC properties as well
    // if (!found.isEmpty()) {
    // throw new Exception(String.format("Could not find a properties '%s'", found));
    // }
    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:org.apache.olingo.fit.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 XMLEventWriter writer = getEventWriter(bos);

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

    try {//w  w w .  j  a v  a 2s.c  o m
        final XMLElement linkElement = extractElement(reader, writer,
                Collections.<String>singletonList(Constants.get(ConstantKey.LINK)),
                Collections.<Map.Entry<String, String>>singletonList(
                        new SimpleEntry<String, String>("title", linkName)),
                false, 0, -1, -1).getValue();
        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());
}

From source file:org.apache.olingo.fit.utils.XMLUtilities.java

@Override
public InputStream replaceProperty(final InputStream src, final InputStream replacement,
        final List<String> path, final boolean justValue) throws Exception {

    final List<String> pathElements = new ArrayList<String>();

    for (String element : path) {
        pathElements.add(Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + element);
    }//from ww  w. ja v  a 2s . co  m

    final XMLEventReader reader = getEventReader(src);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    final Map.Entry<Integer, XMLElement> element = extractElement(reader, writer, pathElements, 0, 3, 4);

    if (justValue) {
        writer.add(element.getValue().getStart());
    }

    final XMLEventReader changesReader = new XMLEventReaderWrapper(replacement);

    while (changesReader.hasNext()) {
        final XMLEvent event = changesReader.nextEvent();
        if (event.isStartElement()
                && event.asStartElement().getName().equals(element.getValue().getStart().getName())) {
            writer.add(element.getValue().getStart());
            writer.add(changesReader);
        } else {
            writer.add(event);
        }
    }

    changesReader.close();
    IOUtils.closeQuietly(replacement);

    if (justValue) {
        writer.add(element.getValue().getEnd());
    }

    writer.add(reader);

    reader.close();
    IOUtils.closeQuietly(src);

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

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

From source file:org.apache.olingo.fit.utils.XMLUtilities.java

@Override
public InputStream deleteProperty(final InputStream src, final List<String> path) throws Exception {
    final XMLEventReader reader = getEventReader(src);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    final XMLEventReader changesReader = new XMLEventReaderWrapper(IOUtils.toInputStream(
            String.format("<%s m:null=\"true\" />", path.get(path.size() - 1)), Constants.ENCODING));

    writer.add(changesReader);/*  ww  w. ja  va 2s .c  o m*/
    changesReader.close();

    writer.add(reader);

    reader.close();
    IOUtils.closeQuietly(src);

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

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

From source file:org.atricore.idbus.capabilities.sso.support.core.util.XmlUtils.java

public static String marshal(Object msg, final String msgQName, final String msgLocalName,
        String[] userPackages) throws Exception {

    TreeSet<String> contextPackages = new TreeSet<String>();
    for (int i = 0; i < userPackages.length; i++) {
        String userPackage = userPackages[i];
        contextPackages.add(userPackage);
    }//from   w w  w.ja  va 2  s . c  o m

    JAXBContext jaxbContext = JAXBUtils.getJAXBContext(contextPackages, constructionType,
            contextPackages.toString(), XmlUtils.class.getClassLoader(), new HashMap<String, Object>());
    Marshaller marshaller = JAXBUtils.getJAXBMarshaller(jaxbContext);

    JAXBElement jaxbRequest = new JAXBElement(new QName(msgQName, msgLocalName), msg.getClass(), msg);

    Writer writer = new StringWriter();

    // Support XMLDsig
    XMLEventWriter xmlWriter = staxOF.createXMLEventWriter(writer);
    marshaller.marshal(jaxbRequest, xmlWriter);
    xmlWriter.flush();
    JAXBUtils.releaseJAXBMarshaller(jaxbContext, marshaller);

    return writer.toString();

}

From source file:org.codice.ddf.spatial.ogc.wfs.transformer.handlebars.HandlebarsWfsFeatureTransformer.java

private void readGmlData(XMLEventReader xmlEventReader, String elementName, Map<String, String> contextMap)
        throws XMLStreamException {

    if (!xmlEventReader.peek().isStartElement()) {
        LOGGER.debug("Problem reading gml data for element: {}. Invalid xml element provided.", elementName);
        return;//w  w  w . j  av a 2s  .  c o  m
    }

    StringWriter stringWriter = new StringWriter();
    XMLEventWriter eventWriter = XML_OUTPUT_FACTORY.createXMLEventWriter(stringWriter);

    if (eventWriter == null) {
        LOGGER.debug("Problem reading gml data for element: {}. Event writer is null", elementName);
        return;
    }

    int count = 0;
    boolean addEvent = true;

    try {
        while (addEvent) {
            XMLEvent xmlEvent = xmlEventReader.nextEvent();

            // populate the start element with the namespaces
            if (xmlEvent.isStartElement()) {
                xmlEvent = addNamespacesToStartElement(xmlEvent.asStartElement());
                count++;
            } else if (xmlEvent.isEndElement()) {
                if (count == 0) {
                    addEvent = false;
                    eventWriter.flush();
                    LOGGER.debug("String writer: {}", stringWriter);
                    contextMap.put(elementName, stringWriter.toString());
                }
                count--;
            }

            if (addEvent) {
                eventWriter.add(xmlEvent);
            }
        }
    } finally {
        eventWriter.close();
    }
}

From source file:org.emonocot.job.io.StaxEventItemWriter.java

/**
 * Writes simple XML header containing:/*from w  ww .j  a  v  a2 s  .c om*/
 * <ul>
 * <li>xml declaration - defines encoding and XML version</li>
 * <li>opening tag of the root element and its attributes</li>
 * </ul>
 * If this is not sufficient for you, simply override this method. Encoding,
 * version and root tag name can be retrieved with corresponding getters.
 *
 * @param writer
 *            XML event writer
 * @throws XMLStreamException if there is a problem starting the document
 */
protected final void startDocument(final XMLEventWriter writer) throws XMLStreamException {

    XMLEventFactory factory = XMLEventFactory.newInstance();

    // write start document
    writer.add(factory.createStartDocument(getEncoding(), getVersion()));

    // write root tag
    writer.add(
            factory.createStartElement(getRootTagNamespacePrefix(), getRootTagNamespace(), getRootTagName()));
    if (StringUtils.hasText(getRootTagNamespace())) {
        if (StringUtils.hasText(getRootTagNamespacePrefix())) {
            writer.add(factory.createNamespace(getRootTagNamespacePrefix(), getRootTagNamespace()));
        } else {
            writer.add(factory.createNamespace(getRootTagNamespace()));
        }
    }

    // write root tag attributes
    if (!CollectionUtils.isEmpty(getRootElementAttributes())) {

        for (Map.Entry<String, String> entry : getRootElementAttributes().entrySet()) {
            String key = entry.getKey();
            if (key.startsWith("xmlns")) {
                String prefix = "";
                if (key.contains(":")) {
                    prefix = key.substring(key.indexOf(":") + 1);
                }
                writer.add(factory.createNamespace(prefix, entry.getValue()));
            } else {
                writer.add(factory.createAttribute(key, entry.getValue()));
            }
        }

    }

    /*
     * This forces the flush to write the end of the root element and avoids
     * an off-by-one error on restart.
     */
    writer.add(factory.createIgnorableSpace(""));
    writer.flush();

}

From source file:org.mcisb.subliminal.SubliminalUtils.java

/**
 * /* w  ww  .  j  a v a 2 s .c  o  m*/
 * @param elementName
 * @param is
 * @param onlyValues
 * @return Collection
 * @throws XMLStreamException
 * @throws UnsupportedEncodingException
 */
private 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:org.springframework.batch.item.xml.StaxEventItemWriter.java

/**
 * Writes simple XML header containing://from   w w  w  . j a  va 2 s .c o  m
 * <ul>
 * <li>xml declaration - defines encoding and XML version</li>
 * <li>opening tag of the root element and its attributes</li>
 * </ul>
 * If this is not sufficient for you, simply override this method. Encoding,
 * version and root tag name can be retrieved with corresponding getters.
 * 
 * @param writer XML event writer
 * @throws XMLStreamException
 */
protected void startDocument(XMLEventWriter writer) throws XMLStreamException {

    XMLEventFactory factory = createXmlEventFactory();

    // write start document
    writer.add(factory.createStartDocument(getEncoding(), getVersion()));

    // write root tag
    writer.add(
            factory.createStartElement(getRootTagNamespacePrefix(), getRootTagNamespace(), getRootTagName()));
    if (StringUtils.hasText(getRootTagNamespace())) {
        if (StringUtils.hasText(getRootTagNamespacePrefix())) {
            writer.add(factory.createNamespace(getRootTagNamespacePrefix(), getRootTagNamespace()));
        } else {
            writer.add(factory.createNamespace(getRootTagNamespace()));
        }
    }

    // write root tag attributes
    if (!CollectionUtils.isEmpty(getRootElementAttributes())) {

        for (Map.Entry<String, String> entry : getRootElementAttributes().entrySet()) {
            String key = entry.getKey();
            if (key.startsWith("xmlns")) {
                String prefix = "";
                if (key.contains(":")) {
                    prefix = key.substring(key.indexOf(":") + 1);
                }
                writer.add(factory.createNamespace(prefix, entry.getValue()));
            } else {
                writer.add(factory.createAttribute(key, entry.getValue()));
            }
        }

    }

    /*
     * This forces the flush to write the end of the root element and avoids
     * an off-by-one error on restart.
     */
    writer.add(factory.createIgnorableSpace(""));
    writer.flush();

}

From source file:org.xmlsh.commands.internal.xml2json.java

private byte[] serializeAsXML(XMLEventReader reader) throws XMLStreamException {

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLOutputFactory fact = new OutputFactory();

    XMLEventWriter writer = fact.createXMLEventWriter(bos, kENCODING_UTF_8);
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();

        if (event.isEndElement() && event.asEndElement().getName().equals(kELEM_STRING))
            break;
        writer.add(event);/*ww  w .jav a2  s .  c  o m*/
    }

    writer.flush();
    writer.close();
    return bos.toByteArray();

}