Example usage for io.netty.channel ChannelPromise setFailure

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

Introduction

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

Prototype

@Override
    ChannelPromise setFailure(Throwable cause);

Source Link

Usage

From source file:com.ebay.jetstream.messaging.transport.netty.autoflush.handler.NettyAutoFlushBatcher.java

License:MIT License

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

    if (!ctx.channel().isActive()) {

        ReferenceCountUtil.release(msg);

        // we might get here as channel is closed but upstream has not been notified yet. It could be still sending us events.
        // in such a case we will inform the future and send an exception upstream

        Throwable cause = new Exception("passed channel not active - "
                + ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress());

        promise.setFailure(cause);

        ctx.fireExceptionCaught(cause);//from w  w w.  ja  v  a 2s  . c  o m

        return;
    }

    AutoFlushWriterChannelQueue queue = m_channelQueue.get(ctx.channel());

    if (queue == null) {
        queue = new AutoFlushWriterChannelQueue(m_maxFlushBufferSz.get());
        queue.setChannelHandlerContext(ctx);
        m_channelQueue.put(ctx.channel(), queue);
    }

    MessageEvent e = new MessageEvent(msg, promise);

    queue.add(e);

    if (queue.isTimeToFlush()) {

        flush(ctx, queue);

    }

}

From source file:com.test.AbstractBootstrap.java

License:Apache License

private ChannelFuture doBind(final SocketAddress localAddress) {
    final ChannelFuture regFuture = initAndRegister();
    final Channel channel = regFuture.channel();
    if (regFuture.cause() != null) {
        return regFuture;
    }//w  w  w  .java 2s .  c  om

    if (regFuture.isDone()) {
        // At this point we know that the registration was complete and successful.
        ChannelPromise promise = channel.newPromise();
        doBind0(regFuture, channel, localAddress, promise);
        return promise;
    } else {
        // Registration future is almost always fulfilled already, but just in case it's not.
        final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
        regFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Throwable cause = future.cause();
                if (cause != null) {
                    // Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an
                    // IllegalStateException once we try to access the EventLoop of the Channel.
                    promise.setFailure(cause);
                } else {
                    // Registration was successful, so set the correct executor to use.
                    // See https://github.com/netty/netty/issues/2586
                    promise.executor = channel.eventLoop();
                }
                doBind0(regFuture, channel, localAddress, promise);
            }
        });
        return promise;
    }
}

From source file:com.test.AbstractBootstrap.java

License:Apache License

private static void doBind0(final ChannelFuture regFuture, final Channel channel,
        final SocketAddress localAddress, final ChannelPromise promise) {

    // This method is invoked before channelRegistered() is triggered.  Give user handlers a chance to set up
    // the pipeline in its channelRegistered() implementation.
    channel.eventLoop().execute(new Runnable() {
        @Override/*from w w  w.  j  a  v a 2s  . c o m*/
        public void run() {
            if (regFuture.isSuccess()) {
                channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            } else {
                promise.setFailure(regFuture.cause());
            }
        }
    });
}

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

License:Apache License

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

        HttpDataFrame httpDataFrame = (HttpDataFrame) msg;
        int streamId = httpDataFrame.getStreamId();

        // Frames must not be sent on half-closed streams
        if (httpConnection.isLocalSideClosed(streamId)) {
            promise.setFailure(PROTOCOL_EXCEPTION);
            return;
        }/*from  www  .j  a  v a 2s  . c  om*/

        // HTTP/2 DATA frame flow control processing requirements:
        //
        // Sender must not send a data frame with data length greater
        // than the transfer window size.
        //
        // After sending each data frame, the sender decrements its
        // transfer window size by the amount of data transmitted.
        //
        // When the window size becomes less than or equal to 0, the
        // sender must pause transmitting data frames.

        int dataLength = httpDataFrame.content().readableBytes();
        int sendWindowSize = httpConnection.getSendWindowSize(streamId);
        int connectionSendWindowSize = httpConnection.getSendWindowSize(HTTP_CONNECTION_STREAM_ID);
        sendWindowSize = Math.min(sendWindowSize, connectionSendWindowSize);

        if (sendWindowSize <= 0) {
            // Stream is stalled -- enqueue Data frame and return
            httpConnection.putPendingWrite(streamId, new HttpConnection.PendingWrite(httpDataFrame, promise));
            return;
        } else if (sendWindowSize < dataLength) {
            // Stream is not stalled but we cannot send the entire frame
            httpConnection.updateSendWindowSize(streamId, -1 * sendWindowSize);
            httpConnection.updateSendWindowSize(HTTP_CONNECTION_STREAM_ID, -1 * sendWindowSize);

            // Create a partial data frame whose length is the current window size
            ByteBuf data = httpDataFrame.content().readSlice(sendWindowSize);
            ByteBuf partialDataFrame = httpFrameEncoder.encodeDataFrame(streamId, false, data);

            // Enqueue the remaining data (will be the first frame queued)
            httpConnection.putPendingWrite(streamId, new HttpConnection.PendingWrite(httpDataFrame, promise));

            ChannelPromise writeFuture = ctx.channel().newPromise();

            // The transfer window size is pre-decremented when sending a data frame downstream.
            // Close the connection on write failures that leaves the transfer window in a corrupt state.
            writeFuture.addListener(connectionErrorListener);

            ctx.write(partialDataFrame, writeFuture);
            return;
        } else {
            // Window size is large enough to send entire data frame
            httpConnection.updateSendWindowSize(streamId, -1 * dataLength);
            httpConnection.updateSendWindowSize(HTTP_CONNECTION_STREAM_ID, -1 * dataLength);

            // The transfer window size is pre-decremented when sending a data frame downstream.
            // Close the connection on write failures that leaves the transfer window in a corrupt state.
            promise.addListener(connectionErrorListener);
        }

        // Close the local side of the stream if this is the last frame
        if (httpDataFrame.isLast()) {
            halfCloseStream(streamId, false, promise);
        }

        ByteBuf frame = httpFrameEncoder.encodeDataFrame(streamId, httpDataFrame.isLast(),
                httpDataFrame.content());
        ctx.write(frame, promise);

    } else if (msg instanceof HttpHeadersFrame) {

        HttpHeadersFrame httpHeadersFrame = (HttpHeadersFrame) msg;
        int streamId = httpHeadersFrame.getStreamId();

        if (streamId <= lastStreamId) {
            // Frames must not be sent on half-closed (local) or closed streams
            if (httpConnection.isLocalSideClosed(streamId)) {
                promise.setFailure(PROTOCOL_EXCEPTION);
                return;
            }
        } else {
            if (isRemoteInitiatedId(streamId)) {
                promise.setFailure(PROTOCOL_EXCEPTION);
                return;
            }
            // Try to accept the stream
            boolean exclusive = httpHeadersFrame.isExclusive();
            int dependency = httpHeadersFrame.getDependency();
            int weight = httpHeadersFrame.getWeight();
            if (!acceptStream(streamId, exclusive, dependency, weight)) {
                promise.setFailure(PROTOCOL_EXCEPTION);
                return;
            }
        }

        // Close the local side of the stream if this is the last frame
        if (httpHeadersFrame.isLast()) {
            halfCloseStream(streamId, false, promise);
        }

        synchronized (httpHeaderBlockEncoder) {
            ByteBuf frame = httpFrameEncoder.encodeHeadersFrame(httpHeadersFrame.getStreamId(),
                    httpHeadersFrame.isLast(), httpHeadersFrame.isExclusive(), httpHeadersFrame.getDependency(),
                    httpHeadersFrame.getWeight(), httpHeaderBlockEncoder.encode(ctx, httpHeadersFrame));
            // Writes of compressed data must occur in order
            ctx.write(frame, promise);
        }

    } else if (msg instanceof HttpPriorityFrame) {

        HttpPriorityFrame httpPriorityFrame = (HttpPriorityFrame) msg;
        int streamId = httpPriorityFrame.getStreamId();
        boolean exclusive = httpPriorityFrame.isExclusive();
        int dependency = httpPriorityFrame.getDependency();
        int weight = httpPriorityFrame.getWeight();
        setPriority(streamId, exclusive, dependency, weight);
        ByteBuf frame = httpFrameEncoder.encodePriorityFrame(streamId, exclusive, dependency, weight);
        ctx.write(frame, promise);

    } else if (msg instanceof HttpRstStreamFrame) {

        HttpRstStreamFrame httpRstStreamFrame = (HttpRstStreamFrame) msg;
        removeStream(httpRstStreamFrame.getStreamId(), promise);
        ByteBuf frame = httpFrameEncoder.encodeRstStreamFrame(httpRstStreamFrame.getStreamId(),
                httpRstStreamFrame.getErrorCode().getCode());
        ctx.write(frame, promise);

    } else if (msg instanceof HttpSettingsFrame) {

        // TODO(jpinner) currently cannot have more than one settings frame outstanding at a time

        HttpSettingsFrame httpSettingsFrame = (HttpSettingsFrame) msg;
        if (httpSettingsFrame.isAck()) {
            // Cannot send an acknowledgement frame
            promise.setFailure(PROTOCOL_EXCEPTION);
            return;
        }

        int newHeaderTableSize = httpSettingsFrame.getValue(HttpSettingsFrame.SETTINGS_HEADER_TABLE_SIZE);
        if (newHeaderTableSize >= 0) {
            headerTableSize = newHeaderTableSize;
            changeDecoderHeaderTableSize = true;
        }

        int newConcurrentStreams = httpSettingsFrame
                .getValue(HttpSettingsFrame.SETTINGS_MAX_CONCURRENT_STREAMS);
        if (newConcurrentStreams >= 0) {
            localConcurrentStreams = newConcurrentStreams;
        }

        int newInitialWindowSize = httpSettingsFrame.getValue(HttpSettingsFrame.SETTINGS_INITIAL_WINDOW_SIZE);
        if (newInitialWindowSize >= 0) {
            updateInitialReceiveWindowSize(newInitialWindowSize);
        }

        ByteBuf frame = httpFrameEncoder.encodeSettingsFrame(httpSettingsFrame);
        ctx.write(frame, promise);

    } else if (msg instanceof HttpPushPromiseFrame) {

        if (!pushEnabled) {
            promise.setFailure(PROTOCOL_EXCEPTION);
            return;
        }

        // TODO(jpinner) handle push promise frames
        promise.setFailure(PROTOCOL_EXCEPTION);

        //      synchronized (httpHeaderBlockEncoder) {
        //        HttpPushPromiseFrame httpPushPromiseFrame = (HttpPushPromiseFrame) msg;
        //        ChannelBuffer frame = httpFrameEncoder.encodePushPromiseFrame(
        //            httpPushPromiseFrame.getStreamId(),
        //            httpPushPromiseFrame.getPromisedStreamId(),
        //            httpHeaderBlockEncoder.encode(ctx, httpPushPromiseFrame)
        //        );
        //        // Writes of compressed data must occur in order
        //        Channels.write(ctx, e.getFuture(), frame, e.getRemoteAddress());
        //      }

    } else if (msg instanceof HttpPingFrame) {

        HttpPingFrame httpPingFrame = (HttpPingFrame) msg;
        if (httpPingFrame.isPong()) {
            // Cannot send a PONG frame
            promise.setFailure(PROTOCOL_EXCEPTION);
        } else {
            ByteBuf frame = httpFrameEncoder.encodePingFrame(httpPingFrame.getData(), false);
            ctx.write(frame, promise);
        }

    } else if (msg instanceof HttpGoAwayFrame) {

        // Why is this being sent? Intercept it and fail the write.
        // Should have sent a CLOSE ChannelStateEvent
        promise.setFailure(PROTOCOL_EXCEPTION);

    } else if (msg instanceof HttpWindowUpdateFrame) {

        HttpWindowUpdateFrame httpWindowUpdateFrame = (HttpWindowUpdateFrame) msg;
        int streamId = httpWindowUpdateFrame.getStreamId();

        if (handleStreamWindowUpdates || streamId == HTTP_CONNECTION_STREAM_ID) {
            // Why is this being sent? Intercept it and fail the write.
            promise.setFailure(PROTOCOL_EXCEPTION);
        } else {
            int windowSizeIncrement = httpWindowUpdateFrame.getWindowSizeIncrement();
            httpConnection.updateReceiveWindowSize(streamId, windowSizeIncrement);
            ByteBuf frame = httpFrameEncoder.encodeWindowUpdateFrame(streamId, windowSizeIncrement);
            ctx.write(frame, promise);
        }

    } else {

        ctx.write(msg, promise);
    }
}

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

License:Apache License

private ChannelPromise getMessageFuture(final ChannelHandlerContext ctx, final ChannelPromise promise,
        final int streamId, HttpMessage message) {
    if (message instanceof StreamedHttpMessage && !((StreamedHttpMessage) message).getContent().isClosed()) {
        final Pipe<HttpContent> pipe = ((StreamedHttpMessage) message).getContent();

        ChannelPromise writeFuture = ctx.channel().newPromise();
        writeFuture.addListener(new ChannelFutureListener() {
            @Override//from   w w w .  j a  v  a 2 s . co m
            public void operationComplete(ChannelFuture future) throws Exception {
                // Channel's thread
                // First frame has been written

                if (future.isSuccess()) {
                    pipe.receive().addListener(new ChunkListener(ctx, streamId, pipe, promise));
                } else if (future.isCancelled()) {
                    pipe.close();
                    promise.cancel(true);
                } else {
                    pipe.close();
                    promise.setFailure(future.cause());
                }
            }
        });

        return writeFuture;
    } else {
        return promise;
    }
}

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.ja v a2s  . c om*/
    }
    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

/**
 * Attempts to create a new stream from the given command. If there are too many active streams,
 * the creation request is queued./*from  w  w  w . j  av a 2  s. c  o m*/
 */
private void createStream(CreateStreamCommand command, ChannelPromise promise) throws Exception {
    if (lifecycleManager.getShutdownThrowable() != null) {
        command.stream().setNonExistent();
        // The connection is going away (it is really the GOAWAY case),
        // just terminate the stream now.
        command.stream().transportReportStatus(lifecycleManager.getShutdownStatus(), RpcProgress.REFUSED, true,
                new Metadata());
        promise.setFailure(lifecycleManager.getShutdownThrowable());
        return;
    }

    // Get the stream ID for the new stream.
    int streamId;
    try {
        streamId = incrementAndGetNextStreamId();
    } catch (StatusException e) {
        command.stream().setNonExistent();
        // Stream IDs have been exhausted for this connection. Fail the promise immediately.
        promise.setFailure(e);

        // Initiate a graceful shutdown if we haven't already.
        if (!connection().goAwaySent()) {
            logger.fine("Stream IDs have been exhausted for this connection. "
                    + "Initiating graceful shutdown of the connection.");
            lifecycleManager.notifyShutdown(e.getStatus());
            close(ctx(), ctx().newPromise());
        }
        return;
    }

    NettyClientStream.TransportState stream = command.stream();
    Http2Headers headers = command.headers();
    stream.setId(streamId);

    PerfMark.startTask("NettyClientHandler.createStream", stream.tag());
    PerfMark.linkIn(command.getLink());
    try {
        createStreamTraced(streamId, stream, headers, command.isGet(), command.shouldBeCountedForInUse(),
                promise);
    } finally {
        PerfMark.stopTask("NettyClientHandler.createStream", stream.tag());
    }
}

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/*from   w w  w.  j a v a2s .co m*/
                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.NettyServerHandler.java

License:Apache License

/**
 * Handler for commands sent from the stream.
 *///from   w w  w. j av a2s  .  c  o m
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof SendGrpcFrameCommand) {
        sendGrpcFrame(ctx, (SendGrpcFrameCommand) msg, promise);
    } else if (msg instanceof SendResponseHeadersCommand) {
        sendResponseHeaders(ctx, (SendResponseHeadersCommand) msg, promise);
    } else if (msg instanceof CancelServerStreamCommand) {
        cancelStream(ctx, (CancelServerStreamCommand) msg, promise);
    } else if (msg instanceof ForcefulCloseCommand) {
        forcefulClose(ctx, (ForcefulCloseCommand) msg, promise);
    } else {
        AssertionError e = new AssertionError("Write called for unexpected type: " + msg.getClass().getName());
        ReferenceCountUtil.release(msg);
        promise.setFailure(e);
        throw e;
    }
}

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

License:Apache License

/**
 * Buffers the write until either {@link #writeBufferedAndRemove(ChannelHandlerContext)} is
 * called, or we have somehow failed. If we have already failed in the past, then the write
 * will fail immediately./*from   w  w w.  jav  a 2 s .  c o m*/
 */
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    if (failCause != null) {
        promise.setFailure(failCause);
        ReferenceCountUtil.release(msg);
    } else {
        bufferedWrites.add(new ChannelWrite(msg, promise));
    }
}