List of usage examples for io.netty.channel ChannelFuture getNow
V getNow();
From source file:com.relayrides.pushy.apns.ApnsClient.java
License:Open Source License
/** * <p>Sends a push notification to the APNs gateway.</p> * * <p>This method returns a {@code Future} that indicates whether the notification was accepted or rejected by the * gateway. If the notification was accepted, it may be delivered to its destination device at some time in the * future, but final delivery is not guaranteed. Rejections should be considered permanent failures, and callers * should <em>not</em> attempt to re-send the notification.</p> * * <p>The returned {@code Future} may fail with an exception if the notification could not be sent. Failures to * <em>send</em> a notification to the gatewayi.e. those that fail with exceptionsshould generally be considered * non-permanent, and callers should attempt to re-send the notification when the underlying problem has been * resolved.</p>/*from w w w. ja v a2 s .co m*/ * * <p>In particular, attempts to send a notification when the client is not connected will fail with a * {@link ClientNotConnectedException}. If the client was previously connected and has not been explicitly * disconnected (via the {@link ApnsClient#disconnect()} method), the client will attempt to reconnect * automatically. Callers may wait for a reconnection attempt to complete by waiting for the {@code Future} returned * by the {@link ApnsClient#getReconnectionFuture()} method.</p> * * @param notification the notification to send to the APNs gateway * * @param <T> the type of notification to be sent * * @return a {@code Future} that will complete when the notification has been either accepted or rejected by the * APNs gateway * * @since 0.8 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public <T extends ApnsPushNotification> Future<PushNotificationResponse<T>> sendNotification( final T notification) { final Future<PushNotificationResponse<T>> responseFuture; final long notificationId = this.nextNotificationId.getAndIncrement(); // Instead of synchronizing here, we keep a final reference to the connection ready promise. We can get away // with this because we're not changing the state of the connection or its promises. Keeping a reference ensures // we won't suddenly "lose" the channel and get a NullPointerException, but risks sending a notification after // things have shut down. In that case, though, the returned futures should fail quickly, and the benefit of // not synchronizing for every write seems worth it. final ChannelPromise connectionReadyPromise = this.connectionReadyPromise; if (connectionReadyPromise != null && connectionReadyPromise.isSuccess() && connectionReadyPromise.channel().isActive()) { final Channel channel = connectionReadyPromise.channel(); final Promise<PushNotificationResponse<ApnsPushNotification>> responsePromise = new DefaultPromise( channel.eventLoop()); channel.writeAndFlush(new PushNotificationAndResponsePromise(notification, responsePromise)) .addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { ApnsClient.this.metricsListener.handleNotificationSent(ApnsClient.this, notificationId); } else { responsePromise.tryFailure(future.cause()); } } }); responseFuture = (Future) responsePromise; } else { log.debug("Failed to send push notification because client is not connected: {}", notification); responseFuture = new FailedFuture<>(GlobalEventExecutor.INSTANCE, NOT_CONNECTED_EXCEPTION); } responseFuture.addListener(new GenericFutureListener<Future<PushNotificationResponse<T>>>() { @Override public void operationComplete(final Future<PushNotificationResponse<T>> future) throws Exception { if (future.isSuccess()) { final PushNotificationResponse<T> response = future.getNow(); if (response.isAccepted()) { ApnsClient.this.metricsListener.handleNotificationAccepted(ApnsClient.this, notificationId); } else { ApnsClient.this.metricsListener.handleNotificationRejected(ApnsClient.this, notificationId); } } else { ApnsClient.this.metricsListener.handleWriteFailure(ApnsClient.this, notificationId); } } }); return responseFuture; }
From source file:com.turo.pushy.apns.ApnsClient.java
License:Open Source License
/** * <p>Sends a push notification to the APNs gateway.</p> * * <p>This method returns a {@code Future} that indicates whether the notification was accepted or rejected by the * gateway. If the notification was accepted, it may be delivered to its destination device at some time in the * future, but final delivery is not guaranteed. Rejections should be considered permanent failures, and callers * should <em>not</em> attempt to re-send the notification.</p> * * <p>The returned {@code Future} may fail with an exception if the notification could not be sent. Failures to * <em>send</em> a notification to the gatewayi.e. those that fail with exceptionsshould generally be considered * non-permanent, and callers should attempt to re-send the notification when the underlying problem has been * resolved.</p>//from w w w . ja v a 2 s . c om * * @param notification the notification to send to the APNs gateway * * @param <T> the type of notification to be sent * * @return a {@code Future} that will complete when the notification has been either accepted or rejected by the * APNs gateway * * @see com.turo.pushy.apns.util.concurrent.PushNotificationResponseListener * * @since 0.8 */ @SuppressWarnings("unchecked") public <T extends ApnsPushNotification> PushNotificationFuture<T, PushNotificationResponse<T>> sendNotification( final T notification) { final PushNotificationFuture<T, PushNotificationResponse<T>> responseFuture; if (!this.isClosed.get()) { final PushNotificationPromise<T, PushNotificationResponse<T>> responsePromise = new PushNotificationPromise<>( this.eventLoopGroup.next(), notification); final long notificationId = this.nextNotificationId.getAndIncrement(); this.channelPool.acquire().addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> acquireFuture) throws Exception { if (acquireFuture.isSuccess()) { final Channel channel = acquireFuture.getNow(); channel.writeAndFlush(responsePromise) .addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { ApnsClient.this.metricsListener.handleNotificationSent(ApnsClient.this, notificationId); } } }); ApnsClient.this.channelPool.release(channel); } else { responsePromise.tryFailure(acquireFuture.cause()); } } }); responsePromise.addListener(new PushNotificationResponseListener<T>() { @Override public void operationComplete(final PushNotificationFuture<T, PushNotificationResponse<T>> future) throws Exception { if (future.isSuccess()) { final PushNotificationResponse response = future.getNow(); if (response.isAccepted()) { ApnsClient.this.metricsListener.handleNotificationAccepted(ApnsClient.this, notificationId); } else { ApnsClient.this.metricsListener.handleNotificationRejected(ApnsClient.this, notificationId); } } else { ApnsClient.this.metricsListener.handleWriteFailure(ApnsClient.this, notificationId); } } }); responseFuture = responsePromise; } else { final PushNotificationPromise<T, PushNotificationResponse<T>> failedPromise = new PushNotificationPromise<>( GlobalEventExecutor.INSTANCE, notification); failedPromise.setFailure(CLIENT_CLOSED_EXCEPTION); responseFuture = failedPromise; } return responseFuture; }
From source file:org.acmsl.katas.antlr4netty.InterpreterServer.java
License:Open Source License
/** * Wraps given {@link ChannelFuture} to ensure the event loops * shut down gracefully./* ww w. j av a 2 s . co m*/ * @param target the original channel future. * @param bossGroup the boss group. * @param workerGroup the worker group. * @return the wrapped future. */ @NotNull protected ChannelFuture wrap(@NotNull final ChannelFuture target, @NotNull final NioEventLoopGroup bossGroup, @NotNull final NioEventLoopGroup workerGroup) { return new ChannelFuture() { @Override public Channel channel() { return target.channel(); } /** * {@inheritDoc} */ @Override public ChannelFuture addListener( @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) { return target.addListener(listener); } /** * {@inheritDoc} */ @Override public ChannelFuture addListeners( @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) { return target.addListeners(listeners); } /** * {@inheritDoc} */ @Override public ChannelFuture removeListener( @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) { return target.removeListener(listener); } /** * {@inheritDoc} */ @Override public ChannelFuture removeListeners( @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) { return target.removeListeners(listeners); } /** * {@inheritDoc} */ @Override public ChannelFuture sync() throws InterruptedException { ChannelFuture result = null; try { result = target.sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } return result; } /** * {@inheritDoc} */ @Override public ChannelFuture syncUninterruptibly() { return target.syncUninterruptibly(); } /** * {@inheritDoc} */ @Override public ChannelFuture await() throws InterruptedException { return target.await(); } /** * {@inheritDoc} */ @Override public ChannelFuture awaitUninterruptibly() { return target.awaitUninterruptibly(); } /** * {@inheritDoc} */ @Override public boolean isSuccess() { return target.isSuccess(); } /** * {@inheritDoc} */ @Override public boolean isCancellable() { return target.isCancellable(); } /** * {@inheritDoc} */ @Override public Throwable cause() { return target.cause(); } /** * {@inheritDoc} */ @Override public boolean await(final long timeout, @NotNull final TimeUnit unit) throws InterruptedException { return target.await(timeout, unit); } /** * {@inheritDoc} */ @Override public boolean await(final long timeoutMillis) throws InterruptedException { return target.await(timeoutMillis); } /** * {@inheritDoc} */ @Override public boolean awaitUninterruptibly(final long timeout, @NotNull final TimeUnit unit) { return target.awaitUninterruptibly(timeout, unit); } /** * {@inheritDoc} */ @Override public boolean awaitUninterruptibly(final long timeoutMillis) { return target.awaitUninterruptibly(timeoutMillis); } /** * {@inheritDoc} */ @Override public Void getNow() { return target.getNow(); } /** * {@inheritDoc} */ @Override public boolean cancel(final boolean mayInterruptIfRunning) { return target.cancel(mayInterruptIfRunning); } /** * {@inheritDoc} */ @Override public boolean isCancelled() { return target.isCancelled(); } /** * {@inheritDoc} */ @Override public boolean isDone() { return target.isDone(); } /** * {@inheritDoc} */ @Override public Void get() throws InterruptedException, ExecutionException { return target.get(); } /** * {@inheritDoc} */ @Override public Void get(final long timeout, @NotNull final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return target.get(timeout, unit); } }; }
From source file:org.redisson.CommandBatchExecutorService.java
License:Apache License
public void execute(final Entry entry, final int slot, final Promise<Void> mainPromise, final AtomicInteger slots, final int attempt) { if (!connectionManager.getShutdownLatch().acquire()) { mainPromise.setFailure(new IllegalStateException("Redisson is shutdown")); return;/*from w w w .j ava 2 s. com*/ } final Promise<Void> attemptPromise = connectionManager.newPromise(); final AtomicReference<RedisException> ex = new AtomicReference<RedisException>(); final TimerTask retryTimerTask = new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (attemptPromise.isDone()) { return; } if (attempt == connectionManager.getConfig().getRetryAttempts()) { attemptPromise.setFailure(ex.get()); return; } attemptPromise.cancel(true); int count = attempt + 1; execute(entry, slot, mainPromise, slots, count); } }; try { org.redisson.client.RedisConnection connection; if (entry.isReadOnlyMode()) { connection = connectionManager.connectionReadOp(slot); } else { connection = connectionManager.connectionWriteOp(slot); } ArrayList<CommandData<?, ?>> list = new ArrayList<CommandData<?, ?>>(entry.getCommands().size()); for (CommandEntry c : entry.getCommands()) { list.add(c.getCommand()); } ChannelFuture future = connection.send(new CommandsData(attemptPromise, list)); ex.set(new RedisTimeoutException()); final Timeout timeout = connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getTimeout(), TimeUnit.MILLISECONDS); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { timeout.cancel(); ex.set(new WriteRedisConnectionException("channel: " + future.channel() + " closed")); connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS); } } }); if (entry.isReadOnlyMode()) { attemptPromise.addListener(connectionManager.createReleaseReadListener(slot, connection, timeout)); } else { attemptPromise.addListener(connectionManager.createReleaseWriteListener(slot, connection, timeout)); } } catch (RedisException e) { ex.set(e); connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS); } attemptPromise.addListener(new FutureListener<Void>() { @Override public void operationComplete(Future<Void> future) throws Exception { if (future.isCancelled()) { return; } if (future.cause() instanceof RedisMovedException) { RedisMovedException ex = (RedisMovedException) future.cause(); execute(entry, ex.getSlot(), mainPromise, slots, attempt); return; } if (future.isSuccess()) { if (slots.decrementAndGet() == 0) { mainPromise.setSuccess(future.getNow()); } } else { mainPromise.setFailure(future.cause()); } } }); }
From source file:org.redisson.CommandExecutorService.java
License:Apache License
protected <V, R> void async(final boolean readOnlyMode, final int slot, final MultiDecoder<Object> messageDecoder, final Codec codec, final RedisCommand<V> command, final Object[] params, final Promise<R> mainPromise, final int attempt) { if (!connectionManager.getShutdownLatch().acquire()) { mainPromise.setFailure(new IllegalStateException("Redisson is shutdown")); return;//ww w .j a v a2s .c o m } final Promise<R> attemptPromise = connectionManager.newPromise(); final AtomicReference<RedisException> ex = new AtomicReference<RedisException>(); final TimerTask retryTimerTask = new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (attemptPromise.isDone()) { return; } if (attempt == connectionManager.getConfig().getRetryAttempts()) { attemptPromise.setFailure(ex.get()); return; } if (!attemptPromise.cancel(false)) { return; } int count = attempt + 1; async(readOnlyMode, slot, messageDecoder, codec, command, params, mainPromise, count); } }; try { org.redisson.client.RedisConnection connection; if (readOnlyMode) { connection = connectionManager.connectionReadOp(slot); } else { connection = connectionManager.connectionWriteOp(slot); } log.debug("getting connection for command {} via slot {} using {}", command, slot, connection.getRedisClient().getAddr()); ChannelFuture future = connection .send(new CommandData<V, R>(attemptPromise, messageDecoder, codec, command, params)); ex.set(new RedisTimeoutException()); final Timeout timeout = connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getTimeout(), TimeUnit.MILLISECONDS); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { timeout.cancel(); ex.set(new WriteRedisConnectionException("Can't send command: " + command + ", params: " + params + ", channel: " + future.channel(), future.cause())); connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS); } } }); if (readOnlyMode) { attemptPromise.addListener(connectionManager.createReleaseReadListener(slot, connection, timeout)); } else { attemptPromise.addListener(connectionManager.createReleaseWriteListener(slot, connection, timeout)); } } catch (RedisException e) { ex.set(e); connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS); } attemptPromise.addListener(new FutureListener<R>() { @Override public void operationComplete(Future<R> future) throws Exception { if (future.isCancelled()) { return; } // TODO cancel timeout if (future.cause() instanceof RedisMovedException) { RedisMovedException ex = (RedisMovedException) future.cause(); connectionManager.getTimer().newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS); async(readOnlyMode, ex.getSlot(), messageDecoder, codec, command, params, mainPromise, attempt); return; } if (future.isSuccess()) { mainPromise.setSuccess(future.getNow()); } else { mainPromise.setFailure(future.cause()); } } }); }
From source file:org.skfiy.typhon.net.Netty4Connector.java
License:Apache License
@Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING);/* w ww .ja v a2 s . c o m*/ ChannelFuture channelFuture = channel.closeFuture(); serverBootstrap.group().shutdownGracefully(); serverBootstrap.childGroup().shutdownGracefully(); channelFuture.getNow(); fireLifecycleListener(STOP_EVENT); }