View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.http.impl.io;
29  
30  import java.io.IOException;
31  import java.io.OutputStream;
32  
33  import org.apache.http.io.SessionOutputBuffer;
34  import org.apache.http.util.Args;
35  
36  /**
37   * Output stream that cuts off after a defined number of bytes. This class
38   * is used to send content of HTTP messages where the end of the content entity
39   * is determined by the value of the {@code Content-Length header}.
40   * Entities transferred using this stream can be maximum {@link Long#MAX_VALUE}
41   * long.
42   * <p>
43   * Note that this class NEVER closes the underlying stream, even when close
44   * gets called.  Instead, the stream will be marked as closed and no further
45   * output will be permitted.
46   *
47   * @since 4.0
48   */
49  public class ContentLengthOutputStream extends OutputStream {
50  
51      /**
52       * Wrapped session output buffer.
53       */
54      private final SessionOutputBuffer out;
55  
56      /**
57       * The maximum number of bytes that can be written the stream. Subsequent
58       * write operations will be ignored.
59       */
60      private final long contentLength;
61  
62      /** Total bytes written */
63      private long total = 0;
64  
65      /** True if the stream is closed. */
66      private boolean closed = false;
67  
68      /**
69       * Wraps a session output buffer and cuts off output after a defined number
70       * of bytes.
71       *
72       * @param out The session output buffer
73       * @param contentLength The maximum number of bytes that can be written to
74       * the stream. Subsequent write operations will be ignored.
75       *
76       * @since 4.0
77       */
78      public ContentLengthOutputStream(final SessionOutputBuffer out, final long contentLength) {
79          super();
80          this.out = Args.notNull(out, "Session output buffer");
81          this.contentLength = Args.notNegative(contentLength, "Content length");
82      }
83  
84      /**
85       * <p>Does not close the underlying socket output.</p>
86       *
87       * @throws IOException If an I/O problem occurs.
88       */
89      @Override
90      public void close() throws IOException {
91          if (!this.closed) {
92              this.closed = true;
93              this.out.flush();
94          }
95      }
96  
97      @Override
98      public void flush() throws IOException {
99          this.out.flush();
100     }
101 
102     @Override
103     public void write(final byte[] b, final int off, final int len) throws IOException {
104         if (this.closed) {
105             throw new IOException("Attempted write to closed stream.");
106         }
107         if (this.total < this.contentLength) {
108             final long max = this.contentLength - this.total;
109             int chunk = len;
110             if (chunk > max) {
111                 chunk = (int) max;
112             }
113             this.out.write(b, off, chunk);
114             this.total += chunk;
115         }
116     }
117 
118     @Override
119     public void write(final byte[] b) throws IOException {
120         write(b, 0, b.length);
121     }
122 
123     @Override
124     public void write(final int b) throws IOException {
125         if (this.closed) {
126             throw new IOException("Attempted write to closed stream.");
127         }
128         if (this.total < this.contentLength) {
129             this.out.write(b);
130             this.total++;
131         }
132     }
133 
134 }