Example usage for io.netty.util.concurrent Future cause

List of usage examples for io.netty.util.concurrent Future cause

Introduction

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

Prototype

Throwable cause();

Source Link

Document

Returns the cause of the failed I/O operation if the I/O operation has failed.

Usage

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

License:Open Source License

private void discardChannel(final Channel channel) {
    assert this.executor.inEventLoop();

    this.idleChannels.remove(channel);
    this.allChannels.remove(channel);

    this.metricsListener.handleConnectionRemoved();

    this.channelFactory.destroy(channel, this.executor.<Void>newPromise())
            .addListener(new GenericFutureListener<Future<Void>>() {
                @Override/*from   w ww .j  ava 2 s  .c  o  m*/
                public void operationComplete(final Future<Void> destroyFuture) throws Exception {
                    if (!destroyFuture.isSuccess()) {
                        log.warn("Failed to destroy channel.", destroyFuture.cause());
                    }
                }
            });
}

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.  j a v  a 2  s .c  o m
 *
 * @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:com.turo.pushy.apns.ApnsClientTest.java

License:Open Source License

@Test
@Parameters({ "true", "false" })
public void testSendNotificationToUntrustedServer(final boolean useTokenAuthentication) throws Exception {
    final ApnsClient cautiousClient;

    if (useTokenAuthentication) {
        cautiousClient = new ApnsClientBuilder().setApnsServer(HOST, PORT).setSigningKey(this.signingKey)
                .setEventLoopGroup(CLIENT_EVENT_LOOP_GROUP).build();
    } else {/*from   w w w  .j a  v  a2  s  .  co  m*/
        try (final InputStream p12InputStream = getClass()
                .getResourceAsStream(MULTI_TOPIC_CLIENT_KEYSTORE_FILENAME)) {
            cautiousClient = new ApnsClientBuilder().setApnsServer(HOST, PORT)
                    .setClientCredentials(p12InputStream, KEYSTORE_PASSWORD)
                    .setEventLoopGroup(CLIENT_EVENT_LOOP_GROUP).build();
        }
    }

    final MockApnsServer server = this.buildServer(new AcceptAllPushNotificationHandlerFactory());

    try {
        server.start(PORT).await();

        final Future<PushNotificationResponse<SimpleApnsPushNotification>> sendFuture = cautiousClient
                .sendNotification(new SimpleApnsPushNotification(DEVICE_TOKEN, TOPIC, PAYLOAD)).await();

        assertFalse("Clients must not connect to untrusted servers.", sendFuture.isSuccess());

        assertTrue("Clients should refuse to connect to untrusted servers due to an SSL handshake failure.",
                sendFuture.cause() instanceof SSLHandshakeException);
    } finally {
        cautiousClient.close().await();
        server.shutdown().await();
    }
}

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

License:Open Source License

@Test
@Parameters({ "true", "false" })
public void testSendManyNotifications(final boolean useTokenAuthentication) throws Exception {
    final int notificationCount = 1000;

    final List<SimpleApnsPushNotification> pushNotifications = new ArrayList<>();

    for (int i = 0; i < notificationCount; i++) {
        final String token = ApnsClientTest.generateRandomDeviceToken();
        final String payload = ApnsClientTest.generateRandomPayload();

        pushNotifications.add(new SimpleApnsPushNotification(token, TOPIC, payload));
    }//  ww  w  . j a va2  s .  c  om

    final List<Future<PushNotificationResponse<SimpleApnsPushNotification>>> futures = new ArrayList<>();

    final MockApnsServer server = this.buildServer(new AcceptAllPushNotificationHandlerFactory());
    final ApnsClient client = useTokenAuthentication ? this.buildTokenAuthenticationClient()
            : this.buildTlsAuthenticationClient();

    try {
        server.start(PORT).await();

        for (final SimpleApnsPushNotification pushNotification : pushNotifications) {
            futures.add(client.sendNotification(pushNotification));
        }

        for (final Future<PushNotificationResponse<SimpleApnsPushNotification>> future : futures) {
            future.await();

            assertTrue("Send future should have succeeded, but failed with: " + future.cause(),
                    future.isSuccess());
        }
    } finally {
        client.close().await();
        server.shutdown().await();
    }
}

From source file:com.turo.pushy.apns.server.BaseHttp2Server.java

License:Open Source License

BaseHttp2Server(final SslContext sslContext, final EventLoopGroup eventLoopGroup) {

    this.sslContext = sslContext;

    if (this.sslContext instanceof ReferenceCounted) {
        ((ReferenceCounted) this.sslContext).retain();
    }//from   w w  w . j  a  v  a 2s.  c o m

    this.bootstrap = new ServerBootstrap();

    if (eventLoopGroup != null) {
        this.bootstrap.group(eventLoopGroup);
        this.shouldShutDownEventLoopGroup = false;
    } else {
        this.bootstrap.group(new NioEventLoopGroup(1));
        this.shouldShutDownEventLoopGroup = true;
    }

    this.allChannels = new DefaultChannelGroup(this.bootstrap.config().group().next());

    this.bootstrap.channel(ServerChannelClassUtil.getServerSocketChannelClass(this.bootstrap.config().group()));
    this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) {
            final SslHandler sslHandler = sslContext.newHandler(channel.alloc());
            channel.pipeline().addLast(sslHandler);
            channel.pipeline().addLast(ConnectionNegotiationErrorHandler.INSTANCE);

            sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(final Future<Channel> handshakeFuture) throws Exception {
                    if (handshakeFuture.isSuccess()) {
                        BaseHttp2Server.this.addHandlersToPipeline(sslHandler.engine().getSession(),
                                channel.pipeline());
                        channel.pipeline().remove(ConnectionNegotiationErrorHandler.INSTANCE);

                        BaseHttp2Server.this.allChannels.add(channel);
                    } else {
                        log.debug("TLS handshake failed.", handshakeFuture.cause());
                    }
                }
            });
        }
    });
}

From source file:com.twitter.http2.PipeTest.java

License:Apache License

@Test
public void testCS() {
    pipe.close();

    Future<Void> sendFuture = pipe.send(MESSAGE);
    assertNotNull(sendFuture.cause());
}

From source file:com.twitter.http2.PipeTest.java

License:Apache License

@Test
public void testCR() {
    pipe.close();

    Future<Object> recvFuture = pipe.receive();
    assertNotNull(recvFuture.cause());
}

From source file:com.twitter.http2.PipeTest.java

License:Apache License

@Test
public void testCSR() {
    pipe.close();/*from  w  w w.  j a  va  2s. co  m*/

    Future<Void> sendFuture = pipe.send(MESSAGE);
    assertNotNull(sendFuture.cause());

    Future<Object> recvFuture = pipe.receive();
    assertNotNull(recvFuture.cause());
    assertNotNull(sendFuture.cause());
}

From source file:com.twitter.http2.PipeTest.java

License:Apache License

@Test
public void testSRCS() {
    Future<Void> sendFuture1 = pipe.send(MESSAGE1);
    assertFalse(sendFuture1.isDone());/*w  w w  .  j  av  a 2 s  . c o  m*/

    Future<Object> recvFuture = pipe.receive();
    assertSame(MESSAGE1, recvFuture.getNow());
    assertTrue(sendFuture1.isSuccess());

    pipe.close();

    Future<Void> sendFuture2 = pipe.send(MESSAGE2);
    assertNotNull(sendFuture2.cause());
}

From source file:com.twitter.http2.PipeTest.java

License:Apache License

@Test
public void testSRCR() {
    Future<Void> sendFuture = pipe.send(MESSAGE);
    assertFalse(sendFuture.isDone());/*from  ww w. java 2 s  .c  o m*/

    Future<Object> recvFuture1 = pipe.receive();
    assertSame(MESSAGE, recvFuture1.getNow());
    assertTrue(sendFuture.isSuccess());

    pipe.close();

    Future<Object> recvFuture2 = pipe.receive();
    assertNotNull(recvFuture2.cause());
    assertTrue(sendFuture.isSuccess());
}