001    
002    /*
003     * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
004     *
005     * $Id: XMLDocumentOutputStream.java 162 2011-10-24 20:42:37Z archie.cobbs $
006     */
007    
008    package org.dellroad.stuff.jibx;
009    
010    import java.io.BufferedOutputStream;
011    import java.io.IOException;
012    import java.io.OutputStream;
013    
014    import org.dellroad.stuff.io.OutputStreamWriter;
015    import org.jibx.runtime.JiBXException;
016    
017    /**
018     * {@link OutputStream} over which XML documents are passed. This class is a companion to {@link XMLDocumentOutputStream}.
019     *
020     * <p>
021     * XML documents are created from Java objects via {@link JiBXUtil#writeObject(Object, OutputStream) JiBXUtil.writeObject()}.
022     * </p>
023     *
024     * <p>
025     * Instances of this class are thread-safe.
026     * </p>
027     *
028     * @param <T> XML document type
029     * @see XMLDocumentInputStream
030     */
031    public class XMLDocumentOutputStream<T> {
032    
033        private final Class<T> type;
034        private final OutputStreamWriter output;
035    
036        /**
037         * Constructor.
038         *
039         * @param type Java type for XML documents
040         * @param output data destination
041         */
042        public XMLDocumentOutputStream(Class<T> type, OutputStream output) {
043            if (type == null)
044                throw new IllegalArgumentException("null type");
045            if (output == null)
046                throw new IllegalArgumentException("null output");
047            this.type = type;
048            this.output = new OutputStreamWriter(new BufferedOutputStream(output));
049        }
050    
051        /**
052         * Write the object encoded as XML to the underlying output stream.
053         * The underlying output stream is flushed.
054         */
055        public synchronized void write(T obj) throws IOException, JiBXException {
056            this.output.start();
057            JiBXUtil.writeObject(obj, this.output);
058            this.output.stop();
059        }
060    
061        /**
062         * Close the underlying output stream.
063         */
064        public void close() throws IOException {
065            this.output.close();
066        }
067    }
068