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.ReadableByteChannel;
34  
35  import org.apache.http.ConnectionClosedException;
36  import org.apache.http.annotation.NotThreadSafe;
37  import org.apache.http.impl.io.HttpTransportMetricsImpl;
38  import org.apache.http.nio.FileContentDecoder;
39  import org.apache.http.nio.reactor.SessionInputBuffer;
40  import org.apache.http.util.Args;
41  
42  /**
43   * Content decoder that cuts off after a defined number of bytes. This class
44   * is used to receive content of HTTP messages where the end of the content
45   * entity is determined by the value of the <code>Content-Length header</code>.
46   * Entities transferred using this stream can be maximum {@link Long#MAX_VALUE}
47   * long.
48   * <p>
49   * This decoder is optimized to transfer data directly from the underlying
50   * I/O session's channel to a {@link FileChannel}, whenever
51   * possible avoiding intermediate buffering in the session buffer.
52   *
53   * @since 4.0
54   */
55  @NotThreadSafe
56  public class LengthDelimitedDecoder extends AbstractContentDecoder
57          implements FileContentDecoder {
58  
59      private final long contentLength;
60  
61      private long len;
62  
63      public LengthDelimitedDecoder(
64              final ReadableByteChannel channel,
65              final SessionInputBuffer buffer,
66              final HttpTransportMetricsImpl metrics,
67              final long contentLength) {
68          super(channel, buffer, metrics);
69          Args.notNegative(contentLength, "Content length");
70          this.contentLength = contentLength;
71      }
72  
73      @Override
74      public int read(final ByteBuffer dst) throws IOException {
75          Args.notNull(dst, "Byte buffer");
76          if (this.completed) {
77              return -1;
78          }
79          final int chunk = (int) Math.min((this.contentLength - this.len), Integer.MAX_VALUE);
80  
81          final int bytesRead;
82          if (this.buffer.hasData()) {
83              final int maxLen = Math.min(chunk, this.buffer.length());
84              bytesRead = this.buffer.read(dst, maxLen);
85          } else {
86              bytesRead = readFromChannel(dst, chunk);
87          }
88          if (bytesRead == -1) {
89              this.completed = true;
90              if (this.len < this.contentLength) {
91                  throw new ConnectionClosedException(
92                          "Premature end of Content-Length delimited message body (expected: "
93                          + this.contentLength + "; received: " + this.len);
94              }
95          }
96          this.len += bytesRead;
97          if (this.len >= this.contentLength) {
98              this.completed = true;
99          }
100         if (this.completed && bytesRead == 0) {
101             return -1;
102         } else {
103             return bytesRead;
104         }
105     }
106 
107     @Override
108     public long transfer(
109             final FileChannel dst,
110             final long position,
111             final long count) throws IOException {
112 
113         if (dst == null) {
114             return 0;
115         }
116         if (this.completed) {
117             return -1;
118         }
119 
120         final int chunk = (int) Math.min((this.contentLength - this.len), Integer.MAX_VALUE);
121 
122         final long bytesRead;
123         if (this.buffer.hasData()) {
124             final int maxLen = Math.min(chunk, this.buffer.length());
125             dst.position(position);
126             bytesRead = this.buffer.read(dst, maxLen);
127         } else {
128             if (this.channel.isOpen()) {
129                 if (position > dst.size()) {
130                     throw new IOException("Position past end of file [" + position +
131                             " > " + dst.size() + "]");
132                 }
133                 bytesRead = dst.transferFrom(this.channel, position, count < chunk ? count : chunk);
134             } else {
135                 bytesRead = -1;
136             }
137             if (bytesRead > 0) {
138                 this.metrics.incrementBytesTransferred(bytesRead);
139             }
140         }
141         if (bytesRead == -1) {
142             this.completed = true;
143             if (this.len < this.contentLength) {
144                 throw new ConnectionClosedException(
145                         "Premature end of Content-Length delimited message body (expected: "
146                         + this.contentLength + "; received: " + this.len);
147             }
148         }
149         this.len += bytesRead;
150         if (this.len >= this.contentLength) {
151             this.completed = true;
152         }
153         return bytesRead;
154     }
155 
156     @Override
157     public String toString() {
158         final StringBuilder sb = new StringBuilder();
159         sb.append("[content length: ");
160         sb.append(this.contentLength);
161         sb.append("; pos: ");
162         sb.append(this.len);
163         sb.append("; completed: ");
164         sb.append(this.completed);
165         sb.append("]");
166         return sb.toString();
167     }
168 }