Search in sources :

Example 11 with DefaultPromise

use of io.netty.util.concurrent.DefaultPromise in project bgpcep by opendaylight.

the class FSMTest method setUp.

@Before
public void setUp() throws UnknownHostException {
    MockitoAnnotations.initMocks(this);
    final List<BgpParameters> tlvs = Lists.newArrayList();
    final List<OptionalCapabilities> capas = Lists.newArrayList();
    capas.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class, new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder().setAfi(this.ipv4tt.getAfi()).setSafi(this.ipv4tt.getSafi()).build()).build()).build()).build());
    capas.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class, new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder().setAfi(this.linkstatett.getAfi()).setSafi(this.linkstatett.getSafi()).build()).build()).build()).build());
    capas.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(new AsNumber(30L)).build()).build()).build());
    capas.add(new OptionalCapabilitiesBuilder().setCParameters(BgpExtendedMessageUtil.EXTENDED_MESSAGE_CAPABILITY).build());
    capas.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class, new CParameters1Builder().setGracefulRestartCapability(new GracefulRestartCapabilityBuilder().build()).build()).build()).build());
    tlvs.add(new BgpParametersBuilder().setOptionalCapabilities(capas).build());
    final BGPSessionPreferences prefs = new BGPSessionPreferences(new AsNumber(30L), (short) 3, new BgpId("1.1.1.1"), new AsNumber(30L), tlvs);
    final ChannelFuture f = mock(ChannelFuture.class);
    doReturn(null).when(f).addListener(any(GenericFutureListener.class));
    final InetAddress peerAddress = InetAddress.getByName("1.1.1.2");
    doAnswer(invocation -> {
        final Object[] args = invocation.getArguments();
        FSMTest.this.receivedMsgs.add((Notification) args[0]);
        return f;
    }).when(this.speakerListener).writeAndFlush(any(Notification.class));
    doReturn(this.eventLoop).when(this.speakerListener).eventLoop();
    doReturn(null).when(this.eventLoop).schedule(any(Runnable.class), any(long.class), any(TimeUnit.class));
    doReturn("TestingChannel").when(this.speakerListener).toString();
    doReturn(new InetSocketAddress(peerAddress, 179)).when(this.speakerListener).remoteAddress();
    doReturn(new InetSocketAddress(peerAddress, 179)).when(this.speakerListener).localAddress();
    doReturn(this.pipeline).when(this.speakerListener).pipeline();
    doReturn(this.pipeline).when(this.pipeline).replace(any(ChannelHandler.class), any(String.class), any(ChannelHandler.class));
    doReturn(null).when(this.pipeline).replace(Matchers.<Class<ChannelHandler>>any(), any(String.class), any(ChannelHandler.class));
    doReturn(this.pipeline).when(this.pipeline).addLast(any(ChannelHandler.class));
    doReturn(mock(ChannelFuture.class)).when(this.speakerListener).close();
    final BGPPeerRegistry peerRegistry = new StrictBGPPeerRegistry();
    peerRegistry.addPeer(new IpAddress(new Ipv4Address(peerAddress.getHostAddress())), new SimpleSessionListener(), prefs);
    this.clientSession = new BGPClientSessionNegotiator(new DefaultPromise<>(GlobalEventExecutor.INSTANCE), this.speakerListener, peerRegistry);
    this.classicOpen = new OpenBuilder().setMyAsNumber(30).setHoldTimer(3).setVersion(new ProtocolVersion((short) 4)).setBgpParameters(tlvs).setBgpIdentifier(new Ipv4Address("1.1.1.2")).build();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ChannelHandler(io.netty.channel.ChannelHandler) BgpParameters(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.BgpParameters) ProtocolVersion(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.ProtocolVersion) Notification(org.opendaylight.yangtools.yang.binding.Notification) As4BytesCapabilityBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.optional.capabilities.c.parameters.As4BytesCapabilityBuilder) CParametersBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.optional.capabilities.CParametersBuilder) BGPSessionPreferences(org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences) TimeUnit(java.util.concurrent.TimeUnit) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Ipv4Address(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address) ChannelFuture(io.netty.channel.ChannelFuture) OptionalCapabilitiesBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.OptionalCapabilitiesBuilder) MultiprotocolCapabilityBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.mp.capabilities.MultiprotocolCapabilityBuilder) OpenBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.OpenBuilder) BGPPeerRegistry(org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry) BgpParametersBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.BgpParametersBuilder) AsNumber(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber) OptionalCapabilities(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.OptionalCapabilities) CParameters1Builder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.CParameters1Builder) BgpId(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.BgpId) DefaultPromise(io.netty.util.concurrent.DefaultPromise) IpAddress(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress) GracefulRestartCapabilityBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.mp.capabilities.GracefulRestartCapabilityBuilder) InetAddress(java.net.InetAddress) Before(org.junit.Before)

Example 12 with DefaultPromise

use of io.netty.util.concurrent.DefaultPromise in project openzaly by akaxincom.

the class NettyClient2 method sendRedisCommand.

public Future<IRedisCommandResponse> sendRedisCommand(final RedisCommand redisCommand) {
    final Future<IRedisCommandResponse> responseFuture;
    // channelPromise.channel().isActive());
    if (channelPromise != null) {
        final ChannelPromise readyPromise = this.channelPromise;
        final DefaultPromise<IRedisCommandResponse> responsePromise = new DefaultPromise<IRedisCommandResponse>(readyPromise.channel().eventLoop());
        // 提交一个事件
        readyPromise.channel().eventLoop().submit(new Runnable() {

            @Override
            public void run() {
                // 将这个结果赋值给responsePromise
                NettyClient2.this.responsePromise = responsePromise;
            }
        });
        readyPromise.channel().writeAndFlush(redisCommand).addListener(new GenericFutureListener<ChannelFuture>() {

            @Override
            public void operationComplete(final ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    // 如果失败了,直接将promise返回
                    responsePromise.tryFailure(future.cause());
                    logger.error("send push message error: {},cause={}", redisCommand, future.cause());
                } else {
                // logger.info("write data to platform success");
                }
            }
        });
        responseFuture = responsePromise;
    } else {
        logger.error("send push error because client is not connected: {}", redisCommand.toString());
        responseFuture = new FailedFuture<IRedisCommandResponse>(GlobalEventExecutor.INSTANCE, CONNECT_EXCEPTION);
    }
    return responseFuture;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultPromise(io.netty.util.concurrent.DefaultPromise) ChannelPromise(io.netty.channel.ChannelPromise)

Example 13 with DefaultPromise

use of io.netty.util.concurrent.DefaultPromise in project ambry by linkedin.

the class Http2MultiplexedChannelPoolTest method minConnectionTest.

/**
 * Minimum Connection is required.
 */
@Test
public void minConnectionTest() throws Exception {
    int minConnections = 2;
    int totalStreamToAcquire = 4;
    List<Channel> channels = new ArrayList<>();
    try {
        ChannelPool connectionPool = Mockito.mock(ChannelPool.class);
        OngoingStubbing<Future<Channel>> mockito = Mockito.when(connectionPool.acquire());
        for (int i = 0; i < minConnections; i++) {
            Channel channel = newHttp2Channel();
            channels.add(channel);
            loopGroup.register(channel).awaitUninterruptibly();
            Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next());
            channelPromise.setSuccess(channel);
            mockito = mockito.thenReturn(channelPromise);
        }
        Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, new HashSet<>(), null, http2ClientConfigForTwoConnection, new Http2ClientMetrics(new MetricRegistry()), streamChannelInitializer);
        List<Channel> toRelease = new ArrayList<>();
        for (int i = 0; i < minConnections; i++) {
            Channel streamChannel = h2Pool.acquire().awaitUninterruptibly().getNow();
            toRelease.add(streamChannel);
            assertTrue(streamChannel instanceof Http2StreamChannel);
            Mockito.verify(connectionPool, Mockito.times(i + 1)).acquire();
        }
        for (int i = minConnections; i < totalStreamToAcquire; i++) {
            Channel streamChannel = h2Pool.acquire().awaitUninterruptibly().getNow();
            toRelease.add(streamChannel);
            assertTrue(streamChannel instanceof Http2StreamChannel);
            // No more parent channel acquisition
            Mockito.verify(connectionPool, Mockito.times(minConnections)).acquire();
        }
        for (Channel streamChannel : toRelease) {
            h2Pool.release(streamChannel).getNow();
        }
    } finally {
        for (Channel channel : channels) {
            channel.close();
        }
    }
}
Also used : ChannelPool(io.netty.channel.pool.ChannelPool) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) Http2StreamChannel(io.netty.handler.codec.http2.Http2StreamChannel) MetricRegistry(com.codahale.metrics.MetricRegistry) ArrayList(java.util.ArrayList) DefaultPromise(io.netty.util.concurrent.DefaultPromise) CompletableFuture(java.util.concurrent.CompletableFuture) Future(io.netty.util.concurrent.Future) FailedFuture(io.netty.util.concurrent.FailedFuture) Http2StreamChannel(io.netty.handler.codec.http2.Http2StreamChannel) MultiplexedChannelRecordTest(com.github.ambry.network.http2.MultiplexedChannelRecordTest) Test(org.junit.Test)

Example 14 with DefaultPromise

use of io.netty.util.concurrent.DefaultPromise in project netty by netty.

the class ThreadPerChannelEventLoopGroupTest method testTerminationFutureSuccessReflectively.

@Test
public void testTerminationFutureSuccessReflectively() throws Exception {
    Field terminationFutureField = ThreadPerChannelEventLoopGroup.class.getDeclaredField("terminationFuture");
    terminationFutureField.setAccessible(true);
    final Exception[] exceptionHolder = new Exception[1];
    for (int i = 0; i < 2; i++) {
        ThreadPerChannelEventLoopGroup loopGroup = new ThreadPerChannelEventLoopGroup(64);
        Promise<?> promise = new DefaultPromise<Void>(GlobalEventExecutor.INSTANCE) {

            @Override
            public Promise<Void> setSuccess(Void result) {
                try {
                    return super.setSuccess(result);
                } catch (IllegalStateException e) {
                    exceptionHolder[0] = e;
                    throw e;
                }
            }
        };
        terminationFutureField.set(loopGroup, promise);
        runTest(loopGroup);
    }
    // The global event executor will not terminate, but this will give the test a chance to fail.
    GlobalEventExecutor.INSTANCE.awaitTermination(100, TimeUnit.MILLISECONDS);
    assertNull(exceptionHolder[0]);
}
Also used : Field(java.lang.reflect.Field) DefaultPromise(io.netty.util.concurrent.DefaultPromise) Test(org.junit.jupiter.api.Test)

Example 15 with DefaultPromise

use of io.netty.util.concurrent.DefaultPromise in project netty by netty.

the class Http2StreamChannelBootstrapTest method open0FailsPromiseOnHttp2MultiplexHandlerError.

@Test
public void open0FailsPromiseOnHttp2MultiplexHandlerError() {
    Http2StreamChannelBootstrap bootstrap = new Http2StreamChannelBootstrap(mock(Channel.class));
    Http2MultiplexHandler handler = new Http2MultiplexHandler(mock(ChannelHandler.class));
    EventExecutor executor = mock(EventExecutor.class);
    when(executor.inEventLoop()).thenReturn(true);
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.executor()).thenReturn(executor);
    when(ctx.handler()).thenReturn(handler);
    Promise<Http2StreamChannel> promise = new DefaultPromise<Http2StreamChannel>(mock(EventExecutor.class));
    bootstrap.open0(ctx, promise);
    assertThat(promise.isDone(), is(true));
    assertThat(promise.cause(), is(instanceOf(IllegalStateException.class)));
}
Also used : EventExecutor(io.netty.util.concurrent.EventExecutor) DefaultPromise(io.netty.util.concurrent.DefaultPromise) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) Test(org.junit.jupiter.api.Test)

Aggregations

DefaultPromise (io.netty.util.concurrent.DefaultPromise)16 Channel (io.netty.channel.Channel)7 ChannelFuture (io.netty.channel.ChannelFuture)6 SocketChannel (io.netty.channel.socket.SocketChannel)6 Future (io.netty.util.concurrent.Future)4 Test (org.junit.Test)4 MetricRegistry (com.codahale.metrics.MetricRegistry)3 MultiplexedChannelRecordTest (com.github.ambry.network.http2.MultiplexedChannelRecordTest)3 ByteBuf (io.netty.buffer.ByteBuf)3 ChannelFutureListener (io.netty.channel.ChannelFutureListener)3 ChannelPool (io.netty.channel.pool.ChannelPool)3 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)3 Http2StreamChannel (io.netty.handler.codec.http2.Http2StreamChannel)3 MqttFixedHeader (io.netty.handler.codec.mqtt.MqttFixedHeader)3 MqttPublishMessage (io.netty.handler.codec.mqtt.MqttPublishMessage)3 MqttPublishVariableHeader (io.netty.handler.codec.mqtt.MqttPublishVariableHeader)3 HashMultimap (com.google.common.collect.HashMultimap)2 ImmutableSet (com.google.common.collect.ImmutableSet)2 Bootstrap (io.netty.bootstrap.Bootstrap)2 ChannelHandler (io.netty.channel.ChannelHandler)2