-
Notifications
You must be signed in to change notification settings - Fork 4
/
AsyncFiles.java
333 lines (301 loc) · 12.4 KB
/
AsyncFiles.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/*
* MIT License
*
* Copyright (c) 2018, Miguel Gamboa (gamboa.pt)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package org.javaync.io;
import kotlinx.coroutines.flow.Flow;
import org.jayield.AsyncQuery;
import org.reactivestreams.Publisher;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import static java.nio.channels.AsynchronousFileChannel.open;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* Asynchronous non-blocking read and write operations with a reactive based API.
* Read operations return a CompletableFuture with a single String or a Publisher
* of strings corresponding to lines.
* Write methods return a CompletableFuture with the final file index after the
* completion of corresponding write operation.
* These operations use an underlying AsynchronousFileChannel.
*/
public class AsyncFiles {
private AsyncFiles() {
}
public static AsyncQuery<String> asyncQuery(String file) {
return asyncQuery(Paths.get(file));
}
public static AsyncQuery<String> asyncQuery(Path file) {
return new AsyncFileQuery(file);
}
/**
* Reads the given file from the beginning using an AsyncFileChannel into
* kotlin asynchronous Flow.
* It uses a ByteBuffer of {@link AbstractAsyncFileReaderLines#BUFFER_SIZE BUFFER_SIZE} capacity
*/
public static Flow<String> flow(Path file) {
return AsyncFileReaderFlow.lines(file);
}
/**
* Reads the given file from the beginning using an AsyncFileChannel
* with a ByteBuffer of {@link AbstractAsyncFileReaderLines#BUFFER_SIZE BUFFER_SIZE} capacity.
*/
public static Publisher<String> lines(String file) {
return lines(Paths.get(file));
}
/**
* Reads the given file from the beginning using an AsyncFileChannel
* with a ByteBuffer of {@link AbstractAsyncFileReaderLines#BUFFER_SIZE BUFFER_SIZE} capacity.
*/
public static Publisher<String> lines(Path file) {
return lines(AbstractAsyncFileReaderLines.BUFFER_SIZE, file);
}
/**
* Reads the given file from the beginning using
* an AsyncFileChannel with a ByteBuffer of
* the specified bufferSize capacity.
*/
public static Publisher<String> lines(int bufferSize, String file) {
return lines(bufferSize, Paths.get(file));
}
/**
* Reads the given file from the beginning using
* an AsyncFileChannel with a ByteBuffer of
* the specified bufferSize capacity.
*/
public static Publisher<String> lines(int bufferSize, Path file) {
return lines(bufferSize, file, StandardOpenOption.READ);
}
/**
* Reads the given file from the beginning using
* an AsyncFileChannel with a ByteBuffer of
* the specified bufferSize capacity.
*/
public static Publisher<String> lines(int bufferSize, Path file, StandardOpenOption...options) {
return sub -> {
AsyncFileReaderLines reader = null;
try {
AsynchronousFileChannel asyncFile = open(file, options);
reader = new AsyncFileReaderLines(sub, asyncFile, bufferSize);
} catch (IOException e) {
sub.onSubscribe(reader);
sub.onError(e);
return;
}
sub.onSubscribe(reader);
};
}
/**
* Reads the file from the beginning using an AsyncFileChannel
* with a ByteBuffer of {@link AbstractAsyncFileReaderLines#BUFFER_SIZE BUFFER_SIZE} capacity.
* It automatically closes the underlying AsyncFileChannel when read is complete.
*/
public static CompletableFuture<String> readAll(String file) {
return readAll(Paths.get(file));
}
/**
* A callback based version of readAll().
* Reads the file from the beginning using an AsyncFileChannel
* with a ByteBuffer of {@link AbstractAsyncFileReaderLines#BUFFER_SIZE BUFFER_SIZE} capacity.
* It automatically closes the underlying AsyncFileChannel when read is complete.
*/
public static void readAll(String file, BiConsumer<Throwable, String> callback) {
readAll(file, AbstractAsyncFileReaderLines.BUFFER_SIZE)
.whenComplete((data, err) -> {
if(err != null) callback.accept(err, null);
else callback.accept(null, data);
});
}
/**
* Reads the file from the beginning using
* an AsyncFileChannel with a ByteBuffer of
* the specified bufferSize capacity.
* It automatically closes the underlying AsyncFileChannel
* when read is complete.
*/
public static CompletableFuture<String> readAll(String file, int bufferSize) {
return readAll(Paths.get(file), bufferSize);
}
/**
* Reads the file from the beginning using an {@link AsynchronousFileChannel}
* with a ByteBuffer of {@link AbstractAsyncFileReaderLines#BUFFER_SIZE BUFFER_SIZE} capacity.
* It automatically closes the underlying AsyncFileChannel
* when read is complete.
*/
public static CompletableFuture<String> readAll(Path file) {
return readAll(file, AbstractAsyncFileReaderLines.BUFFER_SIZE);
}
/**
* Reads the file from the beginning using
* an AsyncFileChannel with a ByteBuffer of
* the specified bufferSize capacity.
* It automatically closes the underlying AsyncFileChannel
* when read is complete.
*/
public static CompletableFuture<String> readAll(Path file, int bufferSize) {
return readAllBytes(file, bufferSize)
.thenApply(bytes -> new String(bytes, UTF_8));
}
/**
* Reads all bytes from the beginning of the file using an AsyncFileChannel
* with a ByteBuffer of {@link AbstractAsyncFileReaderLines#BUFFER_SIZE BUFFER_SIZE} capacity.
*/
public static CompletableFuture<byte[]> readAllBytes(Path file) {
return readAllBytes(file, AbstractAsyncFileReaderLines.BUFFER_SIZE);
}
public static CompletableFuture<byte[]> readAllBytes(String file) {
return readAllBytes(Paths.get(file));
}
/**
* Reads all bytes from the beginning of the file
* using an AsyncFileChannel with a ByteBuffer of
* the specified bufferSize capacity.
*/
public static CompletableFuture<byte[]> readAllBytes(
Path file,
int bufferSize,
StandardOpenOption...options)
{
try {
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
ByteArrayOutputStream out = new ByteArrayOutputStream();
AsynchronousFileChannel asyncFile = open(file, options);
CompletableFuture<byte[]> bytes = AsyncFileReaderBytes
.readAllBytes(asyncFile, buffer, 0, out)
.thenApply(position -> out.toByteArray());
/**
* Deliberately chained in this way.
* Code smell: If closeAfc throws an Exception it will be lost!
*/
bytes.whenCompleteAsync((pos, ex) -> closeAfc(asyncFile));
return bytes;
} catch (IOException e) {
return CompletableFuture.failedFuture(e);
}
}
/**
* Writes bytes to a file.
* The options parameter specifies how the file is created or opened.
* All bytes in the byte array are written to the file.
* The method ensures that the file is closed when all bytes have been
* written (or an I/O error or other runtime exception is thrown).
* Returns a CompletableFuture with the final file index
* after the completion of the corresponding write operation.
* If an I/O error occurs then it may complete the resulting CompletableFuture
* exceptionally.
*/
public static CompletableFuture<Integer> writeBytes(
Path path,
byte[] bytes)
{
return writeBytes(path, bytes, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
}
public static CompletableFuture<Integer> writeBytes(
String file,
byte[] bytes)
{
return writeBytes(Paths.get(file), bytes);
}
/**
* Writes bytes to a file.
* The options parameter specifies how the file is created or opened.
* All bytes in the byte array are written to the file.
* The method ensures that the underlying {@code AsynchronousFileChannel}
* is closed when all bytes have been written (or an I/O error or any other
* runtime exception is thrown).
* Returns a {@code CompletableFuture} with the final file index
* after the completion of the corresponding write operation.
* If an I/O error occurs then it may complete the resulting CompletableFuture
* exceptionally.
*/
public static CompletableFuture<Integer> writeBytes(
Path path,
byte[] bytes,
StandardOpenOption... options)
{
try (AsyncFileWriter writer = new AsyncFileWriter(path, options)) {
writer.write(bytes);
// The call to writer.close() is asynchronous and will chain
// a continuation to close the AsyncFileChannel only after completion.
return writer.getPosition();
} catch (IOException e) {
return CompletableFuture.failedFuture(e);
}
}
/**
* Write lines of text to a file. Each line is a char sequence and
* is written to the file in sequence with each line terminated by
* the platform's line separator, as defined by the system property
* line.separator.
* Returns a CompletableFuture with the final file index
* after the completion of the corresponding write operation.
*/
public static CompletableFuture<Integer> write(
Path path,
Iterable<? extends CharSequence> lines)
{
return write(path, lines, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
}
public static CompletableFuture<Integer> write(
String file,
Iterable<? extends CharSequence> lines)
{
return write(Paths.get(file), lines);
}
/**
* Write lines of text to a file. Each line is a char sequence and
* is written to the file in sequence with each line terminated by
* the platform's line separator, as defined by the system property
* line.separator.
* Returns a {@code CompletableFuture} with the final file index
* after the completion of the corresponding write operation.
*/
public static CompletableFuture<Integer> write(
Path path,
Iterable<? extends CharSequence> lines,
StandardOpenOption... options)
{
try (AsyncFileWriter writer = new AsyncFileWriter(path, options)) {
lines.forEach(writer::writeLine);
// The call to writer.close() is asynchronous and will chain
// a continuation to close the AsyncFileChannel only after completion.
return writer.getPosition();
} catch (Exception e) {
return CompletableFuture.failedFuture(e);
}
}
static void closeAfc(AsynchronousFileChannel asyncFile) {
try {
asyncFile.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}