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      public void reset() {
95          if (this.shutdown) {
96              return;
97          }
98          this.lock.lock();
99          try {
100             clear();
101             this.endOfStream = false;
102         } finally {
103             this.lock.unlock();
104         }
105     }
106 
107     @Override
108     public boolean hasData() {
109         this.lock.lock();
110         try {
111             return super.hasData();
112         } finally {
113             this.lock.unlock();
114         }
115     }
116 
117     @Override
118     public int available() {
119         this.lock.lock();
120         try {
121             return super.available();
122         } finally {
123             this.lock.unlock();
124         }
125     }
126 
127     @Override
128     public int capacity() {
129         this.lock.lock();
130         try {
131             return super.capacity();
132         } finally {
133             this.lock.unlock();
134         }
135     }
136 
137     @Override
138     public int length() {
139         this.lock.lock();
140         try {
141             return super.length();
142         } finally {
143             this.lock.unlock();
144         }
145     }
146 
147     /**
148      * @deprecated (4.3) use {@link #produceContent(ContentEncoder, IOControl)}
149      */
150     @Deprecated
151     public int produceContent(final ContentEncoder encoder) throws IOException {
152         return produceContent(encoder, null);
153     }
154 
155     /**
156      * @since 4.3
157      */
158     public int produceContent(final ContentEncoder encoder, final IOControl ioctrl) throws IOException {
159         if (this.shutdown) {
160             return -1;
161         }
162         this.lock.lock();
163         try {
164             if (ioctrl != null) {
165                 this.ioctrl = ioctrl;
166             }
167             setOutputMode();
168             int bytesWritten = 0;
169             if (super.hasData()) {
170                 bytesWritten = encoder.write(this.buffer);
171                 if (encoder.isCompleted()) {
172                     this.endOfStream = true;
173                 }
174             }
175             if (!super.hasData()) {
176                 // No more buffered content
177                 // If at the end of the stream, terminate
178                 if (this.endOfStream && !encoder.isCompleted()) {
179                     encoder.complete();
180                 }
181                 if (!this.endOfStream) {
182                     // suspend output events
183                     if (this.ioctrl != null) {
184                         this.ioctrl.suspendOutput();
185                     }
186                 }
187             }
188             this.condition.signalAll();
189             return bytesWritten;
190         } finally {
191             this.lock.unlock();
192         }
193     }
194 
195     public void close() {
196         shutdown();
197     }
198 
199     public void shutdown() {
200         if (this.shutdown) {
201             return;
202         }
203         this.shutdown = true;
204         this.lock.lock();
205         try {
206             this.condition.signalAll();
207         } finally {
208             this.lock.unlock();
209         }
210     }
211 
212     public void write(final byte[] b, final int off, final int len) throws IOException {
213         if (b == null) {
214             return;
215         }
216         int pos = off;
217         this.lock.lock();
218         try {
219             Asserts.check(!this.shutdown && !this.endOfStream, "Buffer already closed for writing");
220             setInputMode();
221             int remaining = len;
222             while (remaining > 0) {
223                 if (!this.buffer.hasRemaining()) {
224                     flushContent();
225                     setInputMode();
226                 }
227                 final int chunk = Math.min(remaining, this.buffer.remaining());
228                 this.buffer.put(b, pos, chunk);
229                 remaining -= chunk;
230                 pos += chunk;
231             }
232         } finally {
233             this.lock.unlock();
234         }
235     }
236 
237     public void write(final byte[] b) throws IOException {
238         if (b == null) {
239             return;
240         }
241         write(b, 0, b.length);
242     }
243 
244     public void write(final int b) throws IOException {
245         this.lock.lock();
246         try {
247             Asserts.check(!this.shutdown && !this.endOfStream, "Buffer already closed for writing");
248             setInputMode();
249             if (!this.buffer.hasRemaining()) {
250                 flushContent();
251                 setInputMode();
252             }
253             this.buffer.put((byte)b);
254         } finally {
255             this.lock.unlock();
256         }
257     }
258 
259     public void flush() throws IOException {
260     }
261 
262     private void flushContent() throws IOException {
263         this.lock.lock();
264         try {
265             try {
266                 while (super.hasData()) {
267                     if (this.shutdown) {
268                         throw new InterruptedIOException("Output operation aborted");
269                     }
270                     if (this.ioctrl != null) {
271                         this.ioctrl.requestOutput();
272                     }
273                     this.condition.await();
274                 }
275             } catch (final InterruptedException ex) {
276                 throw new IOException("Interrupted while flushing the content buffer");
277             }
278         } finally {
279             this.lock.unlock();
280         }
281     }
282 
283     public void writeCompleted() throws IOException {
284         this.lock.lock();
285         try {
286             if (this.endOfStream) {
287                 return;
288             }
289             this.endOfStream = true;
290             if (this.ioctrl != null) {
291                 this.ioctrl.requestOutput();
292             }
293         } finally {
294             this.lock.unlock();
295         }
296     }
297 
298 }