Skip to content

Instantly share code, notes, and snippets.

@alexlehm
Last active September 16, 2018 03:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexlehm/b5726ded353eaafd14f4 to your computer and use it in GitHub Desktop.
Save alexlehm/b5726ded353eaafd14f4 to your computer and use it in GitHub Desktop.
vertx http download
import org.junit.Test;
import org.vertx.java.core.AsyncResult;
import org.vertx.java.core.Handler;
import org.vertx.java.core.file.AsyncFile;
import org.vertx.java.core.http.HttpClient;
import org.vertx.java.core.http.HttpClientResponse;
import org.vertx.java.core.streams.Pump;
import org.vertx.testtools.TestVerticle;
public class DownloadTest extends TestVerticle {
@Test
public void downloadTest() {
String downloadUrl = "/apache/httpd/httpd-2.4.10.tar.bz2";
String target = "httpd.tar.gz";
HttpClient httpClient = vertx.createHttpClient().setHost("supergsego.com").setPort(80);
httpClient.get(downloadUrl, new Handler<HttpClientResponse>() {
public void handle(final HttpClientResponse httpEvent) {
//pause the http response till we complete setting up our
//async file handler
httpEvent.pause();
//setup file open handler
vertx.fileSystem().open(target, null, false, true, true, true, new Handler<AsyncResult<AsyncFile>>() {
public void handle(AsyncResult<AsyncFile> fileEvent) {
if(fileEvent.failed()){
fileEvent.cause().printStackTrace();
return;
}
final AsyncFile asynFile = fileEvent.result();
final Pump downloadPump = Pump.createPump(httpEvent, asynFile);
downloadPump.start();
//resume the receive operation
httpEvent.resume();
httpEvent.endHandler(new Handler<Void>() {
public void handle(Void event) {
//close the file
asynFile.flush().close(new Handler<AsyncResult<Void>>() {
public void handle(AsyncResult<Void> event) {
System.out.println("Is file close ok? = " + event.failed());
}
});
System.out.println("File download operation complets: Download size = "
+ downloadPump.bytesPumped());
}
});
}
});
}
}).exceptionHandler(new Handler<Throwable>() {
public void handle(Throwable event) {
System.out.println(event);
}
}).end();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment