1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.vfs2.provider.sftp;
18
19 import java.io.DataInputStream;
20 import java.io.FilterInputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23
24 import org.apache.commons.vfs2.FileSystemException;
25 import org.apache.commons.vfs2.provider.AbstractRandomAccessStreamContent;
26 import org.apache.commons.vfs2.util.RandomAccessMode;
27
28
29
30
31 class SftpRandomAccessContent extends AbstractRandomAccessStreamContent {
32
33
34 protected long filePointer;
35
36 private final SftpFileObject fileObject;
37 private DataInputStream dis;
38 private InputStream mis;
39
40 SftpRandomAccessContent(final SftpFileObject fileObject, final RandomAccessMode mode) {
41 super(mode);
42
43 this.fileObject = fileObject;
44
45 }
46
47 @Override
48 public void close() throws IOException {
49 if (dis != null) {
50
51 mis.close();
52
53
54 final DataInputStream oldDis = dis;
55 dis = null;
56 oldDis.close();
57 mis = null;
58 }
59 }
60
61 @Override
62 protected DataInputStream getDataInputStream() throws IOException {
63 if (dis != null) {
64 return dis;
65 }
66
67
68 mis = fileObject.getInputStream(filePointer);
69 dis = new DataInputStream(new FilterInputStream(mis) {
70 @Override
71 public void close() throws IOException {
72 SftpRandomAccessContent.this.close();
73 }
74
75 @Override
76 public int read() throws IOException {
77 final int ret = super.read();
78 if (ret > -1) {
79 filePointer++;
80 }
81 return ret;
82 }
83
84 @Override
85 public int read(final byte[] b) throws IOException {
86 final int ret = super.read(b);
87 if (ret > -1) {
88 filePointer += ret;
89 }
90 return ret;
91 }
92
93 @Override
94 public int read(final byte[] b, final int off, final int len) throws IOException {
95 final int ret = super.read(b, off, len);
96 if (ret > -1) {
97 filePointer += ret;
98 }
99 return ret;
100 }
101 });
102
103 return dis;
104 }
105
106 @Override
107 public long getFilePointer() throws IOException {
108 return filePointer;
109 }
110
111 @Override
112 public long length() throws IOException {
113 return fileObject.getContent().getSize();
114 }
115
116 @Override
117 public void seek(final long pos) throws IOException {
118 if (pos == filePointer) {
119
120 return;
121 }
122
123 if (pos < 0) {
124 throw new FileSystemException("vfs.provider/random-access-invalid-position.error", Long.valueOf(pos));
125 }
126 if (dis != null) {
127 close();
128 }
129
130 filePointer = pos;
131 }
132 }