1 /*
   2  * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 



  26 package sun.nio.cs;
  27 
  28 import java.io.FileOutputStream;
  29 import java.io.IOException;
  30 import java.io.OutputStream;
  31 import java.io.UnsupportedEncodingException;
  32 import java.io.Writer;
  33 import java.nio.ByteBuffer;
  34 import java.nio.CharBuffer;
  35 import java.nio.channels.WritableByteChannel;
  36 import java.nio.charset.Charset;
  37 import java.nio.charset.CharsetEncoder;
  38 import java.nio.charset.CoderResult;
  39 import java.nio.charset.CodingErrorAction;
  40 import java.nio.charset.IllegalCharsetNameException;
  41 
  42 public class StreamEncoder extends Writer
  43 {
  44 
  45     private static final int DEFAULT_BYTE_BUFFER_SIZE = 8192;
  46 
  47     private volatile boolean closed;
  48 
  49     private void ensureOpen() throws IOException {
  50         if (closed)
  51             throw new IOException("Stream closed");
  52     }
  53 
  54     // Factories for java.io.OutputStreamWriter
  55     public static StreamEncoder forOutputStreamWriter(OutputStream out,
  56                                                       Object lock,
  57                                                       String charsetName)
  58         throws UnsupportedEncodingException
  59     {
  60         String csn = charsetName;
  61         if (csn == null)
  62             csn = Charset.defaultCharset().name();
  63         try {
  64             if (Charset.isSupported(csn))
  65                 return new StreamEncoder(out, lock, Charset.forName(csn));
  66         } catch (IllegalCharsetNameException x) { }
  67         throw new UnsupportedEncodingException (csn);
  68     }
  69 
  70     public static StreamEncoder forOutputStreamWriter(OutputStream out,
  71                                                       Object lock,
  72                                                       Charset cs)
  73     {
  74         return new StreamEncoder(out, lock, cs);
  75     }
  76 
  77     public static StreamEncoder forOutputStreamWriter(OutputStream out,
  78                                                       Object lock,
  79                                                       CharsetEncoder enc)
  80     {
  81         return new StreamEncoder(out, lock, enc);
  82     }
  83 
  84 
  85     // Factory for java.nio.channels.Channels.newWriter
  86 
  87     public static StreamEncoder forEncoder(WritableByteChannel ch,
  88                                            CharsetEncoder enc,
  89                                            int minBufferCap)
  90     {
  91         return new StreamEncoder(ch, enc, minBufferCap);
  92     }
  93 
  94 
  95     // -- Public methods corresponding to those in OutputStreamWriter --
  96 
  97     // All synchronization and state/argument checking is done in these public
  98     // methods; the concrete stream-encoder subclasses defined below need not
  99     // do any such checking.
 100 
 101     public String getEncoding() {
 102         if (isOpen())
 103             return encodingName();
 104         return null;
 105     }
 106 
 107     public void flushBuffer() throws IOException {
 108         synchronized (lock) {
 109             if (isOpen())
 110                 implFlushBuffer();
 111             else
 112                 throw new IOException("Stream closed");
 113         }
 114     }
 115 
 116     public void write(int c) throws IOException {
 117         char cbuf[] = new char[1];
 118         cbuf[0] = (char) c;
 119         write(cbuf, 0, 1);
 120     }
 121 
 122     public void write(char cbuf[], int off, int len) throws IOException {
 123         synchronized (lock) {
 124             ensureOpen();
 125             if ((off < 0) || (off > cbuf.length) || (len < 0) ||
 126                 ((off + len) > cbuf.length) || ((off + len) < 0)) {
 127                 throw new IndexOutOfBoundsException();
 128             } else if (len == 0) {
 129                 return;
 130             }
 131             implWrite(cbuf, off, len);
 132         }
 133     }
 134 
 135     public void write(String str, int off, int len) throws IOException {
 136         /* Check the len before creating a char buffer */
 137         if (len < 0)
 138             throw new IndexOutOfBoundsException();
 139         char cbuf[] = new char[len];
 140         str.getChars(off, off + len, cbuf, 0);
 141         write(cbuf, 0, len);
 142     }
 143 
 144     public void write(CharBuffer cb) throws IOException {
 145         int position = cb.position();
 146         try {
 147             synchronized (lock) {
 148                 ensureOpen();
 149                 implWrite(cb);
 150             }
 151         } finally {
 152             cb.position(position);
 153         }
 154     }
 155 
 156     public void flush() throws IOException {
 157         synchronized (lock) {
 158             ensureOpen();
 159             implFlush();
 160         }
 161     }
 162 
 163     public void close() throws IOException {
 164         synchronized (lock) {
 165             if (closed)
 166                 return;
 167             try {
 168                 implClose();
 169             } finally {
 170                 closed = true;
 171             }
 172         }
 173     }
 174 
 175     private boolean isOpen() {
 176         return !closed;
 177     }
 178 
 179 
 180     // -- Charset-based stream encoder impl --
 181 
 182     private Charset cs;
 183     private CharsetEncoder encoder;
 184     private ByteBuffer bb;
 185 
 186     // Exactly one of these is non-null
 187     private final OutputStream out;
 188     private WritableByteChannel ch;
 189 
 190     // Leftover first char in a surrogate pair
 191     private boolean haveLeftoverChar = false;
 192     private char leftoverChar;
 193     private CharBuffer lcb = null;
 194 
 195     private StreamEncoder(OutputStream out, Object lock, Charset cs) {
 196         this(out, lock,
 197          cs.newEncoder()
 198          .onMalformedInput(CodingErrorAction.REPLACE)
 199          .onUnmappableCharacter(CodingErrorAction.REPLACE));
 200     }
 201 
 202     private StreamEncoder(OutputStream out, Object lock, CharsetEncoder enc) {
 203         super(lock);
 204         this.out = out;
 205         this.ch = null;
 206         this.cs = enc.charset();
 207         this.encoder = enc;
 208 
 209         // This path disabled until direct buffers are faster
 210         if (false && out instanceof FileOutputStream) {
 211                 ch = ((FileOutputStream)out).getChannel();
 212         if (ch != null)
 213                     bb = ByteBuffer.allocateDirect(DEFAULT_BYTE_BUFFER_SIZE);
 214         }
 215             if (ch == null) {
 216         bb = ByteBuffer.allocate(DEFAULT_BYTE_BUFFER_SIZE);
 217         }
 218     }
 219 
 220     private StreamEncoder(WritableByteChannel ch, CharsetEncoder enc, int mbc) {
 221         this.out = null;
 222         this.ch = ch;
 223         this.cs = enc.charset();
 224         this.encoder = enc;
 225         this.bb = ByteBuffer.allocate(mbc < 0
 226                                   ? DEFAULT_BYTE_BUFFER_SIZE
 227                                   : mbc);
 228     }
 229 
 230     private void writeBytes() throws IOException {
 231         bb.flip();
 232         int lim = bb.limit();
 233         int pos = bb.position();
 234         assert (pos <= lim);
 235         int rem = (pos <= lim ? lim - pos : 0);
 236 
 237             if (rem > 0) {
 238         if (ch != null) {
 239             if (ch.write(bb) != rem)
 240                 assert false : rem;
 241         } else {
 242             out.write(bb.array(), bb.arrayOffset() + pos, rem);
 243         }
 244         }
 245         bb.clear();
 246         }
 247 
 248     private void flushLeftoverChar(CharBuffer cb, boolean endOfInput)
 249         throws IOException
 250     {
 251         if (!haveLeftoverChar && !endOfInput)
 252             return;
 253         if (lcb == null)
 254             lcb = CharBuffer.allocate(2);
 255         else
 256             lcb.clear();
 257         if (haveLeftoverChar)
 258             lcb.put(leftoverChar);
 259         if ((cb != null) && cb.hasRemaining())
 260             lcb.put(cb.get());
 261         lcb.flip();
 262         while (lcb.hasRemaining() || endOfInput) {
 263             CoderResult cr = encoder.encode(lcb, bb, endOfInput);
 264             if (cr.isUnderflow()) {
 265                 if (lcb.hasRemaining()) {
 266                     leftoverChar = lcb.get();
 267                     if (cb != null && cb.hasRemaining()) {
 268                         lcb.clear();
 269                         lcb.put(leftoverChar).put(cb.get()).flip();
 270                         continue;
 271                     }
 272                     return;
 273                 }
 274                 break;
 275             }
 276             if (cr.isOverflow()) {
 277                 assert bb.position() > 0;
 278                 writeBytes();
 279                 continue;
 280             }
 281             cr.throwException();
 282         }
 283         haveLeftoverChar = false;
 284     }
 285 
 286     void implWrite(char cbuf[], int off, int len)
 287         throws IOException
 288     {
 289         CharBuffer cb = CharBuffer.wrap(cbuf, off, len);
 290         implWrite(cb);
 291     }
 292 
 293     void implWrite(CharBuffer cb)
 294         throws IOException
 295     {
 296         if (haveLeftoverChar) {
 297             flushLeftoverChar(cb, false);
 298         }
 299 
 300         while (cb.hasRemaining()) {
 301             CoderResult cr = encoder.encode(cb, bb, false);
 302             if (cr.isUnderflow()) {
 303                 assert (cb.remaining() <= 1) : cb.remaining();
 304                 if (cb.remaining() == 1) {
 305                     haveLeftoverChar = true;
 306                     leftoverChar = cb.get();
 307                 }
 308                 break;
 309             }
 310             if (cr.isOverflow()) {
 311                 assert bb.position() > 0;
 312                 writeBytes();
 313                 continue;
 314             }
 315             cr.throwException();
 316         }
 317     }
 318 
 319     void implFlushBuffer() throws IOException {
 320         if (bb.position() > 0)
 321         writeBytes();
 322     }
 323 
 324     void implFlush() throws IOException {
 325         implFlushBuffer();
 326         if (out != null)
 327         out.flush();
 328     }
 329 
 330     void implClose() throws IOException {
 331         flushLeftoverChar(null, true);
 332         try {
 333             for (;;) {
 334                 CoderResult cr = encoder.flush(bb);
 335                 if (cr.isUnderflow())
 336                     break;
 337                 if (cr.isOverflow()) {
 338                     assert bb.position() > 0;
 339                     writeBytes();
 340                     continue;
 341                 }
 342                 cr.throwException();
 343             }
 344 
 345             if (bb.position() > 0)
 346                 writeBytes();
 347             if (ch != null)
 348                 ch.close();
 349             else {
 350                 try {
 351                     out.flush();
 352                 } finally {
 353                     out.close();
 354                 }
 355             }
 356         } catch (IOException x) {
 357             encoder.reset();
 358             throw x;
 359         }
 360     }
 361 
 362     String encodingName() {
 363         return ((cs instanceof HistoricallyNamedCharset)
 364             ? ((HistoricallyNamedCharset)cs).historicalName()
 365             : cs.name());
 366     }
 367 }
--- EOF ---