-
Notifications
You must be signed in to change notification settings - Fork 69
/
FileDownloadExample.java
81 lines (69 loc) · 2.36 KB
/
FileDownloadExample.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
import io.activej.csp.file.ChannelFileWriter;
import io.activej.csp.supplier.ChannelSuppliers;
import io.activej.eventloop.Eventloop;
import io.activej.fs.tcp.RemoteFileSystem;
import io.activej.inject.Injector;
import io.activej.inject.annotation.Inject;
import io.activej.inject.annotation.Provides;
import io.activej.inject.module.Module;
import io.activej.launcher.Launcher;
import io.activej.reactor.nio.NioReactor;
import io.activej.service.ServiceGraphModule;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
/**
* This example demonstrates downloading file from RemoteFS server.
* To run this example you should first launch ServerSetupExample and then FileUploadExample
*/
@SuppressWarnings("unused")
public final class FileDownloadExample extends Launcher {
private static final int SERVER_PORT = 6732;
private static final String REQUIRED_FILE = "example.txt";
private static final String DOWNLOADED_FILE = "downloaded_example.txt";
private Path clientStorage;
@Override
protected void onInit(Injector injector) throws Exception {
clientStorage = Files.createTempDirectory("client_storage");
}
@Inject
private RemoteFileSystem client;
@Inject
private NioReactor reactor;
@Provides
NioReactor reactor() {
return Eventloop.create();
}
@Provides
RemoteFileSystem remoteFileSystem(NioReactor reactor) {
return RemoteFileSystem.create(reactor, new InetSocketAddress(SERVER_PORT));
}
@Override
protected Module getModule() {
return ServiceGraphModule.create();
}
//[START EXAMPLE]
@Override
protected void run() throws Exception {
ExecutorService executor = newSingleThreadExecutor();
CompletableFuture<Void> future = reactor.submit(() ->
ChannelSuppliers.ofPromise(client.download(REQUIRED_FILE))
.streamTo(ChannelFileWriter.open(executor, clientStorage.resolve(DOWNLOADED_FILE)))
.whenResult(() -> System.out.printf("%nFile '%s' successfully downloaded to '%s'%n%n",
REQUIRED_FILE, clientStorage))
);
try {
future.get();
} finally {
executor.shutdown();
}
}
//[END EXAMPLE]
public static void main(String[] args) throws Exception {
FileDownloadExample example = new FileDownloadExample();
example.launch(args);
}
}