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.File;
30  import java.io.IOException;
31  import java.io.RandomAccessFile;
32  import java.nio.ByteBuffer;
33  import java.util.Set;
34  import java.util.concurrent.atomic.AtomicReference;
35  
36  import org.apache.hc.core5.http.ContentType;
37  import org.apache.hc.core5.http.nio.AsyncEntityProducer;
38  import org.apache.hc.core5.http.nio.DataStreamChannel;
39  import org.apache.hc.core5.util.Args;
40  import org.apache.hc.core5.util.Asserts;
41  
42  /**
43   * @since 5.0
44   */
45  public final class FileEntityProducer implements AsyncEntityProducer {
46  
47      private final File file;
48      private final ByteBuffer bytebuf;
49      private final long length;
50      private final ContentType contentType;
51      private final AtomicReference<Exception> exception;
52  
53      private AtomicReference<RandomAccessFile> accessFileRef;
54      private boolean eof;
55  
56      public FileEntityProducer(final File file, final int bufferSize, final ContentType contentType) {
57          this.file = Args.notNull(file, "File");
58          this.length = file.length();
59          this.bytebuf = ByteBuffer.allocate((int)(bufferSize > this.length ? bufferSize : this.length));
60          this.contentType = contentType;
61          this.accessFileRef = new AtomicReference<>(null);
62          this.exception = new AtomicReference<>(null);
63      }
64  
65      public FileEntityProducer(final File file, final ContentType contentType) {
66          this(file, 8192, contentType);
67      }
68  
69      public FileEntityProducer(final File content) {
70          this(content, ContentType.APPLICATION_OCTET_STREAM);
71      }
72  
73      @Override
74      public boolean isRepeatable() {
75          return true;
76      }
77  
78      @Override
79      public String getContentType() {
80          return contentType != null ? contentType.toString() : null;
81      }
82  
83      @Override
84      public long getContentLength() {
85          return length;
86      }
87  
88      @Override
89      public int available() {
90          return Integer.MAX_VALUE;
91      }
92  
93      @Override
94      public String getContentEncoding() {
95          return null;
96      }
97  
98      @Override
99      public boolean isChunked() {
100         return false;
101     }
102 
103     @Override
104     public Set<String> getTrailerNames() {
105         return null;
106     }
107 
108     @Override
109     public void produce(final DataStreamChannel channel) throws IOException {
110         RandomAccessFile accessFile = accessFileRef.get();
111         if (accessFile == null) {
112             accessFile = new RandomAccessFile(file, "r");
113             Asserts.check(accessFileRef.getAndSet(accessFile) == null, "Illegal producer state");
114         }
115         if (!eof) {
116             final int bytesRead = accessFile.getChannel().read(bytebuf);
117             if (bytesRead < 0) {
118                 eof = true;
119             }
120         }
121         if (bytebuf.position() > 0) {
122             bytebuf.flip();
123             channel.write(bytebuf);
124             bytebuf.compact();
125         }
126         if (eof && bytebuf.position() == 0) {
127             channel.endStream();
128             releaseResources();
129         }
130     }
131 
132     @Override
133     public void failed(final Exception cause) {
134         if (exception.compareAndSet(null, cause)) {
135             releaseResources();
136         }
137     }
138 
139     public Exception getException() {
140         return exception.get();
141     }
142 
143     @Override
144     public void releaseResources() {
145         eof = false;
146         final RandomAccessFile accessFile = accessFileRef.getAndSet(null);
147         if (accessFile != null) {
148             try {
149                 accessFile.close();
150             } catch (final IOException ignore) {
151             }
152         }
153     }
154 
155 }