Example usage for javax.xml.stream XMLOutputFactory createXMLEventWriter

List of usage examples for javax.xml.stream XMLOutputFactory createXMLEventWriter

Introduction

In this page you can find the example usage for javax.xml.stream XMLOutputFactory createXMLEventWriter.

Prototype

public abstract XMLEventWriter createXMLEventWriter(java.io.Writer stream) throws XMLStreamException;

Source Link

Document

Create a new XMLEventWriter that writes to a writer

Usage

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  . j  a va 2 s .  com

    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

private InputStream addAtomEditLink(final InputStream content, final String title, final String href)
        throws Exception {
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();

    final ByteArrayOutputStream copy = new ByteArrayOutputStream();
    IOUtils.copy(content, copy);/*from  ww w  . j  a  v  a2 s.c  o m*/

    IOUtils.closeQuietly(content);

    XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

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

    try {
        // check edit link existence
        final XmlElement editLink = getAtomElement(reader, writer, LINK,
                Collections.<Map.Entry<String, String>>singletonList(
                        new AbstractMap.SimpleEntry<String, String>("rel", "edit")));
        writer.add(editLink.getStart());
        writer.add(editLink.getContentReader());
        writer.add(editLink.getEnd());
        writer.add(reader);
    } catch (Exception e) {
        reader.close();
        reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

        bos = new ByteArrayOutputStream();
        writer = xof.createXMLEventWriter(bos);

        final XmlElement entryElement = getAtomElement(reader, writer, "entry");

        writer.add(entryElement.getStart());
        addAtomElement(IOUtils.toInputStream(
                String.format("<link rel=\"edit\" title=\"%s\" href=\"%s\" />", title, href)), writer);
        writer.add(entryElement.getContentReader());
        writer.add(entryElement.getEnd());

        writer.add(reader);

        writer.flush();
        writer.close();
    } finally {
        reader.close();
    }

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

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

public InputStream addAtomContent(final InputStream content, final String title, final String href)
        throws Exception {
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();

    final ByteArrayOutputStream copy = new ByteArrayOutputStream();
    IOUtils.copy(content, copy);/*from   ww w  .  j a  v a2  s. c  om*/

    IOUtils.closeQuietly(content);

    XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

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

    try {
        // check edit link existence
        XmlElement contentElement = getAtomElement(reader, writer, "content");
        writer.add(contentElement.getStart());
        writer.add(contentElement.getContentReader());
        writer.add(contentElement.getEnd());
        writer.add(reader);
    } catch (Exception e) {
        reader.close();
        reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

        bos = new ByteArrayOutputStream();
        writer = xof.createXMLEventWriter(bos);

        if (isMediaContent(title)) {
            final XmlElement entryElement = getAtomElement(reader, writer, "entry");

            writer.add(entryElement.getStart());
            writer.add(entryElement.getContentReader());

            addAtomElement(
                    IOUtils.toInputStream(String.format("<content type=\"*/*\" src=\"%s/$value\" />", href)),
                    writer);

            writer.add(entryElement.getEnd());
        } else {
            try {
                final XmlElement entryElement = getAtomElement(reader, writer, PROPERTIES);

                addAtomElement(IOUtils.toInputStream("<content type=\"application/xml\">"), writer);

                writer.add(entryElement.getStart());
                writer.add(entryElement.getContentReader());
                writer.add(entryElement.getEnd());

                addAtomElement(IOUtils.toInputStream("</content>"), writer);
            } catch (Exception nf) {
                reader.close();
                reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

                bos = new ByteArrayOutputStream();
                writer = xof.createXMLEventWriter(bos);

                final XmlElement entryElement = getAtomElement(reader, writer, "entry");
                writer.add(entryElement.getStart());
                writer.add(entryElement.getContentReader());

                addAtomElement(IOUtils.toInputStream("<content type=\"application/xml\"/>"), writer);

                writer.add(entryElement.getEnd());
            }
        }

        writer.add(reader);

        writer.flush();
        writer.close();
    } finally {
        reader.close();
    }

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

From source file:com.gtwm.pb.model.manageData.DataManagement.java

/**
 * Based on http://www.vogella.de/articles/RSSFeed/article.html
 *///w ww.  j a  v a2 s.  c o  m
private String generateRSS(AppUserInfo user, BaseReportInfo report, List<DataRowInfo> reportDataRows)
        throws XMLStreamException, ObjectNotFoundException {
    // Create a XMLOutputFactory
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    // Create XMLEventWriter
    StringWriter stringWriter = new StringWriter();
    XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(stringWriter);
    // Create a EventFactory
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent end = eventFactory.createDTD("\n");
    // Create and write Start Tag
    StartDocument startDocument = eventFactory.createStartDocument();
    eventWriter.add(startDocument);
    // Create open tag
    eventWriter.add(end);
    StartElement rssStart = eventFactory.createStartElement("", "", "rss");
    eventWriter.add(rssStart);
    eventWriter.add(eventFactory.createAttribute("version", "2.0"));
    eventWriter.add(end);
    eventWriter.add(eventFactory.createStartElement("", "", "channel"));
    eventWriter.add(end);
    // Write the different nodes
    this.createNode(eventWriter, "title", report.getModule().getModuleName() + " - " + report.getReportName());
    // TODO: Don't hard code host part of URL
    String reportLink = "https://appserver.gtportalbase.com/agileBase/AppController.servlet?return=gui/display_application&set_table="
            + report.getParentTable().getInternalTableName() + "&set_report=" + report.getInternalReportName();
    this.createNode(eventWriter, "link", reportLink);
    this.createNode(eventWriter, "description", "A live data feed from www.agilebase.co.uk");
    DateFormat dateFormatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
    Date lastDataChangeDate = new Date(getLastCompanyDataChangeTime(user.getCompany()));
    this.createNode(eventWriter, "pubdate", dateFormatter.format(lastDataChangeDate));
    for (DataRowInfo reportDataRow : reportDataRows) {
        eventWriter.add(eventFactory.createStartElement("", "", "item"));
        eventWriter.add(end);
        this.createNode(eventWriter, "title", buildEventTitle(report, reportDataRow, false));
        this.createNode(eventWriter, "description", reportDataRow.toString());
        String rowLink = reportLink + "&set_row_id=" + reportDataRow.getRowId();
        this.createNode(eventWriter, "link", rowLink);
        this.createNode(eventWriter, "guid", rowLink);
        eventWriter.add(end);
        eventWriter.add(eventFactory.createEndElement("", "", "item"));
        eventWriter.add(end);
    }
    eventWriter.add(eventFactory.createEndElement("", "", "channel"));
    eventWriter.add(end);
    eventWriter.add(eventFactory.createEndElement("", "", "rss"));
    eventWriter.add(end);
    return stringWriter.toString();
}

From source file:org.alex73.osm.converters.bel.Convert.java

public static void main(String[] args) throws Exception {
    loadStreetNamesForHouses();/*from   w  ww . j  ava  2s.co m*/

    InputStream in = new BZip2CompressorInputStream(
            new BufferedInputStream(new FileInputStream("tmp/belarus-latest.osm.bz2"), BUFFER_SIZE));

    // create xml event reader for input stream
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent newLine = eventFactory.createCharacters("\n");
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLOutputFactory xof = XMLOutputFactory.newInstance();
    XMLEventReader reader = xif.createXMLEventReader(in);
    XMLEventWriter wrCyr = xof.createXMLEventWriter(
            new BufferedOutputStream(new FileOutputStream("tmp/belarus-bel.osm"), BUFFER_SIZE));
    XMLEventWriter wrInt = xof.createXMLEventWriter(
            new BufferedOutputStream(new FileOutputStream("tmp/belarus-intl.osm"), BUFFER_SIZE));

    // initialize jaxb
    JAXBContext jaxbCtx = JAXBContext.newInstance(Node.class, Way.class, Relation.class);
    Unmarshaller um = jaxbCtx.createUnmarshaller();
    Marshaller m = jaxbCtx.createMarshaller();
    m.setProperty(Marshaller.JAXB_FRAGMENT, true);
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    XMLEvent e = null;
    while ((e = reader.peek()) != null) {
        boolean processed = false;
        if (e.isStartElement()) {
            StartElement se = (StartElement) e;
            switch (se.getName().getLocalPart()) {
            case "way":
                Way way = um.unmarshal(reader, Way.class).getValue();
                if (way.getId() == 25439425) {
                    System.out.println();
                }
                fixBel(way.getTag(), "name:be", "name");
                String nameBeHouse = houseStreetBe.get(way.getId());
                if (nameBeHouse != null) {
                    setTag(way.getTag(), "addr:street", nameBeHouse);
                }
                m.marshal(way, wrCyr);
                fixInt(way.getTag());
                m.marshal(way, wrInt);
                wrCyr.add(newLine);
                wrInt.add(newLine);
                processed = true;
                break;
            case "node":
                Node node = um.unmarshal(reader, Node.class).getValue();
                fixBel(node.getTag(), "name:be", "name");
                // fixBel(node.getTag(),"addr:street:be","addr:street");
                m.marshal(node, wrCyr);
                fixInt(node.getTag());
                m.marshal(node, wrInt);
                wrCyr.add(newLine);
                wrInt.add(newLine);
                processed = true;
                break;
            case "relation":
                Relation relation = um.unmarshal(reader, Relation.class).getValue();
                fixBel(relation.getTag(), "name:be", "name");
                // fixBel(relation.getTag(),"addr:street:be","addr:street");
                m.marshal(relation, wrCyr);
                fixInt(relation.getTag());
                m.marshal(relation, wrInt);
                wrCyr.add(newLine);
                wrInt.add(newLine);
                processed = true;
                break;
            }
        }
        if (!processed) {
            wrCyr.add(e);
            wrInt.add(e);
        }
        reader.next();
    }

    wrCyr.flush();
    wrCyr.close();
    wrInt.flush();
    wrInt.close();
    System.out.println("UniqueTranslatedTags: " + uniqueTranslatedTags);
}

From source file:org.dkpro.core.io.xces.XcesBasicXmlWriter.java

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    OutputStream docOS = null;/*from   w  ww. jav a  2s.  c o m*/
    try {
        docOS = getOutputStream(aJCas, filenameSuffix);
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        XMLEventWriter xmlEventWriter = new IndentingXMLEventWriter(
                xmlOutputFactory.createXMLEventWriter(docOS));
        JAXBContext context = JAXBContext.newInstance(XcesBodyBasic.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        XMLEventFactory xmlef = XMLEventFactory.newInstance();
        xmlEventWriter.add(xmlef.createStartDocument());
        // Begin cesDoc
        xmlEventWriter.add(xmlef.createStartElement("", "", "cesDoc"));
        // Begin and End cesHeader
        xmlEventWriter.add(xmlef.createStartElement("", "", "cesHeader"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "cesHeader"));

        // Begin text and body
        xmlEventWriter.add(xmlef.createStartElement("", "", "text"));
        // xmlEventWriter.add(xmlef.createStartElement("", "", "body"));

        // Begin body of all the paragraphs            
        Collection<Paragraph> parasInCas = JCasUtil.select(aJCas, Paragraph.class);
        XcesBodyBasic xb = convertToXcesBasicPara(parasInCas);
        marshaller.marshal(new JAXBElement<XcesBodyBasic>(new QName("body"), XcesBodyBasic.class, xb),
                xmlEventWriter);
        // End body of all the paragraphs
        // xmlEventWriter.add(xmlef.createEndElement("", "", "body"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "text"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "cesDoc"));
        xmlEventWriter.add(xmlef.createEndDocument());
    } catch (Exception e) {
        throw new AnalysisEngineProcessException(e);
    } finally {
        closeQuietly(docOS);
    }

}

From source file:org.dkpro.core.io.xces.XcesXmlWriter.java

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    OutputStream docOS = null;//w ww. jav a  2  s  .c  o m
    try {
        docOS = getOutputStream(aJCas, filenameSuffix);
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        XMLEventWriter xmlEventWriter = new IndentingXMLEventWriter(
                xmlOutputFactory.createXMLEventWriter(docOS));
        JAXBContext context = JAXBContext.newInstance(XcesBody.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        XMLEventFactory xmlef = XMLEventFactory.newInstance();
        xmlEventWriter.add(xmlef.createStartDocument());
        // Begin cesDoc
        xmlEventWriter.add(xmlef.createStartElement("", "", "cesDoc"));
        // Begin and End cesHeader
        xmlEventWriter.add(xmlef.createStartElement("", "", "cesHeader"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "cesHeader"));

        // Begin text and body
        xmlEventWriter.add(xmlef.createStartElement("", "", "text"));
        // xmlEventWriter.add(xmlef.createStartElement("", "", "body"));

        // Begin body of all the paragraphs            
        Collection<Paragraph> parasInCas = JCasUtil.select(aJCas, Paragraph.class);
        XcesBody xb = convertToXcesPara(parasInCas);
        marshaller.marshal(new JAXBElement<XcesBody>(new QName("body"), XcesBody.class, xb), xmlEventWriter);
        // End body of all the paragraphs
        // xmlEventWriter.add(xmlef.createEndElement("", "", "body"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "text"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "cesDoc"));
        xmlEventWriter.add(xmlef.createEndDocument());
    } catch (Exception e) {
        throw new AnalysisEngineProcessException(e);
    } finally {
        closeQuietly(docOS);
    }

}

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

/**
 * Helper method for opening output source at given file position.
 * @param position Set the position//from  ww w  . j  a v a 2s .c o  m
 * @param restarted Is this execution being restarted
 */
private void open(final long position, final boolean restarted) {

    File file;
    FileOutputStream os = null;

    try {
        file = resource.getFile();
        FileUtils.setUpOutputFile(file, restarted, overwriteOutput);
        Assert.state(resource.exists(), "Output resource must exist");
        os = new FileOutputStream(file, true);
        channel = os.getChannel();
        setPosition(position);
    } catch (IOException ioe) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]",
                ioe);
    }

    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();

    if (outputFactory.isPropertySupported("com.ctc.wstx.automaticEndElements")) {
        // If the current XMLOutputFactory implementation is supplied by
        // Woodstox >= 3.2.9 we want to disable its
        // automatic end element feature (see:
        // http://jira.codehaus.org/browse/WSTX-165) per
        // http://jira.springframework.org/browse/BATCH-761.
        outputFactory.setProperty("com.ctc.wstx.automaticEndElements", Boolean.FALSE);
    }

    try {
        if (transactional) {
            bufferedWriter = new TransactionAwareBufferedWriter(new OutputStreamWriter(os, encoding),
                    new Runnable() {
                        public void run() {
                            closeStream();
                        }
                    });
        } else {
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, encoding));
        }
        delegateEventWriter = outputFactory.createXMLEventWriter(bufferedWriter);
        eventWriter = new NoStartEndDocumentStreamWriter(delegateEventWriter);
        if (!restarted) {
            startDocument(delegateEventWriter);
        }
    } catch (XMLStreamException xse) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]",
                xse);
    } catch (UnsupportedEncodingException e) {
        throw new DataAccessResourceFailureException(
                "Unable to write to file resource: [" + resource + "] with encoding=[" + encoding + "]", e);
    }

}

From source file:org.sakaiproject.nakamura.proxy.RSSProxyPostProcessor.java

public void process(Map<String, Object> templateParams, SlingHttpServletResponse response,
        ProxyResponse proxyResponse) throws IOException {
    if (proxyResponse.getResultCode() == HttpServletResponse.SC_PRECONDITION_FAILED) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This RSS feed is too big ");
        return;/*  w  ww .  j a  v a 2  s .c om*/
    }

    Map<String, String[]> headers = proxyResponse.getResponseHeaders();

    // Check if the content-length is smaller than the maximum (if any).
    String[] contentLengthHeader = headers.get("Content-Length");
    if (contentLengthHeader != null) {
        int length = Integer.parseInt(contentLengthHeader[0]);
        if (length > maxLength) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "This RSS feed is too big. The maximum for a feed is: " + maxLength);
            return;
        }
    }

    // Check if the Content-Type we get is valid (if any).
    String[] contentTypeHeader = headers.get("Content-Type");
    if (contentTypeHeader != null) {
        String contentType = contentTypeHeader[0];
        if (contentType.contains(";")) {
            contentType = contentType.substring(0, contentType.indexOf(';'));
        }
        if (!contentTypes.contains(contentType)) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "This URL doesn't send a proper Content-Type back");
            return;
        }
    }

    boolean isValid = false;
    InputStream in = proxyResponse.getResponseBodyAsInputStream();
    InputStreamReader reader = new InputStreamReader(in);

    // XMLStreamWriter writer = null;
    XMLEventWriter writer = null;
    ByteArrayOutputStream out = null;

    int i = 0;
    try {
        XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(reader);
        // Create a temporary outputstream where we can write to.
        out = new ByteArrayOutputStream();

        Set<String> checkedElements = null;

        XMLOutputFactory outputFactory = new WstxOutputFactory();
        writer = outputFactory.createXMLEventWriter(out);

        while (eventReader.hasNext()) {
            XMLEvent e = eventReader.nextEvent();
            // Stream it to an output stream.
            writer.add(e);

            if (!isValid) {
                if (e.getEventType() == XMLEvent.START_ELEMENT) {
                    StartElement el = e.asStartElement();
                    String name = el.getName().getLocalPart().toLowerCase();
                    if (checkedElements == null) {
                        // get the right format to validate against
                        String formatKey = name;
                        Attribute attr = el.getAttributeByName(new QName("version"));
                        if (attr != null) {
                            formatKey += "-" + attr.getValue();
                        }
                        Set<String> format = formats.get(formatKey);
                        if (format != null) {
                            checkedElements = new HashSet<String>(format);
                        }
                    } else {
                        checkedElements.remove(name);

                        if (checkedElements.isEmpty()) {
                            isValid = true;
                        }
                    }
                }

                if (i > eventsThreshold) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This file is too complex.");
                    return;
                }
                i++;
            }
        }

        if (!isValid) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid RSS file.");
            return;
        }

        // Check if we are not streaming a gigantic file..
        if (out.size() > maxLength) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This file is too big.");
            return;
        }

        for (Entry<String, String[]> h : proxyResponse.getResponseHeaders().entrySet()) {
            for (String v : h.getValue()) {
                response.setHeader(h.getKey(), v);
            }
        }
        // We always return 200 when we get to this point.
        response.setStatus(200);
        response.setHeader("Content-Length", Integer.toString(out.size()));
        // Write the cached stream to the output.
        out.writeTo(response.getOutputStream());

    } catch (XMLStreamException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This is not a valid XML file.");
    } catch (Exception e) {
        logger.warn("Exception reading RSS feed.", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "General exception caught.");
    } finally {
        if (out != null) {
            out.close();
        }
        reader.close();
        try {
            if (writer != null)
                writer.close();
        } catch (XMLStreamException e) {
            // Not much we can do?
            e.printStackTrace();
        }
    }

}

From source file:org.springframework.batch.item.xml.StaxEventItemWriter.java

/**
 * Subclasses can override to customize the writer.
 * @param outputFactory//from w  w  w. j a  v  a2 s .  c  o  m
 * @param writer
 * @return an xml writer
 * @throws XMLStreamException
 */
protected XMLEventWriter createXmlEventWriter(XMLOutputFactory outputFactory, Writer writer)
        throws XMLStreamException {
    return outputFactory.createXMLEventWriter(writer);
}