Skip to content

Instantly share code, notes, and snippets.

@klaeufer
Last active May 4, 2016 20:19
Show Gist options
  • Select an option

  • Save klaeufer/e6e3333004d157ad7e06 to your computer and use it in GitHub Desktop.

Select an option

Save klaeufer/e6e3333004d157ad7e06 to your computer and use it in GitHub Desktop.
Example of asynchronous, cancelable downloading using the Ning AsyncHttpClient (see also https://trello.com/c/KTUBorWF/78-project-4)
// long download: https://downloads.gradle.org/distributions/gradle-2.3-src.zip
// short download: https://repo1.maven.org/maven2/com/ning/async-http-client/1.9.20/async-http-client-1.9.20.jar
// dependencies: see build.sbt
// usage: val f = download(url, localFileName)
// to cancel (if desired): f.cancel(true)
import com.ning.http.client._
import com.ning.http.client.listener._
import java.io.{ File, FileOutputStream }
def fileSaver(name: String) = new TransferListener {
val file = new File(name)
var stream: Option[FileOutputStream] = None
def onRequestHeadersSent(headers: FluentCaseInsensitiveStringsMap): Unit = ()
def onResponseHeadersReceived(headers: FluentCaseInsensitiveStringsMap): Unit =
stream = Some(new FileOutputStream(file))
def onBytesReceived(buffer: Array[Byte]): Unit =
stream.get.write(buffer)
def onBytesSent(amount: Long, current: Long, total: Long): Unit = ()
def onRequestResponseCompleted(): Unit = stream.get.close()
def onThrowable(t: Throwable): Unit = stream.get.close()
}
val progressReporter = new TransferListener {
def onRequestHeadersSent(headers: FluentCaseInsensitiveStringsMap): Unit = ()
def onResponseHeadersReceived(headers: FluentCaseInsensitiveStringsMap): Unit = print("+")
def onBytesReceived(buffer: Array[Byte]): Unit = print("*")
def onBytesSent(amount: Long, current: Long, total: Long): Unit = ()
def onRequestResponseCompleted(): Unit = println("!")
def onThrowable(t: Throwable): Unit = { }
}
val client = new AsyncHttpClient
def download(url: String, local: String): ListenableFuture[Response] = {
val t = new TransferCompletionHandler
t.addTransferListener(fileSaver(local))
t.addTransferListener(progressReporter)
client.prepareGet(url).execute(t)
}
scalaVersion := "2.11.8"
scalacOptions in Compile ++= Seq("-feature", "-unchecked", "-deprecation")
libraryDependencies ++= Seq(
"io.reactivex" %% "rxscala" % "+",
"com.ning" % "async-http-client" % "+",
"org.slf4j" % "slf4j-simple" % "+"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment