Skip to content

Instantly share code, notes, and snippets.

@mikesname
Last active August 12, 2016 09:25
Show Gist options
  • Save mikesname/5b7124f51a8705eb7bdb0ff329255390 to your computer and use it in GitHub Desktop.
Save mikesname/5b7124f51a8705eb7bdb0ff329255390 to your computer and use it in GitHub Desktop.
package controllers;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
import play.cache.CacheApi;
import play.cache.Cached;
import play.filters.csrf.AddCSRFToken;
import play.filters.csrf.CSRF;
import play.libs.Json;
import play.libs.concurrent.HttpExecutionContext;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Http.Cookie;
import play.mvc.Result;
import akka.NotUsed;
import akka.actor.Status;
import akka.stream.OverflowStrategy;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
@Singleton
@AddCSRFToken
public class GetHandler extends Controller {
@Inject
private ActorSystem actorSystem;
@Inject
private CacheApi cache;
@Inject
private HttpExecutionContext httpExecutionContext;
public static class Worker extends UntypedActor {
@Override
public void onReceive(Object msg) {
if (msg instanceof ActorRef) {
ActorRef sourceActor = (ActorRef)msg;
for (int i = 0; i < 20; i++) {
sourceActor.tell(ByteString.fromString(String.valueOf(i) + "<br/>\n"), null);
try {
Thread.sleep(500);//intentional delay
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sourceActor.tell(new Status.Success(NotUsed.getInstance()), null);
} else {
unhandled(msg);
}
}
}
public CompletionStage<Result> index() {
return CompletableFuture.supplyAsync(() ->
Source.<ByteString>actorRef(256, OverflowStrategy.dropNew())
.mapMaterializedValue(sourceActor -> {
actorSystem
.actorOf(Props.create(Worker.class))
.tell(sourceActor, null);
return sourceActor;
})
).thenApplyAsync(chunks -> ok().chunked(chunks).as("text/html"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment