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