1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portal.kernel.io.unsync;
16  
17  import java.io.IOException;
18  import java.io.OutputStream;
19  
20  /**
21   * <a href="UnsyncBufferedOutputStream.java.html"><b><i>View Source</i></b></a>
22   *
23   * <p>
24   * See http://issues.liferay.com/browse/LPS-6648.
25   * </p>
26   *
27   * @author Shuyang Zhou
28   */
29  public class UnsyncBufferedOutputStream extends UnsyncFilterOutputStream {
30  
31      public UnsyncBufferedOutputStream(OutputStream outputStream) {
32          this(outputStream, _DEFAULT_BUFFER_SIZE);
33      }
34  
35      public UnsyncBufferedOutputStream(OutputStream outputStream, int size) {
36          super(outputStream);
37  
38          buffer = new byte[size];
39      }
40  
41      public void flush() throws IOException {
42          if (count > 0) {
43              outputStream.write(buffer, 0, count);
44  
45              count = 0;
46          }
47  
48          outputStream.flush();
49      }
50  
51      public void write(byte[] byteArray, int offset, int length)
52          throws IOException {
53  
54          if (length >= buffer.length) {
55              if (count > 0) {
56                  outputStream.write(buffer, 0, count);
57  
58                  count = 0;
59              }
60  
61              outputStream.write(byteArray, offset, length);
62  
63              return;
64          }
65  
66          if (count > 0 && length > buffer.length - count) {
67              outputStream.write(buffer, 0, count);
68  
69              count = 0;
70          }
71  
72          System.arraycopy(byteArray, offset, buffer, count, length);
73  
74          count += length;
75      }
76  
77      public void write(byte[] byteArray) throws IOException {
78          write(byteArray, 0, byteArray.length);
79      }
80  
81      public void write(int b) throws IOException {
82          if (count >= buffer.length) {
83              outputStream.write(buffer, 0, count);
84  
85              count = 0;
86          }
87  
88          buffer[count++] = (byte)b;
89      }
90  
91      protected byte[] buffer;
92      protected int count;
93  
94      private static int _DEFAULT_BUFFER_SIZE = 8192;
95  
96  }