View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.channel;
17  
18  import io.netty.util.AbstractReferenceCounted;
19  import io.netty.util.IllegalReferenceCountException;
20  import io.netty.util.internal.ObjectUtil;
21  import io.netty.util.internal.logging.InternalLogger;
22  import io.netty.util.internal.logging.InternalLoggerFactory;
23  
24  import java.io.File;
25  import java.io.IOException;
26  import java.io.RandomAccessFile;
27  import java.nio.channels.FileChannel;
28  import java.nio.channels.WritableByteChannel;
29  
30  import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
31  
32  /**
33   * Default {@link FileRegion} implementation which transfer data from a {@link FileChannel} or {@link File}.
34   *
35   * Be aware that the {@link FileChannel} will be automatically closed once {@link #refCnt()} returns
36   * {@code 0}.
37   */
38  public class DefaultFileRegion extends AbstractReferenceCounted implements FileRegion {
39  
40      private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultFileRegion.class);
41      private final File f;
42      private final long position;
43      private final long count;
44      private long transferred;
45      private FileChannel file;
46  
47      /**
48       * Create a new instance
49       *
50       * @param fileChannel      the {@link FileChannel} which should be transferred
51       * @param position         the position from which the transfer should start
52       * @param count            the number of bytes to transfer
53       */
54      public DefaultFileRegion(FileChannel fileChannel, long position, long count) {
55          this.file = ObjectUtil.checkNotNull(fileChannel, "fileChannel");
56          this.position = checkPositiveOrZero(position, "position");
57          this.count = checkPositiveOrZero(count, "count");
58          this.f = null;
59      }
60  
61      /**
62       * Create a new instance using the given {@link File}. The {@link File} will be opened lazily or
63       * explicitly via {@link #open()}.
64       *
65       * @param file         the {@link File} which should be transferred
66       * @param position     the position from which the transfer should start
67       * @param count        the number of bytes to transfer
68       */
69      public DefaultFileRegion(File file, long position, long count) {
70          this.f = ObjectUtil.checkNotNull(file, "file");
71          this.position = checkPositiveOrZero(position, "position");
72          this.count = checkPositiveOrZero(count, "count");
73      }
74  
75      /**
76       * Returns {@code true} if the {@link FileRegion} has a open file-descriptor
77       */
78      public boolean isOpen() {
79          return file != null;
80      }
81  
82      FileChannel fileChannel() {
83          return file;
84      }
85  
86      /**
87       * Explicitly open the underlying file-descriptor if not done yet.
88       */
89      public void open() throws IOException {
90          if (!isOpen() && refCnt() > 0) {
91              // Only open if this DefaultFileRegion was not released yet.
92              file = new RandomAccessFile(f, "r").getChannel();
93          }
94      }
95  
96      @Override
97      public long position() {
98          return position;
99      }
100 
101     @Override
102     public long count() {
103         return count;
104     }
105 
106     @Deprecated
107     @Override
108     public long transfered() {
109         return transferred;
110     }
111 
112     @Override
113     public long transferred() {
114         return transferred;
115     }
116 
117     @Override
118     public long transferTo(WritableByteChannel target, long position) throws IOException {
119         long count = this.count - position;
120         if (count < 0 || position < 0) {
121             throw new IllegalArgumentException(
122                     "position out of range: " + position +
123                     " (expected: 0 - " + (this.count - 1) + ')');
124         }
125         if (count == 0) {
126             return 0L;
127         }
128         if (refCnt() == 0) {
129             throw new IllegalReferenceCountException(0);
130         }
131         // Call open to make sure fc is initialized. This is a no-oop if we called it before.
132         open();
133 
134         long written = file.transferTo(this.position + position, count, target);
135         if (written > 0) {
136             transferred += written;
137         } else if (written == 0) {
138             // If the amount of written data is 0 we need to check if the requested count is bigger then the
139             // actual file itself as it may have been truncated on disk.
140             //
141             // See https://github.com/netty/netty/issues/8868
142             validate(this, position);
143         }
144         return written;
145     }
146 
147     @Override
148     protected void deallocate() {
149         FileChannel file = this.file;
150 
151         if (file == null) {
152             return;
153         }
154         this.file = null;
155 
156         try {
157             file.close();
158         } catch (IOException e) {
159             logger.warn("Failed to close a file.", e);
160         }
161     }
162 
163     @Override
164     public FileRegion retain() {
165         super.retain();
166         return this;
167     }
168 
169     @Override
170     public FileRegion retain(int increment) {
171         super.retain(increment);
172         return this;
173     }
174 
175     @Override
176     public FileRegion touch() {
177         return this;
178     }
179 
180     @Override
181     public FileRegion touch(Object hint) {
182         return this;
183     }
184 
185     static void validate(DefaultFileRegion region, long position) throws IOException {
186         // If the amount of written data is 0 we need to check if the requested count is bigger then the
187         // actual file itself as it may have been truncated on disk.
188         //
189         // See https://github.com/netty/netty/issues/8868
190         long size = region.file.size();
191         long count = region.count - position;
192         if (region.position + count + position > size) {
193             throw new IOException("Underlying file size " + size + " smaller then requested count " + region.count);
194         }
195     }
196 }