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