io.netty.channel.ChannelHandlerAdapter Java Examples

The following examples show how to use io.netty.channel.ChannelHandlerAdapter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProtocolNegotiators.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
public Handler newHandler(GrpcHttp2ConnectionHandler handler) {
  final HostPort hostPort = parseAuthority(handler.getAuthority());

  ChannelHandler sslBootstrap = new ChannelHandlerAdapter() {
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
      SSLEngine sslEngine = sslContext.newEngine(ctx.alloc(), hostPort.host, hostPort.port);
      SSLParameters sslParams = sslEngine.getSSLParameters();
      sslParams.setEndpointIdentificationAlgorithm("HTTPS");
      sslEngine.setSSLParameters(sslParams);
      ctx.pipeline().replace(this, null, new SslHandler(sslEngine, false));
    }
  };
  return new BufferUntilTlsNegotiatedHandler(sslBootstrap, handler);
}
 
Example #2
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void connectionFailuresPropagated() throws Exception {
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelHandlerAdapter() {});
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  // Write before connect.  In the event connect fails, the pipeline is torn down and the handler
  // won't be able to fail the writes with the correct exception.
  ChannelFuture wf = chan.writeAndFlush(new Object());
  chan.connect(new LocalAddress("bogus"));

  try {
    wf.sync();
    fail();
  } catch (Exception e) {
    assertThat(e).isInstanceOf(ConnectException.class);
    assertThat(e).hasMessageThat().contains("connection refused");
  }
}
 
Example #3
Source File: SdsProtocolNegotiators.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
ServerSdsHandler(
        GrpcHttp2ConnectionHandler grpcHandler,
        DownstreamTlsContext downstreamTlsContext,
        ProtocolNegotiator fallbackProtocolNegotiator) {
  super(
      // superclass (InternalProtocolNegotiators.ProtocolNegotiationHandler) expects 'next'
      // handler but we don't have a next handler _yet_. So we "disable" superclass's behavior
      // here and then manually add 'next' when we call fireProtocolNegotiationEvent()
      new ChannelHandlerAdapter() {
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
          ctx.pipeline().remove(this);
        }
      });
  checkNotNull(grpcHandler, "grpcHandler");
  this.grpcHandler = grpcHandler;
  this.downstreamTlsContext = downstreamTlsContext;
  this.fallbackProtocolNegotiator = fallbackProtocolNegotiator;
}
 
Example #4
Source File: SdsProtocolNegotiators.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
ClientSdsHandler(
    GrpcHttp2ConnectionHandler grpcHandler, UpstreamTlsContext upstreamTlsContext) {
  super(
      // superclass (InternalProtocolNegotiators.ProtocolNegotiationHandler) expects 'next'
      // handler but we don't have a next handler _yet_. So we "disable" superclass's behavior
      // here and then manually add 'next' when we call fireProtocolNegotiationEvent()
      new ChannelHandlerAdapter() {
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
          ctx.pipeline().remove(this);
        }
      });
  checkNotNull(grpcHandler, "grpcHandler");
  this.grpcHandler = grpcHandler;
  this.upstreamTlsContext = upstreamTlsContext;
}
 
Example #5
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addSeveralByteEncodersWhenCodec() {
	ChannelHandler encoder1 = new LineBasedFrameDecoder(12);
	ChannelHandler encoder2 = new LineBasedFrameDecoder(13);

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new HttpServerCodec())
	       .addLast(NettyPipeline.HttpTrafficHandler, new ChannelDuplexHandler())
	       .addLast(NettyPipeline.ReactiveBridge, new ChannelHandlerAdapter() {
	       });

	testContext.addHandlerFirst("encoder1", encoder1)
	           .addHandlerFirst("encoder2", encoder2);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					NettyPipeline.HttpTrafficHandler,
					"encoder2",
					"encoder1",
					NettyPipeline.ReactiveBridge,
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #6
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addNonByteEncoderWhenFullReactorPipeline() {

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new HttpServerCodec())
	       .addLast(NettyPipeline.HttpTrafficHandler, new ChannelDuplexHandler())
	       .addLast(NettyPipeline.ReactiveBridge, new ChannelHandlerAdapter() {
	       });
	ChannelHandler encoder = new ChannelHandlerAdapter() {
	};

	testContext.addHandlerFirst("encoder", encoder);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					NettyPipeline.HttpTrafficHandler,
					"encoder",
					NettyPipeline.ReactiveBridge,
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #7
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addNonByteEncoderWhenNoRight() {

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new ChannelHandlerAdapter() {
	       });
	ChannelHandler encoder = new ChannelHandlerAdapter() {
	};

	testContext.addHandlerFirst("encoder", encoder);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					"encoder",
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #8
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addNonByteEncoderWhenNoLeft() {

	channel.pipeline()
	       .addLast(NettyPipeline.ReactiveBridge, new ChannelHandlerAdapter() {
	       });
	ChannelHandler encoder = new ChannelHandlerAdapter() {
	};

	testContext.addHandlerFirst("encoder", encoder);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList("encoder",
					NettyPipeline.ReactiveBridge,
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #9
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addByteEncoderWhenFullReactorPipeline() {

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new HttpServerCodec())
	       .addLast(NettyPipeline.HttpTrafficHandler, new ChannelDuplexHandler())
	       .addLast(NettyPipeline.ReactiveBridge, new ChannelHandlerAdapter() {
	       });
	ChannelHandler encoder = new LineBasedFrameDecoder(12);

	testContext.addHandlerFirst("encoder", encoder);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					NettyPipeline.HttpTrafficHandler,
					"encoder",
					NettyPipeline.ReactiveBridge,
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #10
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addByteEncoderWhenNoRight() {

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new ChannelHandlerAdapter() {
	       });
	ChannelHandler encoder = new LineBasedFrameDecoder(12);

	testContext.addHandlerFirst("encoder", encoder);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					"encoder",
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #11
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addByteEncoderWhenNoLeft() {

	channel.pipeline()
	       .addLast(NettyPipeline.ReactiveBridge, new ChannelHandlerAdapter() {
	       });
	ChannelHandler encoder = new LineBasedFrameDecoder(12);

	testContext.addHandlerFirst("encoder", encoder);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList("encoder",
					NettyPipeline.ReactiveBridge,
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #12
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addNonByteDecoderWhenFullReactorPipeline() {

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new HttpServerCodec())
	       .addLast(NettyPipeline.HttpTrafficHandler, new ChannelDuplexHandler())
	       .addLast(NettyPipeline.ReactiveBridge, new ChannelHandlerAdapter() {
	       });
	ChannelHandler decoder = new ChannelHandlerAdapter() {
	};

	testContext.addHandlerLast("decoder", decoder);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					NettyPipeline.HttpTrafficHandler,
					"decoder",
					NettyPipeline.ReactiveBridge,
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #13
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addNonByteDecoderWhenNoRight() {

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new ChannelHandlerAdapter() {
	       });
	ChannelHandler decoder = new ChannelHandlerAdapter() {
	};

	testContext.addHandlerLast("decoder", decoder);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					"decoder",
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #14
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addNonByteDecoderWhenNoLeft() {

	channel.pipeline()
	       .addLast(NettyPipeline.ReactiveBridge, new ChannelHandlerAdapter() {
	       });
	ChannelHandler decoder = new ChannelHandlerAdapter() {
	};

	testContext.addHandlerLast("decoder", decoder);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList("decoder",
					NettyPipeline.ReactiveBridge,
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #15
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addByteDecoderWhenNoRight() {

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new ChannelHandlerAdapter() {
	       });
	ChannelHandler decoder = new LineBasedFrameDecoder(12);

	testContext.addHandlerLast("decoder", decoder)
	           .addHandlerFirst("decoder$extract",
			           NettyPipeline.inboundHandler(ADD_EXTRACTOR));

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					"decoder$extract",
					"decoder",
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #16
Source File: MonoSendManyTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void testPromiseSendTimeout() {
	//use an extra handler
	EmbeddedChannel channel = new EmbeddedChannel(new WriteTimeoutHandler(1), new ChannelHandlerAdapter() {});

	Flux<String> flux = Flux.range(0, 257).map(count -> count + "");
	Mono<Void> m = MonoSendMany.objectSource(flux, channel, b -> false);

	StepVerifier.create(m)
	            .then(() -> {
	                channel.runPendingTasks(); //run flush
	                for (int i = 0; i < 257; i++) {
	                    assertThat(channel.<String>readOutbound()).isEqualTo(i + "");
	                }
	            })
	            .verifyComplete();
}
 
Example #17
Source File: MonoSendManyTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void cleanupFuseableSyncCloseFuture() {
	//use an extra handler
	EmbeddedChannel channel = new EmbeddedChannel(new ChannelHandlerAdapter() {});

	Mono<Void> m = MonoSendMany.objectSource(Flux.fromArray(new String[]{"test", "test2"}), channel, b -> false);

	List<WeakReference<Subscription>> _w = new ArrayList<>(1);
	StepVerifier.create(m)
	            .consumeSubscriptionWith(s -> _w.add(new WeakReference<>(s)))
	            .then(() -> {
		            channel.runPendingTasks();
		            assertThat(channel.<String>readOutbound()).isEqualToIgnoringCase("test");
		            assertThat(channel.<String>readOutbound()).isEqualToIgnoringCase("test2");
	            })
	            .verifyComplete();

	System.gc();
	wait(_w.get(0));
}
 
Example #18
Source File: MonoSendManyTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void cleanupFuseableAsyncCloseFuture() {
	//use an extra handler
	EmbeddedChannel channel = new EmbeddedChannel(new ChannelHandlerAdapter() {});

	Mono<Void> m = MonoSendMany.objectSource(Flux.fromArray(new String[]{"test", "test2"}).limitRate(10), channel, b -> false);

	List<WeakReference<Subscription>> _w = new ArrayList<>(1);
	StepVerifier.create(m)
	            .consumeSubscriptionWith(s -> _w.add(new WeakReference<>(s)))
	            .then(() -> {
		            channel.runPendingTasks();
		            assertThat(channel.<String>readOutbound()).isEqualToIgnoringCase("test");
		            assertThat(channel.<String>readOutbound()).isEqualToIgnoringCase("test2");
	            })
	            .verifyComplete();

	System.gc();
	wait(_w.get(0));
}
 
Example #19
Source File: MonoSendManyTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void cleanupFuseableErrorCloseFuture() {
	//use an extra handler
	EmbeddedChannel channel = new EmbeddedChannel(new ChannelHandlerAdapter() {});

	Mono<Void> m = MonoSendMany.objectSource(Flux.fromArray(new String[]{"test", "test2"}).concatWith(Mono.error(new Exception("boo"))).limitRate(10), channel, b -> false);

	List<WeakReference<Subscription>> _w = new ArrayList<>(1);
	StepVerifier.create(m)
	            .consumeSubscriptionWith(s -> _w.add(new WeakReference<>(s)))
	            .then(() -> {
		            channel.runPendingTasks();
		            assertThat(channel.<String>readOutbound()).isEqualToIgnoringCase("test");
		            assertThat(channel.<String>readOutbound()).isEqualToIgnoringCase("test2");
	            })
	            .verifyErrorMessage("boo");

	System.gc();
	wait(_w.get(0));
}
 
Example #20
Source File: MonoSendManyTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void cleanupCancelCloseFuture() {
	//use an extra handler
	EmbeddedChannel channel = new EmbeddedChannel(new ChannelHandlerAdapter() {});

	Mono<Void> m = MonoSendMany.objectSource(Flux.fromArray(new String[]{"test", "test2"}).concatWith(Mono.never()), channel, b -> false);

	List<WeakReference<Subscription>> _w = new ArrayList<>(1);
	StepVerifier.create(m)
	            .consumeSubscriptionWith(s -> _w.add(new WeakReference<>(s)))
	            .then(channel::runPendingTasks)
	            .thenCancel()
	            .verify();

	System.gc();
	wait(_w.get(0));
}
 
Example #21
Source File: MonoSendManyTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void cleanupErrorCloseFuture() {
	//use an extra handler
	EmbeddedChannel channel = new EmbeddedChannel(new ChannelHandlerAdapter() {});

	Mono<Void> m = MonoSendMany.objectSource(Mono.error(new Exception("boo")), channel, b -> false);

	List<WeakReference<Subscription>> _w = new ArrayList<>(1);
	StepVerifier.create(m)
	            .consumeSubscriptionWith(s -> _w.add(new WeakReference<>(s)))
	            .then(channel::runPendingTasks)
	            .verifyErrorMessage("boo");

	System.gc();
	wait(_w.get(0));
}
 
Example #22
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addByteDecoderWhenFullReactorPipeline() {

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new HttpServerCodec())
	       .addLast(NettyPipeline.HttpTrafficHandler, new ChannelDuplexHandler())
	       .addLast(NettyPipeline.ReactiveBridge, new ChannelHandlerAdapter() {
	       });
	ChannelHandler decoder = new LineBasedFrameDecoder(12);

	testContext.addHandlerLast("decoder", decoder)
	           .addHandlerFirst("decoder$extract",
			           NettyPipeline.inboundHandler(ADD_EXTRACTOR));

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					NettyPipeline.HttpTrafficHandler,
					"decoder$extract",
					"decoder",
					NettyPipeline.ReactiveBridge,
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #23
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void handlerRemovedFailuresPropagated() throws Exception {
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelHandlerAdapter() {
        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) {
          ctx.pipeline().remove(
              ctx.pipeline().context(WriteBufferingAndExceptionHandler.class).name());
        }
      });
  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  ChannelFuture sf = new ServerBootstrap()
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelHandlerAdapter() {})
      .group(group)
      .bind(addr);
  server = sf.channel();
  sf.sync();

  chan.connect(addr);
  ChannelFuture wf = chan.writeAndFlush(new Object());
  chan.pipeline().removeFirst();

  try {
    wf.sync();
    fail();
  } catch (Exception e) {
    Status status = Status.fromThrowable(e);
    assertThat(status.getCode()).isEqualTo(Code.INTERNAL);
    assertThat(status.getDescription()).contains("Buffer removed");
  }
}
 
Example #24
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void uncaughtReadFails() throws Exception {
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelHandlerAdapter() {});
  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  ChannelFuture sf = new ServerBootstrap()
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelHandlerAdapter() {})
      .group(group)
      .bind(addr);
  server = sf.channel();
  sf.sync();

  ChannelFuture wf = chan.writeAndFlush(new Object());
  chan.connect(addr);
  chan.pipeline().fireChannelRead(Unpooled.copiedBuffer(new byte[] {'a'}));

  try {
    wf.sync();
    fail();
  } catch (Exception e) {
    Status status = Status.fromThrowable(e);
    assertThat(status.getCode()).isEqualTo(Code.INTERNAL);
    assertThat(status.getDescription()).contains("channelRead() missed");
  }
}
 
Example #25
Source File: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void waitUntilActiveHandler_channelActive() throws Exception {
  final CountDownLatch latch = new CountDownLatch(1);
  WaitUntilActiveHandler handler =
      new WaitUntilActiveHandler(new ChannelHandlerAdapter() {
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
          assertTrue(ctx.channel().isActive());
          latch.countDown();
          super.handlerAdded(ctx);
        }
      });

  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .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();
  chan.pipeline().fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT);
  assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
  assertNull(chan.pipeline().context(WaitUntilActiveHandler.class));
}
 
Example #26
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void uncaughtException_closeAtMostOnce() throws Exception {
  final AtomicInteger closes = new AtomicInteger();
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelDuplexHandler() {
        @Override
        public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
          closes.getAndIncrement();
          // Simulates a loop between this handler and the WriteBufferingAndExceptionHandler.
          ctx.fireExceptionCaught(Status.ABORTED.withDescription("zap").asRuntimeException());
          super.close(ctx, promise);
        }
      });
  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  ChannelFuture sf = new ServerBootstrap()
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelHandlerAdapter() {})
      .group(group)
      .bind(addr);
  server = sf.channel();
  sf.sync();

  chan.connect(addr).sync();
  chan.close().sync();
  assertEquals(1, closes.get());
}
 
Example #27
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void uncaughtExceptionFailuresPropagated() throws Exception {
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelHandlerAdapter() {});
  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  ChannelFuture sf = new ServerBootstrap()
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelHandlerAdapter() {})
      .group(group)
      .bind(addr);
  server = sf.channel();
  sf.sync();

  ChannelFuture wf = chan.writeAndFlush(new Object());
  chan.connect(addr);
  chan.pipeline().fireExceptionCaught(Status.ABORTED.withDescription("zap").asRuntimeException());

  try {
    wf.sync();
    fail();
  } catch (Exception e) {
    Status status = Status.fromThrowable(e);
    assertThat(status.getCode()).isEqualTo(Code.ABORTED);
    assertThat(status.getDescription()).contains("zap");
  }
}
 
Example #28
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void channelCloseFailuresPropagated() throws Exception {
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelHandlerAdapter() {});
  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  ChannelFuture sf = new ServerBootstrap()
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelHandlerAdapter() {})
      .group(group)
      .bind(addr);
  server = sf.channel();
  sf.sync();

  ChannelFuture wf = chan.writeAndFlush(new Object());
  chan.connect(addr);
  chan.close();

  try {
    wf.sync();
    fail();
  } catch (Exception e) {
    Status status = Status.fromThrowable(e);
    assertThat(status.getCode()).isEqualTo(Code.UNAVAILABLE);
    assertThat(status.getDescription())
        .contains("Connection closing while performing protocol negotiation");
  }
}
 
Example #29
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void channelInactiveFailuresPropagated() throws Exception {
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelHandlerAdapter() {});
  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  ChannelFuture sf = new ServerBootstrap()
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelHandlerAdapter() {})
      .group(group)
      .bind(addr);
  server = sf.channel();
  sf.sync();

  ChannelFuture wf = chan.writeAndFlush(new Object());
  chan.connect(addr);
  chan.pipeline().fireChannelInactive();

  try {
    wf.sync();
    fail();
  } catch (Exception e) {
    Status status = Status.fromThrowable(e);
    assertThat(status.getCode()).isEqualTo(Code.UNAVAILABLE);
    assertThat(status.getDescription())
        .contains("Connection closed while performing protocol negotiation");
  }
}
 
Example #30
Source File: ProtocolNegotiators.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * Create a server plaintext handler for gRPC.
 */
public static ProtocolNegotiator serverPlaintext() {
  return new ProtocolNegotiator() {
    @Override
    public Handler newHandler(final GrpcHttp2ConnectionHandler handler) {
      class PlaintextHandler extends ChannelHandlerAdapter implements Handler {
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
          // Set sttributes before replace to be sure we pass it before accepting any requests.
          handler.handleProtocolNegotiationCompleted(Attributes.newBuilder()
              .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, ctx.channel().remoteAddress())
              .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, ctx.channel().localAddress())
              .build(),
              /*securityInfo=*/ null);
          // Just replace this handler with the gRPC handler.
          ctx.pipeline().replace(this, null, handler);
        }

        @Override
        public AsciiString scheme() {
          return Utils.HTTP;
        }
      }

      return new PlaintextHandler();
    }

    @Override
    public void close() {}
  };
}