port update checker to CompletableFuture

This commit is contained in:
FalsePattern committed 2022-06-19 22:57:11 +02:00
1 parent 454e62c348
commit 06833a3607
5 files changed
+144 -137

No files matched your search

@@ -6,6 +6,9 @@ import lombok.var;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
public class Internet {
@@ -27,6 +30,21 @@ public class Internet {
}
}
public static CompletableFuture<byte[]> download(URL URL) {
return CompletableFuture.supplyAsync(() -> {
val result = new ByteArrayOutputStream();
AtomicReference<Exception> caught = new AtomicReference<>();
connect(URL, caught::set, (input) -> {
try {
transferAndClose(input, result);
} catch (IOException e) {
throw new CompletionException(e);
}
});
return result.toByteArray();
});
}
public static void transferAndClose(InputStream is, OutputStream target) throws IOException {
var bytesRead = 0;