Java XML Document to Stream writeXml(OutputStream outputEntry, Document document)

Here you can find the source of writeXml(OutputStream outputEntry, Document document)

Description

write Xml

License

Apache License

Declaration

public static final void writeXml(OutputStream outputEntry, Document document) 

Method Source Code

//package com.java2s;
/**//from w  w  w .  ja va2 s .  c o m
 * Copyright (C) 2005-2009 Alfresco Software Limited.
 *
 * This file is part of the Spring Surf Extension project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.springframework.util.Assert;
import org.w3c.dom.Document;

public class Main {
    private static final TransformerFactory transformerFactory = TransformerFactory.newInstance();

    public static final void writeXml(OutputStream outputEntry, Document document) {
        writeXml(createIndentingTransformer(), outputEntry, document);
    }

    public static final void writeXml(Transformer transformer, OutputStream outputEntry, Document document) {
        Assert.notNull(transformer, "Transformer required");
        Assert.notNull(outputEntry, "Output entry required");
        Assert.notNull(document, "Document required");

        transformer.setOutputProperty(OutputKeys.METHOD, "xml");

        try {
            transformer.transform(new DOMSource(document), createUnixStreamResultForEntry(outputEntry));
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
    }

    /**
     * @return a transformer that indents entries by 4 characters (never null)
     */
    public static final Transformer createIndentingTransformer() {
        Transformer xformer;
        try {
            xformer = transformerFactory.newTransformer();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");
        xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        return xformer;
    }

    /**
     * Creates a {@link StreamResult} by wrapping the given outputEntry in an
     * {@link OutputStreamWriter} that transforms Windows line endings (\r\n) 
     * into Unix line endings (\n) on Windows for consistency with Roo's templates.  
     * @param outputEntry
     * @return StreamResult 
     * @throws UnsupportedEncodingException 
     */
    private static StreamResult createUnixStreamResultForEntry(OutputStream outputEntry)
            throws UnsupportedEncodingException {
        final Writer writer;
        if (System.getProperty("line.separator").equals("\r\n")) {
            writer = new OutputStreamWriter(outputEntry, "ISO-8859-1") {
                public void write(char[] cbuf, int off, int len) throws IOException {
                    for (int i = off; i < off + len; i++) {
                        if (cbuf[i] != '\r' || (i < cbuf.length - 1 && cbuf[i + 1] != '\n')) {
                            super.write(cbuf[i]);
                        }
                    }
                }

                public void write(int c) throws IOException {
                    if (c != '\r')
                        super.write(c);
                }

                public void write(String str, int off, int len) throws IOException {
                    String orig = str.substring(off, off + len);
                    String filtered = orig.replace("\r\n", "\n");
                    int lengthDiff = orig.length() - filtered.length();
                    if (filtered.endsWith("\r")) {
                        super.write(filtered.substring(0, filtered.length() - 1), 0, len - lengthDiff - 1);
                    } else {
                        super.write(filtered, 0, len - lengthDiff);
                    }
                }
            };
        } else {
            writer = new OutputStreamWriter(outputEntry, "ISO-8859-1");
        }
        return new StreamResult(writer);
    }
}

Related

  1. writeXML(Document doc, OutputStream out)
  2. writeXml(Document doc, OutputStream outputStream)
  3. writeXML(Document document, OutputStream os)
  4. writeXML(final Document doc, final OutputStream out)
  5. writeXML(OutputStream os, Document doc)
  6. writeXmlDocumentToStream(Document document, OutputStream stream)