com.google.sitebricks.SitebricksAsyncHandler Maven / Gradle / Ivy
package com.google.sitebricks;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.servlet.ServletScopes;
import com.google.sitebricks.headless.NettyReplyMaker;
import com.google.sitebricks.headless.Reply;
import com.google.sitebricks.headless.Request;
import com.google.sitebricks.routing.RoutingDispatcher;
import com.google.sitebricks.routing.RoutingDispatcher.Events;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpHeaders.Names;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.handler.codec.http.websocket.WebSocketFrame;
import org.jboss.netty.util.CharsetUtil;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* @author [email protected] (Dhanji R. Prasanna)
*/
@Singleton
class SitebricksAsyncHandler extends SimpleChannelUpstreamHandler {
private static final Key HTTP_REQUEST_KEY = Key.get(HttpRequest.class);
private final RoutingDispatcher dispatcher;
private final Provider bootstrapper;
private final Provider teardowner;
private final Provider requestProvider;
private final NettyReplyMaker replyMaker;
@Inject
SitebricksAsyncHandler(RoutingDispatcher dispatcher, Provider bootstrapper,
Provider teardowner,
Provider requestProvider,
NettyReplyMaker replyMaker) {
this.dispatcher = dispatcher;
this.bootstrapper = bootstrapper;
this.teardowner = teardowner;
this.replyMaker = replyMaker;
this.requestProvider = requestProvider;
}
private Config config;
public void startup(Config config) {
this.config = config;
bootstrapper.get().start();
}
public void shutdown() {
teardowner.get().shutdown();
}
@Override
public void messageReceived(final ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
Object message = e.getMessage();
if (message instanceof HttpRequest) {
// Handle normal request.
HttpRequest request = (HttpRequest) message;
// Scope this request using Guice thread-local scopes.
Map,Object> seedMap = Maps.newHashMap();
seedMap.put(HTTP_REQUEST_KEY, request);
ServletScopes.scopeRequest(new Callable