List of usage examples for io.netty.util.concurrent Promise trySuccess
boolean trySuccess(V result);
From source file:com.linecorp.armeria.common.RequestContext.java
License:Apache License
/** * Resolves the specified {@code promise} with the specified {@code result} so that the {@code promise} is * marked as 'done'. If {@code promise} is done already, this method does the following: * <ul>/*from w w w.ja va 2 s . c o m*/ * <li>Log a warning about the failure, and</li> * <li>Release {@code result} if it is {@linkplain ReferenceCounted a reference-counted object}, * such as {@link ByteBuf} and {@link FullHttpResponse}.</li> * </ul> * Note that a {@link Promise} can be done already even if you did not call this method in the following * cases: * <ul> * <li>Invocation timeout - The invocation associated with the {@link Promise} has been timed out.</li> * <li>User error - A service implementation called any of the following methods more than once: * <ul> * <li>{@link #resolvePromise(Promise, Object)}</li> * <li>{@link #rejectPromise(Promise, Throwable)}</li> * <li>{@link Promise#setSuccess(Object)}</li> * <li>{@link Promise#setFailure(Throwable)}</li> * <li>{@link Promise#cancel(boolean)}</li> * </ul> * </li> * </ul> */ @Deprecated default void resolvePromise(Promise<?> promise, Object result) { @SuppressWarnings("unchecked") final Promise<Object> castPromise = (Promise<Object>) promise; if (castPromise.trySuccess(result)) { // Resolved successfully. return; } try { if (!(promise.cause() instanceof TimeoutException)) { // Log resolve failure unless it is due to a timeout. LoggerFactory.getLogger(RequestContext.class) .warn("Failed to resolve a completed promise ({}) with {}", promise, result); } } finally { ReferenceCountUtil.safeRelease(result); } }
From source file:com.linecorp.armeria.common.ServiceInvocationContext.java
License:Apache License
/** * Resolves the specified {@code promise} with the specified {@code result} so that the {@code promise} is * marked as 'done'. If {@code promise} is done already, this method does the following: * <ul>/*from w ww . j a v a2 s . co m*/ * <li>Log a warning about the failure, and</li> * <li>Release {@code result} if it is {@linkplain ReferenceCounted a reference-counted object}, * such as {@link ByteBuf} and {@link FullHttpResponse}.</li> * </ul> * Note that a {@link Promise} can be done already even if you did not call this method in the following * cases: * <ul> * <li>Invocation timeout - The invocation associated with the {@link Promise} has been timed out.</li> * <li>User error - A service implementation called any of the following methods more than once: * <ul> * <li>{@link #resolvePromise(Promise, Object)}</li> * <li>{@link #rejectPromise(Promise, Throwable)}</li> * <li>{@link Promise#setSuccess(Object)}</li> * <li>{@link Promise#setFailure(Throwable)}</li> * <li>{@link Promise#cancel(boolean)}</li> * </ul> * </li> * </ul> */ public void resolvePromise(Promise<?> promise, Object result) { @SuppressWarnings("unchecked") final Promise<Object> castPromise = (Promise<Object>) promise; if (castPromise.trySuccess(result)) { // Resolved successfully. return; } try { if (!(promise.cause() instanceof TimeoutException)) { // Log resolve failure unless it is due to a timeout. logger().warn("Failed to resolve a completed promise ({}) with {}", promise, result); } } finally { ReferenceCountUtil.safeRelease(result); } }
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/*from w w w . j a v a 2 s . co 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.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 w w w. j a va 2 s . c o 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: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 {/* ww w.j av a 2s .c om*/ 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();/*from w ww. j a v a2 s . c om*/ } } else { promise.tryFailure(future.cause()); } }
From source file:io.codis.nedis.NedisClientBuilder.java
License:Apache License
public Future<NedisClientImpl> connect(SocketAddress remoteAddress) { validateGroupConfig();//from w w w .ja v a 2s . c o m 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 void initialize(final Promise<NedisClient> promise, final NedisClientImpl client, State state) { switch (state) { case AUTH://from ww w .j av a 2 s . c o m if (password == null) { initialize(promise, client, State.SELECT); } else { client.auth0(password).addListener(new InitializeFutureListener(promise, client, State.SELECT)); } break; case SELECT: if (database == 0) { initialize(promise, client, State.CLIENT_SETNAME); } else { client.select0(database) .addListener(new InitializeFutureListener(promise, client, State.CLIENT_SETNAME)); } break; case CLIENT_SETNAME: if (clientName == null) { promise.trySuccess(client); } else { client.clientSetname0(clientName) .addListener(new InitializeFutureListener(promise, client, State.FINISH)); } break; case FINISH: promise.trySuccess(client); break; } }
From source file:io.codis.nedis.PromiseConverter.java
License:Apache License
public static PromiseConverter<List<byte[]>> toList(EventExecutor executor) { return new PromiseConverter<List<byte[]>>(executor) { @Override/*from w w w.jav a 2 s .c om*/ public FutureListener<Object> newListener(final Promise<List<byte[]>> promise) { return new FutureListener<Object>() { @SuppressWarnings("unchecked") @Override public void operationComplete(Future<Object> future) throws Exception { if (future.isSuccess()) { Object resp = future.getNow(); if (resp instanceof RedisResponseException) { promise.tryFailure((RedisResponseException) resp); } else if (resp == RedisResponseDecoder.NULL_REPLY) { promise.trySuccess(null); } else { promise.trySuccess((List<byte[]>) resp); } } else { promise.tryFailure(future.cause()); } } }; } }; }
From source file:io.codis.nedis.PromiseConverter.java
License:Apache License
public static PromiseConverter<Boolean> toBoolean(EventExecutor executor) { return new PromiseConverter<Boolean>(executor) { @Override//w ww . j a v a 2s .c o m public FutureListener<Object> newListener(final Promise<Boolean> promise) { return new FutureListener<Object>() { @Override public void operationComplete(Future<Object> future) throws Exception { if (future.isSuccess()) { Object resp = future.getNow(); if (resp instanceof RedisResponseException) { promise.tryFailure((RedisResponseException) resp); } else if (resp == RedisResponseDecoder.NULL_REPLY) { promise.trySuccess(false); } else if (resp instanceof String) { promise.trySuccess(true); } else { promise.trySuccess(((Long) resp).intValue() != 0); } } else { promise.tryFailure(future.cause()); } } }; } }; }