List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:io.gatling.http.client.impl.DigestAuthHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (digestHeader == null) { // initial state if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status() == HttpResponseStatus.UNAUTHORIZED) { String authenticateHeader = getHeaderWithPrefix(response.headers().getAll(WWW_AUTHENTICATE), "Digest"); if (authenticateHeader != null) { digestHeader = realm.computeAuthorizationHeader(tx.request.getMethod(), tx.request.getUri(), authenticateHeader); return; }/*from w w w . jav a 2s. c o m*/ } } // nothing this handler can do about it // either we don't need authentication, or auth scheme is not Digest ctx.fireChannelRead(msg); } else if (msg instanceof LastHttpContent) { // send new request // FIXME make sure connection can be reused, otherwise use a new one // FIXME check what happens if buildRequest throws WritableRequest request = WritableRequestBuilder.buildRequest(tx.request, ctx.alloc(), config, false); request.getRequest().headers().add(AUTHORIZATION, digestHeader); // FIXME write can throw Exception!!! request.write(ctx); ctx.pipeline().remove(this); } // initial response chunks are just ignored }
From source file:io.grpc.alts.internal.TsiHandshakeHandler.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // Process the data. If we need to send more data, do so now. if (handshaker.processBytesFromPeer(in) && handshaker.isInProgress()) { sendHandshake(ctx);//from w ww . j a v a2s.co m } // If the handshake is complete, transition to the framing state. if (!handshaker.isInProgress()) { TsiPeer peer = handshaker.extractPeer(); Object authContext = handshaker.extractPeerObject(); SecurityDetails details = handshakeValidator.validatePeerObject(authContext); // createFrameProtector must be called last. TsiFrameProtector protector = handshaker.createFrameProtector(ctx.alloc()); TsiFrameHandler framer; boolean success = false; try { framer = new TsiFrameHandler(protector); // adding framer and next handler after this handler before removing Decoder (current // handler). This will prevents any missing read from decoder and/or unframed write from // next handler. ctx.pipeline().addAfter(ctx.name(), null, framer); ctx.pipeline().addAfter(ctx.pipeline().context(framer).name(), null, next); ctx.pipeline().remove(ctx.name()); fireProtocolNegotiationEvent(ctx, peer, authContext, details); success = true; } finally { if (!success && protector != null) { protector.destroy(); } } } }
From source file:io.grpc.netty.ProtocolNegotiators.java
License:Apache License
@VisibleForTesting static void logSslEngineDetails(Level level, ChannelHandlerContext ctx, String msg, @Nullable Throwable t) { if (!log.isLoggable(level)) { return;// w w w . jav a2 s. c o m } SslHandler sslHandler = ctx.pipeline().get(SslHandler.class); SSLEngine engine = sslHandler.engine(); StringBuilder builder = new StringBuilder(msg); builder.append("\nSSLEngine Details: [\n"); if (engine instanceof OpenSslEngine) { builder.append(" OpenSSL, "); builder.append("Version: 0x").append(Integer.toHexString(OpenSsl.version())); builder.append(" (").append(OpenSsl.versionString()).append("), "); builder.append("ALPN supported: ").append(OpenSsl.isAlpnSupported()); } else if (JettyTlsUtil.isJettyAlpnConfigured()) { builder.append(" Jetty ALPN"); } else if (JettyTlsUtil.isJettyNpnConfigured()) { builder.append(" Jetty NPN"); } else if (JettyTlsUtil.isJava9AlpnAvailable()) { builder.append(" JDK9 ALPN"); } builder.append("\n TLS Protocol: "); builder.append(engine.getSession().getProtocol()); builder.append("\n Application Protocol: "); builder.append(sslHandler.applicationProtocol()); builder.append("\n Need Client Auth: "); builder.append(engine.getNeedClientAuth()); builder.append("\n Want Client Auth: "); builder.append(engine.getWantClientAuth()); builder.append("\n Supported protocols="); builder.append(Arrays.toString(engine.getSupportedProtocols())); builder.append("\n Enabled protocols="); builder.append(Arrays.toString(engine.getEnabledProtocols())); builder.append("\n Supported ciphers="); builder.append(Arrays.toString(engine.getSupportedCipherSuites())); builder.append("\n Enabled ciphers="); builder.append(Arrays.toString(engine.getEnabledCipherSuites())); builder.append("\n]"); log.log(level, builder.toString(), t); }
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.ja v a2 s. c o 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.WriteBufferingAndExceptionHandler.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().addBefore(ctx.name(), null, next); super.handlerAdded(ctx); // kick off protocol negotiation. ctx.pipeline().fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT); }
From source file:io.grpc.netty.WriteBufferingAndExceptionHandler.java
License:Apache License
/** * If this channel becomes inactive, then notify all buffered writes that we failed. *///w w w .ja v a 2s . c o m @Override public void channelInactive(ChannelHandlerContext ctx) { Status status = Status.UNAVAILABLE.withDescription( "Connection closed while performing protocol negotiation for " + ctx.pipeline().names()); failWrites(status.asRuntimeException()); }
From source file:io.grpc.netty.WriteBufferingAndExceptionHandler.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { assert cause != null; Throwable previousFailure = failCause; Status status = Utils.statusFromThrowable(cause) .augmentDescription("Channel Pipeline: " + ctx.pipeline().names()); failWrites(status.asRuntimeException()); // Check to see if the channel is active and this is the first failure. If a downstream // handler triggers an exception in close(), avoid being reentrant. This is not obviously // correct, so here are the cases and how they are correctly handled: // 1. !active, prev==null: the channel is inactive, no-op // 2. !active, prev!=null: the channel is inactive, no-op // 3. active, prev==null: this is the first error, close // 4a. active, prev!=null[channelInactive]: impossible, no-op // 4b. active, prev!=null[close]: close() cannot succeed, no point in calling ctx.close(). // 4c. active, prev!=null[handlerRemoved]: channel will be closed out-of-band by buffered write. // 4d. active, prev!=null[connect]: impossible, channel can't be active after a failed connect. if (ctx.channel().isActive() && previousFailure == null) { final class LogOnFailure implements ChannelFutureListener { @Override// ww w .ja va2s.c o m public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) { logger.log(Level.FINE, "Failed closing channel", future.cause()); } } } ctx.close().addListener(new LogOnFailure()); } }
From source file:io.grpc.netty.WriteBufferingAndExceptionHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try {//from w w w . j a va 2 s. c o m if (logger.isLoggable(Level.FINE)) { Object loggedMsg = msg instanceof ByteBuf ? ByteBufUtil.hexDump((ByteBuf) msg) : msg; logger.log(Level.FINE, "Unexpected channelRead()->{0} reached end of pipeline {1}", new Object[] { loggedMsg, ctx.pipeline().names() }); } exceptionCaught(ctx, Status.INTERNAL.withDescription("channelRead() missed by ProtocolNegotiator handler: " + msg) .asRuntimeException()); } finally { ReferenceCountUtil.safeRelease(msg); } }
From source file:io.grpc.netty.WriteBufferingAndExceptionHandler.java
License:Apache License
/** * If we are still performing protocol negotiation, then this will propagate failures to all * buffered writes.//from w ww .j a v a 2 s. c om */ @Override public void close(ChannelHandlerContext ctx, ChannelPromise future) throws Exception { Status status = Status.UNAVAILABLE.withDescription( "Connection closing while performing protocol negotiation for " + ctx.pipeline().names()); failWrites(status.asRuntimeException()); super.close(ctx, future); }
From source file:io.grpc.netty.WriteBufferingAndExceptionHandler.java
License:Apache License
@SuppressWarnings("FutureReturnValueIgnored") final void writeBufferedAndRemove(ChannelHandlerContext ctx) { // TODO(carl-mastrangelo): remove the isActive check and just fail if not yet ready. if (!ctx.channel().isActive() || writing) { return;/* w ww . ja v a 2 s . c om*/ } // Make sure that method can't be reentered, so that the ordering // in the queue can't be messed up. writing = true; while (!bufferedWrites.isEmpty()) { ChannelWrite write = bufferedWrites.poll(); ctx.write(write.msg, write.promise); } if (flushRequested) { ctx.flush(); } // Removal has to happen last as the above writes will likely trigger // new writes that have to be added to the end of queue in order to not // mess up the ordering. ctx.pipeline().remove(this); }