Example usage for io.netty.channel ChannelPromise isSuccess

List of usage examples for io.netty.channel ChannelPromise isSuccess

Introduction

In this page you can find the example usage for io.netty.channel ChannelPromise isSuccess.

Prototype

boolean isSuccess();

Source Link

Document

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

Usage

From source file:ccwihr.client.t2.HttpResponseHandler.java

License:Apache License

/**
 * Wait (sequentially) for a time duration for each anticipated response
 *
 * @param timeout Value of time to wait for each response
 * @param unit Units associated with {@code timeout}
 * @see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise)
 *///from   w  ww .  j  av  a  2  s  .c o m
public void awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet()
            .iterator();
    while (itr.hasNext()) {
        Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
        ChannelFuture writeFuture = entry.getValue().getKey();
        if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
        }
        if (!writeFuture.isSuccess()) {
            throw new RuntimeException(writeFuture.cause());
        }
        ChannelPromise promise = entry.getValue().getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        System.out.println("---Stream id: " + entry.getKey() + " received---");
        itr.remove();
    }
}

From source file:cn.jpush.api.common.connection.HttpResponseHandler.java

License:Apache License

/**
 * Wait (sequentially) for a time duration for each anticipated response
 *
 * @param timeout Value of time to wait for each response
 * @param unit Units associated with {@code timeout}
 * @see HttpResponseHandler#put(int, ChannelFuture, ChannelPromise)
 *///w ww.j a  v a 2  s  . co m
public void awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet()
            .iterator();
    while (itr.hasNext()) {
        Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
        ChannelFuture writeFuture = entry.getValue().getKey();
        if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
        }
        if (!writeFuture.isSuccess()) {
            throw new RuntimeException(writeFuture.cause());
        }
        ChannelPromise promise = entry.getValue().getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        System.out.println("---Stream id: " + entry.getKey() + " received---");
        System.out.println("---Stream id: " + promise.toString());
        itr.remove();
    }
}

From source file:com.github.milenkovicm.kafka.handler.MetadataHandler.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

    final ControlTuple tuple = (ControlTuple) msg;
    final int currentCorrelation = correlation++;
    ByteBuf kafkaMessage = createMetadataRequest(ctx.alloc(), tuple.topicName, currentCorrelation);

    // not sure if it is possible that tread may read response message before it
    // puts future in the map. that's why I have it here .
    acks.put(currentCorrelation, tuple.promise);
    promise.addListener(new GenericFutureListener<ChannelPromise>() {
        @Override//from w  w w  .j a v a  2s .co m
        public void operationComplete(ChannelPromise future) throws Exception {
            // shouldn't be possible to cancel this operation
            //                if (future.isCancelled()) {
            //                    tuple.promise.cancel(true);
            //                    return;
            //                }
            if (future.isDone() && !future.isSuccess()) {
                acks.remove(currentCorrelation);
                tuple.promise.setFailure(future.cause());
            }
        }
    });
    super.write(ctx, kafkaMessage, promise);
}

From source file:com.relayrides.pushy.apns.ApnsClient.java

License:Open Source License

/**
 * Indicates whether this client is connected to the APNs gateway and ready to send push notifications.
 *
 * @return {@code true} if this client is connected and ready to send notifications or {@code false} otherwise
 *
 * @since 0.5/*from   www .  j  av  a  2s.c o m*/
 */
public boolean isConnected() {
    final ChannelPromise connectionReadyPromise = this.connectionReadyPromise;
    return (connectionReadyPromise != null && connectionReadyPromise.isSuccess());
}

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 .jav a  2  s  . com
 *
 * <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.ApnsClientHandler.java

License:Open Source License

private void writePushNotification(final ChannelHandlerContext context,
        final PushNotificationPromise responsePromise, final ChannelPromise writePromise) {
    if (context.channel().isActive()) {
        final int streamId = this.connection().local().incrementAndGetNextStreamId();

        if (streamId > 0) {
            // We'll attach the push notification and response promise to the stream as soon as the stream is created.
            // Because we're using a StreamBufferingEncoder under the hood, there's no guarantee as to when the stream
            // will actually be created, and so we attach these in the onStreamAdded listener to make sure everything
            // is happening in a predictable order.
            this.unattachedResponsePromisesByStreamId.put(streamId, responsePromise);
            final ApnsPushNotification pushNotification = responsePromise.getPushNotification();

            final Http2Headers headers = getHeadersForPushNotification(pushNotification, streamId);

            final ChannelPromise headersPromise = context.newPromise();
            this.encoder().writeHeaders(context, streamId, headers, 0, false, headersPromise);
            log.trace("Wrote headers on stream {}: {}", streamId, headers);

            final ByteBuf payloadBuffer = context.alloc().ioBuffer(INITIAL_PAYLOAD_BUFFER_CAPACITY);
            payloadBuffer.writeBytes(pushNotification.getPayload().getBytes(StandardCharsets.UTF_8));

            final ChannelPromise dataPromise = context.newPromise();
            this.encoder().writeData(context, streamId, payloadBuffer, 0, true, dataPromise);
            log.trace("Wrote payload on stream {}: {}", streamId, pushNotification.getPayload());

            final PromiseCombiner promiseCombiner = new PromiseCombiner();
            promiseCombiner.addAll((ChannelFuture) headersPromise, dataPromise);
            promiseCombiner.finish(writePromise);

            writePromise.addListener(new GenericFutureListener<ChannelPromise>() {

                @Override/*from   ww w  .  ja v a 2 s. c om*/
                public void operationComplete(final ChannelPromise future) {
                    if (!future.isSuccess()) {
                        log.trace("Failed to write push notification on stream {}.", streamId, future.cause());
                        responsePromise.tryFailure(future.cause());
                    }
                }
            });
        } else {
            // This is very unlikely, but in the event that we run out of stream IDs, we need to open a new
            // connection. Just closing the context should be enough; automatic reconnection should take things
            // from there.
            writePromise.tryFailure(STREAMS_EXHAUSTED_EXCEPTION);
            context.channel().close();
        }
    } else {
        writePromise.tryFailure(STREAM_CLOSED_BEFORE_REPLY_EXCEPTION);
    }
}

From source file:http.HTTPResponseHandler.java

License:Open Source License

/**
 * Provide asynchronous response to HTTP2 request
 *
 * @param streamId StreamID/*from  w w  w.j a  va  2 s .c  om*/
 * @return Response string
 */
public String getResponse(int streamId) {

    String message = streamIdResponseMap.get(streamId);
    if (message != null) {
        return message;
    } else {
        Entry<ChannelFuture, ChannelPromise> channelFutureChannelPromiseEntry = streamIdPromiseMap
                .get(streamId);
        if (channelFutureChannelPromiseEntry != null) {
            ChannelFuture writeFuture = channelFutureChannelPromiseEntry.getKey();
            if (!writeFuture.awaitUninterruptibly(ServerUtil.HTTP2_RESPONSE_TIME_OUT,
                    ServerUtil.HTTP2_RESPONSE_TIME_UNIT)) {
                streamIdPromiseMap.remove(streamId);
                throw new IllegalStateException("Timed out waiting to write for stream id " + streamId);
            }
            if (!writeFuture.isSuccess()) {
                streamIdPromiseMap.remove(streamId);
                throw new RuntimeException(writeFuture.cause());
            }
            ChannelPromise promise = channelFutureChannelPromiseEntry.getValue();
            if (!promise.awaitUninterruptibly(ServerUtil.HTTP2_RESPONSE_TIME_OUT,
                    ServerUtil.HTTP2_RESPONSE_TIME_UNIT)) {
                streamIdPromiseMap.remove(streamId);
                throw new IllegalStateException("Timed out waiting for response on stream id " + streamId);
            }
            if (!promise.isSuccess()) {
                streamIdPromiseMap.remove(streamId);
                throw new RuntimeException(promise.cause());
            }
        }
    }
    return streamIdResponseMap.get(streamId);
}

From source file:http2.client.HttpResponseHandler.java

License:Apache License

/**
 * anticipated : ?//from   w  w w.  j  a  va  2s.c  om
 * Wait (sequentially) for a time duration for each anticipated response
 *
 * @param timeout Value of time to wait for each response
 * @param unit Units associated with {@code timeout}
 * @see HttpResponseHandler#put(int, ChannelFuture, ChannelPromise)
 */
public void awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet()
            .iterator();
    while (itr.hasNext()) {
        Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
        ChannelFuture writeFuture = entry.getValue().getKey();
        //
        if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
        }
        //
        if (!writeFuture.isSuccess()) {
            throw new RuntimeException(writeFuture.cause());
        }
        //
        ChannelPromise promise = entry.getValue().getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        System.out.println("---Stream id: " + entry.getKey() + " received---");
        itr.remove();
    }
}

From source file:io.aos.netty5.http2.client.HttpResponseHandler.java

License:Apache License

/**
 * Wait (sequentially) for a time duration for each anticipated response
 *
 * @param timeout Value of time to wait for each response
 * @param unit Units associated with {@code timeout}
 * @see {@link io.netty.example.http2.client.HttpResponseHandler#put put}
 *//*from w ww  .  j  ava2s.c  o  m*/
public void awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, ChannelPromise>> itr = streamidPromiseMap.entrySet().iterator();
    while (itr.hasNext()) {
        Entry<Integer, ChannelPromise> entry = itr.next();
        ChannelPromise promise = entry.getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        System.out.println("---Stream id: " + entry.getKey() + " received---");
        itr.remove();
    }
}

From source file:jmeter.plugins.http2.sampler.HttpResponseHandler.java

License:Apache License

/**
 * Wait (sequentially) for a time duration for each anticipated response
 *
 * @param timeout Value of time to wait for each response
 * @param unit Units associated with {@code timeout}
 * @see HttpResponseHandler#put(int, ChannelPromise)
 *//*from   w  w w . ja va 2 s  .  c om*/
public SortedMap<Integer, FullHttpResponse> awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, ChannelPromise>> itr = streamidPromiseMap.entrySet().iterator();

    while (itr.hasNext()) {
        Entry<Integer, ChannelPromise> entry = itr.next();
        ChannelPromise promise = entry.getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        System.out.println("---Stream id: " + entry.getKey() + " received---");
        itr.remove();
    }

    return streamidResponseMap;
}