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.hc.core5.http.nio.entity;
28  
29  import java.io.IOException;
30  import java.nio.ByteBuffer;
31  import java.util.Collections;
32  import java.util.Set;
33  import java.util.concurrent.locks.ReentrantLock;
34  
35  import org.apache.hc.core5.annotation.Contract;
36  import org.apache.hc.core5.annotation.ThreadingBehavior;
37  import org.apache.hc.core5.http.ContentType;
38  import org.apache.hc.core5.http.nio.AsyncEntityProducer;
39  import org.apache.hc.core5.http.nio.DataStreamChannel;
40  import org.apache.hc.core5.http.nio.StreamChannel;
41  import org.apache.hc.core5.util.Args;
42  
43  /**
44   * Abstract binary entity content producer.
45   *
46   * @since 5.0
47   */
48  @Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL)
49  public abstract class AbstractBinAsyncEntityProducer implements AsyncEntityProducer {
50  
51      enum State { ACTIVE, FLUSHING, END_STREAM }
52  
53      private final int fragmentSizeHint;
54      private final ByteBuffer byteBuffer;
55      private final ContentType contentType;
56  
57      private final ReentrantLock lock;
58  
59      private volatile State state;
60  
61      public AbstractBinAsyncEntityProducer(final int fragmentSizeHint, final ContentType contentType) {
62          this.fragmentSizeHint = fragmentSizeHint >= 0 ? fragmentSizeHint : 0;
63          this.byteBuffer = ByteBuffer.allocate(this.fragmentSizeHint);
64          this.contentType = contentType;
65          this.state = State.ACTIVE;
66          this.lock = new ReentrantLock();
67      }
68  
69      private void flush(final StreamChannel<ByteBuffer> channel) throws IOException {
70          if (byteBuffer.position() > 0) {
71              byteBuffer.flip();
72              channel.write(byteBuffer);
73              byteBuffer.compact();
74          }
75      }
76  
77      final int writeData(final StreamChannel<ByteBuffer> channel, final ByteBuffer src) throws IOException {
78          final int chunk = src.remaining();
79          if (chunk == 0) {
80              return 0;
81          }
82          if (chunk > fragmentSizeHint) {
83              // the data chunk is greater than the fragment hint
84              // attempt to write it out to the channel directly
85  
86              // flush the buffer if not empty
87              flush(channel);
88              if (byteBuffer.position() == 0) {
89                  return channel.write(src);
90              }
91          } else {
92              // the data chunk is smaller than the fragment hint
93              // attempt to buffer it
94  
95              // flush the buffer if there is not enough space to store the chunk
96              if (byteBuffer.remaining() < chunk) {
97                  flush(channel);
98              }
99              if (byteBuffer.remaining() >= chunk) {
100                 byteBuffer.put(src);
101                 if (!byteBuffer.hasRemaining()) {
102                     flush(channel);
103                 }
104                 return chunk;
105             }
106         }
107         return 0;
108     }
109 
110     final void streamEnd(final StreamChannel<ByteBuffer> channel) throws IOException {
111         if (state == State.ACTIVE) {
112             state = State.FLUSHING;
113             flush(channel);
114             if (byteBuffer.position() == 0) {
115                 state = State.END_STREAM;
116                 channel.endStream();
117             }
118         }
119     }
120 
121     /**
122      * Returns the number of bytes immediately available for output.
123      * This method can be used as a hint to control output events
124      * of the underlying I/O session.
125      *
126      * @return the number of bytes immediately available for output
127      */
128     protected abstract int availableData();
129 
130     /**
131      * Triggered to signal the ability of the underlying byte channel
132      * to accept more data. The data producer can choose to write data
133      * immediately inside the call or asynchronously at some later point.
134      * <p>
135      * {@link StreamChannel} passed to this method is threading-safe.
136      *
137      * @param channel the data channel capable to accepting more data.
138      */
139     protected abstract void produceData(StreamChannel<ByteBuffer> channel) throws IOException;
140 
141     @Override
142     public final String getContentType() {
143         return contentType != null ? contentType.toString() : null;
144     }
145 
146     @Override
147     public String getContentEncoding() {
148         return null;
149     }
150 
151     @Override
152     public boolean isChunked() {
153         return false;
154     }
155 
156     @Override
157     public Set<String> getTrailerNames() {
158         return Collections.emptySet();
159     }
160 
161     @Override
162     public long getContentLength() {
163         return -1;
164     }
165 
166     @Override
167     public final int available() {
168         if (state == State.ACTIVE) {
169             return availableData();
170         } else {
171             lock.lock();
172             try {
173                 return byteBuffer.position();
174             } finally {
175                 lock.unlock();
176             }
177         }
178     }
179 
180     @Override
181     public final void produce(final DataStreamChannel channel) throws IOException {
182         lock.lock();
183         try {
184             if (state == State.ACTIVE) {
185                 produceData(new StreamChannel<ByteBuffer>() {
186 
187                     @Override
188                     public int write(final ByteBuffer src) throws IOException {
189                         Args.notNull(src, "Buffer");
190                         lock.lock();
191                         try {
192                             return writeData(channel, src);
193                         } finally {
194                             lock.unlock();
195                         }
196                     }
197 
198                     @Override
199                     public void endStream() throws IOException {
200                         lock.lock();
201                         try {
202                             streamEnd(channel);
203                         } finally {
204                             lock.unlock();
205                         }
206                     }
207 
208                 });
209             }
210             if (state == State.FLUSHING) {
211                 flush(channel);
212                 if (byteBuffer.position() == 0) {
213                     state = State.END_STREAM;
214                     channel.endStream();
215                 }
216             }
217         } finally {
218             lock.unlock();
219         }
220     }
221 
222     @Override
223     public void releaseResources() {
224         state = State.ACTIVE;
225     }
226 
227 }