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:org.jfxvnc.net.rfb.codec.ProtocolHandshakeHandler.java

License:Apache License

private void handleServerVersion(final ChannelHandlerContext ctx, ProtocolVersion version) {

    logger.debug("server version: {}", version);
    if (version.isGreaterThan(config.versionProperty().get())) {
        logger.debug("set client version: {}", config.versionProperty().get());
        version = config.versionProperty().get();
    }/* w  w w  .  j  a  va 2  s . c  o  m*/

    RfbClientHandshakerFactory hsFactory = new RfbClientHandshakerFactory();
    handshaker = hsFactory.newRfbClientHandshaker(version);
    handshaker.handshake(ctx.channel()).addListener((future) -> {
        if (!future.isSuccess()) {
            ctx.fireExceptionCaught(future.cause());
        } else {
            ctx.pipeline().fireUserEventTriggered(ProtocolState.HANDSHAKE_STARTED);
        }

    });
}

From source file:org.jfxvnc.net.rfb.codec.ProtocolHandshakeHandler.java

License:Apache License

private void handleSecurityTypes(final ChannelHandlerContext ctx, SecurityTypesEvent msg) {

    SecurityType[] supportTypes = msg.getSecurityTypes();
    if (supportTypes.length == 0) {
        ctx.fireExceptionCaught(new ProtocolException("no security types supported"));
        return;/*from  w w w.ja  va 2  s . c  o  m*/
    }

    SecurityType userSecType = config.securityProperty().get();
    boolean isSupported = Arrays.stream(supportTypes).anyMatch(i -> i == userSecType);
    if (!isSupported) {
        ctx.fireExceptionCaught(new ProtocolException(
                String.format("Authentication: '%s' is not supported. The server supports only (%s)",
                        userSecType, Arrays.toString(supportTypes))));
        return;
    }

    if (userSecType == SecurityType.NONE) {
        logger.debug("none security type available");
        ctx.writeAndFlush(Unpooled.buffer(1).writeByte(userSecType.getType()));
        ctx.pipeline().fireUserEventTriggered(ProtocolState.SECURITY_COMPLETE);
        return;
    }

    RfbSecurityHandshakerFactory secFactory = new RfbSecurityHandshakerFactory();

    secHandshaker = secFactory.newRfbSecurityHandshaker(userSecType);
    if (secHandshaker == null) {
        ctx.fireExceptionCaught(
                new ProtocolException(String.format("Authentication: '%s' is not supported yet", userSecType)));
        return;
    }
    secHandshaker.handshake(ctx.channel(), msg.isResponse()).addListener((future) -> {
        if (future.isSuccess()) {
            ctx.pipeline().fireUserEventTriggered(ProtocolState.SECURITY_STARTED);
        } else {
            ctx.fireExceptionCaught(future.cause());
        }
    });

}

From source file:org.jfxvnc.net.rfb.codec.ProtocolHandshakeHandler.java

License:Apache License

private void handleSecurityResult(final ChannelHandlerContext ctx, final SecurityResultEvent msg) {
    if (msg.isPassed()) {
        logger.info("security passed: {}", msg);
        boolean sharedFlag = config.sharedProperty().get();
        ctx.writeAndFlush(new SharedEvent(sharedFlag)).addListener((future) -> {
            if (!future.isSuccess()) {
                ctx.fireExceptionCaught(future.cause());
            } else {
                ctx.pipeline().fireUserEventTriggered(ProtocolState.SECURITY_COMPLETE);
            }/*w ww  . ja v  a  2 s  .  c  om*/
        });
        return;
    }
    ctx.pipeline().fireUserEventTriggered(ProtocolState.SECURITY_FAILED);
    if (msg.getThrowable() != null) {
        ctx.fireExceptionCaught(msg.getThrowable());
    }

}

From source file:org.jooby.internal.netty.NettyPush.java

License:Apache License

public NettyPush(final ChannelHandlerContext ctx, final int streamId, final String authority,
        final String scheme) {
    this.ctx = ctx;
    HttpToHttp2ConnectionHandler handler = ctx.pipeline().get(HttpToHttp2ConnectionHandler.class);
    this.encoder = handler.encoder();
    this.streamId = streamId;
    this.authority = authority;
    this.scheme = scheme;
}

From source file:org.jooby.internal.netty.NettyResponse.java

License:Apache License

@Override
public void send(final InputStream stream) throws Exception {
    byte[] chunk = new byte[bufferSize];
    int count = ByteStreams.read(stream, chunk, 0, bufferSize);
    if (count <= 0) {
        return;//from  www.  j a  v  a2 s. c om
    }
    ByteBuf buffer = Unpooled.wrappedBuffer(chunk, 0, count);
    if (count < bufferSize) {
        send(buffer);
    } else {
        DefaultHttpResponse rsp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);

        if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
            headers.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
        } else {
            if (keepAlive) {
                headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            }
        }

        // dump headers
        rsp.headers().set(headers);
        ChannelHandlerContext ctx = this.ctx;
        ctx.channel().attr(NettyRequest.NEED_FLUSH).set(false);

        // add chunker
        chunkHandler(ctx.pipeline());

        // group all write
        ctx.channel().eventLoop().execute(() -> {
            // send headers
            ctx.write(rsp);
            // send head chunk
            ctx.write(buffer);
            // send tail
            ctx.write(new ChunkedStream(stream, bufferSize));
            keepAlive(ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT));
        });
    }

    committed = true;
}

From source file:org.jooby.internal.netty.NettyResponse.java

License:Apache License

@Override
public void send(final FileChannel channel, final long offset, final long count) throws Exception {
    DefaultHttpResponse rsp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
        headers.remove(HttpHeaderNames.TRANSFER_ENCODING);
        headers.set(HttpHeaderNames.CONTENT_LENGTH, count);
    }//from   ww  w  .  j a v a2  s  .co m

    if (keepAlive) {
        headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    // dump headers
    rsp.headers().set(headers);
    ChannelHandlerContext ctx = this.ctx;
    ctx.channel().attr(NettyRequest.NEED_FLUSH).set(false);

    ChannelPipeline pipeline = ctx.pipeline();
    boolean ssl = pipeline.get(SslHandler.class) != null;

    if (ssl) {
        // add chunker
        chunkHandler(pipeline);

        // Create the chunked input here already, to properly handle the IOException
        HttpChunkedInput chunkedInput = new HttpChunkedInput(
                new ChunkedNioFile(channel, offset, count, bufferSize));

        ctx.channel().eventLoop().execute(() -> {
            // send headers
            ctx.write(rsp);
            // chunked file
            keepAlive(ctx.writeAndFlush(chunkedInput));
        });
    } else {
        ctx.channel().eventLoop().execute(() -> {
            // send headers
            ctx.write(rsp);
            // file region
            ctx.write(new DefaultFileRegion(channel, offset, count));
            keepAlive(ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT));
        });
    }

    committed = true;

}

From source file:org.kobeyoung81.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/*from w w w.  j  a v a2s .co m*/
        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) {
                                ctx.pipeline().remove(SocksServerConnectHandler.this);
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                            }
                        });
                //System.out.println(request.toString());
            } 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 DirectClientHandler(promise));
    //System.out.println(request.host() +":"+ request.port());
    //SocksCmdRequest re = new SocksCmdRequest(request.cmdType(), request.addressType(), "192.168.87.103", 8080);
    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:org.lanternpowered.pingy.PingyLegacyHandler.java

License:MIT License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg0) throws Exception {
    final ByteBuf msg = (ByteBuf) msg0;

    boolean legacy = false;
    msg.markReaderIndex();//from w w  w  . j  a v a 2  s  . c o  m
    try {
        // Try first as a legacy ping message
        int messageId = msg.readUnsignedByte();
        // Make sure that old clients don't attempt to login
        if (messageId == 0x02) {
            legacy = this.tryHandleLegacyJoin(ctx, msg);
        } else if (messageId == 0xfe) {
            legacy = this.tryHandleLegacyPing(ctx, msg);
        }
    } catch (Exception e) {
    }
    if (!legacy) {
        msg.resetReaderIndex();
        ctx.pipeline().remove(this);
        ctx.fireChannelRead(msg);
    } else {
        msg.release();
    }
}

From source file:org.lanternpowered.pingy.PingyLegacyHandler.java

License:MIT License

/**
 * Sends a disconnect message to a legacy client and closes the connection.
 *
 * @param ctx The channel handler context
 * @param message The message//www.  j  av a2s. com
 */
private static void sendLegacyDisconnectMessage(ChannelHandlerContext ctx, String message) {
    byte[] data = message.getBytes(StandardCharsets.UTF_16BE);

    ByteBuf output = ctx.alloc().buffer();
    output.writeByte(0xff);
    output.writeShort(data.length >> 1);
    output.writeBytes(data);

    ctx.pipeline().firstContext().writeAndFlush(output).addListener(ChannelFutureListener.CLOSE);
}

From source file:org.legacy.network.protocol.handshake.HandshakeDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    if (buffer.isReadable()) {
        if (ctx.pipeline().get(HandshakeDecoder.class) != null) {
            ctx.pipeline().remove(this);
        }//from   ww  w .ja v  a2  s .c o m
        int opcode = buffer.readUnsignedByte() & 0xFF;
        switch (opcode) {
        case 15:
            int size = buffer.readUnsignedByte();
            if (buffer.readableBytes() < size) {
                ctx.channel().close();
                return;
            }
            int major_version = buffer.readInt();
            int minor_version = buffer.readInt();
            if (major_version != Framework.MAJOR_VERSION || minor_version != Framework.MINOR_VERSION) {
                buffer.writeByte(6);
                ctx.channel().close();
                return;
            }
            String ondemand_token = BufferUtils.readBufferedString(buffer);
            if (!ondemand_token.equals(Framework.ONDEMAND_SESSION_TOKEN)) {
                ctx.channel().close();
                return;
            }
            ByteBuf buf = Unpooled.buffer();
            buf.writeByte(0);
            for (int element : Framework.CRC_UPDATE_KEYS) {
                buf.writeInt(element);
            }
            ctx.channel().write(buf);
            ctx.pipeline().addBefore("channel-handler", "decoder", new OnDemandDecoder());
            break;
        default:
            LegacyLogger.fireWarnMessage(this, "Unknown Handshake Opcode: " + opcode);
        }
    }
}