Example usage for io.netty.channel ChannelPromise setSuccess

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

Introduction

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

Prototype

ChannelPromise setSuccess();

Source Link

Usage

From source file:com.couchbase.client.core.endpoint.AbstractEndpointTest.java

License:Apache License

@Test
public void shouldSwallowDuplicateConnectAttempts() {
    BootstrapAdapter bootstrap = mock(BootstrapAdapter.class);
    final ChannelPromise promise = channel.newPromise();
    when(bootstrap.connect()).thenReturn(promise);
    Endpoint endpoint = new DummyEndpoint(bootstrap);

    final CountDownLatch latch = new CountDownLatch(1);
    new Thread(new Runnable() {
        @Override/*  w ww .ja  v a  2  s .  c  o  m*/
        public void run() {
            try {
                latch.await();
            } catch (InterruptedException e) {
            }
            promise.setSuccess();
        }
    }).start();

    Observable<LifecycleState> attempt1 = endpoint.connect();
    Observable<LifecycleState> attempt2 = endpoint.connect();
    latch.countDown();

    assertEquals(LifecycleState.CONNECTED, attempt1.toBlocking().single());
    assertEquals(LifecycleState.CONNECTING, attempt2.toBlocking().single());
    verify(bootstrap, times(1)).connect();
}

From source file:com.couchbase.client.core.endpoint.AbstractEndpointTest.java

License:Apache License

@Test
public void shouldStopConnectIfDisconnectOverrides() {
    BootstrapAdapter bootstrap = mock(BootstrapAdapter.class);
    final ChannelPromise promise = channel.newPromise();
    when(bootstrap.connect()).thenReturn(promise);
    Endpoint endpoint = new DummyEndpoint(bootstrap);

    final CountDownLatch latch = new CountDownLatch(1);
    new Thread(new Runnable() {
        @Override//from  www.j  a va2 s. co  m
        public void run() {
            try {
                latch.await();
            } catch (InterruptedException e) {
            }
            promise.setSuccess();
        }
    }).start();

    Observable<LifecycleState> connect = endpoint.connect();
    Observable<LifecycleState> disconnect = endpoint.disconnect();
    latch.countDown();

    assertEquals(LifecycleState.DISCONNECTED, connect.toBlocking().single());
    assertEquals(LifecycleState.DISCONNECTED, disconnect.toBlocking().single());
}

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

License:Apache License

/**
 * Writes an HTTP chunk downstream as one or more HTTP/2 frames.
 *///from w  ww  . j  a v  a 2s.  c om
protected void writeChunk(ChannelHandlerContext ctx, ChannelPromise future, int streamId, HttpContent content) {

    HttpFrame[] httpFrames = createHttpDataFrames(streamId, content.content());

    if (content instanceof LastHttpContent) {
        LastHttpContent trailer = (LastHttpContent) content;
        HttpHeaders trailers = trailer.trailingHeaders();
        if (trailers.isEmpty()) {
            if (httpFrames.length == 0) {
                HttpDataFrame httpDataFrame = new DefaultHttpDataFrame(streamId);
                httpDataFrame.setLast(true);
                httpFrames = new HttpFrame[1];
                httpFrames[0] = httpDataFrame;
            } else {
                HttpDataFrame httpDataFrame = (HttpDataFrame) httpFrames[httpFrames.length - 1];
                httpDataFrame.setLast(true);
            }
        } else {
            // Create HTTP HEADERS frame out of trailers
            HttpHeadersFrame httpHeadersFrame = new DefaultHttpHeadersFrame(streamId);
            httpHeadersFrame.setLast(true);
            for (Map.Entry<String, String> entry : trailer.trailingHeaders()) {
                httpHeadersFrame.headers().add(entry.getKey(), entry.getValue());
            }
            if (httpFrames.length == 0) {
                httpFrames = new HttpFrame[1];
                httpFrames[0] = httpHeadersFrame;
            } else {
                HttpFrame[] copy = new HttpFrame[httpFrames.length + 1];
                for (int i = 0; i < httpFrames.length; i++) {
                    copy[i] = httpFrames[i];
                }
                copy[httpFrames.length] = httpHeadersFrame;
                httpFrames = copy;
            }
        }
    }

    ChannelPromise frameFuture = getFrameFuture(ctx, future, httpFrames);

    // Trigger a write
    frameFuture.setSuccess();
}

From source file:com.yahoo.pulsar.broker.service.Consumer.java

License:Apache License

/**
 * Dispatch a list of entries to the consumer.
 *
 * @return a promise that can be use to track when all the data has been written into the socket
 *//*from   ww w .  ja v a  2 s .  c om*/
public Pair<ChannelPromise, Integer> sendMessages(final List<Entry> entries) {
    final ChannelHandlerContext ctx = cnx.ctx();
    final MutablePair<ChannelPromise, Integer> sentMessages = new MutablePair<ChannelPromise, Integer>();
    final ChannelPromise writePromise = ctx.newPromise();
    sentMessages.setLeft(writePromise);
    if (entries.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("[{}] List of messages is empty, triggering write future immediately for consumerId {}",
                    subscription, consumerId);
        }
        writePromise.setSuccess();
        sentMessages.setRight(0);
        return sentMessages;
    }

    sentMessages.setRight(updatePermitsAndPendingAcks(entries));

    ctx.channel().eventLoop().execute(() -> {
        for (int i = 0; i < entries.size(); i++) {
            Entry entry = entries.get(i);
            PositionImpl pos = (PositionImpl) entry.getPosition();
            MessageIdData.Builder messageIdBuilder = MessageIdData.newBuilder();
            MessageIdData messageId = messageIdBuilder.setLedgerId(pos.getLedgerId())
                    .setEntryId(pos.getEntryId()).build();

            ByteBuf metadataAndPayload = entry.getDataBuffer();

            // skip checksum by incrementing reader-index if consumer-client doesn't support checksum verification
            if (cnx.getRemoteEndpointProtocolVersion() < ProtocolVersion.v6.getNumber()) {
                readChecksum(metadataAndPayload);
            }

            // stats
            msgOut.recordEvent(metadataAndPayload.readableBytes());

            if (log.isDebugEnabled()) {
                log.debug("[{}] Sending message to consumerId {}, entry id {}", subscription, consumerId,
                        pos.getEntryId());
            }

            // We only want to pass the "real" promise on the last entry written
            ChannelPromise promise = ctx.voidPromise();
            if (i == (entries.size() - 1)) {
                promise = writePromise;
            }
            ctx.write(Commands.newMessage(consumerId, messageId, metadataAndPayload), promise);
            messageId.recycle();
            messageIdBuilder.recycle();
        }

        ctx.flush();
    });

    return sentMessages;
}

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

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    int streamId = Integer.parseInt(msg.headers().get(Http2HttpHeaders.Names.STREAM_ID));
    ChannelPromise promise = streamidPromiseMap.get(streamId);
    if (promise == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {//from   w w w.ja v a2  s.c o m
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
        }

        promise.setSuccess();
    }
}

From source file:io.grpc.alts.internal.TsiFrameHandler.java

License:Apache License

@Override
@SuppressWarnings("FutureReturnValueIgnored") // for setSuccess
public void write(ChannelHandlerContext ctx, Object message, ChannelPromise promise) {
    if (protector == null) {
        promise.setFailure(new IllegalStateException("write() called after close()"));
        return;//from   w w w  . j  ava  2s  . co  m
    }
    ByteBuf msg = (ByteBuf) message;
    if (!msg.isReadable()) {
        // Nothing to encode.
        promise.setSuccess();
        return;
    }

    // Just add the message to the pending queue. We'll write it on the next flush.
    pendingUnprotectedWrites.add(msg, promise);
}

From source file:io.grpc.netty.NettyClientHandler.java

License:Apache License

private void createStreamTraced(final int streamId, final NettyClientStream.TransportState stream,
        final Http2Headers headers, boolean isGet, final boolean shouldBeCountedForInUse,
        final ChannelPromise promise) {
    // Create an intermediate promise so that we can intercept the failure reported back to the
    // application.
    ChannelPromise tempPromise = ctx().newPromise();
    encoder().writeHeaders(ctx(), streamId, headers, 0, isGet, tempPromise)
            .addListener(new ChannelFutureListener() {
                @Override//  w w  w  .j a  v a2  s . com
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        // The http2Stream will be null in case a stream buffered in the encoder
                        // was canceled via RST_STREAM.
                        Http2Stream http2Stream = connection().stream(streamId);
                        if (http2Stream != null) {
                            stream.getStatsTraceContext().clientOutboundHeaders();
                            http2Stream.setProperty(streamKey, stream);

                            // This delays the in-use state until the I/O completes, which technically may
                            // be later than we would like.
                            if (shouldBeCountedForInUse) {
                                inUseState.updateObjectInUse(http2Stream, true);
                            }

                            // Attach the client stream to the HTTP/2 stream object as user data.
                            stream.setHttp2Stream(http2Stream);
                        }
                        // Otherwise, the stream has been cancelled and Netty is sending a
                        // RST_STREAM frame which causes it to purge pending writes from the
                        // flow-controller and delete the http2Stream. The stream listener has already
                        // been notified of cancellation so there is nothing to do.

                        // Just forward on the success status to the original promise.
                        promise.setSuccess();
                    } else {
                        final Throwable cause = future.cause();
                        if (cause instanceof StreamBufferingEncoder.Http2GoAwayException) {
                            StreamBufferingEncoder.Http2GoAwayException e = (StreamBufferingEncoder.Http2GoAwayException) cause;
                            lifecycleManager.notifyShutdown(statusFromGoAway(e.errorCode(), e.debugData()));
                            promise.setFailure(lifecycleManager.getShutdownThrowable());
                        } else {
                            promise.setFailure(cause);
                        }
                    }
                }
            });
}

From source file:io.grpc.netty.NettyClientHandler.java

License:Apache License

/**
 * Cancels this stream./*from   w  w w  .  j  av a  2  s.co m*/
 */
private void cancelStream(ChannelHandlerContext ctx, CancelClientStreamCommand cmd, ChannelPromise promise) {
    NettyClientStream.TransportState stream = cmd.stream();
    PerfMark.startTask("NettyClientHandler.cancelStream", stream.tag());
    PerfMark.linkIn(cmd.getLink());
    try {
        Status reason = cmd.reason();
        if (reason != null) {
            stream.transportReportStatus(reason, true, new Metadata());
        }
        if (!cmd.stream().isNonExistent()) {
            encoder().writeRstStream(ctx, stream.id(), Http2Error.CANCEL.code(), promise);
        } else {
            promise.setSuccess();
        }
    } finally {
        PerfMark.stopTask("NettyClientHandler.cancelStream", stream.tag());
    }
}

From source file:io.grpc.netty.NettyClientHandler.java

License:Apache License

/**
 * Sends a PING frame. If a ping operation is already outstanding, the callback in the message is
 * registered to be called when the existing operation completes, and no new frame is sent.
 */// www  .  j a  v a 2 s.c  om
private void sendPingFrameTraced(ChannelHandlerContext ctx, SendPingCommand msg, ChannelPromise promise) {
    // Don't check lifecycleManager.getShutdownStatus() since we want to allow pings after shutdown
    // but before termination. After termination, messages will no longer arrive because the
    // pipeline clears all handlers on channel close.

    PingCallback callback = msg.callback();
    Executor executor = msg.executor();
    // we only allow one outstanding ping at a time, so just add the callback to
    // any outstanding operation
    if (ping != null) {
        promise.setSuccess();
        ping.addCallback(callback, executor);
        return;
    }

    // Use a new promise to prevent calling the callback twice on write failure: here and in
    // NettyClientTransport.ping(). It may appear strange, but it will behave the same as if
    // ping != null above.
    promise.setSuccess();
    promise = ctx().newPromise();
    // set outstanding operation
    long data = USER_PING_PAYLOAD;
    Stopwatch stopwatch = stopwatchFactory.get();
    stopwatch.start();
    ping = new Http2Ping(data, stopwatch);
    ping.addCallback(callback, executor);
    // and then write the ping
    encoder().writePing(ctx, false, USER_PING_PAYLOAD, promise);
    ctx.flush();
    final Http2Ping finalPing = ping;
    promise.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                transportTracer.reportKeepAliveSent();
            } else {
                Throwable cause = future.cause();
                if (cause instanceof ClosedChannelException) {
                    cause = lifecycleManager.getShutdownThrowable();
                    if (cause == null) {
                        cause = Status.UNKNOWN.withDescription("Ping failed but for unknown reason.")
                                .withCause(future.cause()).asException();
                    }
                }
                finalPing.failed(cause);
                if (ping == finalPing) {
                    ping = null;
                }
            }
        }
    });
}

From source file:io.grpc.netty.NettyClientHandler.java

License:Apache License

private void forcefulClose(final ChannelHandlerContext ctx, final ForcefulCloseCommand msg,
        ChannelPromise promise) throws Exception {
    // close() already called by NettyClientTransport, so just need to clean up streams
    connection().forEachActiveStream(new Http2StreamVisitor() {
        @Override/*from   ww w  .  j  ava  2s . c om*/
        public boolean visit(Http2Stream stream) throws Http2Exception {
            NettyClientStream.TransportState clientStream = clientStream(stream);
            Tag tag = clientStream != null ? clientStream.tag() : PerfMark.createTag();
            PerfMark.startTask("NettyClientHandler.forcefulClose", tag);
            PerfMark.linkIn(msg.getLink());
            try {
                if (clientStream != null) {
                    clientStream.transportReportStatus(msg.getStatus(), true, new Metadata());
                    resetStream(ctx, stream.id(), Http2Error.CANCEL.code(), ctx.newPromise());
                }
                stream.close();
                return true;
            } finally {
                PerfMark.stopTask("NettyClientHandler.forcefulClose", tag);
            }
        }
    });
    promise.setSuccess();
}