io.netty.channel.local.LocalChannel Java Examples

The following examples show how to use io.netty.channel.local.LocalChannel. 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: SslServerInitializerTest.java    From nomulus with Apache License 2.0 7 votes vote down vote up
private ChannelHandler getClientHandler(
    X509Certificate trustedCertificate, PrivateKey privateKey, X509Certificate certificate) {
  return new ChannelInitializer<LocalChannel>() {
    @Override
    protected void initChannel(LocalChannel ch) throws Exception {
      SslContextBuilder sslContextBuilder =
          SslContextBuilder.forClient().trustManager(trustedCertificate).sslProvider(sslProvider);
      if (privateKey != null && certificate != null) {
        sslContextBuilder.keyManager(privateKey, certificate);
      }
      SslHandler sslHandler =
          sslContextBuilder.build().newHandler(ch.alloc(), SSL_HOST, SSL_PORT);

      // Enable hostname verification.
      SSLEngine sslEngine = sslHandler.engine();
      SSLParameters sslParameters = sslEngine.getSSLParameters();
      sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
      sslEngine.setSSLParameters(sslParameters);

      ch.pipeline().addLast(sslHandler);
    }
  };
}
 
Example #2
Source File: DefaultChannelPipelineTest.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Test
public void testFireChannelRegistered() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    ChannelPipeline pipeline = new LocalChannel().pipeline();
    pipeline.addLast(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
                    latch.countDown();
                }
            });
        }
    });
    group.register(pipeline.channel());
    assertTrue(latch.await(2, TimeUnit.SECONDS));
}
 
Example #3
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveChannelHandler() {
    ChannelPipeline pipeline = new LocalChannel().pipeline();

    ChannelHandler handler1 = newHandler();
    ChannelHandler handler2 = newHandler();
    ChannelHandler handler3 = newHandler();

    pipeline.addLast("handler1", handler1);
    pipeline.addLast("handler2", handler2);
    pipeline.addLast("handler3", handler3);
    assertSame(pipeline.get("handler1"), handler1);
    assertSame(pipeline.get("handler2"), handler2);
    assertSame(pipeline.get("handler3"), handler3);

    pipeline.remove(handler1);
    assertNull(pipeline.get("handler1"));
    pipeline.remove(handler2);
    assertNull(pipeline.get("handler2"));
    pipeline.remove(handler3);
    assertNull(pipeline.get("handler3"));
}
 
Example #4
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFireChannelRegistered() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    ChannelPipeline pipeline = new LocalChannel().pipeline();
    pipeline.addLast(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
                    latch.countDown();
                }
            });
        }
    });
    group.register(pipeline.channel());
    assertTrue(latch.await(2, TimeUnit.SECONDS));
}
 
Example #5
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testReplaceChannelHandler() {
    ChannelPipeline pipeline = new LocalChannel().pipeline();

    ChannelHandler handler1 = newHandler();
    pipeline.addLast("handler1", handler1);
    pipeline.addLast("handler2", handler1);
    pipeline.addLast("handler3", handler1);
    assertSame(pipeline.get("handler1"), handler1);
    assertSame(pipeline.get("handler2"), handler1);
    assertSame(pipeline.get("handler3"), handler1);

    ChannelHandler newHandler1 = newHandler();
    pipeline.replace("handler1", "handler1", newHandler1);
    assertSame(pipeline.get("handler1"), newHandler1);

    ChannelHandler newHandler3 = newHandler();
    pipeline.replace("handler3", "handler3", newHandler3);
    assertSame(pipeline.get("handler3"), newHandler3);

    ChannelHandler newHandler2 = newHandler();
    pipeline.replace("handler2", "handler2", newHandler2);
    assertSame(pipeline.get("handler2"), newHandler2);
}
 
Example #6
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testWrongPromiseChannel() throws Exception {
    ChannelPipeline pipeline = new LocalChannel().pipeline();
    group.register(pipeline.channel()).sync();

    ChannelPipeline pipeline2 = new LocalChannel().pipeline();
    group.register(pipeline2.channel()).sync();

    try {
        ChannelPromise promise2 = pipeline2.channel().newPromise();
        pipeline.close(promise2);
    } finally {
        pipeline.close();
        pipeline2.close();
    }
}
 
Example #7
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 3000)
public void testAddHandlerBeforeRegisteredThenReplace() throws Exception {
    final EventLoop loop = group.next();
    final CountDownLatch latch = new CountDownLatch(1);

    CheckEventExecutorHandler handler = new CheckEventExecutorHandler(loop);
    ChannelPipeline pipeline = new LocalChannel().pipeline();
    pipeline.addFirst(handler);
    assertFalse(handler.addedPromise.isDone());
    group.register(pipeline.channel());
    handler.addedPromise.syncUninterruptibly();
    pipeline.replace(handler, null, new ChannelHandlerAdapter() {
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            latch.countDown();
        }
    });
    handler.removedPromise.syncUninterruptibly();
    latch.await();
}
 
Example #8
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 3000)
public void testHandlerAddedExceptionFromChildHandlerIsPropagated() {
    final EventExecutorGroup group1 = new DefaultEventExecutorGroup(1);
    try {
        final Promise<Void> promise = group1.next().newPromise();
        final AtomicBoolean handlerAdded = new AtomicBoolean();
        final Exception exception = new RuntimeException();
        ChannelPipeline pipeline = new LocalChannel().pipeline();
        pipeline.addLast(group1, new CheckExceptionHandler(exception, promise));
        pipeline.addFirst(new ChannelHandlerAdapter() {
            @Override
            public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                handlerAdded.set(true);
                throw exception;
            }
        });
        assertFalse(handlerAdded.get());
        group.register(pipeline.channel());
        promise.syncUninterruptibly();
    } finally {
        group1.shutdownGracefully();
    }
}
 
Example #9
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 3000)
public void testHandlerRemovedExceptionFromChildHandlerIsPropagated() {
    final EventExecutorGroup group1 = new DefaultEventExecutorGroup(1);
    try {
        final Promise<Void> promise = group1.next().newPromise();
        String handlerName = "foo";
        final Exception exception = new RuntimeException();
        ChannelPipeline pipeline = new LocalChannel().pipeline();
        pipeline.addLast(handlerName, new ChannelHandlerAdapter() {
            @Override
            public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
                throw exception;
            }
        });
        pipeline.addLast(group1, new CheckExceptionHandler(exception, promise));
        group.register(pipeline.channel()).syncUninterruptibly();
        pipeline.remove(handlerName);
        promise.syncUninterruptibly();
    } finally {
        group1.shutdownGracefully();
    }
}
 
Example #10
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 2000)
public void testAddRemoveHandlerCalledOnceRegistered() throws Throwable {
    ChannelPipeline pipeline = new LocalChannel().pipeline();
    CallbackCheckHandler handler = new CallbackCheckHandler();

    pipeline.addFirst(handler);
    pipeline.remove(handler);

    assertNull(handler.addedHandler.getNow());
    assertNull(handler.removedHandler.getNow());

    group.register(pipeline.channel()).syncUninterruptibly();
    Throwable cause = handler.error.get();
    if (cause != null) {
        throw cause;
    }

    assertTrue(handler.addedHandler.get());
    assertTrue(handler.removedHandler.get());
}
 
Example #11
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 3000)
public void testAddBefore() throws Throwable {
    ChannelPipeline pipeline1 = new LocalChannel().pipeline();
    ChannelPipeline pipeline2 = new LocalChannel().pipeline();

    EventLoopGroup defaultGroup = new DefaultEventLoopGroup(2);
    try {
        EventLoop eventLoop1 = defaultGroup.next();
        EventLoop eventLoop2 = defaultGroup.next();

        eventLoop1.register(pipeline1.channel()).syncUninterruptibly();
        eventLoop2.register(pipeline2.channel()).syncUninterruptibly();

        CountDownLatch latch = new CountDownLatch(2 * 10);
        for (int i = 0; i < 10; i++) {
            eventLoop1.execute(new TestTask(pipeline2, latch));
            eventLoop2.execute(new TestTask(pipeline1, latch));
        }
        latch.await();
    } finally {
        defaultGroup.shutdownGracefully();
    }
}
 
Example #12
Source File: BootstrapTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncResolutionSuccess() throws Exception {
    final Bootstrap bootstrapA = new Bootstrap();
    bootstrapA.group(groupA);
    bootstrapA.channel(LocalChannel.class);
    bootstrapA.resolver(new TestAddressResolverGroup(true));
    bootstrapA.handler(dummyHandler);

    final ServerBootstrap bootstrapB = new ServerBootstrap();
    bootstrapB.group(groupB);
    bootstrapB.channel(LocalServerChannel.class);
    bootstrapB.childHandler(dummyHandler);
    SocketAddress localAddress = bootstrapB.bind(LocalAddress.ANY).sync().channel().localAddress();

    // Connect to the server using the asynchronous resolver.
    bootstrapA.connect(localAddress).sync();
}
 
Example #13
Source File: BootstrapTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncResolutionFailure() throws Exception {
    final Bootstrap bootstrapA = new Bootstrap();
    bootstrapA.group(groupA);
    bootstrapA.channel(LocalChannel.class);
    bootstrapA.resolver(new TestAddressResolverGroup(false));
    bootstrapA.handler(dummyHandler);

    final ServerBootstrap bootstrapB = new ServerBootstrap();
    bootstrapB.group(groupB);
    bootstrapB.channel(LocalServerChannel.class);
    bootstrapB.childHandler(dummyHandler);
    SocketAddress localAddress = bootstrapB.bind(LocalAddress.ANY).sync().channel().localAddress();

    // Connect to the server using the asynchronous resolver.
    ChannelFuture connectFuture = bootstrapA.connect(localAddress);

    // Should fail with the UnknownHostException.
    assertThat(connectFuture.await(10000), is(true));
    assertThat(connectFuture.cause(), is(instanceOf(UnknownHostException.class)));
    assertThat(connectFuture.channel().isOpen(), is(false));
}
 
Example #14
Source File: MockClient.java    From simulacron with Apache License 2.0 6 votes vote down vote up
MockClient(EventLoopGroup elg, FrameCodec<ByteBuf> frameCodec) {
  // Set up so written Frames are encoded into bytes, received bytes are encoded into Frames put
  // on queue.
  cb.group(elg)
      .channel(LocalChannel.class)
      .handler(
          new ChannelInitializer<LocalChannel>() {
            @Override
            protected void initChannel(LocalChannel ch) throws Exception {
              ch.pipeline()
                  .addLast(new FrameEncoder(frameCodec))
                  .addLast(new TestFrameDecoder(frameCodec))
                  .addLast(
                      new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg)
                            throws Exception {
                          responses.offer((Frame) msg);
                        }
                      });
            }
          });
}
 
Example #15
Source File: TestServer.java    From nomulus with Apache License 2.0 6 votes vote down vote up
public TestServer(
    EventLoopGroup eventLoopGroup,
    LocalAddress localAddress,
    ImmutableList<? extends ChannelHandler> handlers) {
  // Creates ChannelInitializer with handlers specified
  ChannelInitializer<LocalChannel> serverInitializer =
      new ChannelInitializer<LocalChannel>() {
        @Override
        protected void initChannel(LocalChannel ch) {
          for (ChannelHandler handler : handlers) {
            ch.pipeline().addLast(handler);
          }
        }
      };
  // Sets up serverBootstrap with specified initializer, eventLoopGroup, and using
  // LocalServerChannel class
  ServerBootstrap serverBootstrap =
      new ServerBootstrap()
          .group(eventLoopGroup)
          .channel(LocalServerChannel.class)
          .childHandler(serverInitializer);

  ChannelFuture unusedFuture = serverBootstrap.bind(localAddress).syncUninterruptibly();
}
 
Example #16
Source File: SslClientInitializerTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailure_defaultTrustManager_rejectSelfSignedCert() throws Exception {
  SelfSignedCaCertificate ssc = SelfSignedCaCertificate.create(SSL_HOST);
  LocalAddress localAddress =
      new LocalAddress("DEFAULT_TRUST_MANAGER_REJECT_SELF_SIGNED_CERT_" + sslProvider);
  nettyRule.setUpServer(localAddress, getServerHandler(false, ssc.key(), ssc.cert()));
  SslClientInitializer<LocalChannel> sslClientInitializer =
      new SslClientInitializer<>(
          sslProvider, hostProvider, portProvider, ImmutableList.of(), null, null);
  nettyRule.setUpClient(localAddress, sslClientInitializer);
  // The connection is now terminated, both the client side and the server side should get
  // exceptions.
  nettyRule.assertThatClientRootCause().isInstanceOf(CertPathBuilderException.class);
  nettyRule.assertThatServerRootCause().isInstanceOf(SSLException.class);
  assertThat(nettyRule.getClientChannel().isActive()).isFalse();
}
 
Example #17
Source File: NettyRule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Sets up a server channel bound to the given local address. */
public void setUpServer(LocalAddress localAddress, ChannelHandler... handlers) {
  checkState(echoHandler == null, "Can't call setUpServer twice");
  echoHandler = new EchoHandler();
  ChannelInitializer<LocalChannel> serverInitializer =
      new ChannelInitializer<LocalChannel>() {
        @Override
        protected void initChannel(LocalChannel ch) {
          // Add the given handler
          ch.pipeline().addLast(handlers);
          // Add the "echoHandler" last to log the incoming message and send it back
          ch.pipeline().addLast(echoHandler);
          serverChannel = ch;
        }
      };
  ServerBootstrap sb =
      new ServerBootstrap()
          .group(eventLoopGroup)
          .channel(LocalServerChannel.class)
          .childHandler(serverInitializer);
  ChannelFuture unusedFuture = sb.bind(localAddress).syncUninterruptibly();
}
 
Example #18
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotPinExecutor() {
    EventExecutorGroup group = new DefaultEventExecutorGroup(2);
    ChannelPipeline pipeline = new LocalChannel().pipeline();
    pipeline.channel().config().setOption(ChannelOption.SINGLE_EVENTEXECUTOR_PER_GROUP, false);

    pipeline.addLast(group, "h1", new ChannelInboundHandlerAdapter());
    pipeline.addLast(group, "h2", new ChannelInboundHandlerAdapter());

    EventExecutor executor1 = pipeline.context("h1").executor();
    EventExecutor executor2 = pipeline.context("h2").executor();
    assertNotNull(executor1);
    assertNotNull(executor2);
    assertNotSame(executor1, executor2);
    group.shutdownGracefully(0, 0, TimeUnit.SECONDS);
}
 
Example #19
Source File: TestChangePasswordRESTHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private FullHttpResponse callRestChangePassword(String emailAddress, boolean daoReturn, boolean bindClient) throws Exception {
   Person person = new Person();
   person.setId(UUID.randomUUID());
   EasyMock.expect(request.content()).andReturn(Unpooled.copiedBuffer(generateClientMessage(generateRequest(emailAddress, "old_password", "new_password")).getBytes()));
   EasyMock.expect(personDAO.findByEmail(emailAddress)).andReturn(person).anyTimes();
   EasyMock.expect(personDAO.updatePassword(emailAddress, "old_password", "new_password")).andReturn(daoReturn).anyTimes();
   EasyMock.expect(platformBus.send(EasyMock.anyObject())).andReturn(null).anyTimes();
   EasyMock.expect(this.ctx.channel()).andReturn(new LocalChannel()).anyTimes();
 
   replay();
   
   if(true){
      Client client = EasyMock.createNiceMock(ShiroClient.class);
      EasyMock.expect(client.isAuthenticated()).andReturn(true);
      EasyMock.expect(client.getPrincipalName()).andReturn(emailAddress);
      EasyMock.replay(client);
      Client.bind(ctx.channel(), client);
   }
   
   FullHttpResponse response = handler.respond(request, ctx);
   verify();
   return response;
}
 
Example #20
Source File: NettyRule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Sets up a client channel connecting to the give local address. */
void setUpClient(LocalAddress localAddress, ChannelHandler handler) {
  checkState(echoHandler != null, "Must call setUpServer before setUpClient");
  checkState(dumpHandler == null, "Can't call setUpClient twice");
  dumpHandler = new DumpHandler();
  ChannelInitializer<LocalChannel> clientInitializer =
      new ChannelInitializer<LocalChannel>() {
        @Override
        protected void initChannel(LocalChannel ch) throws Exception {
          // Add the given handler
          ch.pipeline().addLast(handler);
          // Add the "dumpHandler" last to log the incoming message
          ch.pipeline().addLast(dumpHandler);
        }
      };
  Bootstrap b =
      new Bootstrap()
          .group(eventLoopGroup)
          .channel(LocalChannel.class)
          .handler(clientInitializer);
  clientChannel = b.connect(localAddress).syncUninterruptibly().channel();
}
 
Example #21
Source File: DefaultChannelPipelineTest.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveChannelHandler() {
    ChannelPipeline pipeline = new LocalChannel().pipeline();

    ChannelHandler handler1 = newHandler();
    ChannelHandler handler2 = newHandler();
    ChannelHandler handler3 = newHandler();

    pipeline.addLast("handler1", handler1);
    pipeline.addLast("handler2", handler2);
    pipeline.addLast("handler3", handler3);
    assertSame(pipeline.get("handler1"), handler1);
    assertSame(pipeline.get("handler2"), handler2);
    assertSame(pipeline.get("handler3"), handler3);

    pipeline.remove(handler1);
    assertNull(pipeline.get("handler1"));
    pipeline.remove(handler2);
    assertNull(pipeline.get("handler2"));
    pipeline.remove(handler3);
    assertNull(pipeline.get("handler3"));
}
 
Example #22
Source File: BootstrapTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test(expected = ConnectException.class, timeout = 10000)
public void testLateRegistrationConnect() throws Exception {
    EventLoopGroup group = new DelayedEventLoopGroup();
    try {
        final Bootstrap bootstrapA = new Bootstrap();
        bootstrapA.group(group);
        bootstrapA.channel(LocalChannel.class);
        bootstrapA.handler(dummyHandler);
        bootstrapA.connect(LocalAddress.ANY).syncUninterruptibly();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #23
Source File: BootstrapTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10000)
public void testConnectDeadLock() throws Exception {
    final Bootstrap bootstrapA = new Bootstrap();
    bootstrapA.group(groupA);
    bootstrapA.channel(LocalChannel.class);
    bootstrapA.handler(dummyHandler);

    final Bootstrap bootstrapB = new Bootstrap();
    bootstrapB.group(groupB);
    bootstrapB.channel(LocalChannel.class);
    bootstrapB.handler(dummyHandler);

    List<Future<?>> bindFutures = new ArrayList<Future<?>>();

    // Try to connect from each other.
    for (int i = 0; i < 1024; i ++) {
        bindFutures.add(groupA.next().submit(new Runnable() {
            @Override
            public void run() {
                bootstrapB.connect(LocalAddress.ANY);
            }
        }));

        bindFutures.add(groupB.next().submit(new Runnable() {
            @Override
            public void run() {
                bootstrapA.connect(LocalAddress.ANY);
            }
        }));
    }

    for (Future<?> f: bindFutures) {
        f.sync();
    }
}
 
Example #24
Source File: BootstrapTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10000)
public void testBindDeadLock() throws Exception {
    final Bootstrap bootstrapA = new Bootstrap();
    bootstrapA.group(groupA);
    bootstrapA.channel(LocalChannel.class);
    bootstrapA.handler(dummyHandler);

    final Bootstrap bootstrapB = new Bootstrap();
    bootstrapB.group(groupB);
    bootstrapB.channel(LocalChannel.class);
    bootstrapB.handler(dummyHandler);

    List<Future<?>> bindFutures = new ArrayList<Future<?>>();

    // Try to bind from each other.
    for (int i = 0; i < 1024; i ++) {
        bindFutures.add(groupA.next().submit(new Runnable() {
            @Override
            public void run() {
                bootstrapB.bind(LocalAddress.ANY);
            }
        }));

        bindFutures.add(groupB.next().submit(new Runnable() {
            @Override
            public void run() {
                bootstrapA.bind(LocalAddress.ANY);
            }
        }));
    }

    for (Future<?> f: bindFutures) {
        f.sync();
    }
}
 
Example #25
Source File: ChannelInitializerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = TIMEOUT_MILLIS)
public void firstHandlerInPipelineShouldReceiveChannelRegisteredEvent() {
    testChannelRegisteredEventPropagation(new ChannelInitializer<LocalChannel>() {
        @Override
        public void initChannel(LocalChannel channel) {
            channel.pipeline().addFirst(testHandler);
        }
    });
}
 
Example #26
Source File: ProbingActionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_newChannel() throws Exception {
  // setup

  LocalAddress address = new LocalAddress(ADDRESS_NAME);
  Bootstrap bootstrap =
      new Bootstrap().group(nettyRule.getEventLoopGroup()).channel(LocalChannel.class);

  // Sets up a Protocol corresponding to when a new connection is created.
  Protocol protocol =
      Protocol.builder()
          .setHandlerProviders(ImmutableList.of(() -> conversionHandler, () -> testHandler))
          .setName(PROTOCOL_NAME)
          .setPort(TEST_PORT)
          .setPersistentConnection(false)
          .build();

  nettyRule.setUpServer(address);

  // Sets up a ProbingAction with existing channel using test specified attributes.
  ProbingAction action =
      ProbingAction.builder()
          .setBootstrap(bootstrap)
          .setProtocol(protocol)
          .setDelay(Duration.ZERO)
          .setOutboundMessage(new TestMessage(TEST_MESSAGE))
          .setHost(ADDRESS_NAME)
          .build();

  // tests main function of ProbingAction
  ChannelFuture future = action.call();

  // Tests to see if message is properly sent to remote server
  nettyRule.assertReceivedMessage(TEST_MESSAGE);

  future = future.syncUninterruptibly();
  // Tests to see that, since server responds, we have set future to true
  assertThat(future.isSuccess()).isTrue();
  assertThat(((TestActionHandler) testHandler).getResponse().toString()).isEqualTo(TEST_MESSAGE);
}
 
Example #27
Source File: ChannelInitializerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    group = new DefaultEventLoopGroup(1);
    server = new ServerBootstrap()
            .group(group)
            .channel(LocalServerChannel.class)
            .localAddress(SERVER_ADDRESS);
    client = new Bootstrap()
            .group(group)
            .channel(LocalChannel.class)
            .handler(new ChannelInboundHandlerAdapter());
    testHandler = new InspectableHandler();
}
 
Example #28
Source File: DefaultChannelPipelineTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testCancelWriteAndFlush() throws Exception {
    ChannelPipeline pipeline = new LocalChannel().pipeline();
    ChannelPromise promise = pipeline.channel().newPromise();
    assertTrue(promise.cancel(false));
    ByteBuf buffer = Unpooled.buffer();
    assertEquals(1, buffer.refCnt());
    ChannelFuture future = pipeline.writeAndFlush(buffer, promise);
    assertTrue(future.isCancelled());
    assertEquals(0, buffer.refCnt());
}
 
Example #29
Source File: SslClientInitializerTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailure_customTrustManager_serverCertExpired() throws Exception {
  LocalAddress localAddress =
      new LocalAddress("CUSTOM_TRUST_MANAGER_SERVE_CERT_EXPIRED_" + sslProvider);

  // Generate a new key pair.
  KeyPair keyPair = getKeyPair();

  // Generate a self signed certificate, and use it to sign the key pair.
  SelfSignedCaCertificate ssc = SelfSignedCaCertificate.create();
  X509Certificate cert =
      signKeyPair(
          ssc,
          keyPair,
          SSL_HOST,
          Date.from(Instant.now().minus(Duration.ofDays(2))),
          Date.from(Instant.now().minus(Duration.ofDays(1))));

  // Set up the server to use the signed cert and private key to perform handshake;
  PrivateKey privateKey = keyPair.getPrivate();
  nettyRule.setUpServer(localAddress, getServerHandler(false, privateKey, cert));

  // Set up the client to trust the self signed cert used to sign the cert that server provides.
  SslClientInitializer<LocalChannel> sslClientInitializer =
      new SslClientInitializer<>(
          sslProvider, hostProvider, portProvider, ImmutableList.of(ssc.cert()), null, null);
  nettyRule.setUpClient(localAddress, sslClientInitializer);

  verifySslExcpetion(
      nettyRule.getClientChannel(),
      channel -> channel.pipeline().get(SslHandler.class).handshakeFuture().get(),
      CertificateExpiredException.class);
}
 
Example #30
Source File: HandlerPublisherVerificationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<Long> createFailedPublisher() {
    LocalChannel channel = new LocalChannel();
    eventLoop.register(channel);
    HandlerPublisher<Long> publisher = new HandlerPublisher<>(channel.eventLoop(), Long.class);
    channel.pipeline().addLast("publisher", publisher);
    channel.pipeline().fireExceptionCaught(new RuntimeException("failed"));

    return publisher;
}