Example usage for io.netty.channel SimpleChannelInboundHandler SimpleChannelInboundHandler

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

Introduction

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

Prototype

protected SimpleChannelInboundHandler() 

Source Link

Document

see #SimpleChannelInboundHandler(boolean) with true as boolean parameter.

Usage

From source file:me.netty.http.Http2ServerInitializer.java

License:Apache License

/**
 * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0
 *//* www.  j  av  a  2  s.  c o  m*/
private void configureClearText(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    final HttpServerCodec sourceCodec = new HttpServerCodec();

    p.addLast(sourceCodec);
    p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory));
    p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
            // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
            ChannelPipeline pipeline = ctx.pipeline();
            ChannelHandlerContext thisCtx = pipeline.context(this);
            pipeline.addAfter(thisCtx.name(), null, new Http1Handler());
            pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength));
            ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
        }
    });

    p.addLast(new UserEventLogger());
}

From source file:net.sourceforge.entrainer.gui.socket.EntrainerSocketConnector.java

License:Open Source License

private ChannelHandler getWebSocketHandler() {
    try {//from   w  w  w.  jav  a 2 s. c  o  m
        return new SimpleChannelInboundHandler<Object>() {

            private URI uri = new URI("ws://" + ipAddress + ":" + port + WebSocketHandler.WEBSOCKET_PATH);
            HttpHeaders customHeaders = new DefaultHttpHeaders();

            private final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory
                    .newHandshaker(uri, WebSocketVersion.V13, null, false, customHeaders);
            private ChannelPromise handshakeFuture;

            @Override
            public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                handshakeFuture = ctx.newPromise();
            }

            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                handshaker.handshake(ctx.channel());
            }

            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                remoteDisconnection();
            }

            @Override
            public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                Channel ch = ctx.channel();
                if (!handshaker.isHandshakeComplete()) {
                    handshaker.finishHandshake(ch, (FullHttpResponse) msg);
                    handshakeFuture.setSuccess();

                    requestState(ctx);
                    return;
                }

                if (msg instanceof FullHttpResponse) {
                    FullHttpResponse response = (FullHttpResponse) msg;
                    throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus()
                            + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
                }

                WebSocketFrame frame = (WebSocketFrame) msg;
                if (frame instanceof TextWebSocketFrame) {
                    TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
                    executeJsonMessage(textFrame.text());
                } else if (frame instanceof PongWebSocketFrame) {
                    System.out.println("WebSocket Client received pong");
                } else if (frame instanceof CloseWebSocketFrame) {
                    ch.close();
                }
            }

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                cause.printStackTrace();

                if (!handshakeFuture.isDone()) {
                    handshakeFuture.setFailure(cause);
                }

                ctx.close();
            }
        };
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.sourceforge.entrainer.gui.socket.EntrainerSocketConnector.java

License:Open Source License

private ChannelHandler getJavaHandler() {
    return new SimpleChannelInboundHandler<String>() {

        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            requestState(ctx);/*  www . ja  v a 2  s .com*/
        }

        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            remoteDisconnection();
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, final String msg) throws Exception {
            executeXmlMessage(msg);
        }
    };
}

From source file:net.tomp2p.connection.Sender.java

License:Apache License

/**
 * This method initiates the reverse connection setup (or short: rconSetup).
 * It creates a new Message and sends it via relay to the unreachable peer
 * which then connects to this peer again. After the connectMessage from the
 * unreachable peer this peer will send the original Message and its content
 * directly./*from ww w  . ja  v  a2 s  . com*/
 * 
 * @param handler
 * @param futureResponse
 * @param message
 * @param channelCreator
 * @param connectTimeoutMillis
 * @param peerConnection
 * @param timeoutHandler
 */
private void handleRcon(final SimpleChannelInboundHandler<Message> handler, final FutureResponse futureResponse,
        final Message message, final ChannelCreator channelCreator, final int connectTimeoutMillis,
        final PeerConnection peerConnection, final TimeoutFactory timeoutHandler) {
    message.keepAlive(true);

    LOG.debug("initiate reverse connection setup to peer with peerAddress {}", message.recipient());
    Message rconMessage = createRconMessage(message);
    final FutureResponse rconResponse = new FutureResponse(rconMessage);

    // cache the original message until the connection is established
    cachedRequests.put(message.messageId(),
            new Pair<FutureResponse, FutureResponse>(futureResponse, rconResponse));

    // wait for response (whether the reverse connection setup was
    // successful)

    SimpleChannelInboundHandler<Message> rconInboundHandler = new SimpleChannelInboundHandler<Message>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
            if (msg.command() == Commands.RCON.getNr() && msg.type() == Type.OK) {
                LOG.debug("Successfully set up the reverse connection to peer {}",
                        message.recipient().peerId());
                rconResponse.response(msg);
            } else {
                LOG.debug("Could not acquire a reverse connection, msg: {}", message);
                rconResponse.failed("Could not acquire a reverse connection, msg: " + message);
                futureResponse.failed(rconResponse);
                cachedRequests.remove(message.messageId());
            }
        }
    };

    // send reverse connection request instead of normal message
    sendTCP(rconInboundHandler, rconResponse, rconMessage, channelCreator, connectTimeoutMillis,
            connectTimeoutMillis, peerConnection);
}

From source file:net.tomp2p.rpc.PingRPC.java

License:Apache License

/**
 * Ping a peer, and request the other peer to return the source port of our
 * socket used to send the message. This method needs to do the setup of a
 * ChannelFuture manually since we need to know the port number of the
 * assigned socket.//from  w  w w  .  jav  a2s  . c o m
 * 
 * @param remotePeer
 *            The destination peer
 * @param channelCreator
 *            The channel creator where we create a UPD channel
 * @return The future that will be triggered when we receive an answer or
 *         something fails.
 */
public FutureDone<List<PeerSocketAddress>> pingNATType(final PeerAddress remotePeer,
        final ChannelCreator channelCreator, final ConnectionConfiguration configuration, final Peer peer) {
    final FutureDone<List<PeerSocketAddress>> fDone = new FutureDone<List<PeerSocketAddress>>();
    final List<PeerSocketAddress> peerSocketAddresses = new ArrayList<PeerSocketAddress>(2);
    final Message message = createMessage(remotePeer, RPC.Commands.PING.getNr(), Type.REQUEST_5);
    final FutureResponse futureResponse = new FutureResponse(message);
    final SimpleChannelInboundHandler<Message> inbound = new SimpleChannelInboundHandler<Message>() {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
            if (!msg.peerSocketAddresses().isEmpty() && msg.type() == Type.OK) {
                peerSocketAddresses.add(msg.peerSocketAddresses().get(0));
                fDone.done(peerSocketAddresses);
                ctx.close();
            }
        }
    };
    Utils.addReleaseListener(channelCreator, futureResponse);
    final ChannelFuture cF = channelCreator.createUDP(false,
            peer.connectionBean().sender().configureHandlers(inbound, futureResponse, 30, false),
            futureResponse);
    cF.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                InetSocketAddress srcAddress = (InetSocketAddress) future.channel().localAddress();
                peerSocketAddresses.add(new PeerSocketAddress(srcAddress.getAddress(), srcAddress.getPort(),
                        srcAddress.getPort()));
                peer.connectionBean().sender().afterConnect(futureResponse, message, future, false);
            }
        }
    });
    return fDone;
}

From source file:netty5.http.server.Http2ServerInitializer.java

License:Apache License

/**
 * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.
 *///  w w  w  .  ja  v a 2  s.  c  o m
private static void configureClearText(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    final HttpServerCodec sourceCodec = new HttpServerCodec();

    p.addLast(sourceCodec);
    p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory));
    p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
        @Override
        protected void messageReceived(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
            // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
            System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)");
            ctx.pipeline().replace(this, "http-hello-world",
                    new HelloWorldHttp1Handler("Direct. No Upgrade Attempted."));
            ctx.fireChannelRead(msg);
        }
    });

    p.addLast(new UserEventLogger());
}

From source file:org.apache.activemq.artemis.tests.integration.transports.netty.NettyConnectorWithHTTPUpgradeTest.java

License:Apache License

private void startWebServer(int port) throws InterruptedException {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from  www  .  ja  v  a2  s  . co m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    // create a HTTP server
                    ChannelPipeline p = ch.pipeline();
                    p.addLast("decoder", new HttpRequestDecoder());
                    p.addLast("encoder", new HttpResponseEncoder());
                    p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() {
                        // handle HTTP GET + Upgrade with a handshake specific to ActiveMQ Artemis remoting.
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (msg instanceof HttpRequest) {
                                HttpRequest request = (HttpRequest) msg;

                                for (Map.Entry<String, String> entry : request.headers()) {
                                    System.out.println(entry);
                                }
                                String upgrade = request.headers().get(UPGRADE);
                                String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY);

                                FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
                                        SWITCHING_PROTOCOLS);
                                response.headers().set(UPGRADE, upgrade);
                                response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT,
                                        createExpectedResponse(MAGIC_NUMBER, secretKey));
                                ctx.writeAndFlush(response);

                                // when the handshake is successful, the HTTP handlers are removed
                                ctx.pipeline().remove("decoder");
                                ctx.pipeline().remove("encoder");
                                ctx.pipeline().remove(this);

                                System.out.println("HTTP handshake sent, transferring channel");
                                // transfer the control of the channel to the Netty Acceptor
                                NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService()
                                        .getAcceptor(acceptorName);
                                acceptor.transfer(ctx.channel());
                                // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones.
                            }
                        }
                    });
                }

                @Override
                public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                    ctx.flush();
                }
            });
    b.bind(port).sync();
}

From source file:org.apache.activemq.tests.integration.transports.netty.NettyConnectorWithHTTPUpgradeTest.java

License:Apache License

private void startWebServer(int port) throws InterruptedException {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/* w  w  w.  j a  v  a2s. c om*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    // create a HTTP server
                    ChannelPipeline p = ch.pipeline();
                    p.addLast("decoder", new HttpRequestDecoder());
                    p.addLast("encoder", new HttpResponseEncoder());
                    p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() {
                        // handle HTTP GET + Upgrade with a handshake specific to ActiveMQ remoting.
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (msg instanceof HttpRequest) {
                                HttpRequest request = (HttpRequest) msg;

                                for (Map.Entry<String, String> entry : request.headers()) {
                                    System.out.println(entry);
                                }
                                String upgrade = request.headers().get(UPGRADE);
                                String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY);

                                FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
                                        SWITCHING_PROTOCOLS);
                                response.headers().set(UPGRADE, upgrade);
                                response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT,
                                        createExpectedResponse(MAGIC_NUMBER, secretKey));
                                ctx.writeAndFlush(response);

                                // when the handshake is successful, the HTTP handlers are removed
                                ctx.pipeline().remove("decoder");
                                ctx.pipeline().remove("encoder");
                                ctx.pipeline().remove(this);

                                System.out.println("HTTP handshake sent, transferring channel");
                                // transfer the control of the channel to the Netty Acceptor
                                NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService()
                                        .getAcceptor(acceptorName);
                                acceptor.transfer(ctx.channel());
                                // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones.
                            }
                        }
                    });
                }

                @Override
                public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                    ctx.flush();
                }
            });
    b.bind(port).sync();
}

From source file:org.apache.hadoop.hbase.io.asyncfs.FanOutOneBlockAsyncDFSOutputHelper.java

License:Apache License

private static void processWriteBlockResponse(Channel channel, final DatanodeInfo dnInfo,
        final Promise<Channel> promise, final int timeoutMs) {
    channel.pipeline().addLast(new IdleStateHandler(timeoutMs, 0, 0, TimeUnit.MILLISECONDS),
            new ProtobufVarint32FrameDecoder(), new ProtobufDecoder(BlockOpResponseProto.getDefaultInstance()),
            new SimpleChannelInboundHandler<BlockOpResponseProto>() {

                @Override/* w ww.  j a v  a2s.c o m*/
                protected void channelRead0(ChannelHandlerContext ctx, BlockOpResponseProto resp)
                        throws Exception {
                    Status pipelineStatus = resp.getStatus();
                    if (PipelineAck.isRestartOOBStatus(pipelineStatus)) {
                        throw new IOException("datanode " + dnInfo + " is restarting");
                    }
                    String logInfo = "ack with firstBadLink as " + resp.getFirstBadLink();
                    if (resp.getStatus() != Status.SUCCESS) {
                        if (resp.getStatus() == Status.ERROR_ACCESS_TOKEN) {
                            throw new InvalidBlockTokenException("Got access token error" + ", status message "
                                    + resp.getMessage() + ", " + logInfo);
                        } else {
                            throw new IOException("Got error" + ", status=" + resp.getStatus().name()
                                    + ", status message " + resp.getMessage() + ", " + logInfo);
                        }
                    }
                    // success
                    ChannelPipeline p = ctx.pipeline();
                    for (ChannelHandler handler; (handler = p.removeLast()) != null;) {
                        // do not remove all handlers because we may have wrap or unwrap handlers at the header
                        // of pipeline.
                        if (handler instanceof IdleStateHandler) {
                            break;
                        }
                    }
                    // Disable auto read here. Enable it after we setup the streaming pipeline in
                    // FanOutOneBLockAsyncDFSOutput.
                    ctx.channel().config().setAutoRead(false);
                    promise.trySuccess(ctx.channel());
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    promise.tryFailure(new IOException("connection to " + dnInfo + " is closed"));
                }

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == READER_IDLE) {
                        promise.tryFailure(
                                new IOException("Timeout(" + timeoutMs + "ms) waiting for response"));
                    } else {
                        super.userEventTriggered(ctx, evt);
                    }
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    promise.tryFailure(cause);
                }
            });
}

From source file:org.apache.hadoop.hbase.util.FanOutOneBlockAsyncDFSOutput.java

License:Apache License

private void setupReceiver(final int timeoutMs) {
    SimpleChannelInboundHandler<PipelineAckProto> ackHandler = new SimpleChannelInboundHandler<PipelineAckProto>() {

        @Override/*w ww  . j  a va 2s  . c o  m*/
        public boolean isSharable() {
            return true;
        }

        @Override
        protected void channelRead0(final ChannelHandlerContext ctx, PipelineAckProto ack) throws Exception {
            final Status reply = getStatus(ack);
            if (reply != Status.SUCCESS) {
                failed(ctx.channel(), new Supplier<Throwable>() {

                    @Override
                    public Throwable get() {
                        return new IOException("Bad response " + reply + " for block " + locatedBlock.getBlock()
                                + " from datanode " + ctx.channel().remoteAddress());
                    }
                });
                return;
            }
            if (PipelineAck.isRestartOOBStatus(reply)) {
                failed(ctx.channel(), new Supplier<Throwable>() {

                    @Override
                    public Throwable get() {
                        return new IOException("Restart response " + reply + " for block "
                                + locatedBlock.getBlock() + " from datanode " + ctx.channel().remoteAddress());
                    }
                });
                return;
            }
            if (ack.getSeqno() == HEART_BEAT_SEQNO) {
                return;
            }
            completed(ctx.channel());
        }

        @Override
        public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
            failed(ctx.channel(), new Supplier<Throwable>() {

                @Override
                public Throwable get() {
                    return new IOException("Connection to " + ctx.channel().remoteAddress() + " closed");
                }
            });
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, final Throwable cause) throws Exception {
            failed(ctx.channel(), new Supplier<Throwable>() {

                @Override
                public Throwable get() {
                    return cause;
                }
            });
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent e = (IdleStateEvent) evt;
                if (e.state() == IdleState.READER_IDLE) {
                    failed(ctx.channel(), new Supplier<Throwable>() {

                        @Override
                        public Throwable get() {
                            return new IOException("Timeout(" + timeoutMs + "ms) waiting for response");
                        }
                    });
                } else if (e.state() == IdleState.WRITER_IDLE) {
                    PacketHeader heartbeat = new PacketHeader(4, 0, HEART_BEAT_SEQNO, false, 0, false);
                    int len = heartbeat.getSerializedSize();
                    ByteBuf buf = alloc.buffer(len);
                    heartbeat.putInBuffer(buf.nioBuffer(0, len));
                    buf.writerIndex(len);
                    ctx.channel().writeAndFlush(buf);
                }
                return;
            }
            super.userEventTriggered(ctx, evt);
        }

    };
    for (Channel ch : datanodeList) {
        ch.pipeline().addLast(new IdleStateHandler(timeoutMs, timeoutMs / 2, 0, TimeUnit.MILLISECONDS),
                new ProtobufVarint32FrameDecoder(), new ProtobufDecoder(PipelineAckProto.getDefaultInstance()),
                ackHandler);
        ch.config().setAutoRead(true);
    }
}