Java Code Examples for io.netty.util.concurrent.Future

The following are top voted examples for showing how to use io.netty.util.concurrent.Future. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: elasticsearch_my   File: Netty4Transport.java   Source Code and License 7 votes vote down vote up
@Override
@SuppressForbidden(reason = "debug")
protected void stopInternal() {
    Releasables.close(serverOpenChannels, () -> {
        final List<Tuple<String, Future<?>>> serverBootstrapCloseFutures = new ArrayList<>(serverBootstraps.size());
        for (final Map.Entry<String, ServerBootstrap> entry : serverBootstraps.entrySet()) {
            serverBootstrapCloseFutures.add(
                Tuple.tuple(entry.getKey(), entry.getValue().config().group().shutdownGracefully(0, 5, TimeUnit.SECONDS)));
        }
        for (final Tuple<String, Future<?>> future : serverBootstrapCloseFutures) {
            future.v2().awaitUninterruptibly();
            if (!future.v2().isSuccess()) {
                logger.debug(
                    (Supplier<?>) () -> new ParameterizedMessage(
                        "Error closing server bootstrap for profile [{}]", future.v1()), future.v2().cause());
            }
        }
        serverBootstraps.clear();

        if (bootstrap != null) {
            bootstrap.config().group().shutdownGracefully(0, 5, TimeUnit.SECONDS).awaitUninterruptibly();
            bootstrap = null;
        }
    });
}
 
Example 2
Project: JRediClients   File: RedissonPermitExpirableSemaphore.java   Source Code and License 6 votes vote down vote up
public RFuture<String> tryAcquireAsync() {
    final RPromise<String> result = newPromise();
    RFuture<String> res = tryAcquireAsync(1, nonExpirableTimeout);
    res.addListener(new FutureListener<String>() {
        @Override
        public void operationComplete(Future<String> future) throws Exception {
            if (!future.isSuccess()) {
                result.tryFailure(future.cause());
                return;
            }
            
            String permitId = future.getNow();
            if (permitId != null && !permitId.startsWith(":")) {
                if (!result.trySuccess(permitId)) {
                    releaseAsync(permitId);
                }
            } else {
                result.trySuccess(null);
            }
        }
    });
    return result;
}
 
Example 3
Project: JRediClients   File: RedissonPermitExpirableSemaphore.java   Source Code and License 6 votes vote down vote up
@Override
public RFuture<Void> releaseAsync(final String permitId) {
    final RPromise<Void> result = newPromise();
    tryReleaseAsync(permitId).addListener(new FutureListener<Boolean>() {
        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            if (!future.isSuccess()) {
                result.tryFailure(future.cause());
                return;
            }
            
            if (future.getNow()) {
                result.trySuccess(null);
            } else {
                result.tryFailure(new IllegalArgumentException("Permit with id " + permitId + " has already been released or doesn't exist"));
            }
        }
    });
    return result;
}
 
Example 4
Project: JRediClients   File: RedissonBinaryStream.java   Source Code and License 6 votes vote down vote up
private void write(final byte[] value, final RPromise<Void> result, final int chunkSize, final int i) {
    final int len = Math.min(value.length - i*chunkSize, chunkSize);
    byte[] bytes = Arrays.copyOfRange(value, i*chunkSize, i*chunkSize + len);
    writeAsync(bytes).addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (!future.isSuccess()) {
                result.tryFailure(future.cause());
                return;
            }
            
            int j = i + 1;
            if (j*chunkSize > value.length) {
                result.trySuccess(null);
            } else {
                write(value, result, chunkSize, j);
            }
        }
    });
}
 
Example 5
Project: BaseClient   File: NetworkManager.java   Source Code and License 6 votes vote down vote up
public void sendPacket(Packet packetIn, GenericFutureListener <? extends Future <? super Void >> listener, GenericFutureListener <? extends Future <? super Void >> ... listeners)
{
    if (this.isChannelOpen())
    {
        this.flushOutboundQueue();
        this.dispatchPacket(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener));
    }
    else
    {
        this.field_181680_j.writeLock().lock();

        try
        {
            this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener)));
        }
        finally
        {
            this.field_181680_j.writeLock().unlock();
        }
    }
}
 
Example 6
Project: BaseClient   File: NetHandlerPlayServer.java   Source Code and License 6 votes vote down vote up
/**
 * Kick a player from the server with a reason
 */
public void kickPlayerFromServer(String reason)
{
    final ChatComponentText chatcomponenttext = new ChatComponentText(reason);
    this.netManager.sendPacket(new S40PacketDisconnect(chatcomponenttext), new GenericFutureListener < Future <? super Void >> ()
    {
        public void operationComplete(Future <? super Void > p_operationComplete_1_) throws Exception
        {
            NetHandlerPlayServer.this.netManager.closeChannel(chatcomponenttext);
        }
    }, new GenericFutureListener[0]);
    this.netManager.disableAutoRead();
    Futures.getUnchecked(this.serverController.addScheduledTask(new Runnable()
    {
        public void run()
        {
            NetHandlerPlayServer.this.netManager.checkDisconnected();
        }
    }));
}
 
Example 7
Project: JRediClients   File: ConnectionPool.java   Source Code and License 6 votes vote down vote up
private RFuture<T> acquireConnection(RedisCommand<?> command, final ClientConnectionsEntry entry) {
    final RPromise<T> result = connectionManager.newPromise();

    AcquireCallback<T> callback = new AcquireCallback<T>() {
        @Override
        public void run() {
            result.removeListener(this);
            connectTo(entry, result);
        }
        
        @Override
        public void operationComplete(Future<T> future) throws Exception {
            entry.removeConnection(this);
        }
    };
    
    result.addListener(callback);
    acquireConnection(entry, callback);
    
    return result;
}
 
Example 8
Project: JRediClients   File: ConnectionPool.java   Source Code and License 6 votes vote down vote up
private void createConnection(final ClientConnectionsEntry entry, final RPromise<T> promise) {
    RFuture<T> connFuture = connect(entry);
    connFuture.addListener(new FutureListener<T>() {
        @Override
        public void operationComplete(Future<T> future) throws Exception {
            if (!future.isSuccess()) {
                promiseFailure(entry, promise, future.cause());
                return;
            }

            T conn = future.getNow();
            if (!conn.isActive()) {
                promiseFailure(entry, promise, conn);
                return;
            }

            connectedSuccessful(entry, promise, conn);
        }
    });
}
 
Example 9
Project: BaseClient   File: NetworkManager.java   Source Code and License 6 votes vote down vote up
public void sendPacket(Packet packetIn, GenericFutureListener <? extends Future <? super Void >> listener, GenericFutureListener <? extends Future <? super Void >> ... listeners)
{
    if (this.isChannelOpen())
    {
        this.flushOutboundQueue();
        this.dispatchPacket(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener));
    }
    else
    {
        this.field_181680_j.writeLock().lock();

        try
        {
            this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener)));
        }
        finally
        {
            this.field_181680_j.writeLock().unlock();
        }
    }
}
 
Example 10
Project: JRediClients   File: MasterSlaveEntry.java   Source Code and License 6 votes vote down vote up
private void psubscribe(final String channelName, final Collection<RedisPubSubListener<?>> listeners,
        final Codec subscribeCodec) {
    RFuture<PubSubConnectionEntry> subscribeFuture = connectionManager.psubscribe(channelName, subscribeCodec, null);
    subscribeFuture.addListener(new FutureListener<PubSubConnectionEntry>() {
        @Override
        public void operationComplete(Future<PubSubConnectionEntry> future)
                throws Exception {
            if (!future.isSuccess()) {
                psubscribe(channelName, listeners, subscribeCodec);
                return;
            }
            
            PubSubConnectionEntry newEntry = future.getNow();
            for (RedisPubSubListener<?> redisPubSubListener : listeners) {
                newEntry.addListener(channelName, redisPubSubListener);
            }
            log.debug("resubscribed listeners for '{}' channel-pattern", channelName);
        }
    });
}
 
Example 11
Project: aws-sdk-java-v2   File: RunnableRequest.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
    context.channelPool().acquire().addListener((Future<Channel> channelFuture) -> {
        if (channelFuture.isSuccess()) {
            try {
                channel = channelFuture.getNow();
                initializePerRequestHandlers();
                channel.attr(REQUEST_CONTEXT_KEY).set(context);
                channel.attr(RESPONSE_COMPLETE_KEY).set(false);
                makeRequest(context.nettyRequest());
            } catch (Exception e) {
                handleFailure(() -> "Failed to make request to " + endpoint(), e);
            }
        } else {
            handleFailure(() -> "Failed to create connection to " + endpoint(), channelFuture.cause());
        }
    });
}
 
Example 12
Project: JRediClients   File: RedissonReadLock.java   Source Code and License 6 votes vote down vote up
@Override
public RFuture<Boolean> forceUnlockAsync() {
    RFuture<Boolean> result = commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
            "if (redis.call('hget', KEYS[1], 'mode') == 'read') then " +
                "redis.call('del', KEYS[1]); " +
                "redis.call('publish', KEYS[2], ARGV[1]); " +
                "return 1; " +
            "end; " +
            "return 0; ",
            Arrays.<Object>asList(getName(), getChannelName()), LockPubSub.unlockMessage);

      result.addListener(new FutureListener<Boolean>() {
          @Override
          public void operationComplete(Future<Boolean> future) throws Exception {
              if (future.isSuccess() && future.getNow()) {
                  cancelExpirationRenewal();
              }
          }
      });

      return result;
}
 
Example 13
Project: JRediClients   File: ClusterConnectionManager.java   Source Code and License 6 votes vote down vote up
private void checkClusterState(final ClusterServersConfig cfg, final Iterator<URI> iterator, final AtomicReference<Throwable> lastException) {
    if (!iterator.hasNext()) {
        log.error("Can't update cluster state", lastException.get());
        scheduleClusterChangeCheck(cfg, null);
        return;
    }
    if (!getShutdownLatch().acquire()) {
        return;
    }
    final URI uri = iterator.next();
    RFuture<RedisConnection> connectionFuture = connect(cfg, uri);
    connectionFuture.addListener(new FutureListener<RedisConnection>() {
        @Override
        public void operationComplete(Future<RedisConnection> future) throws Exception {
            if (!future.isSuccess()) {
                lastException.set(future.cause());
                getShutdownLatch().release();
                checkClusterState(cfg, iterator, lastException);
                return;
            }

            RedisConnection connection = future.getNow();
            updateClusterState(cfg, connection, iterator, uri);
        }
    });
}
 
Example 14
Project: JRediClients   File: CommandAsyncService.java   Source Code and License 6 votes vote down vote up
private <R, T> void retryReadRandomAsync(final RedisCommand<T> command, final RPromise<R> mainPromise,
        final List<MasterSlaveEntry> nodes, final Object... params) {
    final RPromise<R> attemptPromise = connectionManager.newPromise();
    attemptPromise.addListener(new FutureListener<R>() {
        @Override
        public void operationComplete(Future<R> future) throws Exception {
            if (future.isSuccess()) {
                if (future.getNow() == null) {
                    if (nodes.isEmpty()) {
                        mainPromise.trySuccess(null);
                    } else {
                        retryReadRandomAsync(command, mainPromise, nodes, params);
                    }
                } else {
                    mainPromise.trySuccess(future.getNow());
                }
            } else {
                mainPromise.tryFailure(future.cause());
            }
        }
    });

    MasterSlaveEntry entry = nodes.remove(0);
    async(true, new NodeSource(entry), connectionManager.getCodec(), command, params, attemptPromise, 0);
}
 
Example 15
Project: JRediClients   File: CommandAsyncService.java   Source Code and License 6 votes vote down vote up
protected <V, R> void releaseConnection(final NodeSource source, final RFuture<RedisConnection> connectionFuture,
        final boolean isReadOnly, RPromise<R> attemptPromise, final AsyncDetails<V, R> details) {
    attemptPromise.addListener(new FutureListener<R>() {
        @Override
        public void operationComplete(Future<R> future) throws Exception {
            if (!connectionFuture.isSuccess()) {
                return;
            }

            RedisConnection connection = connectionFuture.getNow();
            connectionManager.getShutdownLatch().release();
            if (isReadOnly) {
                connectionManager.releaseRead(source, connection);
            } else {
                connectionManager.releaseWrite(source, connection);
            }

            if (log.isDebugEnabled()) {
                log.debug("connection released for command {} and params {} from slot {} using connection {}",
                        details.getCommand(), Arrays.toString(details.getParams()), details.getSource(), connection);
            }
        }
    });
}
 
Example 16
Project: JRediClients   File: RedissonLock.java   Source Code and License 6 votes vote down vote up
private RFuture<Boolean> tryAcquireOnceAsync(long leaseTime, TimeUnit unit, final long threadId) {
    if (leaseTime != -1) {
        return tryLockInnerAsync(leaseTime, unit, threadId, RedisCommands.EVAL_NULL_BOOLEAN);
    }
    RFuture<Boolean> ttlRemainingFuture = tryLockInnerAsync(commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(), TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_NULL_BOOLEAN);
    ttlRemainingFuture.addListener(new FutureListener<Boolean>() {
        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            if (!future.isSuccess()) {
                return;
            }

            Boolean ttlRemaining = future.getNow();
            // lock acquired
            if (ttlRemaining) {
                scheduleExpirationRenewal(threadId);
            }
        }
    });
    return ttlRemainingFuture;
}
 
Example 17
Project: JRediClients   File: RedissonLock.java   Source Code and License 6 votes vote down vote up
private <T> RFuture<Long> tryAcquireAsync(long leaseTime, TimeUnit unit, final long threadId) {
    if (leaseTime != -1) {
        return tryLockInnerAsync(leaseTime, unit, threadId, RedisCommands.EVAL_LONG);
    }
    RFuture<Long> ttlRemainingFuture = tryLockInnerAsync(commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(), TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_LONG);
    ttlRemainingFuture.addListener(new FutureListener<Long>() {
        @Override
        public void operationComplete(Future<Long> future) throws Exception {
            if (!future.isSuccess()) {
                return;
            }

            Long ttlRemaining = future.getNow();
            // lock acquired
            if (ttlRemaining == null) {
                scheduleExpirationRenewal(threadId);
            }
        }
    });
    return ttlRemainingFuture;
}
 
Example 18
Project: BaseClient   File: NetworkManager.java   Source Code and License 6 votes vote down vote up
public void sendPacket(Packet packetIn)
{
    if (this.isChannelOpen())
    {
        this.flushOutboundQueue();
        this.dispatchPacket(packetIn, (GenericFutureListener <? extends Future <? super Void >> [])null);
    }
    else
    {
        this.field_181680_j.writeLock().lock();

        try
        {
            this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])null));
        }
        finally
        {
            this.field_181680_j.writeLock().unlock();
        }
    }
}
 
Example 19
Project: JRediClients   File: RedissonMap.java   Source Code and License 6 votes vote down vote up
private void loadValue(final K key, final RPromise<V> result, final RLock lock,
        final long threadId) {
    commandExecutor.getConnectionManager().getExecutor().execute(new Runnable() {
        @Override
        public void run() {
            final V value = options.getLoader().load(key);
            if (value == null) {
                result.trySuccess(value);
                return;
            }
                
            externalPutAsync(key, value).addListener(new FutureListener<V>() {
                @Override
                public void operationComplete(Future<V> future) throws Exception {
                    if (!future.isSuccess()) {
                        lock.unlockAsync(threadId);
                        result.tryFailure(future.cause());
                        return;
                    }
                    
                    unlock(result, lock, threadId, value);
                }
            });
        }
    });
}
 
Example 20
Project: drift   File: ConnectionFactory.java   Source Code and License 6 votes vote down vote up
@Override
public Future<Channel> getConnection(HostAndPort address)
{
    try {
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .option(CONNECT_TIMEOUT_MILLIS, saturatedCast(connectTimeout.toMillis()))
                .handler(new ThriftClientInitializer(
                        messageFraming,
                        messageEncoding,
                        requestTimeout,
                        socksProxy,
                        sslContextSupplier));

        Promise<Channel> promise = group.next().newPromise();
        bootstrap.connect(new InetSocketAddress(address.getHost(), address.getPort()))
                .addListener((ChannelFutureListener) future -> notifyConnect(future, promise));
        return promise;
    }
    catch (Throwable e) {
        return group.next().newFailedFuture(new TTransportException(e));
    }
}
 
Example 21
Project: CustomWorldGen   File: NetworkManager.java   Source Code and License 6 votes vote down vote up
public void sendPacket(Packet<?> packetIn)
{
    if (this.isChannelOpen())
    {
        this.flushOutboundQueue();
        this.dispatchPacket(packetIn, (GenericFutureListener <? extends Future <? super Void >> [])null);
    }
    else
    {
        this.readWriteLock.writeLock().lock();

        try
        {
            this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])null));
        }
        finally
        {
            this.readWriteLock.writeLock().unlock();
        }
    }
}
 
Example 22
Project: DecompiledMinecraft   File: NetHandlerPlayServer.java   Source Code and License 6 votes vote down vote up
/**
 * Kick a player from the server with a reason
 */
public void kickPlayerFromServer(String reason)
{
    final ChatComponentText chatcomponenttext = new ChatComponentText(reason);
    this.netManager.sendPacket(new S40PacketDisconnect(chatcomponenttext), new GenericFutureListener < Future <? super Void >> ()
    {
        public void operationComplete(Future <? super Void > p_operationComplete_1_) throws Exception
        {
            NetHandlerPlayServer.this.netManager.closeChannel(chatcomponenttext);
        }
    }, new GenericFutureListener[0]);
    this.netManager.disableAutoRead();
    Futures.getUnchecked(this.serverController.addScheduledTask(new Runnable()
    {
        public void run()
        {
            NetHandlerPlayServer.this.netManager.checkDisconnected();
        }
    }));
}
 
Example 23
Project: DecompiledMinecraft   File: NetworkManager.java   Source Code and License 6 votes vote down vote up
public void sendPacket(Packet packetIn)
{
    if (this.isChannelOpen())
    {
        this.flushOutboundQueue();
        this.dispatchPacket(packetIn, (GenericFutureListener <? extends Future <? super Void >> [])null);
    }
    else
    {
        this.field_181680_j.writeLock().lock();

        try
        {
            this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])null));
        }
        finally
        {
            this.field_181680_j.writeLock().unlock();
        }
    }
}
 
Example 24
Project: DecompiledMinecraft   File: NetworkManager.java   Source Code and License 6 votes vote down vote up
public void sendPacket(Packet packetIn, GenericFutureListener <? extends Future <? super Void >> listener, GenericFutureListener <? extends Future <? super Void >> ... listeners)
{
    if (this.isChannelOpen())
    {
        this.flushOutboundQueue();
        this.dispatchPacket(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener));
    }
    else
    {
        this.field_181680_j.writeLock().lock();

        try
        {
            this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener)));
        }
        finally
        {
            this.field_181680_j.writeLock().unlock();
        }
    }
}
 
Example 25
Project: DecompiledMinecraft   File: NetworkManager.java   Source Code and License 6 votes vote down vote up
public void sendPacket(Packet packetIn)
{
    if (this.isChannelOpen())
    {
        this.flushOutboundQueue();
        this.dispatchPacket(packetIn, (GenericFutureListener <? extends Future <? super Void >> [])null);
    }
    else
    {
        this.field_181680_j.writeLock().lock();

        try
        {
            this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])null));
        }
        finally
        {
            this.field_181680_j.writeLock().unlock();
        }
    }
}
 
Example 26
Project: DecompiledMinecraft   File: NetworkManager.java   Source Code and License 6 votes vote down vote up
public void sendPacket(Packet packetIn, GenericFutureListener <? extends Future <? super Void >> listener, GenericFutureListener <? extends Future <? super Void >> ... listeners)
{
    if (this.isChannelOpen())
    {
        this.flushOutboundQueue();
        this.dispatchPacket(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener));
    }
    else
    {
        this.field_181680_j.writeLock().lock();

        try
        {
            this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener)));
        }
        finally
        {
            this.field_181680_j.writeLock().unlock();
        }
    }
}
 
Example 27
Project: ClientAPI   File: MixinNetworkManager.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("AmbiguousMixinReference")
@Redirect(method = "sendPacket", at = @At(value = "INVOKE", target = "net/minecraft/network/NetworkManager.dispatchPacket(Lnet/minecraft/network/Packet;[Lio/netty/util/concurrent/GenericFutureListener;)V"))
private void sendPacket(NetworkManager networkManager, Packet<?> packetIn, @Nullable final GenericFutureListener<? extends Future<?super Void>>[] futureListeners) {
    PacketEvent event = new PacketEvent.Send(packetIn);
    ClientAPI.EVENT_BUS.post(event);
    if (event.isCancelled())
        return;

    this.dispatchPacket(event.getPacket(), null);
}
 
Example 28
Project: fastdfs-spring-boot   File: FastdfsExecutor.java   Source Code and License 5 votes vote down vote up
@Override
public void operationComplete(Future<Channel> cf) throws Exception {

    if (cf.isCancelled()) {
        promise.cancel(true);
        return;
    }

    if (!cf.isSuccess()) {
        promise.completeExceptionally(cf.cause());
        return;
    }

    Channel channel = cf.getNow();
    promise.whenComplete((result, error) -> pool.release(channel));

    try {

        FastdfsOperation<T> fastdfsOperation = new FastdfsOperation<>(channel, requester, replier, promise);
        if (LOG.isDebugEnabled()) {
            LOG.debug("execute {}", fastdfsOperation);
        }

        fastdfsOperation.execute();
    } catch (Exception e) {
        promise.completeExceptionally(e);
    }
}
 
Example 29
Project: ClusterDeviceControlPlatform   File: NettyServer.java   Source Code and License 5 votes vote down vote up
private void startListenerHandle(Future future, SuccessfulListener listener) {
    try {
        Thread.sleep(10);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    if (!future.isSuccess()) future.cause().printStackTrace();
    if (listener != null) listener.onSuccess(future.isSuccess());
}
 
Example 30
Project: JRediClients   File: BaseRemoteService.java   Source Code and License 5 votes vote down vote up
private void awaitResultAsync(final RemoteInvocationOptions optionsCopy, final RemotePromise<Object> result,
        final RemoteServiceRequest request, final String responseName, final String ackName) {
    RFuture<Boolean> deleteFuture = redisson.getBucket(ackName).deleteAsync();
    deleteFuture.addListener(new FutureListener<Boolean>() {
        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            if (!future.isSuccess()) {
                result.tryFailure(future.cause());
                return;
            }

            awaitResultAsync(optionsCopy, result, request, responseName);
        }
    });
}
 
Example 31
Project: JRediClients   File: MapWriterPromise.java   Source Code and License 5 votes vote down vote up
public MapWriterPromise(RFuture<R> f, final CommandAsyncExecutor commandExecutor, final MapWriterTask<R> task) {
    f.addListener(new FutureListener<R>() {
        @Override
        public void operationComplete(final Future<R> future) throws Exception {
            if (!future.isSuccess()) {
                tryFailure(future.cause());
                return;
            }

            if (task.condition(future)) {
                commandExecutor.getConnectionManager().getExecutor().execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            task.execute();
                        } catch (Exception e) {
                            tryFailure(e);
                            return;
                        }
                        trySuccess(future.getNow());
                    }
                });
            } else {
                trySuccess(future.getNow());
            }
        }
    });
}
 
Example 32
Project: JRediClients   File: MapWriteBehindListener.java   Source Code and License 5 votes vote down vote up
@Override
public void operationComplete(Future<R> future) throws Exception {
    if (future.isSuccess() && task.condition(future)) {
        enqueueRunnable(new Runnable() {
            @Override
            public void run() {
                try {
                    task.execute();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
    }
}
 
Example 33
Project: JRediClients   File: TransferListener.java   Source Code and License 5 votes vote down vote up
@Override
public void operationComplete(Future<T> future) throws Exception {
    if (!future.isSuccess()) {
        promise.tryFailure(future.cause());
        return;
    }
   
    promise.trySuccess(future.getNow());
}
 
Example 34
Project: JRediClients   File: NettyFuturePublisher.java   Source Code and License 5 votes vote down vote up
@Override
 public void subscribe(final Subscriber<? super T> subscriber) {
     try {
         subscriber.onSubscribe(new ReactiveSubscription<T>(this, subscriber) {

             @Override
             protected void onRequest(long n) {
                 supplier.get().addListener(new FutureListener<T>() {
                     @Override
                     public void operationComplete(Future<T> future) throws Exception {
                         if (!future.isSuccess()) {
                             onError(future.cause());
                             return;
                         }
                         
                         if (future.getNow() != null) {
                             onNext(future.getNow());
                         }
                         onComplete();
                     }
                 });
             }
         });
     } catch (Throwable throwable) {
//Exceptions.throwIfFatal(throwable);
         Exceptions.getFinalCause(throwable);
         subscriber.onError(throwable);
     }
 }
 
Example 35
Project: JRediClients   File: ConnectionPool.java   Source Code and License 5 votes vote down vote up
public RFuture<Void> add(final ClientConnectionsEntry entry) {
    final RPromise<Void> promise = connectionManager.newPromise();
    promise.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            entries.add(entry);
        }
    });
    initConnections(entry, promise, true);
    return promise;
}
 
Example 36
Project: JRediClients   File: MasterSlaveEntry.java   Source Code and License 5 votes vote down vote up
private void subscribe(final String channelName, final Collection<RedisPubSubListener<?>> listeners,
        final Codec subscribeCodec) {
    RFuture<PubSubConnectionEntry> subscribeFuture = connectionManager.subscribe(subscribeCodec, channelName, listeners.toArray(new RedisPubSubListener[listeners.size()]));
    subscribeFuture.addListener(new FutureListener<PubSubConnectionEntry>() {
        
        @Override
        public void operationComplete(Future<PubSubConnectionEntry> future)
                throws Exception {
            if (future.isSuccess()) {
                log.debug("resubscribed listeners of '{}' channel to {}", channelName, future.getNow().getConnection().getRedisClient());
            }
        }
    });
}
 
Example 37
Project: JRediClients   File: FutureConnectionListener.java   Source Code and License 5 votes vote down vote up
@Override
public void operationComplete(Future<Object> future) throws Exception {
    if (!future.isSuccess()) {
        connection.closeAsync();
        connectionPromise.tryFailure(future.cause());
        return;
    }
    if (commandsCounter.decrementAndGet() == 0) {
        connectionPromise.trySuccess(connection);
    }
}
 
Example 38
Project: JRediClients   File: MasterSlaveConnectionManager.java   Source Code and License 5 votes vote down vote up
private void subscribe(final String channelName, final RPromise<PubSubConnectionEntry> promise,
        final PubSubType type, final AsyncSemaphore lock, final PubSubConnectionEntry connEntry,
        final RedisPubSubListener<?>... listeners) {
    for (RedisPubSubListener<?> listener : listeners) {
        connEntry.addListener(channelName, listener);
    }
    connEntry.getSubscribeFuture(channelName, type).addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            lock.release();
            promise.trySuccess(connEntry);
        }
    });
}
 
Example 39
Project: dremio-oss   File: BasicClient.java   Source Code and License 5 votes vote down vote up
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
  if (!future.isSuccess()) {
    logger.error("Unable to maintain connection {}.  Closing connection.", connection.getName());
    connection.close();
  }
}
 
Example 40
Project: azeroth   File: FastdfsExecutor.java   Source Code and License 5 votes vote down vote up
@Override
public void operationComplete(Future<Channel> cf) throws Exception {

    if (cf.isCancelled()) {
        promise.cancel(true);
        return;
    }

    if (!cf.isSuccess()) {
        promise.completeExceptionally(cf.cause());
        return;
    }

    Channel channel = cf.getNow();
    promise.whenComplete((result, error) -> pool.release(channel));

    try {

        FastdfsOperation<T> fastdfsOperation = new FastdfsOperation<>(channel, requestor,
            replier, promise);
        if (LOG.isDebugEnabled()) {
            LOG.debug("execute {}", fastdfsOperation);
        }

        fastdfsOperation.execute();
    } catch (Exception e) {
        promise.completeExceptionally(e);
    }
}