Example usage for io.netty.util.concurrent Promise tryFailure

List of usage examples for io.netty.util.concurrent Promise tryFailure

Introduction

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

Prototype

boolean tryFailure(Throwable cause);

Source Link

Document

Marks this future as a failure and notifies all listeners.

Usage

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

License:Open Source License

/**
 * Creates and connects a new channel. The initial connection attempt may be delayed to accommodate exponential
 * back-off requirements.//from   w  w  w  . j  av  a 2s  . c o m
 *
 * @param channelReadyPromise the promise to be notified when a channel has been created and connected to the APNs
 * server
 *
 * @return a future that will be notified once a channel has been created and connected to the APNs server
 */
@Override
public Future<Channel> create(final Promise<Channel> channelReadyPromise) {
    final long delay = this.currentDelaySeconds.get();

    channelReadyPromise.addListener(new GenericFutureListener<Future<Channel>>() {

        @Override
        public void operationComplete(final Future<Channel> future) {
            final long updatedDelay = future.isSuccess() ? 0
                    : Math.max(Math.min(delay * 2, MAX_CONNECT_DELAY_SECONDS), MIN_CONNECT_DELAY_SECONDS);

            ApnsChannelFactory.this.currentDelaySeconds.compareAndSet(delay, updatedDelay);
        }
    });

    this.bootstrapTemplate.config().group().schedule(new Runnable() {

        @Override
        public void run() {

            final Bootstrap bootstrap = ApnsChannelFactory.this.bootstrapTemplate.clone()
                    .channelFactory(new AugmentingReflectiveChannelFactory<>(
                            ClientChannelClassUtil.getSocketChannelClass(
                                    ApnsChannelFactory.this.bootstrapTemplate.config().group()),
                            CHANNEL_READY_PROMISE_ATTRIBUTE_KEY, channelReadyPromise));

            final ChannelFuture connectFuture = bootstrap.connect();

            connectFuture.addListener(new GenericFutureListener<ChannelFuture>() {

                @Override
                public void operationComplete(final ChannelFuture future) {
                    if (!future.isSuccess()) {
                        // This may seem spurious, but our goal here is to accurately report the cause of
                        // connection failure; if we just wait for connection closure, we won't be able to
                        // tell callers anything more specific about what went wrong.
                        tryFailureAndLogRejectedCause(channelReadyPromise, future.cause());
                    }
                }
            });

            connectFuture.channel().closeFuture().addListener(new GenericFutureListener<ChannelFuture>() {

                @Override
                public void operationComplete(final ChannelFuture future) {
                    // We always want to try to fail the "channel ready" promise if the connection closes; if it has
                    // already succeeded, this will have no effect.
                    channelReadyPromise.tryFailure(
                            new IllegalStateException("Channel closed before HTTP/2 preface completed."));
                }
            });

        }
    }, delay, TimeUnit.SECONDS);

    return channelReadyPromise;
}

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

License:Open Source License

private static void tryFailureAndLogRejectedCause(final Promise<?> promise, final Throwable cause) {
    if (!promise.tryFailure(cause)) {
        log.warn("Tried to mark promise as \"failed,\" but it was already done.", cause);
    }//from w  w w  . jav  a 2  s. c o m
}

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

License:Open Source License

/**
 * <p>Asynchronously acquires a channel from this channel pool. The acquired channel may be a pre-existing channel
 * stored in the pool or may be a new channel created on demand. If no channels are available and the pool is at
 * capacity, acquisition may be delayed until another caller releases a channel to the pool.</p>
 *
 * <p>When callers are done with a channel, they <em>must</em> release the channel back to the pool via the
 * {@link ApnsChannelPool#release(Channel)} method.</p>
 *
 * @return a {@code Future} that will be notified when a channel is available
 *
 * @see ApnsChannelPool#release(Channel)
 *//*  w ww  .j  ava  2s  .c  o  m*/
Future<Channel> acquire() {
    final Promise<Channel> acquirePromise = new DefaultPromise<>(this.executor);

    if (this.executor.inEventLoop()) {
        this.acquireWithinEventExecutor(acquirePromise);
    } else {
        this.executor.submit(new Runnable() {
            @Override
            public void run() {
                ApnsChannelPool.this.acquireWithinEventExecutor(acquirePromise);
            }
        }).addListener(new GenericFutureListener() {
            @Override
            public void operationComplete(final Future future) throws Exception {
                if (!future.isSuccess()) {
                    acquirePromise.tryFailure(future.cause());
                }
            }
        });
    }

    return acquirePromise;
}

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

License:Open Source License

private void acquireWithinEventExecutor(final Promise<Channel> acquirePromise) {
    assert this.executor.inEventLoop();

    if (!this.isClosed) {
        // We always want to open new channels if we have spare capacity. Once the pool is full, we'll start looking
        // for idle, pre-existing channels.
        if (this.allChannels.size() + this.pendingCreateChannelFutures.size() < this.capacity) {
            final Future<Channel> createChannelFuture = this.channelFactory
                    .create(executor.<Channel>newPromise());
            this.pendingCreateChannelFutures.add(createChannelFuture);

            createChannelFuture.addListener(new GenericFutureListener<Future<Channel>>() {

                @Override/*w w w. j a  v a 2  s  . c o  m*/
                public void operationComplete(final Future<Channel> future) {
                    ApnsChannelPool.this.pendingCreateChannelFutures.remove(createChannelFuture);

                    if (future.isSuccess()) {
                        final Channel channel = future.getNow();

                        ApnsChannelPool.this.allChannels.add(channel);
                        ApnsChannelPool.this.metricsListener.handleConnectionAdded();

                        acquirePromise.trySuccess(channel);
                    } else {
                        ApnsChannelPool.this.metricsListener.handleConnectionCreationFailed();

                        acquirePromise.tryFailure(future.cause());

                        // If we failed to open a connection, this is the end of the line for this acquisition
                        // attempt, and callers won't be able to release the channel (since they didn't get one
                        // in the first place). Move on to the next acquisition attempt if one is present.
                        ApnsChannelPool.this.handleNextAcquisition();
                    }
                }
            });
        } else {
            final Channel channelFromIdlePool = ApnsChannelPool.this.idleChannels.poll();

            if (channelFromIdlePool != null) {
                if (channelFromIdlePool.isActive()) {
                    acquirePromise.trySuccess(channelFromIdlePool);
                } else {
                    // The channel from the idle pool isn't usable; discard it and create a new one instead
                    this.discardChannel(channelFromIdlePool);
                    this.acquireWithinEventExecutor(acquirePromise);
                }
            } else {
                // We don't have any connections ready to go, and don't have any more capacity to create new
                // channels. Add this acquisition to the queue waiting for channels to become available.
                pendingAcquisitionPromises.add(acquirePromise);
            }
        }
    } else {
        acquirePromise.tryFailure(POOL_CLOSED_EXCEPTION);
    }
}

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

License:Open Source License

/**
 * Shuts down this channel pool and releases all retained resources.
 *
 * @return a {@code Future} that will be completed when all resources held by this pool have been released
 *//*w  w w  .ja  v  a 2  s  .co m*/
public Future<Void> close() {
    return this.allChannels.close().addListener(new GenericFutureListener<Future<Void>>() {
        @Override
        public void operationComplete(final Future<Void> future) throws Exception {
            ApnsChannelPool.this.isClosed = true;

            if (ApnsChannelPool.this.channelFactory instanceof Closeable) {
                ((Closeable) ApnsChannelPool.this.channelFactory).close();
            }

            for (final Promise<Channel> acquisitionPromise : ApnsChannelPool.this.pendingAcquisitionPromises) {
                acquisitionPromise.tryFailure(POOL_CLOSED_EXCEPTION);
            }
        }
    });
}

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

License:Open Source License

@Override
public void onStreamClosed(final Http2Stream stream) {
    // Always try to fail promises associated with closed streams; most of the time, this should fail silently, but
    // in cases of unexpected closure, it will make sure that nothing gets left hanging.
    final Promise<PushNotificationResponse<ApnsPushNotification>> responsePromise = stream
            .getProperty(this.responsePromisePropertyKey);

    if (responsePromise != null) {
        final Throwable cause;

        if (stream.getProperty(this.streamErrorCausePropertyKey) != null) {
            cause = stream.getProperty(this.streamErrorCausePropertyKey);
        } else if (this.connectionErrorCause != null) {
            cause = this.connectionErrorCause;
        } else {//from ww  w. j a  v a 2s . c om
            cause = STREAM_CLOSED_BEFORE_REPLY_EXCEPTION;
        }

        responsePromise.tryFailure(cause);
    }
}

From source file:de.unipassau.isl.evs.ssh.app.handler.AbstractAppHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
private boolean setPromiseResult(Promise promise, Message.AddressedMessage message) {
    final MessagePayload payload = message.getPayloadChecked(MessagePayload.class);
    if (payload instanceof ErrorPayload) {
        return promise.tryFailure((ErrorPayload) payload);
    } else {//w w  w  . j  a va2  s .  com
        return promise.trySuccess(payload);
    }
}

From source file:io.airlift.drift.transport.netty.client.ConnectionFactory.java

License:Apache License

private static void notifyConnect(ChannelFuture future, Promise<Channel> promise) {
    if (future.isSuccess()) {
        Channel channel = future.channel();
        if (!promise.trySuccess(channel)) {
            // Promise was completed in the meantime (likely cancelled), just release the channel again
            channel.close();/*w  w w.jav  a 2  s  .  c o m*/
        }
    } else {
        promise.tryFailure(future.cause());
    }
}

From source file:io.codis.nedis.NedisClientBuilder.java

License:Apache License

public Future<NedisClientImpl> connect(SocketAddress remoteAddress) {
    validateGroupConfig();//from ww  w  .  j a  v  a 2s  .com
    Bootstrap b = new Bootstrap().group(group).channel(channelClass).handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new RedisResponseDecoder(),
                    new RedisDuplexHandler(TimeUnit.MILLISECONDS.toNanos(timeoutMs)));
        }

    });
    if (timeoutMs > 0) {
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) Math.min(Integer.MAX_VALUE, timeoutMs));
    }
    ChannelFuture f = b.connect(remoteAddress);
    final Promise<NedisClientImpl> promise = f.channel().eventLoop().newPromise();
    f.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                promise.trySuccess(new NedisClientImpl(future.channel(), pool));
            } else {
                promise.tryFailure(future.cause());
            }
        }
    });
    return promise;
}

From source file:io.codis.nedis.NedisClientPoolImpl.java

License:Apache License

private Future<NedisClient> newClient() {
    Future<NedisClientImpl> f = NedisClientBuilder.create().group(group).channel(channelClass)
            .timeoutMs(timeoutMs).belongTo(this).connect(remoteAddress);

    final Promise<NedisClient> promise = getEventExecutor(f).newPromise();
    f.addListener(new FutureListener<NedisClientImpl>() {

        @Override/*  w  ww .  java2s. c  o m*/
        public void operationComplete(Future<NedisClientImpl> future) throws Exception {
            if (future.isSuccess()) {
                initialize(promise, future.getNow(), State.AUTH);
            } else {
                promise.tryFailure(future.cause());
            }
        }

    });
    return promise;
}