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  
28  package org.apache.http.impl.nio.codecs;
29  
30  import java.io.IOException;
31  import java.nio.ByteBuffer;
32  import java.nio.channels.WritableByteChannel;
33  
34  import org.apache.http.annotation.NotThreadSafe;
35  import org.apache.http.impl.io.HttpTransportMetricsImpl;
36  import org.apache.http.io.BufferInfo;
37  import org.apache.http.nio.reactor.SessionOutputBuffer;
38  import org.apache.http.util.CharArrayBuffer;
39  
40  /**
41   * Implements chunked transfer coding. The content is sent in small chunks.
42   * Entities transferred using this decoder can be of unlimited length.
43   *
44   * @since 4.0
45   */
46  @NotThreadSafe
47  public class ChunkEncoder extends AbstractContentEncoder {
48  
49      private final int fragHint;
50      private final CharArrayBuffer lineBuffer;
51  
52      private final BufferInfo bufferinfo;
53  
54      /**
55       * @since 4.3
56       *
57       * @param channel underlying channel.
58       * @param buffer  session buffer.
59       * @param metrics transport metrics.
60       * @param fragementSizeHint fragment size hint defining an minimal size of a fragment
61       *   that should be written out directly to the channel bypassing the session buffer.
62       *   Value <code>0</code> disables fragment buffering.
63       */
64      public ChunkEncoder(
65              final WritableByteChannel channel,
66              final SessionOutputBuffer buffer,
67              final HttpTransportMetricsImpl metrics,
68              final int fragementSizeHint) {
69          super(channel, buffer, metrics);
70          this.fragHint = fragementSizeHint > 0 ? fragementSizeHint : 0;
71          this.lineBuffer = new CharArrayBuffer(16);
72          if (buffer instanceof BufferInfo) {
73              this.bufferinfo = (BufferInfo) buffer;
74          } else {
75              this.bufferinfo = null;
76          }
77      }
78  
79      public ChunkEncoder(
80              final WritableByteChannel channel,
81              final SessionOutputBuffer buffer,
82              final HttpTransportMetricsImpl metrics) {
83          this(channel, buffer, metrics, 0);
84      }
85  
86      public int write(final ByteBuffer src) throws IOException {
87          if (src == null) {
88              return 0;
89          }
90          assertNotCompleted();
91  
92          int total = 0;
93          while (src.hasRemaining()) {
94              int chunk = src.remaining();
95              int avail;
96              if (this.bufferinfo != null) {
97                  avail = this.bufferinfo.available();
98              } else {
99                  avail = 4096;
100             }
101 
102             // subtract the length of the longest chunk header
103             // 12345678\r\n
104             // <chunk-data>\r\n
105             avail -= 12;
106             if (avail > 0) {
107                 if (avail < chunk) {
108                     // write no more than 'avail' bytes
109                     chunk = avail;
110                     this.lineBuffer.clear();
111                     this.lineBuffer.append(Integer.toHexString(chunk));
112                     this.buffer.writeLine(this.lineBuffer);
113                     final int oldlimit = src.limit();
114                     src.limit(src.position() + chunk);
115                     this.buffer.write(src);
116                     src.limit(oldlimit);
117                 } else {
118                     // write all
119                     this.lineBuffer.clear();
120                     this.lineBuffer.append(Integer.toHexString(chunk));
121                     this.buffer.writeLine(this.lineBuffer);
122                     this.buffer.write(src);
123                 }
124                 this.lineBuffer.clear();
125                 this.buffer.writeLine(this.lineBuffer);
126                 total += chunk;
127             }
128             if (this.buffer.length() >= this.fragHint || src.hasRemaining()) {
129                 final int bytesWritten = flushToChannel();
130                 if (bytesWritten == 0) {
131                     break;
132                 }
133             }
134         }
135         return total;
136     }
137 
138     @Override
139     public void complete() throws IOException {
140         assertNotCompleted();
141         this.lineBuffer.clear();
142         this.lineBuffer.append("0");
143         this.buffer.writeLine(this.lineBuffer);
144         this.lineBuffer.clear();
145         this.buffer.writeLine(this.lineBuffer);
146         super.complete();
147     }
148 
149     @Override
150     public String toString() {
151         final StringBuilder sb = new StringBuilder();
152         sb.append("[chunk-coded; completed: ");
153         sb.append(isCompleted());
154         sb.append("]");
155         return sb.toString();
156     }
157 
158 }