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.http.ContentType;
39  import org.apache.hc.core5.http.nio.AsyncEntityProducer;
40  import org.apache.hc.core5.http.nio.DataStreamChannel;
41  import org.apache.hc.core5.http.nio.StreamChannel;
42  import org.apache.hc.core5.util.Args;
43  
44  /**
45   * Abstract text entity content producer.
46   *
47   * @since 5.0
48   */
49  public abstract class AbstractCharAsyncEntityProducer implements AsyncEntityProducer {
50  
51      private enum State { ACTIVE, FLUSHING, END_STREAM }
52  
53      private static final CharBuffer EMPTY = CharBuffer.wrap(new char[0]);
54  
55      private final ByteBuffer bytebuf;
56      private final int fragmentSizeHint;
57      private final ContentType contentType;
58      private final CharsetEncoder charsetEncoder;
59      private final StreamChannel<CharBuffer> charDataStream;
60  
61      private volatile State state;
62  
63      public AbstractCharAsyncEntityProducer(
64              final int bufferSize,
65              final int fragmentSizeHint,
66              final ContentType contentType) {
67          Args.positive(bufferSize, "Buffer size");
68          this.fragmentSizeHint = fragmentSizeHint >= 0 ? fragmentSizeHint : bufferSize / 2;
69          this.bytebuf = ByteBuffer.allocate(bufferSize);
70          this.contentType = contentType;
71          Charset charset = contentType != null ? contentType.getCharset() : null;
72          if (charset == null) {
73              charset = StandardCharsets.US_ASCII;
74          }
75          this.charsetEncoder = charset.newEncoder();
76          this.charDataStream = new StreamChannel<CharBuffer>() {
77  
78              @Override
79              public int write(final CharBuffer src) throws IOException {
80                  Args.notNull(src, "Buffer");
81                  final int p = src.position();
82                  final CoderResult result = charsetEncoder.encode(src, bytebuf, false);
83                  if (result.isError()) {
84                      result.throwException();
85                  }
86                  return src.position() - p;
87              }
88  
89              @Override
90              public void endStream() throws IOException {
91                  state = State.FLUSHING;
92              }
93  
94          };
95          this.state = State.ACTIVE;
96      }
97  
98      /**
99       * Triggered to signal the ability of the underlying char channel
100      * to accept more data. The data producer can choose to write data
101      * immediately inside the call or asynchronously at some later point.
102      *
103      * @param channel the data channel capable to accepting more data.
104      */
105     protected abstract void produceData(StreamChannel<CharBuffer> channel) throws IOException;
106 
107     @Override
108     public final String getContentType() {
109         return contentType != null ? contentType.toString() : null;
110     }
111 
112     @Override
113     public String getContentEncoding() {
114         return null;
115     }
116 
117     @Override
118     public boolean isChunked() {
119         return false;
120     }
121 
122     @Override
123     public Set<String> getTrailerNames() {
124         return null;
125     }
126 
127     @Override
128     public final void produce(final DataStreamChannel channel) throws IOException {
129         if (state.compareTo(State.ACTIVE) == 0) {
130             produceData(charDataStream);
131         }
132         if (state.compareTo(State.ACTIVE) > 0 || !bytebuf.hasRemaining() || bytebuf.position() >= fragmentSizeHint) {
133             bytebuf.flip();
134             channel.write(bytebuf);
135             bytebuf.compact();
136         }
137         if (state.compareTo(State.FLUSHING) == 0) {
138             final CoderResult result = charsetEncoder.encode(EMPTY, bytebuf, true);
139             if (result.isError()) {
140                 result.throwException();
141             } else if (result.isUnderflow()) {
142                 final CoderResult result2 = charsetEncoder.flush(bytebuf);
143                 if (result2.isError()) {
144                     result.throwException();
145                 } else if (result2.isUnderflow()) {
146                     state = State.END_STREAM;
147                 }
148             }
149         }
150         if (bytebuf.position() == 0 && state.compareTo(State.END_STREAM) == 0) {
151             channel.endStream();
152         }
153     }
154 
155     protected void releaseResourcesInternal() {
156     }
157 
158     @Override
159     public final void releaseResources() {
160         charsetEncoder.reset();
161         state = State.ACTIVE;
162         releaseResourcesInternal();
163     }
164 
165 }