@Override public void exceptionCaught(ChannelHandlerContext context, Throwable cause) { LOG.error(cause.getMessage(), cause); if (context.channel().isOpen()) { context.channel().close(); } }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { final Channel inboundChannel = ctx.channel(); // Start the connection attempt. Bootstrap bootstrap = new Bootstrap(); bootstrap .group(inboundChannel.eventLoop()) .channel(ctx.channel().getClass()) .handler( new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { // Create a default pipeline implementation. ChannelPipeline pipeline = ch.pipeline(); // add logging if (logger.isDebugEnabled()) { pipeline.addLast("logger", new LoggingHandler(" -->")); } // add HTTPS proxy -> server support if (secure) { SSLEngine engine = SSLFactory.sslContext().createSSLEngine(); engine.setUseClientMode(true); pipeline.addLast("proxy -> server ssl", new SslHandler(engine)); } // add handler pipeline.addLast( new ProxyRelayHandler( inboundChannel, bufferedCapacity, new RequestInterceptor(), " -->")); } }) .option(ChannelOption.AUTO_READ, false); ChannelFuture channelFuture = bootstrap.connect(remoteSocketAddress); outboundChannel = channelFuture.channel(); channelFuture.addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { channelBuffer.clear(); bufferedMode = bufferedCapacity > 0; flushedBuffer = false; // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); } } }); }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channel = ctx.channel(); channels.add(channel); attempts = 0; ctx.fireChannelActive(); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); Channel ch = ctx.channel(); if (ch.isActive()) { ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof ContinuationWebSocketFrame) return; if (frame instanceof TextWebSocketFrame) webSocketActor.onMessage(((TextWebSocketFrame) frame).text()); else webSocketActor.onMessage(frame.content().nioBuffer()); }
@Override protected final void die(Throwable cause) { super.die(cause); if (ctx.channel().isOpen()) ctx.close(); // Ensure to release server references userActor = null; ctx = null; }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (!isIgnorableException(cause)) { cause.printStackTrace(); if (ctx.channel().isActive()) { sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); } } }
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof ByteBuf) { // handle normal request final ByteBuf chunk = (ByteBuf) msg; if (flushedBuffer) { bufferedMode = false; } if (bufferedMode) { try { channelBuffer.writeBytes(chunk); ctx.channel().read(); } catch (IndexOutOfBoundsException iobe) { logger.trace( "Flushing buffer upstream and switching to chunked mode as downstream response too large"); bufferedMode = false; // write and flush buffer upstream if (outboundChannel.isActive()) { outboundChannel .writeAndFlush(channelBuffer) .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // write and flush this chunk upstream in case this single chunk is too // large for buffer channelRead(ctx, chunk); } else { future.channel().close(); } } }); } } } else { bufferedMode = false; if (outboundChannel.isActive()) { outboundChannel .writeAndFlush(chunk) .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // was able to flush out data, start to read the next chunk ctx.channel().read(); } else { future.channel().close(); } } }); } } } }
public void channelActive(ChannelHandlerContext p_channelActive_1_) throws Exception { super.channelActive(p_channelActive_1_); this.channel = p_channelActive_1_.channel(); this.socketAddress = this.channel.remoteAddress(); try { this.setConnectionState(EnumConnectionState.HANDSHAKING); } catch (Throwable var3) { logger.fatal(var3); } }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof FullHttpRequest)) { Action<Object> subscriber = channelSubscriptions.get(ctx.channel()); if (subscriber != null) { subscriber.execute(msg); return; } } super.channelRead(ctx, msg); }
/** {@inheritDoc} */ @Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; trackingType = setTrackingType(request); } if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; requestContent.append(chunk.content().toString(Charset.defaultCharset())); if (chunk instanceof LastHttpContent) { // All chunks have been received ResultTO resultTO = submitPayload(requestContent.toString()); responseContent.append(gson.toJson(resultTO)); writeResponse(ctx.channel()); reset(); } } }
public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest nettyRequest) throws Exception { if (!nettyRequest.getDecoderResult().isSuccess()) { sendError(ctx, HttpResponseStatus.BAD_REQUEST); return; } final long startTime = addResponseTimeHeader ? System.nanoTime() : 0; final Request request = new DefaultRequest( new NettyHeadersBackedHeaders(nettyRequest.headers()), nettyRequest.getMethod().name(), nettyRequest.getUri(), nettyRequest.content()); final Channel channel = ctx.channel(); final DefaultMutableStatus responseStatus = new DefaultMutableStatus(); final HttpHeaders nettyHeaders = new DefaultHttpHeaders(false); final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders); final MimeTypes mimeTypes = registry.get(MimeTypes.class); final DefaultEventController<RequestOutcome> requestOutcomeEventController = new DefaultEventController<>(); final AtomicBoolean transmitted = new AtomicBoolean(false); final ResponseTransmitter responseTransmitter = new DefaultResponseTransmitter( transmitted, channel, nettyRequest, request, nettyHeaders, responseStatus, requestOutcomeEventController, startTime); final Action<Action<? super ResponseTransmitter>> responseTransmitterWrapper = Actions.wrap(responseTransmitter); final FileHttpTransmitter fileHttpTransmitter = new DefaultFileHttpTransmitter( nettyHeaders, mimeTypes, compressResponses, compressionMinSize, compressionMimeTypeWhiteList, compressionMimeTypeBlackList, responseTransmitterWrapper); StreamTransmitter streamTransmitter = new DefaultStreamTransmitter(nettyRequest, nettyHeaders, channel); final Response response = new DefaultResponse( responseStatus, responseHeaders, fileHttpTransmitter, streamTransmitter, ctx.alloc(), new Action<ByteBuf>() { @Override public void execute(final ByteBuf byteBuf) throws Exception { responseTransmitterWrapper.execute( new Action<ResponseTransmitter>() { @Override public void execute(ResponseTransmitter responseTransmitter) throws Exception { nettyHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, byteBuf.writerIndex()); responseTransmitter.transmit(new DefaultHttpContent(byteBuf)); } }); } }); InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress(); final BindAddress bindAddress = new InetSocketAddressBackedBindAddress(socketAddress); Action<Action<Object>> subscribeHandler = new Action<Action<Object>>() { @Override public void execute(Action<Object> thing) throws Exception { transmitted.set(true); channelSubscriptions.put(channel, thing); channel .closeFuture() .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { channelSubscriptions.remove(channel); } }); } }; final DirectChannelAccess directChannelAccess = new DefaultDirectChannelAccess(channel, subscribeHandler); final DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants( applicationConstants, bindAddress, request, response, directChannelAccess, requestOutcomeEventController.getRegistry()); DefaultContext.start( execController.getControl(), requestConstants, registry, handlers, return404, new Action<Execution>() { @Override public void execute(Execution execution) throws Exception { if (!transmitted.get()) { Handler lastHandler = requestConstants.handler; StringBuilder description = new StringBuilder(); description .append("No response sent for ") .append(request.getMethod().getName()) .append(" request to ") .append(request.getUri()) .append(" (last handler: "); if (lastHandler instanceof DescribingHandler) { ((DescribingHandler) lastHandler).describeTo(description); } else { DescribingHandlers.describeTo(lastHandler, description); } description.append(")"); String message = description.toString(); LOGGER.warn(message); response.status(500); if (launchConfig.isDevelopment()) { response.send(message); } else { response.send(); } } } }); }
public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest nettyRequest) throws Exception { if (!nettyRequest.getDecoderResult().isSuccess()) { sendError(ctx, HttpResponseStatus.BAD_REQUEST); return; } final long startTime = System.nanoTime(); final Request request = new DefaultRequest( new NettyHeadersBackedHeaders(nettyRequest.headers()), nettyRequest.getMethod().name(), nettyRequest.getUri(), nettyRequest.content()); final Channel channel = ctx.channel(); final DefaultMutableStatus responseStatus = new DefaultMutableStatus(); final HttpHeaders httpHeaders = new DefaultHttpHeaders(false); final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(httpHeaders); FileHttpTransmitter fileHttpTransmitter = new DefaultFileHttpTransmitter( nettyRequest, httpHeaders, channel, compressResponses, addResponseTimeHeader ? startTime : -1); final DefaultEventController<RequestOutcome> requestOutcomeEventController = new DefaultEventController<>(); // We own the lifecycle nettyRequest.content().retain(); final Response response = new DefaultResponse( responseStatus, responseHeaders, fileHttpTransmitter, ctx.alloc(), new Action<ByteBuf>() { @Override public void execute(final ByteBuf byteBuf) throws Exception { final HttpResponse nettyResponse = new CustomHttpResponse(responseStatus.getResponseStatus(), httpHeaders); nettyRequest.content().release(); responseHeaders.set(HttpHeaderConstants.CONTENT_LENGTH, byteBuf.writerIndex()); boolean shouldClose = true; if (channel.isOpen()) { if (isKeepAlive(nettyRequest)) { responseHeaders.set( HttpHeaderConstants.CONNECTION, HttpHeaderConstants.KEEP_ALIVE); shouldClose = false; } long stopTime = System.nanoTime(); if (addResponseTimeHeader) { responseHeaders.set( "X-Response-Time", NumberUtil.toMillisDiffString(startTime, stopTime)); } execController.getExecution().complete(); channel.writeAndFlush(nettyResponse); channel.write(new DefaultHttpContent(byteBuf)); ChannelFuture future = channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (requestOutcomeEventController.isHasListeners()) { Headers headers = new DelegatingHeaders(responseHeaders); Status status = new DefaultStatus(responseStatus.getCode(), responseStatus.getMessage()); SentResponse sentResponse = new DefaultSentResponse(headers, status); RequestOutcome requestOutcome = new DefaultRequestOutcome( request, sentResponse, System.currentTimeMillis()); requestOutcomeEventController.fire(requestOutcome); } if (shouldClose) { future.addListener(ChannelFutureListener.CLOSE); } } } }); InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress(); final BindAddress bindAddress = new InetSocketAddressBackedBindAddress(socketAddress); Action<Action<Object>> subscribeHandler = new Action<Action<Object>>() { @Override public void execute(Action<Object> thing) throws Exception { channelSubscriptions.put(channel, thing); channel .closeFuture() .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { channelSubscriptions.remove(channel); } }); } }; final DirectChannelAccess directChannelAccess = new DefaultDirectChannelAccess(channel, subscribeHandler); execController.start( new Action<Execution>() { @Override public void execute(Execution execution) throws Exception { DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants( applicationConstants, bindAddress, request, response, directChannelAccess, requestOutcomeEventController.getRegistry(), execution); new DefaultContext(requestConstants, registry, handlers, 0, return404).next(); } }); }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); assertQueueEmpty(queue); Assert.assertTrue("Should be writable", ctx.channel().isWritable()); }
@Override public void channelUnregistered(final ChannelHandlerContext ctx) { Flog.log("Disconnected from %s", ctx.channel().remoteAddress()); reconnect(); }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Flog.log("Connected to %s", ctx.channel().remoteAddress()); handler.on_connect(); }
@Override public void channelInactive(@NotNull ChannelHandlerContext context) throws Exception { clientChannels.remove(context.channel()); super.channelInactive(context); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.warn(responseContent.toString(), cause); ctx.channel().close(); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.channel().close(); }
@Override public final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (ctx.channel().isOpen()) ctx.close(); log.error("Exception caught", cause); }
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws SuspendExecution { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse( ctx, req, new DefaultFullHttpResponse(req.getProtocolVersion(), BAD_REQUEST), false); return; } final String uri = req.getUri(); final Context actorCtx = selector.get(ctx, req); assert actorCtx != null; final ReentrantLock lock = actorCtx.getLock(); assert lock != null; lock.lock(); try { final ActorRef<? extends WebMessage> userActorRef = actorCtx.getRef(); ActorImpl internalActor = (ActorImpl) actorCtx.getAttachments().get(ACTOR_KEY); if (userActorRef != null) { if (actorCtx.handlesWithWebSocket(uri)) { if (internalActor == null || !(internalActor instanceof WebSocketActorAdapter)) { //noinspection unchecked webSocketActor = new WebSocketActorAdapter(ctx, (ActorRef<? super WebMessage>) userActorRef); addActorToContextAndUnlock(actorCtx, webSocketActor, lock); } // Handshake final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(uri, null, true); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { @SuppressWarnings("unchecked") final ActorRef<WebMessage> userActorRef0 = (ActorRef<WebMessage>) webSocketActor.userActor; handshaker .handshake(ctx.channel(), req) .addListener( new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) throws Exception { FiberUtil.runInFiber( new SuspendableRunnable() { @Override public void run() throws SuspendExecution, InterruptedException { userActorRef0.send( new WebSocketOpened(WebActorHandler.this.webSocketActor.ref())); } }); } }); } return; } else if (actorCtx.handlesWithHttp(uri)) { if (internalActor == null || !(internalActor instanceof HttpActorAdapter)) { //noinspection unchecked internalActor = new HttpActorAdapter( (ActorRef<HttpRequest>) userActorRef, actorCtx, httpResponseEncoderName); addActorToContextAndUnlock(actorCtx, internalActor, lock); } //noinspection unchecked ((HttpActorAdapter) internalActor).service(ctx, req); return; } } } finally { if (lock.isHeldByCurrentStrand() && lock.isLocked()) lock.unlock(); } sendHttpResponse( ctx, req, new DefaultFullHttpResponse(req.getProtocolVersion(), NOT_FOUND), false); }
@Override public void channelRead0(final ChannelHandlerContext ctx, final String msg) { ctx.write("Hello!\n", ctx.channel().voidPromise()); }
public static ChannelFuture handshake( final ChannelHandlerContext ctx, final HttpRequest request, final String websocketPath, final ChannelHandler handler) { final String connHead = request.getHttpHeaders().getHeaderString(HttpHeaders.Names.CONNECTION); final String upHead = request.getHttpHeaders().getHeaderString(HttpHeaders.Names.UPGRADE); final String sockHead = request.getHttpHeaders().getHeaderString(HttpHeaders.Names.SEC_WEBSOCKET_VERSION); final String keyHead = request.getHttpHeaders().getHeaderString(HttpHeaders.Names.SEC_WEBSOCKET_KEY); try { DefaultHttpRequest req = new DefaultHttpRequest( HttpVersion.HTTP_1_0, HttpMethod.GET, request.getUri().getAbsolutePath().toString()); req.setHeader(HttpHeaders.Names.SEC_WEBSOCKET_VERSION, sockHead); req.setHeader(HttpHeaders.Names.SEC_WEBSOCKET_KEY, keyHead); final Channel channel = ctx.channel(); final String location = getWebSocketLocation(channel.pipeline(), request, websocketPath); final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(location, null, false); final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(channel); return null; } else if (!connHead.toLowerCase().contains(HttpHeaders.Values.UPGRADE.toLowerCase()) || !upHead.toLowerCase().contains(HttpHeaders.Values.WEBSOCKET.toLowerCase())) { // Not a valid socket open request logger.info("Invalid request: " + request.getUri()); return null; } else { // We need to remove the RESTEasy stuff otherwise the Netty logic to write the handshake to // the channel // will never make it back to the client channel.pipeline().remove("resteasyEncoder"); channel.pipeline().remove("resteasyDecoder"); final ChannelFuture handshakeFuture = handshaker.handshake(channel, req); handshakeFuture.addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } else { final ChannelPipeline pipeline = future.channel().pipeline(); pipeline.replace(pipeline.last(), "customSocketHandler", handler); pipeline.addBefore( "customSocketHandler", "socketHandler", new WebSocketProtocolHandler()); } } }); WebSocketProtocolHandler.setHandshaker(ctx, handshaker); return handshakeFuture; // channel.pipeline().addBefore("timeout", "WS403Responder", // WebSocketProtocolHandler.forbiddenHttpRequestResponder()); } } catch (Exception e) { logger.error("Error trying to upgrade the channel to a socket", e); } return null; }
@Override public final void close() { if (ctx.channel().isOpen()) ctx.close(); if (actor != null) actor.die(null); }