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  package org.apache.http.nio.util;
28  
29  import java.io.IOException;
30  import java.io.InterruptedIOException;
31  import java.util.concurrent.locks.Condition;
32  import java.util.concurrent.locks.ReentrantLock;
33  
34  import org.apache.http.annotation.ThreadSafe;
35  import org.apache.http.nio.ContentEncoder;
36  import org.apache.http.nio.IOControl;
37  import org.apache.http.util.Args;
38  import org.apache.http.util.Asserts;
39  
40  /**
41   * Implementation of the {@link ContentOutputBuffer} interface that can be
42   * shared by multiple threads, usually the I/O dispatch of an I/O reactor and
43   * a worker thread.
44   * <p>
45   * The I/O dispatch thread is expected to transfer data from the buffer to
46   *   {@link ContentEncoder} by calling {@link #produceContent(ContentEncoder)}.
47   * <p>
48   * The worker thread is expected to write data to the buffer by calling
49   * {@link #write(int)}, {@link #write(byte[], int, int)} or {@link #writeCompleted()}
50   * <p>
51   * In case of an abnormal situation or when no longer needed the buffer must be
52   * shut down using {@link #shutdown()} method.
53   *
54   * @since 4.0
55   */
56  @ThreadSafe
57  public class SharedOutputBuffer extends ExpandableBuffer implements ContentOutputBuffer {
58  
59      private final ReentrantLock lock;
60      private final Condition condition;
61  
62      private volatile IOControl ioctrl;
63      private volatile boolean shutdown = false;
64      private volatile boolean endOfStream = false;
65  
66      /**
67       * @deprecated (4.3) use {@link SharedOutputBuffer#SharedOutputBuffer(int, ByteBufferAllocator)}
68       */
69      @Deprecated
70      public SharedOutputBuffer(final int buffersize, final IOControl ioctrl, final ByteBufferAllocator allocator) {
71          super(buffersize, allocator);
72          Args.notNull(ioctrl, "I/O content control");
73          this.ioctrl = ioctrl;
74          this.lock = new ReentrantLock();
75          this.condition = this.lock.newCondition();
76      }
77  
78      /**
79       * @since 4.3
80       */
81      public SharedOutputBuffer(final int buffersize, final ByteBufferAllocator allocator) {
82          super(buffersize, allocator);
83          this.lock = new ReentrantLock();
84          this.condition = this.lock.newCondition();
85      }
86  
87      /**
88       * @since 4.3
89       */
90      public SharedOutputBuffer(final int buffersize) {
91          this(buffersize, HeapByteBufferAllocator.INSTANCE);
92      }
93  
94      @Override
95      public void reset() {
96          if (this.shutdown) {
97              return;
98          }
99          this.lock.lock();
100         try {
101             clear();
102             this.endOfStream = false;
103         } finally {
104             this.lock.unlock();
105         }
106     }
107 
108     @Override
109     public boolean hasData() {
110         this.lock.lock();
111         try {
112             return super.hasData();
113         } finally {
114             this.lock.unlock();
115         }
116     }
117 
118     @Override
119     public int available() {
120         this.lock.lock();
121         try {
122             return super.available();
123         } finally {
124             this.lock.unlock();
125         }
126     }
127 
128     @Override
129     public int capacity() {
130         this.lock.lock();
131         try {
132             return super.capacity();
133         } finally {
134             this.lock.unlock();
135         }
136     }
137 
138     @Override
139     public int length() {
140         this.lock.lock();
141         try {
142             return super.length();
143         } finally {
144             this.lock.unlock();
145         }
146     }
147 
148     /**
149      * @deprecated (4.3) use {@link #produceContent(ContentEncoder, IOControl)}
150      */
151     @Override
152     @Deprecated
153     public int produceContent(final ContentEncoder encoder) throws IOException {
154         return produceContent(encoder, null);
155     }
156 
157     /**
158      * @since 4.3
159      */
160     public int produceContent(final ContentEncoder encoder, final IOControl ioctrl) throws IOException {
161         if (this.shutdown) {
162             return -1;
163         }
164         this.lock.lock();
165         try {
166             if (ioctrl != null) {
167                 this.ioctrl = ioctrl;
168             }
169             setOutputMode();
170             int bytesWritten = 0;
171             if (super.hasData()) {
172                 bytesWritten = encoder.write(this.buffer);
173                 if (encoder.isCompleted()) {
174                     this.endOfStream = true;
175                 }
176             }
177             if (!super.hasData()) {
178                 // No more buffered content
179                 // If at the end of the stream, terminate
180                 if (this.endOfStream && !encoder.isCompleted()) {
181                     encoder.complete();
182                 }
183                 if (!this.endOfStream) {
184                     // suspend output events
185                     if (this.ioctrl != null) {
186                         this.ioctrl.suspendOutput();
187                     }
188                 }
189             }
190             this.condition.signalAll();
191             return bytesWritten;
192         } finally {
193             this.lock.unlock();
194         }
195     }
196 
197     public void close() {
198         shutdown();
199     }
200 
201     public void shutdown() {
202         if (this.shutdown) {
203             return;
204         }
205         this.shutdown = true;
206         this.lock.lock();
207         try {
208             this.condition.signalAll();
209         } finally {
210             this.lock.unlock();
211         }
212     }
213 
214     @Override
215     public void write(final byte[] b, final int off, final int len) throws IOException {
216         if (b == null) {
217             return;
218         }
219         int pos = off;
220         this.lock.lock();
221         try {
222             Asserts.check(!this.shutdown && !this.endOfStream, "Buffer already closed for writing");
223             setInputMode();
224             int remaining = len;
225             while (remaining > 0) {
226                 if (!this.buffer.hasRemaining()) {
227                     flushContent();
228                     setInputMode();
229                 }
230                 final int chunk = Math.min(remaining, this.buffer.remaining());
231                 this.buffer.put(b, pos, chunk);
232                 remaining -= chunk;
233                 pos += chunk;
234             }
235         } finally {
236             this.lock.unlock();
237         }
238     }
239 
240     public void write(final byte[] b) throws IOException {
241         if (b == null) {
242             return;
243         }
244         write(b, 0, b.length);
245     }
246 
247     @Override
248     public void write(final int b) throws IOException {
249         this.lock.lock();
250         try {
251             Asserts.check(!this.shutdown && !this.endOfStream, "Buffer already closed for writing");
252             setInputMode();
253             if (!this.buffer.hasRemaining()) {
254                 flushContent();
255                 setInputMode();
256             }
257             this.buffer.put((byte)b);
258         } finally {
259             this.lock.unlock();
260         }
261     }
262 
263     @Override
264     public void flush() throws IOException {
265     }
266 
267     private void flushContent() throws IOException {
268         this.lock.lock();
269         try {
270             try {
271                 while (super.hasData()) {
272                     if (this.shutdown) {
273                         throw new InterruptedIOException("Output operation aborted");
274                     }
275                     if (this.ioctrl != null) {
276                         this.ioctrl.requestOutput();
277                     }
278                     this.condition.await();
279                 }
280             } catch (final InterruptedException ex) {
281                 throw new IOException("Interrupted while flushing the content buffer");
282             }
283         } finally {
284             this.lock.unlock();
285         }
286     }
287 
288     @Override
289     public void writeCompleted() throws IOException {
290         this.lock.lock();
291         try {
292             if (this.endOfStream) {
293                 return;
294             }
295             this.endOfStream = true;
296             if (this.ioctrl != null) {
297                 this.ioctrl.requestOutput();
298             }
299         } finally {
300             this.lock.unlock();
301         }
302     }
303 
304 }