Skip to content

Instantly share code, notes, and snippets.

@fehmicansaglam
Created June 2, 2012 12:48
Show Gist options
  • Save fehmicansaglam/2858265 to your computer and use it in GitHub Desktop.
Save fehmicansaglam/2858265 to your computer and use it in GitHub Desktop.
AsyncStreamHandler
public static ListenableFuture<Response> readFile(final String documentUuid,
final OutputStream os) {
final String requestUrl = ...;
try {
return new AsyncHttpClient().prepareGet(requestUrl)
.addQueryParameter("documentUuid", documentUuid)
.execute(new AsyncStreamHandler(os, documentUuid));
} catch (final IOException e) {
throw new UnexpectedException(e);
}
}
public static void download(final String uuid) throws Throwable {
final Document document = ...;
final PipedInputStream is = new PipedInputStream(8388608);
ResourceApiClient.readFile(uuid, new PipedOutputStream(is));
final String dispositionType = "attachment";
final String contentDisposition = "%s; filename=\"%s\"";
response.contentType = document.contentType;
response.setHeader("Content-Disposition",
String.format(contentDisposition, dispositionType, document.name));
response.setHeader("Content-Length", document.length + "");
response.direct = is;
}
public class AsyncStreamHandler implements AsyncHandler<Response> {
private final Response.ResponseBuilder builder = new Response.ResponseBuilder();
private final OutputStream os;
private final Object id;
public AsyncStreamHandler(final OutputStream os, final Object id) {
this.os = os;
this.id = id;
}
@Override
public STATE onBodyPartReceived(final HttpResponseBodyPart content) throws Exception {
content.writeTo(this.os);
return STATE.CONTINUE;
}
@Override
public STATE onStatusReceived(final HttpResponseStatus status) throws Exception {
Logger.trace("Status %d received for stream %s", status.getStatusCode(), this.id);
this.builder.accumulate(status);
return STATE.CONTINUE;
}
@Override
public STATE onHeadersReceived(final HttpResponseHeaders headers) throws Exception {
this.builder.accumulate(headers);
return STATE.CONTINUE;
}
@Override
public Response onCompleted() throws Exception {
Logger.trace("Stream body of %s completed. Closing OutputStream.", this.id);
this.os.close();
return this.builder.build();
}
@Override
public void onThrowable(final Throwable t) {
Logger.error(t, "Error while downloading stream %s", this.id);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment