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.FileChannel;
33  import java.nio.channels.WritableByteChannel;
34  
35  import org.apache.http.annotation.NotThreadSafe;
36  import org.apache.http.impl.io.HttpTransportMetricsImpl;
37  import org.apache.http.nio.FileContentEncoder;
38  import org.apache.http.nio.reactor.SessionOutputBuffer;
39  
40  /**
41   * Content encoder that cuts off after a defined number of bytes. This class
42   * is used to send content of HTTP messages where the end of the content entity
43   * is determined by the value of the <code>Content-Length header</code>.
44   * Entities transferred using this stream can be maximum {@link Long#MAX_VALUE}
45   * long.
46   * <p>
47   * This decoder is optimized to transfer data directly from
48   * a {@link FileChannel} to the underlying I/O session's channel whenever
49   * possible avoiding intermediate buffering in the session buffer.
50   *
51   * @since 4.0
52   */
53  @NotThreadSafe
54  public class LengthDelimitedEncoder extends AbstractContentEncoder
55          implements FileContentEncoder {
56  
57      private final long contentLength;
58  
59      private long len;
60  
61      public LengthDelimitedEncoder(
62              final WritableByteChannel channel,
63              final SessionOutputBuffer buffer,
64              final HttpTransportMetricsImpl metrics,
65              long contentLength) {
66          super(channel, buffer, metrics);
67          if (contentLength < 0) {
68              throw new IllegalArgumentException("Content length may not be negative");
69          }
70          this.contentLength = contentLength;
71          this.len = 0;
72      }
73  
74      public int write(final ByteBuffer src) throws IOException {
75          if (src == null) {
76              return 0;
77          }
78          assertNotCompleted();
79          int chunk = (int) Math.min((this.contentLength - this.len), Integer.MAX_VALUE);
80  
81          int bytesWritten;
82          if (src.remaining() > chunk) {
83              int oldLimit = src.limit();
84              int newLimit = oldLimit - (src.remaining() - chunk);
85              src.limit(newLimit);
86              bytesWritten = this.channel.write(src);
87              src.limit(oldLimit);
88          } else {
89              bytesWritten = this.channel.write(src);
90          }
91          if (bytesWritten > 0) {
92              this.metrics.incrementBytesTransferred(bytesWritten);
93          }
94          this.len += bytesWritten;
95          if (this.len >= this.contentLength) {
96              this.completed = true;
97          }
98          return bytesWritten;
99      }
100 
101     public long transfer(
102             final FileChannel src,
103             long position,
104             long count) throws IOException {
105 
106         if (src == null) {
107             return 0;
108         }
109         assertNotCompleted();
110         long chunk = Math.min((this.contentLength - this.len), count);
111         long bytesWritten = src.transferTo(position, chunk, this.channel);
112         if (bytesWritten > 0) {
113             this.metrics.incrementBytesTransferred(bytesWritten);
114         }
115         this.len += bytesWritten;
116         if (this.len >= this.contentLength) {
117             this.completed = true;
118         }
119         return bytesWritten;
120     }
121 
122     @Override
123     public String toString() {
124         StringBuilder buffer = new StringBuilder();
125         buffer.append("[content length: ");
126         buffer.append(this.contentLength);
127         buffer.append("; pos: ");
128         buffer.append(this.len);
129         buffer.append("; completed: ");
130         buffer.append(this.completed);
131         buffer.append("]");
132         return buffer.toString();
133     }
134 
135 }