io.netty.channel.DefaultChannelPromise Java Examples

The following examples show how to use io.netty.channel.DefaultChannelPromise. 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: MockChannelHandlerContext.java    From karyon with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelFuture writeAndFlush(Object msg) {
    DefaultChannelPromise promise = new DefaultChannelPromise(channel);
    try {
        if (null != handler) {
            handler.write(this, msg, promise);
            handler.flush(this);
        }
    } catch (Exception e) {
        promise.tryFailure(e);
    }
    return promise;
}
 
Example #2
Source File: NettyClientStreamTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void removeUserAgentFromApplicationHeaders() {
  Metadata metadata = new Metadata();
  metadata.put(GrpcUtil.USER_AGENT_KEY, "bad agent");
  listener = mock(ClientStreamListener.class);
  Mockito.reset(writeQueue);
  ChannelPromise completedPromise = new DefaultChannelPromise(channel)
      .setSuccess();
  when(writeQueue.enqueue(any(QueuedCommand.class), anyBoolean())).thenReturn(completedPromise);

  stream = new NettyClientStream(
      new TransportStateImpl(handler, DEFAULT_MAX_MESSAGE_SIZE),
      methodDescriptor,
      new Metadata(),
      channel,
      AsciiString.of("localhost"),
      AsciiString.of("http"),
      AsciiString.of("good agent"),
      StatsTraceContext.NOOP,
      transportTracer,
      CallOptions.DEFAULT,
      false);
  stream.start(listener);

  ArgumentCaptor<CreateStreamCommand> cmdCap = ArgumentCaptor.forClass(CreateStreamCommand.class);
  verify(writeQueue).enqueue(cmdCap.capture(), eq(false));
  assertThat(ImmutableListMultimap.copyOf(cmdCap.getValue().headers()))
      .containsEntry(Utils.USER_AGENT, AsciiString.of("good agent"));
}
 
Example #3
Source File: NettyStreamTestBase.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotBeReadyForDataAfterWritingLargeMessage() throws IOException {
  sendHeadersIfServer();
  // Make sure the writes don't complete so we "back up"
  ChannelPromise uncompletedPromise = new DefaultChannelPromise(channel);
  when(writeQueue.enqueue(any(QueuedCommand.class), anyBoolean())).thenReturn(uncompletedPromise);

  assertTrue(stream.isReady());
  byte[] msg = largeMessage();
  stream.writeMessage(new ByteArrayInputStream(msg));
  stream.flush();
  assertFalse(stream.isReady());
  verify(listener(), never()).onReady();
}
 
Example #4
Source File: NettyStreamTestBase.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeReadyForDataAfterWritingSmallMessage() throws IOException {
  sendHeadersIfServer();
  // Make sure the writes don't complete so we "back up"
  ChannelPromise uncompletedPromise = new DefaultChannelPromise(channel);
  when(writeQueue.enqueue(any(QueuedCommand.class), anyBoolean())).thenReturn(uncompletedPromise);

  assertTrue(stream.isReady());
  byte[] msg = smallMessage();
  stream.writeMessage(new ByteArrayInputStream(msg));
  stream.flush();
  assertTrue(stream.isReady());
  verify(listener(), never()).onReady();
}
 
Example #5
Source File: NettyStreamTestBase.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/** Set up for test. */
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  when(channel.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
  when(channel.pipeline()).thenReturn(pipeline);
  when(channel.eventLoop()).thenReturn(eventLoop);
  when(channel.newPromise()).thenReturn(new DefaultChannelPromise(channel));
  when(channel.voidPromise()).thenReturn(new DefaultChannelPromise(channel));
  ChannelPromise completedPromise = new DefaultChannelPromise(channel)
      .setSuccess();
  when(channel.write(any())).thenReturn(completedPromise);
  when(channel.writeAndFlush(any())).thenReturn(completedPromise);
  when(writeQueue.enqueue(any(QueuedCommand.class), anyBoolean())).thenReturn(completedPromise);
  when(pipeline.firstContext()).thenReturn(ctx);
  when(eventLoop.inEventLoop()).thenReturn(true);
  when(http2Stream.id()).thenReturn(STREAM_ID);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
      Runnable runnable = (Runnable) invocation.getArguments()[0];
      runnable.run();
      return null;
    }
  }).when(eventLoop).execute(any(Runnable.class));

  stream = createStream();
}
 
Example #6
Source File: PeerTest.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private void mockSession() {
    final EventLoop eventLoop = mock(EventLoop.class);
    final Channel channel = mock(Channel.class);
    final ChannelPipeline pipeline = mock(ChannelPipeline.class);
    doReturn(null).when(eventLoop).schedule(any(Runnable.class), any(long.class), any(TimeUnit.class));
    doReturn(eventLoop).when(channel).eventLoop();
    doReturn(Boolean.TRUE).when(channel).isWritable();
    doReturn(null).when(channel).close();
    doReturn(pipeline).when(channel).pipeline();
    doCallRealMethod().when(channel).toString();
    doReturn(pipeline).when(pipeline).addLast(any(ChannelHandler.class));
    doReturn(new DefaultChannelPromise(channel)).when(channel).writeAndFlush(any(Notification.class));
    doReturn(new InetSocketAddress("localhost", 12345)).when(channel).remoteAddress();
    doReturn(new InetSocketAddress("localhost", 12345)).when(channel).localAddress();
    final List<BgpParameters> params = Lists.newArrayList(new BgpParametersBuilder()
        .setOptionalCapabilities(Lists.newArrayList(new OptionalCapabilitiesBuilder()
            .setCParameters(new CParametersBuilder()
                .addAugmentation(new CParameters1Builder()
                    .setMultiprotocolCapability(new MultiprotocolCapabilityBuilder()
                        .setAfi(Ipv4AddressFamily.class)
                        .setSafi(UnicastSubsequentAddressFamily.class)
                        .build())
                    .build())
                .build())
            .build()))
        .build());
    final Open openObj = new OpenBuilder()
            .setBgpIdentifier(new Ipv4AddressNoZone("1.1.1.1"))
            .setHoldTimer(Uint16.valueOf(50))
            .setMyAsNumber(Uint16.valueOf(72))
            .setBgpParameters(params).build();
    this.session = new BGPSessionImpl(this.classic, channel, openObj, 30, null);
    this.session.setChannelExtMsgCoder(openObj);
}
 
Example #7
Source File: AbstractBootstrap.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
final ChannelFuture initAndRegister() {
    final Channel channel = channelFactory().newChannel();
    try {
        init(channel);
    } catch (Throwable t) {
        channel.unsafe().closeForcibly();
        // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
        return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
    }

    ChannelFuture regFuture = group().register(channel);
    if (regFuture.cause() != null) {
        if (channel.isRegistered()) {
            channel.close();
        } else {
            channel.unsafe().closeForcibly();
        }
    }

    // If we are here and the promise is not failed, it's one of the following cases:
    // 1) If we attempted registration from the event loop, the registration has been completed at this point.
    //    i.e. It's safe to attempt bind() or connect() now because the channel has been registered.
    // 2) If we attempted registration from the other thread, the registration request has been successfully
    //    added to the event loop's task queue for later execution.
    //    i.e. It's safe to attempt bind() or connect() now:
    //         because bind() or connect() will be executed *after* the scheduled registration task is executed
    //         because register(), bind(), and connect() are all bound to the same thread.

    return regFuture;
}
 
Example #8
Source File: DefaultRedisMasterReplicationTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Test
public void testCancelScheduleWhenConnected() throws IOException {

	AtomicInteger replConfCount = new AtomicInteger();

	defaultRedisMasterReplication = new DefaultRedisMasterReplication(redisMaster, redisKeeperServer,
			nioEventLoopGroup, scheduled, replTimeoutMilli, proxyResourceManager) {
		@Override
		protected Command<Object> createReplConf() {
			replConfCount.incrementAndGet();
			return super.createReplConf();
		}
	};

	defaultRedisMasterReplication.onContinue(RunidGenerator.DEFAULT.generateRunid(), RunidGenerator.DEFAULT.generateRunid());

	Channel channel = mock(Channel.class);
	when(channel.closeFuture()).thenReturn(new DefaultChannelPromise(channel));

	defaultRedisMasterReplication.masterConnected(channel);

	int countBefore = replConfCount.get();

	sleep(DefaultRedisMasterReplication.REPLCONF_INTERVAL_MILLI * 2);

	int countAfter = replConfCount.get();

	Assert.assertEquals(countBefore, countAfter);
}
 
Example #9
Source File: DefaultTunnelManagerTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
private Channel fakeChannel() {
    Channel channel = mock(Channel.class);
    ChannelConfig config = mock(ChannelConfig.class);
    when(channel.remoteAddress()).thenReturn(new InetSocketAddress("localhost", randomPort()));
    when(channel.config()).thenReturn(config);
    when(config.isAutoRead()).thenReturn(false);
    when(channel.writeAndFlush(any())).thenReturn(new DefaultChannelPromise(channel));
    return channel;
}
 
Example #10
Source File: ProxyTunnelInitHandlerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void requestWriteFails_failsPromise() {
    DefaultChannelPromise writePromise = new DefaultChannelPromise(mockChannel, GROUP.next());
    writePromise.setFailure(new IOException("boom"));
    when(mockChannel.writeAndFlush(anyObject())).thenReturn(writePromise);

    Promise<Channel> promise = GROUP.next().newPromise();
    ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
    handler.handlerAdded(mockCtx);

    assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse();
}
 
Example #11
Source File: ProxyTunnelInitHandlerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Before
public void methodSetup() {
    when(mockCtx.channel()).thenReturn(mockChannel);
    when(mockCtx.pipeline()).thenReturn(mockPipeline);
    when(mockChannel.pipeline()).thenReturn(mockPipeline);
    when(mockChannel.writeAndFlush(anyObject())).thenReturn(new DefaultChannelPromise(mockChannel, GROUP.next()));
}
 
Example #12
Source File: SmtpSessionTest.java    From NioSmtpClient with Apache License 2.0 5 votes vote down vote up
private void assertExceptionsFiredOnFailure() throws Exception {
  // get the listener added when the channel was written to
  ArgumentCaptor<ChannelFutureListener> captor = ArgumentCaptor.forClass(ChannelFutureListener.class);
  verify(writeFuture, atLeast(1)).addListener(captor.capture());
  ChannelFutureListener addedListener = captor.getValue();

  // tell the listener the write failed
  DefaultChannelPromise promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
  promise.setFailure(new Exception());
  addedListener.operationComplete(promise);

  verify(pipeline).fireExceptionCaught(promise.cause());
}
 
Example #13
Source File: NettySubstitutions.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Substitute
final ChannelFuture initAndRegister() {
    Channel channel = null;
    try {
        channel = channelFactory.newChannel();
        init(channel);
    } catch (Throwable t) {
        // THE FIX IS HERE:
        t.printStackTrace();
        if (channel != null) {
            // channel can be null if newChannel crashed (eg SocketException("too many open files"))
            channel.unsafe().closeForcibly();
        }
        // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
        return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
    }

    ChannelFuture regFuture = config().group().register(channel);
    if (regFuture.cause() != null) {
        if (channel.isRegistered()) {
            channel.close();
        } else {
            channel.unsafe().closeForcibly();
        }
    }

    // If we are here and the promise is not failed, it's one of the following cases:
    // 1) If we attempted registration from the event loop, the registration has been completed at this point.
    //    i.e. It's safe to attempt bind() or connect() now because the channel has been registered.
    // 2) If we attempted registration from the other thread, the registration request has been successfully
    //    added to the event loop's task queue for later execution.
    //    i.e. It's safe to attempt bind() or connect() now:
    //         because bind() or connect() will be executed *after* the scheduled registration task is executed
    //         because register(), bind(), and connect() are all bound to the same thread.

    return regFuture;

}
 
Example #14
Source File: NettyStreamTestBase.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeReadyForDataAfterWritingSmallMessage() throws IOException {
  sendHeadersIfServer();
  // Make sure the writes don't complete so we "back up"
  ChannelPromise uncompletedPromise = new DefaultChannelPromise(channel);
  when(writeQueue.enqueue(any(QueuedCommand.class), anyBoolean())).thenReturn(uncompletedPromise);

  assertTrue(stream.isReady());
  byte[] msg = smallMessage();
  stream.writeMessage(new ByteArrayInputStream(msg));
  stream.flush();
  assertTrue(stream.isReady());
  verify(listener(), never()).onReady();
}
 
Example #15
Source File: NettyStreamTestBase.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotBeReadyForDataAfterWritingLargeMessage() throws IOException {
  sendHeadersIfServer();
  // Make sure the writes don't complete so we "back up"
  ChannelPromise uncompletedPromise = new DefaultChannelPromise(channel);
  when(writeQueue.enqueue(any(QueuedCommand.class), anyBoolean())).thenReturn(uncompletedPromise);

  assertTrue(stream.isReady());
  byte[] msg = largeMessage();
  stream.writeMessage(new ByteArrayInputStream(msg));
  stream.flush();
  assertFalse(stream.isReady());
  verify(listener(), never()).onReady();
}
 
Example #16
Source File: NettyClientStreamTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void removeUserAgentFromApplicationHeaders() {
  Metadata metadata = new Metadata();
  metadata.put(GrpcUtil.USER_AGENT_KEY, "bad agent");
  listener = mock(ClientStreamListener.class);
  Mockito.reset(writeQueue);
  ChannelPromise completedPromise = new DefaultChannelPromise(channel)
      .setSuccess();
  when(writeQueue.enqueue(any(QueuedCommand.class), any(boolean.class)))
      .thenReturn(completedPromise);

  stream = new NettyClientStream(
      new TransportStateImpl(handler, DEFAULT_MAX_MESSAGE_SIZE),
      methodDescriptor,
      new Metadata(),
      channel,
      AsciiString.of("localhost"),
      AsciiString.of("http"),
      AsciiString.of("good agent"),
      StatsTraceContext.NOOP,
      transportTracer,
      CallOptions.DEFAULT);
  stream.start(listener);

  ArgumentCaptor<CreateStreamCommand> cmdCap = ArgumentCaptor.forClass(CreateStreamCommand.class);
  verify(writeQueue).enqueue(cmdCap.capture(), eq(false));
  assertThat(ImmutableListMultimap.copyOf(cmdCap.getValue().headers()))
      .containsEntry(Utils.USER_AGENT, AsciiString.of("good agent"));
}
 
Example #17
Source File: AbstractBootstrap.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
final ChannelFuture initAndRegister() {
    Channel channel = null;
    try {
        channel = channelFactory().newChannel();
        init(channel);
    } catch (Throwable t) {
        if (channel != null) {
            // channel can be null if newChannel crashed (eg SocketException("too many open files"))
            channel.unsafe().closeForcibly();
        }
        // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
        return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
    }

    ChannelFuture regFuture = group().register(channel);
    if (regFuture.cause() != null) {
        if (channel.isRegistered()) {
            channel.close();
        } else {
            channel.unsafe().closeForcibly();
        }
    }

    // If we are here and the promise is not failed, it's one of the following cases:
    // 1) If we attempted registration from the event loop, the registration has been completed at this point.
    //    i.e. It's safe to attempt bind() or connect() now because the channel has been registered.
    // 2) If we attempted registration from the other thread, the registration request has been successfully
    //    added to the event loop's task queue for later execution.
    //    i.e. It's safe to attempt bind() or connect() now:
    //         because bind() or connect() will be executed *after* the scheduled registration task is executed
    //         because register(), bind(), and connect() are all bound to the same thread.

    return regFuture;
}
 
Example #18
Source File: NettyStreamTestBase.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/** Set up for test. */
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  when(channel.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
  when(channel.pipeline()).thenReturn(pipeline);
  when(channel.eventLoop()).thenReturn(eventLoop);
  when(channel.newPromise()).thenReturn(new DefaultChannelPromise(channel));
  when(channel.voidPromise()).thenReturn(new DefaultChannelPromise(channel));
  ChannelPromise completedPromise = new DefaultChannelPromise(channel)
      .setSuccess();
  when(channel.write(any())).thenReturn(completedPromise);
  when(channel.writeAndFlush(any())).thenReturn(completedPromise);
  when(writeQueue.enqueue(any(QueuedCommand.class), anyBoolean())).thenReturn(completedPromise);
  when(pipeline.firstContext()).thenReturn(ctx);
  when(eventLoop.inEventLoop()).thenReturn(true);
  when(http2Stream.id()).thenReturn(STREAM_ID);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
      Runnable runnable = (Runnable) invocation.getArguments()[0];
      runnable.run();
      return null;
    }
  }).when(eventLoop).execute(any(Runnable.class));

  stream = createStream();
}
 
Example #19
Source File: DefaultHttp2FrameWriterTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    frameWriter = new DefaultHttp2FrameWriter();

    outbound = Unpooled.buffer();

    expectedOutbound = Unpooled.EMPTY_BUFFER;

    promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);

    http2HeadersEncoder = new DefaultHttp2HeadersEncoder();

    Answer<Object> answer = new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock var1) throws Throwable {
            Object msg = var1.getArgument(0);
            if (msg instanceof ByteBuf) {
                outbound.writeBytes((ByteBuf) msg);
            }
            ReferenceCountUtil.release(msg);
            return future;
        }
    };
    when(ctx.write(any())).then(answer);
    when(ctx.write(any(), any(ChannelPromise.class))).then(answer);
    when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
    when(ctx.channel()).thenReturn(channel);
    when(ctx.executor()).thenReturn(ImmediateEventExecutor.INSTANCE);
}
 
Example #20
Source File: SmtpSessionTest.java    From NioSmtpClient with Apache License 2.0 5 votes vote down vote up
@Test
public void itClosesTheUnderlyingChannel() {
  DefaultChannelPromise channelPromise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
  when(channel.close()).thenReturn(channelPromise);

  CompletableFuture<Void> f = session.close();
  channelPromise.setSuccess();

  assertThat(f.isDone());
}
 
Example #21
Source File: MockChannelHandlerContext.java    From karyon with Apache License 2.0 4 votes vote down vote up
@Override
public ChannelFuture deregister() {
    DefaultChannelPromise promise = new DefaultChannelPromise(channel);
    promise.setSuccess();
    return promise;
}
 
Example #22
Source File: MockChannelHandlerContext.java    From karyon with Apache License 2.0 4 votes vote down vote up
@Override
public ChannelFuture close() {
    DefaultChannelPromise promise = new DefaultChannelPromise(channel);
    promise.setSuccess();
    return promise;
}
 
Example #23
Source File: MockChannelHandlerContext.java    From karyon with Apache License 2.0 4 votes vote down vote up
@Override
public ChannelFuture disconnect() {
    DefaultChannelPromise promise = new DefaultChannelPromise(channel);
    promise.setSuccess();
    return promise;
}
 
Example #24
Source File: MockChannelHandlerContext.java    From karyon with Apache License 2.0 4 votes vote down vote up
@Override
public ChannelFuture newFailedFuture(Throwable cause) {
    return new DefaultChannelPromise(channel).setFailure(cause);
}
 
Example #25
Source File: MockChannelHandlerContext.java    From karyon with Apache License 2.0 4 votes vote down vote up
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) {
    DefaultChannelPromise promise = new DefaultChannelPromise(channel);
    promise.setSuccess();
    return promise;
}
 
Example #26
Source File: MockChannelHandlerContext.java    From karyon with Apache License 2.0 4 votes vote down vote up
@Override
public ChannelFuture connect(SocketAddress remoteAddress) {
    DefaultChannelPromise promise = new DefaultChannelPromise(channel);
    promise.setSuccess();
    return promise;
}
 
Example #27
Source File: MockChannelHandlerContext.java    From karyon with Apache License 2.0 4 votes vote down vote up
@Override
public ChannelFuture newSucceededFuture() {
    return new DefaultChannelPromise(channel).setSuccess();
}
 
Example #28
Source File: MockChannelHandlerContext.java    From karyon with Apache License 2.0 4 votes vote down vote up
@Override
public ChannelFuture write(Object msg) {
    DefaultChannelPromise promise = new DefaultChannelPromise(channel);
    promise.setSuccess();
    return promise;
}
 
Example #29
Source File: MockChannelHandlerContext.java    From karyon with Apache License 2.0 4 votes vote down vote up
@Override
public ChannelPromise voidPromise() {
    return new DefaultChannelPromise(channel);
}
 
Example #30
Source File: MockChannelHandlerContext.java    From karyon with Apache License 2.0 4 votes vote down vote up
@Override
public ChannelPromise newPromise() {
    return new DefaultChannelPromise(channel);
}