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