-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileReader.java
211 lines (181 loc) · 6.6 KB
/
FileReader.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/*
* Copyright 2018 Alexey Zhytnik
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zhytnik.reactive.io;
import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Flow.Publisher;
import java.util.concurrent.Flow.Subscriber;
import java.util.concurrent.Flow.Subscription;
import java.util.function.Supplier;
/**
* A file reader which reads requested bytes of a file by {@link ByteBuffer}.
* Needs custom memory provider {@link ReadSubscription#setAllocator(Supplier)}.
*
* @author Alexey Zhytnik
*/
public final class FileReader implements Publisher<ByteBuffer> {
/**
* Constructs a FileReader.
*/
public FileReader() {
}
/**
* Reads the file. Fails fast on any {@link IOException}.
* Reads file content by ByteBuffers provided by custom memory allocator until
* requested byte count is read. Invokes {@link Subscriber#onNext(Object)}
* only with content which is placed from position to limit (exclusive),
* never invokes {@link Subscriber#onNext(Object)} without file content.
* Warning: the file content should not be modified during subscription,
* otherwise the result of the execution is undefined.
*
* @param subscriber the subscriber-reader
* @see ReadSubscription
*/
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
try (final ReadRequest r = new ReadRequest(subscriber)) {
subscriber.onSubscribe(r);
if (r.isActive()) r.tryInitialize();
while (r.isActive()) {
final ByteBuffer chunk = r.allocator.get();
final int progress = r.resource.read(chunk, r.position());
chunk.limit(chunk.position());
chunk.position(chunk.limit() - progress);
subscriber.onNext(chunk);
r.update(progress);
}
} catch (Exception error) {
subscriber.onError(error);
}
}
/**
* Represents a file reading subscription.
*
* @author Alexey Zhytnik
*/
public interface ReadSubscription extends Subscription {
/**
* Installs a path to file for reading.
*
* @param path the path to file
*/
void setPath(Path path);
/**
* Installs memory allocator which provides a memory for file reading.
* Each invocation of memory allocator should return a ByteBuffer whose bytes
* from position to limit (exclusive) will be used for writing file content,
* but not all that bytes could be used, limit position could be decreased.
*
* @param allocator the memory allocator
*/
void setAllocator(Supplier<ByteBuffer> allocator);
/**
* Adds bytes for reading. Needs installed path and memory allocator,
* otherwise throws {@link IllegalStateException}.
* A value of {@code Long.MAX_VALUE} is request to read all file,
* in other cases if requested byte count is negative or greater
* than the file's size then {@link IllegalArgumentException} will be thrown.
*
* @param bytes the additional count of bytes for read
*/
@Override
void request(long bytes);
/**
* Stops reading, all used resources will be released after invoking.
*/
@Override
void cancel();
}
private static final class ReadRequest implements ReadSubscription, Closeable {
private long max;
private long limit;
private long position;
private boolean interrupted;
private Path path;
private FileChannel resource;
private Supplier<ByteBuffer> allocator;
private final Subscriber subscriber;
private ReadRequest(Subscriber subscriber) {
this.max = Long.MAX_VALUE;
this.subscriber = subscriber;
}
private void tryInitialize() throws IOException {
final long firstRequestedBytes = limit;
interrupted = true;
resource = FileChannel.open(path, StandardOpenOption.READ);
max = resource.size();
limit = 0;
interrupted = false;
request(firstRequestedBytes);
}
@Override
public void setPath(Path path) {
this.path = path;
}
@Override
public void setAllocator(Supplier<ByteBuffer> allocator) {
this.allocator = allocator;
}
private boolean isActive() {
return !interrupted && position < limit;
}
private long position() {
return position;
}
private void update(int progress) {
position += progress;
}
@Override
public void request(long bytes) {
if (path == null || allocator == null) {
onError(new IllegalStateException("Both Path and Memory allocator should be installed!"));
} else if (bytes < 0) {
onError(new IllegalArgumentException("Requested " + bytes + " bytes!"));
} else if (bytes == Long.MAX_VALUE) {
limit = max;
} else if (limit + bytes <= max) {
limit += bytes;
} else {
onError(new IllegalArgumentException(path + " contains only " + max + " bytes!"));
}
}
private void onError(Throwable error) {
interrupted = true;
subscriber.onError(error);
}
@Override
public void cancel() {
interrupted = true;
}
@Override
public void close() {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
if (!interrupted) onError(e);
}
}
if (!interrupted && position == limit) {
subscriber.onComplete();
}
}
}
}