View Javadoc

1   /*
2    * Copyright (c) 2006-2007 Creative Sphere Limited.
3    * All rights reserved. This program and the accompanying materials
4    * are made available under the terms of the Eclipse Public License v1.0
5    * which accompanies this distribution, and is available at
6    * http://www.eclipse.org/legal/epl-v10.html
7    *
8    * Contributors:
9    *
10   *   Creative Sphere - initial API and implementation
11   *
12   */
13  package org.abstracthorizon.danube.http.util;
14  
15  import java.io.IOException;
16  import java.io.OutputStream;
17  import java.io.UnsupportedEncodingException;
18  import java.io.Writer;
19  import java.nio.charset.Charset;
20  import java.nio.charset.IllegalCharsetNameException;
21  
22  /**
23   *
24   *
25   * @author Daniel Sendula
26   */
27  public class BufferlessOutputStreamWriter extends Writer {
28  
29      protected OutputStream stream;
30  
31      protected Charset charSet;
32  
33      public BufferlessOutputStreamWriter(OutputStream stream) {
34          this.stream = stream;
35      }
36  
37      public BufferlessOutputStreamWriter(OutputStream stream, String encoding) throws UnsupportedEncodingException, IllegalCharsetNameException {
38          this.stream = stream;
39          setEncoding(encoding);
40      }
41  
42      public void setEncoding(String encoding) throws UnsupportedEncodingException, IllegalCharsetNameException {
43          // TODO wrap this method with proper exception
44          if (encoding != null) {
45              if ((charSet == null) || !encoding.equals(charSet.name())) {
46                  charSet = Charset.forName(encoding);
47              }
48          } else {
49              encoding = null;
50          }
51      }
52  
53      public String getEncoding() {
54          if (charSet != null) {
55              return charSet.name();
56          } else {
57              return null;
58          }
59      }
60  
61      @Override
62      public void close() throws IOException {
63          stream.close();
64      }
65  
66      @Override
67      public void flush() throws IOException {
68          stream.close();
69      }
70  
71      @Override
72      public void write(char[] cbuf, int off, int len) throws IOException {
73          String s = new String(cbuf, off, len);
74          if (charSet == null) {
75              stream.write(s.getBytes());
76          } else {
77              stream.write(charSet.encode(s).array());
78          }
79      }
80  
81  
82  }