List of usage examples for io.netty.channel ChannelInboundHandlerAdapter ChannelInboundHandlerAdapter
ChannelInboundHandlerAdapter
From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcClientSession.java
License:Apache License
@Override protected void initChannel(final Channel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ChannelInboundHandlerAdapter() { @Override/*from www .j ava 2 s.c o m*/ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { bumpTimeout(ctx); ctx.fireChannelRead(msg); } }); // first four bytes are length prefix of message, strip first four bytes. pipeline.addLast(new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4)); pipeline.addLast(new NativeRpcDecoder()); pipeline.addLast(new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof NativeRpcError) { final NativeRpcError error = (NativeRpcError) msg; if (log.isTraceEnabled()) { log.trace("[{}] remote error: {}", ctx.channel(), error.getMessage()); } future.fail(new NativeRpcRemoteException(address, error.getMessage())); ctx.channel().close(); return; } if (msg instanceof NativeRpcResponse) { if (log.isTraceEnabled()) { log.trace("[{}] response: cancelling heartbeat", ctx.channel()); } try { handleResponse((NativeRpcResponse) msg); } catch (Exception e) { future.fail(new Exception("Failed to handle response", e)); } return; } if (msg instanceof NativeRpcHeartBeat) { if (log.isTraceEnabled()) { log.trace("[{}] heartbeat: delaying timeout by {}ms", ctx.channel(), heartbeatInterval); } bumpTimeout(ctx); return; } throw new IllegalArgumentException("unable to handle type: " + msg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { future.fail(cause); ctx.channel().close(); } }); pipeline.addLast(new LengthFieldPrepender(4)); pipeline.addLast(new NativeRpcEncoder()); }
From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcClientSessionInitializer.java
License:Apache License
@Override protected void initChannel(final Channel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ChannelInboundHandlerAdapter() { @Override//from ww w . ja va2 s . c o m public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { bumpTimeout(ctx); ctx.fireChannelRead(msg); } }); // first four bytes are length prefix of message, strip first four bytes. pipeline.addLast(new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4)); pipeline.addLast(new NativeRpcDecoder()); pipeline.addLast(new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof NativeRpcError) { final NativeRpcError error = (NativeRpcError) msg; if (log.isTraceEnabled()) { log.trace("[{}] remote error: {}", ctx.channel(), error.getMessage()); } future.fail(new NativeRpcRemoteException(address, error.getMessage())); ctx.channel().close(); return; } if (msg instanceof NativeRpcResponse) { if (log.isTraceEnabled()) { log.trace("[{}] response: cancelling heartbeat", ctx.channel()); } final Timeout old = heartbeatTimeout.getAndSet(null); if (old != null) { old.cancel(); } final NativeRpcResponse response = (NativeRpcResponse) msg; final R responseBody = mapper.readValue(response.getBody(), expected); future.resolve(responseBody); return; } if (msg instanceof NativeRpcHeartBeat) { if (log.isTraceEnabled()) { log.trace("[{}] heartbeat: delaying timeout by {}ms", ctx.channel(), heartbeatInterval); } bumpTimeout(ctx); return; } throw new IllegalArgumentException("unable to handle type: " + msg); } }); pipeline.addLast(new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { future.fail(cause); } }); pipeline.addLast(new LengthFieldPrepender(4)); pipeline.addLast(new NativeRpcEncoder()); }
From source file:com.spotify.netty.handler.codec.zmtp.ZMQIntegrationTest.java
License:Apache License
@Before public void setup() throws InterruptedException { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from ww w . j a va 2s.co m*/ protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ZMTP20Codec(new ZMTPSession(ZMTPConnectionType.Addressed, 1024, identity.getBytes(), ZMTPSocketType.REQ), false)); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); channelsConnected.add(ctx.channel()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { incomingMessages.put((ZMTPIncomingMessage) msg); } }); } }); serverChannel = serverBootstrap.bind(0).sync().channel(); serverAddress = (InetSocketAddress) serverChannel.localAddress(); }
From source file:com.spotify.netty.handler.codec.zmtp.ZMTPTestConnector.java
License:Apache License
public boolean connectAndReceive(final String ip, final int port, final int serverType) { context = ZMQ.context(1);//from w w w .j av a 2 s .c om serverSocket = context.socket(serverType); preConnect(serverSocket); serverSocket.bind("tcp://" + ip + ":" + port); EventLoopGroup group = new NioEventLoopGroup(); // Configure the client. final Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { final ZMTPSession session = new ZMTPSession(ZMTPConnectionType.Addressed, "client".getBytes()); ChannelPipeline pl = ch.pipeline(); pl.addLast(new ZMTP10Codec(session)); pl.addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (onMessage((ZMTPIncomingMessage) msg)) { receivedMessage = true; ctx.channel().close(); } } }); } }); // Start the connection attempt. final ChannelFuture future = bootstrap.connect(new InetSocketAddress(ip, port)); future.awaitUninterruptibly(); afterConnect(serverSocket, future); // Wait until the connection is closed or the connection attempt fails. future.channel().closeFuture().awaitUninterruptibly(); // Shut down thread pools to exit. group.shutdownGracefully(); serverSocket.close(); context.term(); return receivedMessage; }
From source file:com.zextras.modules.chat.services.LocalXmppService.java
License:Open Source License
@Override public void run() { ChatLog.log.info("Listening on port " + DEFAULT_LOCAL_XMPP_PORT); EventLoopGroup acceptorGroup = new NioEventLoopGroup(4); EventLoopGroup channelWorkerGroup = new NioEventLoopGroup(8); Channel channel;//from w ww . j av a2 s . co m try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(acceptorGroup, channelWorkerGroup); bootstrap.channel(NioServerSocketChannel.class); ChannelHandler handler = new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { try { SSLEngine sslEngine = mZimbraSSLContextProvider.get().createSSLEngine(); sslEngine.setUseClientMode(false); SslHandler sslHandler = new SslHandler(sslEngine); ch.pipeline().addFirst("ssl", sslHandler); ch.pipeline().addLast(null, "SubTagTokenizer", new XmlSubTagTokenizer()); ch.pipeline().addLast(null, "XmlTagTokenizer", new XmlTagTokenizer()); ch.pipeline().addAfter("XmlTagTokenizer", "StanzaProcessor", new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { mLocalXmppReceiver.processStanza((String) msg); } }); } catch (Throwable t) { ChatLog.log.warn("Unable to initializer XMPP connection: " + Utils.exceptionToString(t)); ch.close(); } } }; ChannelFuture channelFuture = bootstrap.childHandler(handler).option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 0).bind(DEFAULT_LOCAL_XMPP_PORT).sync(); if (!channelFuture.isSuccess()) { throw channelFuture.cause(); } channel = channelFuture.channel(); mInitializationPromise.setSuccess(null); } catch (Throwable e) { mInitializationPromise.setFailure(e); return; } mLock.lock(); try { while (!mStopRequested) { try { mWaitStopRequest.await(); } catch (InterruptedException ignored) { } } channel.close().sync(); acceptorGroup.shutdownGracefully().sync(); channelWorkerGroup.shutdownGracefully().sync(); } catch (InterruptedException ignored) { } finally { mLock.unlock(); } }
From source file:gedi.remote.RemoteConnections.java
License:Apache License
/** * Connects to the given server; the mechanics is as follows: * <br/>/*w w w.jav a 2s .c o m*/ * The initChannel consumer is supposed to register channel handlers (called upon channel.registered) * <br/> * Depending on the outcome of the Bootrap.connect method, either the errorHandler or the connectedHandler is called. * <br/> * If the connection is lost, the closedHandler is called. * <br/> * If you want to cancel the connection attempt, invoke cancel on the returned ChannelFuture. If you want to terminate the connection, use the * channel object from the connectedHandler. * <br /> * If the channel is unregistered, the added flag is reset for all handlers bound to the channel pipeline (important if you want to reuse * the handlers added by the initChannel consumer). * * @param uri * @param initChannel * @param errorHandler * @param connectedHandler * @param closedHandler * @return */ public ChannelFuture connect(URI uri, Consumer<SocketChannel> initChannel, Consumer<Throwable> errorHandler, Consumer<SocketChannel> connectedHandler, Runnable closedHandler) { final Protocol protocol = ProtocolExtensionPoint.getInstance().get(ExtensionContext.emptyContext(), uri.getScheme()); if (protocol == null) throw new RuntimeException("Protocol " + uri.getScheme() + " unknown!"); EventLoopGroup group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); protocol.setCodecs(pipeline); initChannel.accept(ch); pipeline.addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { pipeline.addLast(new ConfigLoggingHandler(ConfigLoggingHandler.LogLevel.INFO)); connectedHandler.accept(ch); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); closedHandler.run(); } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().iterator().forEachRemaining((e) -> Workarounds.removeAdded(e.getValue())); super.channelUnregistered(ctx); } }); } }); // Make a new connection and wait until closed. ChannelFuture f = b.connect(uri.getHost(), uri.getPort() == -1 ? protocol.getDefaultPort() : uri.getPort()) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { Throwable cause = future.cause(); if (cause != null) { log.log(Level.INFO, "Connection failed to server " + uri + ": " + cause.getMessage()); try { errorHandler.accept(cause); } finally { group.shutdownGracefully(); } } else { log.log(Level.INFO, "Client connected to server " + uri); future.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { log.log(Level.INFO, "Connection closed to server " + uri); group.shutdownGracefully(); } }); } } }); return f; }
From source file:io.advantageous.conekt.test.core.EventLoopGroupTest.java
License:Open Source License
@Test public void testNettyServerUsesContextEventLoop() throws Exception { ContextInternal context = (ContextInternal) conekt.getOrCreateContext(); AtomicReference<Thread> contextThread = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); context.runOnContext(v -> {/*from w ww . j a v a2 s .c om*/ contextThread.set(Thread.currentThread()); latch.countDown(); }); awaitLatch(latch); ServerBootstrap bs = new ServerBootstrap(); bs.group(context.nettyEventLoop()); bs.channel(NioServerSocketChannel.class); bs.option(ChannelOption.SO_BACKLOG, 100); bs.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); }); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; assertEquals("hello", buf.toString(StandardCharsets.UTF_8)); assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); }); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); testComplete(); }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { fail(cause.getMessage()); } }); }); } }); bs.bind("localhost", 1234).sync(); conekt.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> { assertTrue(ar.succeeded()); NetSocket so = ar.result(); so.write(Buffer.buffer("hello")); }); await(); }
From source file:io.grpc.alts.internal.GoogleDefaultProtocolNegotiatorTest.java
License:Apache License
@Test public void altsHandler() { Attributes eagAttributes = Attributes.newBuilder().set(GrpcAttributes.ATTR_LB_PROVIDED_BACKEND, true) .build();/*from ww w. ja v a 2 s .c o m*/ GrpcHttp2ConnectionHandler mockHandler = mock(GrpcHttp2ConnectionHandler.class); when(mockHandler.getEagAttributes()).thenReturn(eagAttributes); final AtomicReference<Throwable> failure = new AtomicReference<>(); ChannelHandler exceptionCaught = new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { failure.set(cause); super.exceptionCaught(ctx, cause); } }; ChannelHandler h = googleProtocolNegotiator.newHandler(mockHandler); EmbeddedChannel chan = new EmbeddedChannel(exceptionCaught); // Add the negotiator handler last, but to the front. Putting this in ctor above would make it // throw early. chan.pipeline().addFirst(h); chan.pipeline().fireUserEventTriggered(InternalProtocolNegotiationEvent.getDefault()); // Check that the message complained about the ALTS code, rather than SSL. ALTS throws on // being added, so it's hard to catch it at the right time to make this assertion. assertThat(failure.get()).hasMessageThat().contains("TsiHandshakeHandler"); }
From source file:io.grpc.netty.ProtocolNegotiatorsTest.java
License:Apache License
@Test public void waitUntilActiveHandler_handlerAdded() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final WaitUntilActiveHandler handler = new WaitUntilActiveHandler(new ChannelHandlerAdapter() { @Override//w w w . j a v a 2 s . co m public void handlerAdded(ChannelHandlerContext ctx) throws Exception { assertTrue(ctx.channel().isActive()); latch.countDown(); super.handlerAdded(ctx); } }); ChannelHandler lateAddingHandler = new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().addLast(handler); ctx.pipeline().fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT); // do not propagate channelActive(). } }; LocalAddress addr = new LocalAddress("local"); ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(lateAddingHandler).group(group) .register(); chan = cf.channel(); ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class) .childHandler(new ChannelHandlerAdapter() { }).group(group).bind(addr); server = sf.channel(); sf.sync(); assertEquals(1, latch.getCount()); chan.connect(addr).sync(); assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); assertNull(chan.pipeline().context(WaitUntilActiveHandler.class)); }
From source file:io.grpc.netty.ProtocolNegotiatorsTest.java
License:Apache License
@Test public void tlsHandler_userEventTriggeredSslEvent_unsupportedProtocol() throws Exception { SslHandler badSslHandler = new SslHandler(engine, false) { @Override//from www .j ava2 s .c o m public String applicationProtocol() { return "badprotocol"; } }; ChannelHandler handler = new ServerTlsHandler(grpcHandler, sslContext); pipeline.addLast(handler); final AtomicReference<Throwable> error = new AtomicReference<>(); ChannelHandler errorCapture = new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { error.set(cause); } }; pipeline.addLast(errorCapture); pipeline.replace(SslHandler.class, null, badSslHandler); channelHandlerCtx = pipeline.context(handler); Object sslEvent = SslHandshakeCompletionEvent.SUCCESS; pipeline.fireUserEventTriggered(sslEvent); // No h2 protocol was specified, so there should be an error, (normally handled by WBAEH) assertThat(error.get()).hasMessageThat().contains("Unable to find compatible protocol"); ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler); assertNull(grpcHandlerCtx); }