Example usage for io.netty.channel ChannelInboundHandlerAdapter ChannelInboundHandlerAdapter

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

Introduction

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

Prototype

ChannelInboundHandlerAdapter

Source Link

Usage

From source file:NettyServer.java

License:Open Source License

void start() throws Exception {
    parentGroup = new NioEventLoopGroup(1);
    childGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap().group(parentGroup, childGroup)
            .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override// ww  w.  j  a v a 2  s . co  m
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();

                    pipeline.addLast("lineFrame", new LineBasedFrameDecoder(256));
                    pipeline.addLast("decoder", new StringDecoder());
                    pipeline.addLast("encoder", new StringEncoder());

                    pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            Channel channel = ctx.channel();
                            channelActiveHandler.accept(channel);
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            messageConsumer.accept(msg);
                        }
                    });
                }
            });
    channel = bootstrap.bind(port).channel();
    System.out.println("NettyServer started");
}

From source file:at.yawk.accordion.netty.NettyConnection.java

License:Mozilla Public License

/**
 * Initialize this channel so messages can be read.
 *///www . jav a  2s . c  om
void init() {
    channel.pipeline().addLast(new Framer()).addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            messageHandler.accept((ByteBuf) msg);
        }
    }).addLast(new ChannelDuplexHandler() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            exceptionHandler.accept(cause);
        }

        @Override
        public void disconnect(ChannelHandlerContext ctx, ChannelPromise future) throws Exception {
            disconnectHandler.run();
        }
    });
}

From source file:at.yawk.votifier.VotifierServerImpl.java

License:Mozilla Public License

public void init() {
    if (!initialized.compareAndSet(false, true)) {
        return;//  w  w  w  .j a  v a 2s . c  o  m
    }

    logger.info("Initializing votifier server...");
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
                    logger.fine("Client disconnected.");
                }

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

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new VoteDecrypter(key)).addLast(new LineSplitter())
                            .addLast(new VoteDecoder()).addLast(new VersionEncoder())
                            .addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg)
                                        throws Exception {
                                    if (!(msg instanceof Operation)) {
                                        return;
                                    }
                                    Operation operation = (Operation) msg;
                                    if (operation.getOperation().equals("VOTE")) {
                                        listener.accept(
                                                new VoteEvent(operation.getUsername(), operation.getService(),
                                                        operation.getAddress(), operation.getTimestamp()));
                                        ctx.channel().close();
                                    } else {
                                        throw new UnsupportedOperationException(operation.getOperation());
                                    }
                                }

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

                    logger.info("Client connected: Sending version packet.");
                    ch.writeAndFlush(version);
                }
            });
}

From source file:cloudfoundry.norouter.f5.dropsonde.LineEventToMetronServer.java

License:Open Source License

@Autowired
public LineEventToMetronServer(@Qualifier("boss") EventLoopGroup boss,
        @Qualifier("worker") EventLoopGroup worker, RouteRegistrar routeRegistrar, MetronClient metronClient,
        F5Properties properties) {
    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*  w ww  .ja va 2s.co  m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LineBasedFrameDecoder(64 * 1024));
                    ch.pipeline().addLast(new LineEventDecoder());
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            LOGGER.warn("An error occurred processing logging events from the LTM.", cause);
                            ctx.close();
                        }

                        @Override
                        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
                            LOGGER.info("New connection from {}", ctx.channel().remoteAddress());
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (msg instanceof LogEvent) {
                                final LogEvent logEvent = (LogEvent) msg;
                                final RouteDetails routeDetails = routeRegistrar
                                        .getRouteByAddress(logEvent.getApplicationAddress());
                                if (routeDetails != null && routeDetails.getApplicationGuid() != null) {
                                    final String appGuid = routeDetails.getApplicationGuid().toString();
                                    final String message = logEvent.getMessage() + " app_id:" + appGuid;
                                    metronClient.createLogEmitter("RTR", logEvent.getLtmIdentifier())
                                            .emit(logEvent.getTimestamp(), appGuid, message);
                                }
                            } else {
                                super.channelRead(ctx, msg);
                            }
                        }
                    });
                }
            });
    bootstrap.bind(properties.getLoggingPort()).syncUninterruptibly();
    LOGGER.info("Listening for logging events from the LTM on port {}", properties.getLoggingPort());
}

From source file:com.android.tools.idea.diagnostics.crash.LocalTestServer.java

License:Apache License

public void start() throws Exception {
    ServerBootstrap b = new ServerBootstrap();
    myEventLoopGroup = new OioEventLoopGroup();
    b.group(myEventLoopGroup).channel(OioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//w w w . j av  a  2  s. c om
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpServerCodec());
                    // Note: Netty's decompressor uses jcraft jzlib, which is not exported as a library
                    // p.addLast(new HttpContentDecompressor());
                    p.addLast(new HttpObjectAggregator(32 * 1024)); // big enough to collect a full thread dump
                    p.addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                            ctx.flush();
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (!(msg instanceof FullHttpRequest)) {
                                return;
                            }

                            FullHttpResponse response = myResponseSupplier.apply((FullHttpRequest) msg);
                            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,
                                    response.content().readableBytes());
                            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            ctx.write(cause.toString()).addListener(ChannelFutureListener.CLOSE);
                        }
                    });
                }
            });

    myChannel = b.bind(myPort).sync().channel();
}

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

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *//*from   www .j a v a2 s .c  o m*/
public static Promise<Rpc> createClient(final LocalConf config, final EventLoopGroup eloop, String host,
        int port, final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(RPC_CLIENT_CONNECT_TIMEOUT);

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
            config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

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

License:Apache License

private Rpc(LocalConf config, Channel channel, EventExecutorGroup egroup) {
    Preconditions.checkArgument(channel != null);
    Preconditions.checkArgument(egroup != null);
    this.config = config;
    this.channel = channel;
    this.channelLock = new Object();
    this.dispatcher = null;
    this.egroup = egroup;
    this.listeners = Lists.newLinkedList();
    this.rpcClosed = new AtomicBoolean();
    this.rpcId = new AtomicLong();

    // Note: this does not work for embedded channels.
    channel.pipeline().addLast("monitor", new ChannelInboundHandlerAdapter() {
        @Override//from w ww  . j  av a 2  s.c om
        public void channelInactive(ChannelHandlerContext ctx) {
            close();
        }
    });
}

From source file:com.cloudera.livy.rsc.rpc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *///from  w w  w.j  av a 2  s  .  c o  m
public static Promise<Rpc> createClient(final RSCConf config, final EventLoopGroup eloop, String host, int port,
        final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(RPC_CLIENT_CONNECT_TIMEOUT);

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
            config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

From source file:com.cloudera.livy.rsc.rpc.Rpc.java

License:Apache License

private Rpc(RSCConf config, Channel channel, EventExecutorGroup egroup) {
    Utils.checkArgument(channel != null);
    Utils.checkArgument(egroup != null);
    this.config = config;
    this.channel = channel;
    this.channelLock = new Object();
    this.dispatcher = null;
    this.egroup = egroup;
    this.rpcClosed = new AtomicBoolean();
    this.rpcId = new AtomicLong();

    // Note: this does not work for embedded channels.
    channel.pipeline().addLast("monitor", new ChannelInboundHandlerAdapter() {
        @Override/*w  ww.  ja va2s.  c o m*/
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            close();
            super.channelInactive(ctx);
        }
    });
}

From source file:com.comphenix.protocol.compat.netty.independent.NettyChannelInjector.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public boolean inject() {
    synchronized (networkManager) {
        if (closed)
            return false;
        if (originalChannel instanceof Factory)
            return false;
        if (!originalChannel.isActive())
            return false;

        // Main thread? We should synchronize with the channel thread, otherwise we might see a
        // pipeline with only some of the handlers removed
        if (Bukkit.isPrimaryThread()) {
            // Just like in the close() method, we'll avoid blocking the main thread
            executeInChannelThread(new Runnable() {
                @Override//from  ww  w .  j a  va2  s. c  om
                public void run() {
                    inject();
                }
            });
            return false; // We don't know
        }

        // Don't inject the same channel twice
        if (findChannelHandler(originalChannel, NettyChannelInjector.class) != null) {
            return false;
        }

        // Get the vanilla decoder, so we don't have to replicate the work
        vanillaDecoder = (ByteToMessageDecoder) originalChannel.pipeline().get("decoder");
        vanillaEncoder = (MessageToByteEncoder<Object>) originalChannel.pipeline().get("encoder");

        if (vanillaDecoder == null)
            throw new IllegalArgumentException(
                    "Unable to find vanilla decoder in " + originalChannel.pipeline());
        if (vanillaEncoder == null)
            throw new IllegalArgumentException(
                    "Unable to find vanilla encoder in " + originalChannel.pipeline());
        patchEncoder(vanillaEncoder);

        if (DECODE_BUFFER == null)
            DECODE_BUFFER = Accessors.getMethodAccessor(vanillaDecoder.getClass(), "decode",
                    ChannelHandlerContext.class, ByteBuf.class, List.class);
        if (ENCODE_BUFFER == null)
            ENCODE_BUFFER = Accessors.getMethodAccessor(vanillaEncoder.getClass(), "encode",
                    ChannelHandlerContext.class, Object.class, ByteBuf.class);

        // Intercept sent packets
        MessageToByteEncoder<Object> protocolEncoder = new MessageToByteEncoder<Object>() {
            @Override
            protected void encode(ChannelHandlerContext ctx, Object packet, ByteBuf output) throws Exception {
                if (packet instanceof WirePacket) {
                    // Special case for wire format
                    NettyChannelInjector.this.encodeWirePacket((WirePacket) packet, new NettyByteBuf(output));
                } else {
                    NettyChannelInjector.this.encode(ctx, packet, output);
                }
            }

            @Override
            public void write(ChannelHandlerContext ctx, Object packet, ChannelPromise promise)
                    throws Exception {
                super.write(ctx, packet, promise);
                NettyChannelInjector.this.finalWrite(ctx, packet, promise);
            }
        };

        // Intercept recieved packets
        ChannelInboundHandlerAdapter finishHandler = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                // Execute context first
                ctx.fireChannelRead(msg);
                NettyChannelInjector.this.finishRead(ctx, msg);
            }
        };

        // Insert our handlers - note that we effectively replace the vanilla encoder/decoder
        originalChannel.pipeline().addBefore("decoder", "protocol_lib_decoder", this);
        originalChannel.pipeline().addBefore("protocol_lib_decoder", "protocol_lib_finish", finishHandler);
        originalChannel.pipeline().addAfter("encoder", "protocol_lib_encoder", protocolEncoder);

        // Intercept all write methods
        channelField.setValue(new NettyChannelProxy(originalChannel, MinecraftReflection.getPacketClass()) {
            // Compatibility with Spigot 1.8
            private final NettyPipelineProxy pipelineProxy = new NettyPipelineProxy(originalChannel.pipeline(),
                    this) {
                @Override
                public ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler) {
                    // Correct the position of the decoder
                    if ("decoder".equals(baseName)) {
                        if (super.get("protocol_lib_decoder") != null && guessCompression(handler)) {
                            super.addBefore("protocol_lib_decoder", name, handler);
                            return this;
                        }
                    }

                    return super.addBefore(baseName, name, handler);
                }
            };

            @Override
            public ChannelPipeline pipeline() {
                return pipelineProxy;
            }

            @Override
            protected <T> Callable<T> onMessageScheduled(final Callable<T> callable,
                    FieldAccessor packetAccessor) {
                final PacketEvent event = handleScheduled(callable, packetAccessor);

                // Handle cancelled events
                if (event != null && event.isCancelled())
                    return null;

                return new Callable<T>() {
                    @Override
                    public T call() throws Exception {
                        T result = null;

                        // This field must only be updated in the pipeline thread
                        currentEvent = event;
                        result = callable.call();
                        currentEvent = null;
                        return result;
                    }
                };
            }

            @Override
            protected Runnable onMessageScheduled(final Runnable runnable, FieldAccessor packetAccessor) {
                final PacketEvent event = handleScheduled(runnable, packetAccessor);

                // Handle cancelled events
                if (event != null && event.isCancelled())
                    return null;

                return new Runnable() {
                    @Override
                    public void run() {
                        currentEvent = event;
                        runnable.run();
                        currentEvent = null;
                    }
                };
            }

            protected PacketEvent handleScheduled(Object instance, FieldAccessor accessor) {
                // Let the filters handle this packet
                Object original = accessor.get(instance);

                // See if we've been instructed not to process packets
                if (!scheduleProcessPackets.get()) {
                    NetworkMarker marker = getMarker(original);

                    if (marker != null) {
                        PacketEvent result = new PacketEvent(NettyChannelInjector.class);
                        result.setNetworkMarker(marker);
                        return result;
                    } else {
                        return BYPASSED_PACKET;
                    }
                }
                PacketEvent event = processSending(original);

                if (event != null && !event.isCancelled()) {
                    Object changed = event.getPacket().getHandle();

                    // Change packet to be scheduled
                    if (original != changed)
                        accessor.set(instance, changed);
                }
                ;
                return event != null ? event : BYPASSED_PACKET;
            }
        });

        injected = true;
        return true;
    }
}