Example usage for io.netty.util.concurrent SucceededFuture SucceededFuture

List of usage examples for io.netty.util.concurrent SucceededFuture SucceededFuture

Introduction

In this page you can find the example usage for io.netty.util.concurrent SucceededFuture SucceededFuture.

Prototype

public SucceededFuture(EventExecutor executor, V result) 

Source Link

Document

Creates a new instance.

Usage

From source file:com.github.spapageo.jannel.client.JannelClientTest.java

License:Open Source License

@Test
@SuppressWarnings("unchecked")
public void testDestroy() throws Exception {
    Future<String> future = new SucceededFuture<String>(ImmediateEventExecutor.INSTANCE, "test");
    when(eventLoopGroup.shutdownGracefully()).thenReturn((Future) future);
    jannelClient.destroy();/*  ww w .  j  a v a  2s  . c  om*/

    verify(eventLoopGroup).shutdownGracefully();
}

From source file:com.lambdaworks.redis.cluster.SingleThreadedReactiveClusterClientTest.java

License:Apache License

@Before
public void before() {

    AtomicReference<EventLoopGroup> ref = new AtomicReference<>();
    DefaultClientResources clientResources = DefaultClientResources.builder()
            .eventExecutorGroup(ImmediateEventExecutor.INSTANCE)
            .eventLoopGroupProvider(new EventLoopGroupProvider() {
                @Override/*w w  w . jav a  2 s. c o m*/
                public <T extends EventLoopGroup> T allocate(Class<T> type) {

                    if (ref.get() == null) {

                        if (type == EpollEventLoopGroup.class) {
                            ref.set(new EpollEventLoopGroup(1));
                        } else {
                            ref.set(new NioEventLoopGroup(1));
                        }
                    }

                    return (T) ref.get();
                }

                @Override
                public int threadPoolSize() {
                    return 0;
                }

                @Override
                public Future<Boolean> release(EventExecutorGroup eventLoopGroup, long quietPeriod,
                        long timeout, TimeUnit unit) {
                    return new SucceededFuture<>(ImmediateEventExecutor.INSTANCE, true);
                }

                @Override
                public Future<Boolean> shutdown(long quietPeriod, long timeout, TimeUnit timeUnit) {
                    ref.get().shutdownGracefully(quietPeriod, timeout, timeUnit);
                    return new SucceededFuture<>(ImmediateEventExecutor.INSTANCE, true);
                }

            }).commandLatencyCollectorOptions(DefaultCommandLatencyCollectorOptions.disabled()).build();

    client = RedisClusterClient.create(clientResources, RedisURI.create("localhost", 7379));
}

From source file:com.lambdaworks.redis.protocol.EmptyClientResources.java

License:Apache License

@Override
public Future<Boolean> shutdown() {
    return new SucceededFuture<>(GlobalEventExecutor.INSTANCE, true);
}

From source file:com.lambdaworks.redis.protocol.EmptyClientResources.java

License:Apache License

@Override
public Future<Boolean> shutdown(long quietPeriod, long timeout, TimeUnit timeUnit) {
    return new SucceededFuture<>(GlobalEventExecutor.INSTANCE, true);
}

From source file:com.relayrides.pushy.apns.ApnsClient.java

License:Open Source License

/**
 * <p>Gracefully disconnects from the APNs gateway. The disconnection process will wait until notifications that
 * have been sent to the APNs server have been either accepted or rejected. Note that some notifications passed to
 * {@link com.relayrides.pushy.apns.ApnsClient#sendNotification(ApnsPushNotification)} may still be enqueued and
 * not yet sent by the time the shutdown process begins; the {@code Futures} associated with those notifications
 * will fail.</p>/*from ww  w . j  a v a2 s  . c o  m*/
 *
 * <p>The returned {@code Future} will be marked as complete when the connection has closed completely. If the
 * connection is already closed when this method is called, the returned {@code Future} will be marked as complete
 * immediately.</p>
 *
 * <p>If a non-null {@code EventLoopGroup} was provided at construction time, clients may be reconnected and reused
 * after they have been disconnected. If no event loop group was provided at construction time, clients may not be
 * restarted after they have been disconnected via this method.</p>
 *
 * @return a {@code Future} that will be marked as complete when the connection has been closed
 *
 * @since 0.5
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Future<Void> disconnect() {
    log.info("Disconnecting.");
    final Future<Void> disconnectFuture;

    synchronized (this.bootstrap) {
        this.reconnectionPromise = null;
        if (this.scheduledReconnectFuture != null) {
            this.scheduledReconnectFuture.cancel(true);
        }

        final Future<Void> channelCloseFuture;

        if (this.connectionReadyPromise != null) {
            channelCloseFuture = this.connectionReadyPromise.channel().close();
        } else {
            channelCloseFuture = new SucceededFuture<>(GlobalEventExecutor.INSTANCE, null);
        }

        if (this.shouldShutDownEventLoopGroup) {
            // Wait for the channel to close before we try to shut down the event loop group
            channelCloseFuture.addListener(new GenericFutureListener<Future<Void>>() {

                @Override
                public void operationComplete(final Future<Void> future) throws Exception {
                    ApnsClient.this.bootstrap.config().group().shutdownGracefully();
                }
            });

            // Since the termination future for the event loop group is a Future<?> instead of a Future<Void>,
            // we'll need to create our own promise and then notify it when the termination future completes.
            disconnectFuture = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);

            this.bootstrap.config().group().terminationFuture().addListener(new GenericFutureListener() {

                @Override
                public void operationComplete(final Future future) throws Exception {
                    assert disconnectFuture instanceof DefaultPromise;
                    ((DefaultPromise<Void>) disconnectFuture).trySuccess(null);
                }
            });
        } else {
            // We're done once we've closed the channel, so we can return the closure future directly.
            disconnectFuture = channelCloseFuture;
        }
    }

    return disconnectFuture;
}

From source file:com.turo.pushy.apns.ApnsClient.java

License:Open Source License

/**
 * <p>Gracefully shuts down the client, closing all connections and releasing all persistent resources. The
 * disconnection process will wait until notifications that have been sent to the APNs server have been either
 * accepted or rejected. Note that some notifications passed to
 * {@link ApnsClient#sendNotification(ApnsPushNotification)} may still be enqueued and not yet sent by the time the
 * shutdown process begins; the {@code Futures} associated with those notifications will fail.</p>
 *
 * <p>The returned {@code Future} will be marked as complete when all connections in this client's pool have closed
 * completely and (if no {@code EventLoopGroup} was provided at construction time) the client's event loop group has
 * shut down. If the client has already shut down, the returned {@code Future} will be marked as complete
 * immediately.</p>/*from   www . j a va 2 s.  co  m*/
 *
 * <p>Clients may not be reused once they have been closed.</p>
 *
 * @return a {@code Future} that will be marked as complete when the client has finished shutting down
 *
 * @since 0.11
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Future<Void> close() {
    log.info("Shutting down.");

    final Future<Void> closeFuture;

    if (this.isClosed.compareAndSet(false, true)) {
        // Since we're (maybe) going to clobber the main event loop group, we should have this promise use the global
        // event executor to notify listeners.
        final Promise<Void> closePromise = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);

        this.channelPool.close().addListener(new GenericFutureListener<Future<Void>>() {

            @Override
            public void operationComplete(final Future<Void> closePoolFuture) throws Exception {
                if (ApnsClient.this.shouldShutDownEventLoopGroup) {
                    ApnsClient.this.eventLoopGroup.shutdownGracefully()
                            .addListener(new GenericFutureListener() {

                                @Override
                                public void operationComplete(final Future future) throws Exception {
                                    closePromise.trySuccess(null);
                                }
                            });
                } else {
                    closePromise.trySuccess(null);
                }
            }
        });

        closeFuture = closePromise;
    } else {
        closeFuture = new SucceededFuture<>(GlobalEventExecutor.INSTANCE, null);
    }

    return closeFuture;
}

From source file:com.turo.pushy.apns.BenchmarkApnsServer.java

License:Open Source License

public Future<Void> shutdown() {
    return (this.allChannels != null) ? this.allChannels.close()
            : new SucceededFuture<Void>(GlobalEventExecutor.INSTANCE, null);
}

From source file:com.turo.pushy.apns.MockApnsServer.java

License:Open Source License

/**
 * <p>Shuts down this server and releases the port to which this server was bound. If a {@code null} event loop
 * group was provided at construction time, the server will also shut down its internally-managed event loop
 * group.</p>//from   w w w  .j a v  a2 s  . co  m
 *
 * <p>If a non-null {@code EventLoopGroup} was provided at construction time, mock servers may be reconnected and
 * reused after they have been shut down. If no event loop group was provided at construction time, mock servers may
 * not be restarted after they have been shut down via this method.</p>
 *
 * @return a {@code Future} that will succeed once the server has finished unbinding from its port and, if the
 * server was managing its own event loop group, its event loop group has shut down
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Future<Void> shutdown() {
    final Future<Void> channelCloseFuture = (this.allChannels != null) ? this.allChannels.close()
            : new SucceededFuture<Void>(GlobalEventExecutor.INSTANCE, null);

    final Future<Void> disconnectFuture;

    if (this.shouldShutDownEventLoopGroup) {
        // Wait for the channel to close before we try to shut down the event loop group
        channelCloseFuture.addListener(new GenericFutureListener<Future<Void>>() {

            @Override
            public void operationComplete(final Future<Void> future) throws Exception {
                MockApnsServer.this.bootstrap.config().group().shutdownGracefully();
            }
        });

        // Since the termination future for the event loop group is a Future<?> instead of a Future<Void>,
        // we'll need to create our own promise and then notify it when the termination future completes.
        disconnectFuture = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);

        this.bootstrap.config().group().terminationFuture().addListener(new GenericFutureListener() {

            @Override
            public void operationComplete(final Future future) throws Exception {
                assert disconnectFuture instanceof DefaultPromise;
                ((DefaultPromise<Void>) disconnectFuture).trySuccess(null);
            }
        });
    } else {
        // We're done once we've closed all the channels, so we can return the closure future directly.
        disconnectFuture = channelCloseFuture;
    }

    return disconnectFuture;
}

From source file:org.opendaylight.controller.config.yang.bgp.rib.impl.AbstractRIBImplModuleTest.java

License:Open Source License

@SuppressWarnings("unchecked")
@Before/*from  w  w w.j  a  v a 2  s  .  c  o m*/
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    final List<ModuleFactory> moduleFactories = getModuleFactories();
    super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(this.mockedContext,
            moduleFactories.toArray(new ModuleFactory[moduleFactories.size()])));

    doAnswer(invocation -> {
        final String str = invocation.getArgumentAt(0, String.class);
        final Filter mockFilter = mock(Filter.class);
        doReturn(str).when(mockFilter).toString();
        return mockFilter;
    }).when(this.mockedContext).createFilter(anyString());

    final ServiceReference<?> emptyServiceReference = mock(ServiceReference.class, "Empty");
    final ServiceReference<?> classLoadingStrategySR = mock(ServiceReference.class, "ClassLoadingStrategy");
    final ServiceReference<?> dataProviderServiceReference = mock(ServiceReference.class, "Data Provider");

    Mockito.doNothing().when(this.mockedContext).addServiceListener(any(ServiceListener.class),
            Mockito.anyString());
    Mockito.doNothing().when(this.mockedContext).removeServiceListener(any(ServiceListener.class));

    Mockito.doNothing().when(this.mockedContext).addBundleListener(any(BundleListener.class));
    Mockito.doNothing().when(this.mockedContext).removeBundleListener(any(BundleListener.class));

    Mockito.doReturn(new Bundle[] {}).when(this.mockedContext).getBundles();

    Mockito.doReturn(new ServiceReference[] {}).when(this.mockedContext)
            .getServiceReferences(Matchers.anyString(), Matchers.anyString());

    Mockito.doReturn("Empty reference").when(emptyServiceReference).toString();
    Mockito.doReturn("Data Provider Service Reference").when(dataProviderServiceReference).toString();
    Mockito.doReturn("Class loading stategy reference").when(classLoadingStrategySR).toString();

    Mockito.doReturn(emptyServiceReference).when(this.mockedContext).getServiceReference(Mockito.anyString());
    Mockito.doReturn(dataProviderServiceReference).when(this.mockedContext)
            .getServiceReference(DataBroker.class);
    Mockito.doReturn(classLoadingStrategySR).when(this.mockedContext)
            .getServiceReference(GeneratedClassLoadingStrategy.class);
    Mockito.doReturn(classLoadingStrategySR).when(this.mockedContext)
            .getServiceReference(ClassLoadingStrategy.class);

    Mockito.doReturn(this.mockedDataProvider).when(this.mockedContext).getService(dataProviderServiceReference);
    Mockito.doReturn(GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy()).when(this.mockedContext)
            .getService(classLoadingStrategySR);
    Mockito.doReturn(null).when(this.mockedContext).getService(emptyServiceReference);

    Mockito.doReturn(this.mockedTransaction).when(this.mockedDataProvider).newReadWriteTransaction();

    Mockito.doReturn(null).when(this.mockedTransaction).read(Mockito.eq(LogicalDatastoreType.OPERATIONAL),
            Mockito.any());
    Mockito.doNothing().when(this.mockedTransaction).put(Mockito.eq(LogicalDatastoreType.OPERATIONAL),
            Mockito.any(), Mockito.any());
    Mockito.doNothing().when(this.mockedTransaction).delete(Mockito.eq(LogicalDatastoreType.OPERATIONAL),
            any(InstanceIdentifier.class));

    Mockito.doReturn(this.mockedFuture).when(this.mockedTransaction).submit();
    Mockito.doReturn(TRANSACTION_NAME).when(this.mockedTransaction).getIdentifier();

    Mockito.doReturn(null).when(this.mockedFuture).get();
    Mockito.doReturn(null).when(this.mockedFuture).checkedGet();

    final SchemaContext context = parseYangStreams(getFilesAsByteSources(getYangModelsPaths()));
    final SchemaService mockedSchemaService = mock(SchemaService.class);
    doReturn(context).when(mockedSchemaService).getGlobalContext();
    doAnswer(invocation -> {
        invocation.getArgumentAt(0, SchemaContextListener.class).onGlobalContextUpdated(context);
        final ListenerRegistration<SchemaContextListener> reg = mock(ListenerRegistration.class);
        doNothing().when(reg).close();
        return reg;
    }).when(mockedSchemaService).registerSchemaContextListener(any(SchemaContextListener.class));

    setupMockService(SchemaService.class, mockedSchemaService);
    setupMockService(YangTextSourceProvider.class, mock(YangTextSourceProvider.class));

    final BindingToNormalizedNodeCodec bindingCodec = BindingToNormalizedNodeCodecFactory
            .newInstance(GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy());
    BindingToNormalizedNodeCodecFactory.registerInstance(bindingCodec, mockedSchemaService);
    setupMockService(BindingToNormalizedNodeCodec.class, bindingCodec);

    final BGPExtensionProviderContext mockContext = mock(BGPExtensionProviderContext.class);
    doReturn(mock(MessageRegistry.class)).when(mockContext).getMessageRegistry();
    setupMockService(BGPExtensionProviderContext.class, mockContext);

    setupMockService(EventLoopGroup.class, NioEventLoopGroupCloseable.newInstance(0));
    setupMockService(EventExecutor.class,
            AutoCloseableEventExecutor.CloseableEventExecutorMixin.globalEventExecutor());

    setupMockService(DOMNotificationService.class, mock(DOMNotificationService.class));
    setupMockService(DOMNotificationPublishService.class, mock(DOMNotificationPublishService.class));
    setupMockService(DOMRpcService.class, mock(DOMRpcService.class));
    setupMockService(DOMRpcProviderService.class, mock(DOMRpcProviderService.class));
    setupMockService(DOMMountPointService.class, mock(DOMMountPointService.class));

    setupMockService(BGPDispatcher.class, this.mockedBGPDispatcher);
    doReturn(new SucceededFuture<>(ImmediateEventExecutor.INSTANCE, null)).when(this.mockedBGPDispatcher)
            .createReconnectingClient(any(InetSocketAddress.class), any(BGPPeerRegistry.class), anyInt(),
                    any(Optional.class));

    setupMockService(BgpDeployer.class, this.bgpDeployer);
    final Global global = mock(Global.class);
    final Bgp globalBgp = mock(Bgp.class);
    doReturn(global).when(globalBgp).getGlobal();
    doReturn("global").when(global).toString();
    doReturn(new ProtocolBuilder().setKey(new ProtocolKey(BGP.class, "bgp"))
            .addAugmentation(Protocol1.class, new Protocol1Builder().setBgp(globalBgp).build()).build())
                    .when(this.bgpMappingService).fromRib(any(), any(), any(), any(), any(), any());
    doNothing().when(this.bgpDeployer).onGlobalModified(any(), any(), any());
    doNothing().when(this.bgpDeployer).onNeighborModified(any(), any(), any());
    doReturn(NEIGHBOR).when(this.bgpMappingService).fromBgpPeer(any(), any(), any(), any(), any(), any(), any(),
            any(), any(), any(), any());
    doReturn(NEIGHBOR).when(this.bgpMappingService).fromApplicationPeer(any(), any());
    doReturn(this.mockedFuture).when(this.bgpDeployer).writeConfiguration(any(), any());
    doReturn(this.mockedFuture).when(this.bgpDeployer).removeConfiguration(any());
    doReturn(this.bgpMappingService).when(this.bgpDeployer).getMappingService();
    doReturn(OPENCONFIG_IID).when(this.bgpDeployer).getInstanceIdentifier();
    final DOMTransactionChain mockedChain = mock(DOMTransactionChain.class);
    final DOMDataWriteTransaction mockedWTx = mock(DOMDataWriteTransaction.class);
    doNothing().when(mockedWTx).put(any(), any(), any());
    doNothing().when(mockedWTx).delete(any(), any());
    doReturn(this.mockedFuture).when(mockedWTx).submit();
    doReturn(mockedWTx).when(mockedChain).newWriteOnlyTransaction();
    doReturn(mockedChain).when(this.mockedRIB).createPeerChain(any());
    doNothing().when(mockedChain).close();
    doReturn(YangInstanceIdentifier.of(BgpRib.QNAME)).when(this.mockedRIB).getYangRibId();
    doReturn(new AsNumber(123456l)).when(this.mockedRIB).getLocalAs();
    doReturn(BGP_ID).when(this.mockedRIB).getBgpIdentifier();
    final BGPRenderStats mockedRenderStats = mock(BGPRenderStats.class);
    doReturn(new UnsignedInt32Counter("counter")).when(mockedRenderStats).getConfiguredPeerCounter();
    doReturn(mockedRenderStats).when(this.mockedRIB).getRenderStats();
    final DOMDataTreeChangeService mockedTreeChangeService = mock(DOMDataTreeChangeService.class);
    final ListenerRegistration mockedListenerReg = mock(ListenerRegistration.class);
    doNothing().when(mockedListenerReg).close();
    doReturn(mockedListenerReg).when(mockedTreeChangeService).registerDataTreeChangeListener(any(), any());
    doReturn(mockedTreeChangeService).when(this.mockedRIB).getService();
    final ImportPolicyPeerTracker mockedImportPolicy = mock(ImportPolicyPeerTracker.class);
    doNothing().when(mockedImportPolicy).peerRoleChanged(any(), any());
    doReturn(null).when(mockedImportPolicy).policyFor(any());
    doReturn(mockedImportPolicy).when(this.mockedRIB).getImportPolicyPeerTracker();
    doReturn(mock(RIBSupportContextRegistry.class)).when(this.mockedRIB).getRibSupportContext();
    doReturn(Collections.emptySet()).when(this.mockedRIB).getLocalTablesKeys();
    doReturn(Collections.emptySet()).when(this.mockedRIB).getLocalTables();
    doReturn(this.mockedBGPDispatcher).when(this.mockedRIB).getDispatcher();
    doReturn(InstanceIdentifier.create(BgpRib.class).child(Rib.class, new RibKey(RIB_ID))).when(this.mockedRIB)
            .getInstanceIdentifier();

    setupMockService(RIB.class, this.mockedRIB);

    setupMockService(RIBExtensionProviderContext.class, new SimpleRIBExtensionProviderContext());

    setupMockService(BGPPeerRegistry.class, StrictBGPPeerRegistry.GLOBAL);

    setupMockService(BGPPeerRuntimeMXBean.class, this.mockedPeer);
}

From source file:org.opendaylight.netconf.topology.AbstractNetconfTopologyTest.java

License:Open Source License

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);

    when(mockedSchemaRepositoryProvider.getSharedSchemaRepository())
            .thenReturn(new SharedSchemaRepository("testingSharedSchemaRepo"));
    when(mockedProcessingExecutor.getExecutor()).thenReturn(MoreExecutors.newDirectExecutorService());
    Future<Void> future = new SucceededFuture<>(ImmediateEventExecutor.INSTANCE, null);
    when(mockedClientDispatcher.createReconnectingClient(any(NetconfReconnectingClientConfiguration.class)))
            .thenReturn(future);// w  ww . ja v a 2  s . c  om

    topology = new TestingAbstractNetconfTopology(TOPOLOGY_ID, mockedClientDispatcher, mockedBindingAwareBroker,
            mockedDataBroker, mockedEventExecutor, mockedKeepaliveExecutor, mockedProcessingExecutor,
            mockedSchemaRepositoryProvider);
}