Example usage for io.netty.channel ChannelHandlerContext channel

List of usage examples for io.netty.channel ChannelHandlerContext channel

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext channel.

Prototype

Channel channel();

Source Link

Document

Return the Channel which is bound to the ChannelHandlerContext .

Usage

From source file:com.chenyang.proxy.http.HttpSchemaHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        String originalHost = HostNamePortUtil.getHostName(httpRequest);
        int originalPort = HostNamePortUtil.getPort(httpRequest);
        HttpRemote apnProxyRemote = new HttpRemote(originalHost, originalPort);

        if (!HostAuthenticationUtil.isValidAddress(apnProxyRemote.getInetSocketAddress())) {
            HttpErrorUtil.writeAndFlush(uaChannelCtx.channel(), HttpResponseStatus.FORBIDDEN);
            return;
        }/*  ww w .j  av  a 2s .  co  m*/

        Channel uaChannel = uaChannelCtx.channel();

        HttpConnectionAttribute apnProxyConnectionAttribute = HttpConnectionAttribute.build(
                uaChannel.remoteAddress().toString(), httpRequest.getMethod().name(), httpRequest.getUri(),
                httpRequest.getProtocolVersion().text(),
                httpRequest.headers().get(HttpHeaders.Names.USER_AGENT), apnProxyRemote);

        uaChannelCtx.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute);
        uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute);

        if (httpRequest.getMethod().equals(HttpMethod.CONNECT)) {
            if (uaChannelCtx.pipeline().get(HttpUserAgentForwardHandler.HANDLER_NAME) != null) {
                uaChannelCtx.pipeline().remove(HttpUserAgentForwardHandler.HANDLER_NAME);
            }
            if (uaChannelCtx.pipeline().get(HttpUserAgentTunnelHandler.HANDLER_NAME) == null) {
                uaChannelCtx.pipeline().addLast(HttpUserAgentTunnelHandler.HANDLER_NAME,
                        new HttpUserAgentTunnelHandler());
            }
        } else {
            if (uaChannelCtx.pipeline().get(HttpUserAgentForwardHandler.HANDLER_NAME) == null) {
                uaChannelCtx.pipeline().addLast(HttpUserAgentForwardHandler.HANDLER_NAME,
                        new HttpUserAgentForwardHandler());
            }
        }
    }

    uaChannelCtx.fireChannelRead(msg);
}

From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {

    final Channel uaChannel = uaChannelCtx.channel();

    final HttpRemote apnProxyRemote = uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        if (remoteChannel != null && remoteChannel.isActive()) {
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {// w ww. j av a  2s  . c o  m

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.AUTO_READ, false)
                    .handler(new HttpRemoteForwardChannelInitializer(uaChannel, this));

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getInetSocketAddress(),
                    new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0));
            remoteChannel = remoteConnectFuture.channel();
            remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel);

            remoteConnectFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote));

                        for (HttpContent hc : httpContentBuffer) {
                            future.channel().writeAndFlush(hc);

                            if (hc instanceof LastHttpContent) {
                                future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future)
                                                    throws Exception {
                                                if (future.isSuccess()) {
                                                    future.channel().read();
                                                }

                                            }
                                        });
                            }
                        }
                        httpContentBuffer.clear();
                    } else {
                        HttpErrorUtil.writeAndFlush(uaChannel, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                        httpContentBuffer.clear();
                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());
        HttpContent hc = ((HttpContent) msg);
        if (remoteChannel != null && remoteChannel.isActive()) {
            remoteChannel.writeAndFlush(hc);

            if (hc instanceof LastHttpContent) {
                remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            future.channel().read();
                        }

                    }
                });
            }
        } else {
            httpContentBuffer.add(hc);
        }
    }

}

From source file:com.chenyang.proxy.http.HttpUserAgentTunnelHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception {

    if (msg instanceof HttpRequest) {
        // Channel uaChannel = uaChannelCtx.channel();

        // connect remote
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.AUTO_READ, false)
                .handler(new HttpTunnelChannelInitializer(uaChannelCtx.channel()));

        final HttpRemote apnProxyRemote = uaChannelCtx.channel().attr(HttpConnectionAttribute.ATTRIBUTE_KEY)
                .get().getRemote();/*from www .  ja va2s  .c om*/

        bootstrap
                .connect(apnProxyRemote.getInetSocketAddress(),
                        new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0))
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(final ChannelFuture future1) throws Exception {
                        if (future1.isSuccess()) {
                            HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse(
                                    HttpVersion.HTTP_1_1,
                                    new HttpResponseStatus(200, "Connection established"));
                            uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse)
                                    .addListener(new ChannelFutureListener() {
                                        @Override
                                        public void operationComplete(ChannelFuture future2) throws Exception {
                                            // remove handlers
                                            uaChannelCtx.pipeline().remove("codec");
                                            uaChannelCtx.pipeline().remove(HttpPreHandler.HANDLER_NAME);
                                            uaChannelCtx.pipeline()
                                                    .remove(HttpUserAgentTunnelHandler.HANDLER_NAME);

                                            uaChannelCtx.pipeline()
                                                    .addLast(new HttpRelayHandler(
                                                            "UA --> " + apnProxyRemote.getRemoteAddr(),
                                                            future1.channel()));
                                        }

                                    });

                        } else {
                            if (uaChannelCtx.channel().isActive()) {
                                uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });

    }
    ReferenceCountUtil.release(msg);
}

From source file:com.chiorichan.http.HttpHandler.java

License:Mozilla Public License

@Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
    Timings.start(this);

    if (msg instanceof FullHttpRequest) {
        if (AppLoader.instances().get(0).runLevel() != RunLevel.RUNNING) {
            // Outputs a very crude raw message if we are running in a low level mode a.k.a. Startup or Reload.
            // While in the mode, much of the server API is potentially unavailable, that is why we do this.

            StringBuilder sb = new StringBuilder();
            sb.append("<h1>503 - Service Unavailable</h1>\n");
            sb.append(//w w  w  .  j  a  v  a2  s.  c  o  m
                    "<p>I'm sorry to have to be the one to tell you this but the server is currently unavailable.</p>\n");
            sb.append(
                    "<p>This is most likely due to many possibilities, most commonly being it's currently booting up. Which would be great news because it means your request should succeed if you try again.</p>\n");
            sb.append(
                    "<p>But it is also possible that the server is actually running in a low level mode or could be offline for some other reason. If you feel this is a mistake, might I suggest you talk with the server admin.</p>\n");
            sb.append("<p><i>You have a good day now and we will see you again soon. :)</i></p>\n");
            sb.append("<hr>\n");
            sb.append("<small>Running <a href=\"https://github.com/ChioriGreene/ChioriWebServer\">"
                    + Versioning.getProduct() + "</a> Version " + Versioning.getVersion() + " (Build #"
                    + Versioning.getBuildNumber() + ")<br />" + Versioning.getCopyright() + "</small>");

            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.valueOf(503), Unpooled.wrappedBuffer(sb.toString().getBytes()));
            ctx.write(response);

            return;
        }

        requestFinished = false;
        requestOrig = (FullHttpRequest) msg;
        request = new HttpRequestWrapper(ctx.channel(), requestOrig, this, ssl, log);
        response = request.getResponse();

        String threadName = Thread.currentThread().getName();

        if (threadName.length() > 10)
            threadName = threadName.substring(0, 2) + ".." + threadName.substring(threadName.length() - 6);
        else if (threadName.length() < 10)
            threadName = threadName + Strings.repeat(" ", 10 - threadName.length());

        log.header("&7[&d%s&7] %s %s [&9%s:%s&7] -> [&a%s:%s&7]", threadName,
                dateFormat.format(Timings.millis()), timeFormat.format(Timings.millis()), request.getIpAddr(),
                request.getRemotePort(), request.getLocalIpAddr(), request.getLocalPort());

        if (HttpHeaderUtil.is100ContinueExpected((HttpRequest) msg))
            send100Continue(ctx);

        if (NetworkSecurity.isIpBanned(request.getIpAddr())) {
            response.sendError(403);
            return;
        }

        Site currentSite = request.getLocation();

        File tmpFileDirectory = currentSite != null ? currentSite.directoryTemp()
                : AppConfig.get().getDirectoryCache();

        setTempDirectory(tmpFileDirectory);

        if (request.isWebsocketRequest()) {
            try {
                WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                        request.getWebSocketLocation(requestOrig), null, true);
                handshaker = wsFactory.newHandshaker(requestOrig);
                if (handshaker == null)
                    WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
                else
                    handshaker.handshake(ctx.channel(), requestOrig);
            } catch (WebSocketHandshakeException e) {
                NetworkManager.getLogger().severe(
                        "A request was made on the websocket uri '/fw/websocket' but it failed to handshake for reason '"
                                + e.getMessage() + "'.");
                response.sendError(500, null, "This URI is for websocket requests only<br />" + e.getMessage());
            }
            return;
        }

        if (request.method() != HttpMethod.GET)
            try {
                decoder = new HttpPostRequestDecoder(factory, requestOrig);
            } catch (ErrorDataDecoderException e) {
                e.printStackTrace();
                response.sendException(e);
                return;
            }

        request.contentSize += requestOrig.content().readableBytes();

        if (decoder != null) {
            try {
                decoder.offer(requestOrig);
            } catch (ErrorDataDecoderException e) {
                e.printStackTrace();
                response.sendError(e);
                // ctx.channel().close();
                return;
            } catch (IllegalArgumentException e) {
                // TODO Handle this further? maybe?
                // java.lang.IllegalArgumentException: empty name
            }
            readHttpDataChunkByChunk();
        }

        handleHttp();

        finish();
    } else if (msg instanceof WebSocketFrame) {
        WebSocketFrame frame = (WebSocketFrame) msg;

        // Check for closing frame
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }

        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        if (!(frame instanceof TextWebSocketFrame))
            throw new UnsupportedOperationException(
                    String.format("%s frame types are not supported", frame.getClass().getName()));

        String request = ((TextWebSocketFrame) frame).text();
        NetworkManager.getLogger()
                .fine("Received '" + request + "' over WebSocket connection '" + ctx.channel() + "'");
        ctx.channel().write(new TextWebSocketFrame(request.toUpperCase()));
    } else if (msg instanceof DefaultHttpRequest) {
        // Do Nothing!
    } else
        NetworkManager.getLogger().warning(
                "Received Object '" + msg.getClass() + "' and had nothing to do with it, is this a bug?");
}

From source file:com.chuck.netty4.websocket.WebSocketFrameHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
    // ping and pong frames already handled
    if (frame instanceof TextWebSocketFrame) {
        // Send the uppercase string back.
        String request = ((TextWebSocketFrame) frame).text();
        logger.info("{} received {}", ctx.channel(), request);
        // ctx.channel().writeAndFlush(
        // new TextWebSocketFrame(request.toUpperCase(Locale.US)));
        Global.group.writeAndFlush(new TextWebSocketFrame(request.toUpperCase(Locale.US)));
    } else {/*www . ja v a 2s.  co m*/
        String message = "unsupported frame type: " + frame.getClass().getName();
        throw new UnsupportedOperationException(message);
    }
}

From source file:com.chuck.netty4.websocket.WebSocketFrameHandler.java

License:Apache License

@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    try {/*w  ww .ja v  a  2  s  .co  m*/
        Global.group.writeAndFlush(new TextWebSocketFrame(ctx.channel() + ""));
        Global.group.remove(ctx.channel());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.chuck.netty4.websocket.WebSocketFrameHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("");
    try {/* w  w  w  .ja  v a 2 s .  c o m*/
        Global.group.add(ctx.channel());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cloudera.livy.client.local.rpc.RpcDispatcher.java

License:Apache License

private void writeMessage(ChannelHandlerContext ctx, Rpc.MessageType replyType, Object payload) {
    ctx.channel().write(new Rpc.MessageHeader(lastHeader.id, replyType));
    ctx.channel().writeAndFlush(payload);
}

From source file:com.cloudera.livy.client.local.rpc.RpcDispatcher.java

License:Apache License

@Override
public final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("[%s] Caught exception in channel pipeline.", name()), cause);
    } else {/*from w w w  . j a  v  a 2 s .co m*/
        LOG.info("[{}] Closing channel due to exception in pipeline ({}).", name(), cause.getMessage());
    }

    if (lastHeader != null) {
        // There's an RPC waiting for a reply. Exception was most probably caught while processing
        // the RPC, so send an error.
        ctx.channel().write(new Rpc.MessageHeader(lastHeader.id, Rpc.MessageType.ERROR));
        ctx.channel().writeAndFlush(Throwables.getStackTraceAsString(cause));
        lastHeader = null;
    }

    ctx.close();
}

From source file:com.cloudera.livy.client.local.rpc.RpcDispatcher.java

License:Apache License

@Override
public final void channelInactive(ChannelHandlerContext ctx) throws Exception {
    if (rpcs.size() > 0) {
        LOG.warn("[{}] Closing RPC channel with {} outstanding RPCs.", name(), rpcs.size());
        for (OutstandingRpc rpc : rpcs) {
            rpc.future.cancel(true);//from  www. ja va 2s  .co m
        }
    } else {
        LOG.debug("Channel {} became inactive.", ctx.channel());
    }
    super.channelInactive(ctx);
}