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.http.nio.client.methods;
28  
29  import java.io.File;
30  import java.io.FileNotFoundException;
31  import java.io.IOException;
32  import java.io.RandomAccessFile;
33  import java.nio.channels.FileChannel;
34  
35  import org.apache.http.Header;
36  import org.apache.http.HttpEntity;
37  import org.apache.http.HttpResponse;
38  import org.apache.http.entity.ContentType;
39  import org.apache.http.entity.FileEntity;
40  import org.apache.http.nio.ContentDecoder;
41  import org.apache.http.nio.ContentDecoderChannel;
42  import org.apache.http.nio.FileContentDecoder;
43  import org.apache.http.nio.IOControl;
44  import org.apache.http.nio.protocol.AbstractAsyncResponseConsumer;
45  import org.apache.http.protocol.HttpContext;
46  import org.apache.http.util.Asserts;
47  
48  /**
49   * {@link org.apache.http.nio.protocol.HttpAsyncResponseConsumer} implementation that
50   * streams content entity enclosed in an HTTP response directly into a file
51   * without an intermediate in-memory buffer.
52   * <p>
53   * This consumer can be useful for file downloads.
54   *
55   * @since 4.0
56   */
57  public abstract class ZeroCopyConsumer<T> extends AbstractAsyncResponseConsumer<T> {
58  
59      private final File file;
60      private final RandomAccessFile accessfile;
61  
62      private HttpResponse response;
63      private ContentType contentType;
64      private Header contentEncoding;
65      private FileChannel fileChannel;
66      private long idx = -1;
67  
68      public ZeroCopyConsumer(final File file) throws FileNotFoundException {
69          super();
70          if (file == null) {
71              throw new IllegalArgumentException("File may nor be null");
72          }
73          this.file = file;
74          this.accessfile = new RandomAccessFile(this.file, "rw");
75      }
76  
77      @Override
78      protected void onResponseReceived(final HttpResponse response) {
79          this.response = response;
80      }
81  
82      @Override
83      protected void onEntityEnclosed(
84              final HttpEntity entity, final ContentType contentType) throws IOException {
85          this.contentType = contentType;
86          this.contentEncoding = entity.getContentEncoding();
87          this.fileChannel = this.accessfile.getChannel();
88          this.idx = 0;
89      }
90  
91      @Override
92      protected void onContentReceived(
93              final ContentDecoder decoder, final IOControl ioControl) throws IOException {
94          Asserts.notNull(this.fileChannel, "File channel");
95          final long transferred;
96          if (decoder instanceof FileContentDecoder) {
97              transferred = ((FileContentDecoder)decoder).transfer(
98                      this.fileChannel, this.idx, Integer.MAX_VALUE);
99          } else {
100             transferred = this.fileChannel.transferFrom(
101                     new ContentDecoderChannel(decoder), this.idx, Integer.MAX_VALUE);
102         }
103         if (transferred > 0) {
104             this.idx += transferred;
105         }
106         if (decoder.isCompleted()) {
107             this.fileChannel.close();
108         }
109     }
110 
111     /**
112      * Invoked to process received file.
113      *
114      * @param response original response head.
115      * @param file file containing response content.
116      * @param contentType the cotnent type.
117      * @return result of the response processing
118      */
119     protected abstract T process(
120             HttpResponse response, File file, ContentType contentType) throws Exception;
121 
122     @Override
123     protected T buildResult(final HttpContext context) throws Exception {
124         final FileEntity entity = new FileEntity(this.file, this.contentType);
125         entity.setContentEncoding(this.contentEncoding);
126         this.response.setEntity(entity);
127         return process(this.response, this.file, this.contentType);
128     }
129 
130     @Override
131     protected void releaseResources() {
132         try {
133             this.accessfile.close();
134         } catch (final IOException ignore) {
135         }
136     }
137 
138 }