Example usage for io.netty.channel ChannelHandlerContext pipeline

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

Introduction

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

Prototype

ChannelPipeline pipeline();

Source Link

Document

Return the assigned ChannelPipeline

Usage

From source file:com.github.sinsinpub.pero.manual.proxyhandler.Socks5ProxyServer.java

License:Apache License

boolean authenticate(ChannelHandlerContext ctx, Object msg) {
    if (username == null) {
        ctx.pipeline().replace(DECODER, DECODER, new Socks5CommandRequestDecoder());
        ctx.write(new DefaultSocks5InitialResponse(Socks5AuthMethod.NO_AUTH));
        return true;
    }//from  w  w w. ja  v  a2 s.  c  o m

    if (msg instanceof Socks5InitialRequest) {
        ctx.pipeline().replace(DECODER, DECODER, new Socks5PasswordAuthRequestDecoder());
        ctx.write(new DefaultSocks5InitialResponse(Socks5AuthMethod.PASSWORD));
        return false;
    }

    Socks5PasswordAuthRequest req = (Socks5PasswordAuthRequest) msg;
    if (req.username().equals(username) && req.password().equals(password)) {
        ctx.pipeline().replace(DECODER, DECODER, new Socks5CommandRequestDecoder());
        ctx.write(new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus.SUCCESS));
        return true;
    }

    ctx.pipeline().replace(DECODER, DECODER, new Socks5PasswordAuthRequestDecoder());
    ctx.write(new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus.FAILURE));
    return false;
}

From source file:com.github.zk1931.jzab.transport.NettyTransportTest.java

License:Apache License

@Test(timeout = 10000)
public void testTieBreaker() throws Exception {
    final String peerA = getUniqueHostPort();
    final String peerB = getUniqueHostPort();
    final CountDownLatch disconnectedA = new CountDownLatch(1);
    final CountDownLatch disconnectedB = new CountDownLatch(1);

    Transport.Receiver receiverA = new Transport.Receiver() {
        public void onReceived(String source, Message message) {
            Assert.fail("Handshake should have failed");
        }//from w w w .j  a  va2 s  .c  om

        public void onDisconnected(String source) {
            LOG.debug("Got disconnected from {}", source);
            disconnectedA.countDown();
        }
    };
    Transport.Receiver receiverB = new Transport.Receiver() {
        public void onReceived(String source, Message message) {
            Assert.fail("Handshake should have failed");
        }

        public void onDisconnected(String source) {
            LOG.debug("Got disconnected from {}", source);
            disconnectedB.countDown();
        }
    };

    final NettyTransport transportA = new NettyTransport(peerA, receiverA, getDirectory());
    final NettyTransport transportB = new NettyTransport(peerB, receiverB, getDirectory());
    transportB.channel.pipeline().addFirst(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            // B initiates another handshake before responding to A's handshake.
            transportB.send(peerA, createAck(new Zxid(0, 0)));
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(msg);
        }
    });

    // A initiates a handshake.
    transportA.send(peerB, createAck(new Zxid(0, 0)));
    disconnectedA.await();
    disconnectedB.await();
    transportA.shutdown();
    transportB.shutdown();
}

From source file:com.gxkj.demo.netty.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override// w  w w  . j  a v  a  2 s .c om
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                                ctx.pipeline().remove(getName());
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.channel().pipeline().addLast(new RelayHandler(outboundChannel));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

    final Channel inboundChannel = ctx.channel();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new DirectClientInitializer(promise));

    b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
            } else {
                // Close the connection if the connection attempt has failed.
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:com.gxkj.demo.netty.socksproxy.SocksServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, SocksRequest socksRequest) throws Exception {
    switch (socksRequest.requestType()) {
    case INIT: {//from  w  w w  .  ja  va 2  s  . c o  m
        //                auth support example
        //                ctx.pipeline().addFirst("socksAuthRequestDecoder",new SocksAuthRequestDecoder());
        //                ctx.write(new SocksInitResponse(SocksMessage.SocksAuthScheme.AUTH_PASSWORD));
        ctx.pipeline().addFirst(SocksCmdRequestDecoder.getName(), new SocksCmdRequestDecoder());
        ctx.write(new SocksInitResponse(SocksAuthScheme.NO_AUTH));
        break;
    }
    case AUTH:
        ctx.pipeline().addFirst(SocksCmdRequestDecoder.getName(), new SocksCmdRequestDecoder());
        ctx.write(new SocksAuthResponse(SocksAuthStatus.SUCCESS));
        break;
    case CMD:
        SocksCmdRequest req = (SocksCmdRequest) socksRequest;
        if (req.cmdType() == SocksCmdType.CONNECT) {
            ctx.pipeline().addLast(SocksServerConnectHandler.getName(), new SocksServerConnectHandler());
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(socksRequest);
        } else {
            ctx.close();
        }
        break;
    case UNKNOWN:
        ctx.close();
        break;
    }
}

From source file:com.hazelcast.openshift.TunnelClientAcceptor.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    ctx.writeAndFlush(response).sync();/*ww w.j av  a 2s. com*/

    ChannelPipeline pipeline = ctx.pipeline();

    Channel forward = createRemoteChannel(ctx.channel());
    if (forward == null) {
        ctx.close();
        return;
    }

    forward.closeFuture().addListener(f -> ctx.close());
    ctx.channel().closeFuture().addListener(f -> forward.close());

    pipeline.addLast(new ProxyForwardHandler(forward));
    pipeline.remove(HttpRequestDecoder.class);
    pipeline.remove(HttpResponseEncoder.class);
    pipeline.remove(this);
}

From source file:com.hazelcast.openshift.TunnelServerConnector.java

License:Open Source License

@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    Promise promise = new Promise();
    Bootstrap bootstrap = createBootstrap(ctx.channel(), promise);
    ChannelFuture future = bootstrap.connect(httpHost, httpPort);
    Channel forward = future.sync().channel();
    forward.closeFuture().addListener(f -> ctx.close());
    ctx.channel().closeFuture().addListener(f -> forward.close());

    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, "/");
    request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    forward.writeAndFlush(request);//from  ww w. j  a v  a2  s  .  co m

    // Wait for the initial http response (ssl established)
    promise.sync(10, TimeUnit.SECONDS);

    // Exchange the HazelcastClient -> TunnelClient handler to proxy
    ChannelPipeline pipeline = ctx.pipeline();
    pipeline.addLast(new ProxyForwardHandler(forward));
    pipeline.remove(this);

    ctx.fireChannelRegistered();
}

From source file:com.hazelcast.simulator.protocol.handler.ConnectionHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
    if (!(obj instanceof ByteBuf)) {
        return;// w  w w  .j  a v a2s .c  o  m
    }

    ByteBuf buf = (ByteBuf) obj;
    if (buf.readableBytes() < MINIMUM_BYTE_BUFFER_SIZE) {
        return;
    }

    if (!isSimulatorMessage(buf) && !isResponse(buf)) {
        LOGGER.warn(format("Invalid connection from %s (no magic bytes found)", ctx.channel().remoteAddress()));
        ctx.close();
        return;
    }

    // the connection is valid so we remove this handler and forward the buffer to the pipeline
    LOGGER.info(format("Valid connection from %s (magic bytes found)", ctx.channel().remoteAddress()));
    isConnectionValid.countDown();
    ctx.pipeline().remove(this);
    ctx.fireChannelRead(obj);

    ctx.channel().closeFuture().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            connectionListener.disconnected(future.channel());
        }
    });

    connectionListener.connected(ctx.channel());
}

From source file:com.hazelcast.simulator.protocol.handler.ConnectionValidationHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
    if (!(obj instanceof ByteBuf)) {
        return;/*from  w w  w.  j  av a 2 s  .c o  m*/
    }

    ByteBuf buf = (ByteBuf) obj;
    if (buf.readableBytes() < MINIMUM_BYTE_BUFFER_SIZE) {
        return;
    }

    if (!isSimulatorMessage(buf) && !isResponse(buf)) {
        LOGGER.warn(format("Invalid connection from %s (no magic bytes found)", ctx.channel().remoteAddress()));
        ctx.close();
        return;
    }

    // the connection is valid so we remove this handler and forward the buffer to the pipeline
    LOGGER.info(format("Valid connection from %s (magic bytes found)", ctx.channel().remoteAddress()));
    ctx.pipeline().remove(this);
    ctx.fireChannelRead(obj);
}

From source file:com.heliosapm.streams.onramp.GZipDetector.java

License:Apache License

/**
 * {@inheritDoc}/*  w  ww  . j  av  a2  s  . com*/
 * @see io.netty.handler.codec.ByteToMessageDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)
 */
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf buff, final List<Object> out)
        throws Exception {
    if (buff.readableBytes() > 4) {
        final int magic1 = buff.getUnsignedByte(buff.readerIndex());
        final int magic2 = buff.getUnsignedByte(buff.readerIndex() + 1);
        if (isGzip(magic1, magic2)) {
            enableGzip(ctx);
        } else {
            ctx.pipeline().remove(this);
        }
        out.add(buff.retain());
    }
}

From source file:com.heliosapm.streams.onramp.GZipDetector.java

License:Apache License

private void enableGzip(final ChannelHandlerContext ctx) {
    final ChannelPipeline p = ctx.pipeline();
    try {/*from ww w . j a  v  a 2s.c  o m*/
        //         p.addAfter("connmgr", "gzipdeflater", new JZlibEncoder(ZlibWrapper.GZIP){
        //            // TODO
        //         });            
        p.addAfter("gzipdetector", "gzipinflater", ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));
        p.remove(this);
    } catch (Exception ex) {
        log.error("Failed to add gzip handlers", ex);
    }
}