001    /* $Id: DocumentOutputStream.java 69 2007-10-24 21:57:43Z ringler $
002    * This class is part of the de.mospace.swing library.
003    * Copyright (C) 2005-2006 Moritz Ringler
004    *
005    * This program is free software; you can redistribute it and/or
006    * modify it under the terms of the GNU General Public License
007    * as published by the Free Software Foundation; either version 2
008    * of the License, or (at your option) any later version.
009    *
010    * This program is distributed in the hope that it will be useful,
011    * but WITHOUT ANY WARRANTY; without even the implied warranty of
012    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013    * GNU General Public License for more details.
014    *
015    * You should have received a copy of the GNU General Public License
016    * along with this program; if not, write to the Free Software
017    * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
018    */
019    package de.mospace.swing.text;
020    
021    import java.awt.Color;
022    import java.awt.EventQueue;
023    import java.io.IOException;
024    import java.io.OutputStream;
025    import java.io.OutputStreamWriter;
026    import java.nio.ByteBuffer;
027    import java.nio.charset.Charset;
028    import java.util.logging.Logger;
029    import javax.swing.SwingUtilities;
030    import javax.swing.text.Document;
031    import javax.swing.text.MutableAttributeSet;
032    import javax.swing.text.SimpleAttributeSet;
033    import javax.swing.text.StyleConstants;
034    
035    /**
036    * An OutputStream that writes to the Document of a Swing text component.
037    *
038    * @version $Revision: 69 $ ($Date: 2007-10-24 23:57:43 +0200 (Mi, 24 Okt 2007) $)
039    * @author Moritz Ringler
040    */
041    public class DocumentOutputStream extends OutputStream {
042        private static final Logger logger = Logger.getLogger(DocumentOutputStream.class.getPackage().getName());
043    
044        private Charset charset;
045        private Document doc;
046        private MutableAttributeSet currentStyle;
047    
048        /** Sets the foreground color for new output.
049        * @param c the new text color
050        */
051        public void setColor(Color c){
052            if(currentStyle == null){
053                currentStyle = new SimpleAttributeSet();
054            }
055            StyleConstants.setForeground (currentStyle, c);
056        }
057    
058        /**
059        * Constructs a new DocumentOutputStream that uses the default system
060        * charset for decoding bytes passed to its write methods.
061        *
062        * @param d the document that this output stream will write to
063        *
064        * @throws NullPointerException if <code>d</code> is <code>null</code>
065        */
066        public DocumentOutputStream(Document d) {
067            d.getClass(); //throws a null pointer exception if d is null
068            charset = Charset.forName(new OutputStreamWriter(this).getEncoding());
069            doc = d;
070        }
071    
072        /**
073        * Creates a new DocumentOutputStream that uses the specified
074        * charset for decoding bytes passed to its write methods.
075        *
076        * @param d the document that this output stream will write to
077        * @param c charset for decoding bytes passed to one of the write methods
078        *
079        * @throws NullPointerException if one of the parameters is <code>null</code>
080        */
081        public DocumentOutputStream(Document d, Charset c) {
082            d.getClass(); //throws a null pointer exception if d is null
083            c.getClass(); //throws a null pointer exception if c is null
084            charset = c;
085            doc = d;
086        }
087    
088        /**
089        * Creates a new DocumentOutputStream that uses the
090        * charset with the specified name for decoding bytes
091        * passed to its write methods.
092        *
093        * @param d the document that this output stream will write to
094        * @param charsetName the name of a charset to use
095        *
096        * @throws NullPointerException if one of the parameters is <code>null</code>
097        * @throws java.nio.charset.UnsupportedCharsetException if the JVM does
098        * not support the charset with the specified name
099        */
100        public DocumentOutputStream(Document d, String charsetName) {
101            d.getClass(); //throws a null pointer exception if d is null
102            charsetName.getClass(); //throws a null pointer exception if charsetName is null
103            charset = Charset.forName(charsetName);
104            doc = d;
105        }
106    
107        /**
108        * Sets the character set used for decoding bytes passed to the write
109        * methods of this DocumentOutputStream. Has no effect when this
110        * OutputStream has been closed.
111        *
112        * @param name charset for decoding bytes
113        *
114        * @throws NullPointerException if <code>name</code> is <code>null</code>
115        * @throws java.nio.charset.UnsupportedCharsetException if the JVM does
116        * not support the charset with the specified name
117        */
118        public void setCharset(String name) {
119            name.getClass();
120            if (doc != null) {
121                charset = Charset.forName(name);
122            }
123        }
124    
125        /**
126        * Sets the character set used for decoding bytes passed to the write
127        * methods of this DocumentOutputStream. Has no effect when this
128        * OutputStream has been closed.
129        *
130        * @param c charset for decoding bytes
131        *
132        * @throws NullPointerException if <code>c</code> is <code>null</code>
133        */
134        public void setCharset(Charset c) {
135            c.getClass();
136            if (doc != null) {
137                charset = c;
138            }
139        }
140    
141        /**
142        * Returns the character set that this DocumentOutputStream uses to write
143        * bytes to its document.
144        *
145        * @return the character set used by this DocumentOutputStream or
146        *         <code>null</code> if this stream has been closed
147        */
148        public Charset getCharset() {
149            return charset;
150        }
151    
152        /**
153        * Returns the character set that this DocumentOutputStream uses to write
154        * bytes to its document.
155        *
156        * @return the character set used by this DocumentOutputStream or
157        *         <code>null</code> if this stream has been closed
158        */
159        public String getCharsetName() {
160            return (charset == null) ? null : charset.name();
161        }
162    
163        /**
164        * Sets the document that this OutputStream writes to. Has no effect when
165        * this OutputStream has been closed.
166        *
167        * @param d the document that this output stream will write to
168        *
169        * @throws NullPointerException if <code>d</code> is <code>null</code>
170        */
171        public void setDocument(Document d) {
172            d.getClass();
173            if (doc != null) {
174                doc = d;
175            }
176        }
177    
178        /**
179        * Returns the document that this OutputStream writes to.
180        *
181        * @return the document that this output stream writes to or
182        *         <code>null</code> if this stream has been closed
183        */
184        public Document getDocument() {
185            return doc;
186        }
187    
188        /**
189        * Closes the output stream. A closed stream cannot perform output
190        * operations and cannot be reopened.
191        */
192        public void close() {
193            doc = null;
194            charset = null;
195        }
196    
197        /**
198        * Inserts the specified byte at the end of the current document of this
199        * DocumentOutputStream. <code>b</code> is converted to a unicode
200        * character by calling the {@link Charset#decode decode} method of the
201        * current charset of this DocumentOutputStream.
202        *
203        * @param b the byte to write
204        * @throws IOException if the output stream has been closed
205        */
206        public void write(int b) throws IOException {
207            write(new byte[]{new Integer(b).byteValue()}, 0, 1);
208        }
209    
210        /**
211        * Inserts the specified bytes at the end of the current document of this
212        * DocumentOutputStream. <code>b</code> is converted to a unicode string
213        * by calling the {@link Charset#decode decode} method of the current
214        * charset of this DocumentOutputStream.<p>
215        * <code>write(b)</code> has exactly the same effect as the call
216        * <code>write(b, 0, b.length)</code>.
217        *
218        * @param b the byte to write
219        * @throws IOException if the output stream has been closed
220        *
221        * @see #write(byte[], int, int)
222        */
223        public void write(byte[] b) throws IOException {
224            write(b, 0, b.length);
225        }
226    
227        /**
228        * Inserts the specified bytes at the end of the current document of this
229        * DocumentOutputStream. <code>b</code> is converted to a unicode string
230        * by calling the {@link Charset#decode decode} method of the current
231        * charset of this DocumentOutputStream.
232        *
233        * @param b the data
234        * @param off the start offset in the data
235        * @param len the number of bytes to write
236        * @throws IOException if the output stream has been closed
237        * @throws NullPointerException if <code>b</code> is <code>null</code>
238        * @throws IndexOutOfBoundsException if the preconditions on the <code>off</code>
239        *         and <code>len</code> parameters do not hold
240        */
241        public void write(byte[] b, int off, int len) throws IOException {
242            b.getClass(); //provoke NullPointerException if b is null
243            if (doc == null) {
244                throw new IOException("Trying to write to a closed output stream.");
245            } else {
246                append((charset.decode(ByteBuffer.wrap(b, off, len))).toString());
247            }
248        }
249    
250        /**
251        * Inserts the specified String at the end of the current document. The
252        * document mutation is always done in the
253        * AWT Event Dispatching Thread. If the caller thread is not the event
254        * dispatching thread, {@link SwingUtilities#invokeLater} will be used.
255        *
256        * @param s the String to append
257        */
258        private void append(final String s) throws IOException {
259            try {
260                if (EventQueue.isDispatchThread()) {
261                    doc.insertString(doc.getLength(), s, currentStyle);
262                } else {
263                    SwingUtilities.invokeLater(new Runnable() {
264                        public void run() {
265                            try{
266                                append(s);
267                            } catch (IOException ex){
268                                logger.severe(ex.toString());
269                            }
270                        }
271                    });
272                }
273            } catch (Exception ex) {
274                IOException iox = new IOException("Cannot write string " + s);
275                iox.initCause(ex);
276                throw iox;
277            }
278        }
279    }