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

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

Introduction

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

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

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  .  jav a  2s.  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>/*  w w w  .  j  av  a  2s .co 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.ApnsClientBenchmark.java

License:Open Source License

@Benchmark
@BenchmarkMode(Mode.SingleShotTime)//from w w w. j  a v  a2 s .co m
@Threads(1)
@Measurement(iterations = 20, batchSize = 1)
@Warmup(iterations = 20, batchSize = 1)
public long testSendNotifications() throws InterruptedException {
    final CountDownLatch countDownLatch = new CountDownLatch(this.pushNotifications.size());

    for (final SimpleApnsPushNotification notification : this.pushNotifications) {
        this.client.sendNotification(notification).addListener(
                new GenericFutureListener<Future<PushNotificationResponse<SimpleApnsPushNotification>>>() {

                    @Override
                    public void operationComplete(
                            final Future<PushNotificationResponse<SimpleApnsPushNotification>> future) {
                        if (future.isSuccess()) {
                            countDownLatch.countDown();
                        }
                    }
                });
    }

    countDownLatch.await();
    return countDownLatch.getCount();
}

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 {/* ww w.ja v a2  s.c  om*/
        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 testSendNotificationAfterClose(final boolean useTokenAuthentication) throws Exception {
    final MockApnsServer server = this.buildServer(new AcceptAllPushNotificationHandlerFactory());
    final ApnsClient client = useTokenAuthentication ? this.buildTokenAuthenticationClient()
            : this.buildTlsAuthenticationClient();

    try {//from  w  w w  .ja va  2 s. co m
        server.start(PORT).await();
        client.close().await();

        final SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(DEVICE_TOKEN, TOPIC,
                PAYLOAD);

        final Future<PushNotificationResponse<SimpleApnsPushNotification>> sendFuture = client
                .sendNotification(pushNotification).await();

        assertFalse("Once a client has closed, attempts to send push notifications should fail.",
                sendFuture.isSuccess());
    } finally {
        client.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));
    }//from   w  ww  .  j  a v a 2  s.  c  o m

    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.ApnsClientTest.java

License:Open Source License

@Test
@Parameters({ "true", "false" })
public void testSendManyNotificationsWithListeners(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));
    }//from   ww  w.ja v  a2 s  .co m

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

    final CountDownLatch countDownLatch = new CountDownLatch(notificationCount);

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

        for (final SimpleApnsPushNotification pushNotification : pushNotifications) {
            final Future<PushNotificationResponse<SimpleApnsPushNotification>> future = client
                    .sendNotification(pushNotification);

            future.addListener(
                    new GenericFutureListener<Future<PushNotificationResponse<SimpleApnsPushNotification>>>() {

                        @Override
                        public void operationComplete(
                                final Future<PushNotificationResponse<SimpleApnsPushNotification>> future) {
                            if (future.isSuccess()) {
                                countDownLatch.countDown();
                            }
                        }
                    });
        }

        countDownLatch.await();
    } finally {
        client.close().await();
        server.shutdown().await();
    }
}

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

License:Open Source License

@Test
@Parameters({ "true", "false" })
public void testRepeatedlySendNotificationAfterConnectionFailure(final boolean useTokenAuthentication)
        throws Exception {
    final ApnsClient client = useTokenAuthentication ? this.buildTokenAuthenticationClient()
            : this.buildTlsAuthenticationClient();

    try {/* w w  w.ja  va  2  s.  c  o m*/
        final SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(DEVICE_TOKEN, TOPIC,
                PAYLOAD);

        for (int i = 0; i < 3; i++) {
            // We should see delays of roughly 0, 1, and 2 seconds; 4 seconds per notification is excessive, but
            // better to play it safe with a timed assertion.
            final Future<PushNotificationResponse<SimpleApnsPushNotification>> sendFuture = client
                    .sendNotification(pushNotification);

            assertTrue(sendFuture.await(4, TimeUnit.SECONDS));
            assertFalse(sendFuture.isSuccess());
        }
    } finally {
        client.close().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 www  . j ava  2  s.c  om*/

    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.turo.pushy.apns.server.MockApnsServerTest.java

License:Open Source License

@Test
public void testListenerInternalServerError() throws Exception {
    final TestMockApnsServerListener listener = new TestMockApnsServerListener();

    final MockApnsServer server = this.buildServer(new PushNotificationHandlerFactory() {

        @Override//from  w ww .  j  a  v  a 2  s.c om
        public PushNotificationHandler buildHandler(final SSLSession sslSession) {
            return new PushNotificationHandler() {

                @Override
                public void handlePushNotification(final Http2Headers headers, final ByteBuf payload) {
                    throw new RuntimeException("Everything is terrible.");
                }
            };
        }
    }, listener);

    final ApnsClient client = this.buildTokenAuthenticationClient();

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

        final SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(DEVICE_TOKEN, TOPIC,
                PAYLOAD);

        final Future<PushNotificationResponse<SimpleApnsPushNotification>> sendFuture = client
                .sendNotification(pushNotification).await();

        assertTrue(sendFuture.isSuccess());

        listener.waitForNonZeroRejectedNotifications();

        assertEquals(RejectionReason.INTERNAL_SERVER_ERROR, listener.mostRecentRejectionReason);
    } finally {
        client.close().await();
        server.shutdown().await();
    }
}