Last active
December 6, 2024 03:20
-
-
Save alexlehm/b5726ded353eaafd14f4 to your computer and use it in GitHub Desktop.
vertx http download
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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