View Javadoc

1   package org.jboss.netty.channel;
2   
3   import java.io.IOException;
4   import java.nio.channels.FileChannel;
5   import java.nio.channels.WritableByteChannel;
6   
7   import org.jboss.netty.logging.InternalLogger;
8   import org.jboss.netty.logging.InternalLoggerFactory;
9   
10  public class DefaultFileRegion implements FileRegion {
11  
12      private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultFileRegion.class);
13  
14      private final FileChannel file;
15      private final long position;
16      private final long count;
17      private final boolean releaseAfterTransfer;
18  
19      public DefaultFileRegion(FileChannel file, long position, long count) {
20          this(file, position, count, false);
21      }
22  
23      public DefaultFileRegion(FileChannel file, long position, long count, boolean releaseAfterTransfer) {
24          this.file = file;
25          this.position = position;
26          this.count = count;
27          this.releaseAfterTransfer = releaseAfterTransfer;
28      }
29  
30      public long getPosition() {
31          return position;
32      }
33  
34      public long getCount() {
35          return count;
36      }
37  
38      public boolean releaseAfterTransfer() {
39          return releaseAfterTransfer;
40      }
41  
42      public long transferTo(WritableByteChannel target, long position) throws IOException {
43          long count = this.count - position;
44          if (count < 0 || position < 0) {
45              throw new IllegalArgumentException(
46                      "position out of range: " + position +
47                      " (expected: 0 - " + (this.count - 1) + ")");
48          }
49          if (count == 0) {
50              return 0L;
51          }
52  
53          return file.transferTo(this.position + position, count, target);
54      }
55  
56      public void releaseExternalResources() {
57          try {
58              file.close();
59          } catch (IOException e) {
60              logger.warn("Failed to close a file.", e);
61          }
62      }
63  }