Java Code Examples for io.netty.channel.ChannelPromise#tryFailure()

The following examples show how to use io.netty.channel.ChannelPromise#tryFailure() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CompressorHttp2ConnectionEncoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture writeHeaders(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
        boolean endStream, ChannelPromise promise) {
    try {
        // Determine if compression is required and sanitize the headers.
        EmbeddedChannel compressor = newCompressor(ctx, headers, endStream);

        // Write the headers and create the stream object.
        ChannelFuture future = super.writeHeaders(ctx, streamId, headers, padding, endStream, promise);

        // After the stream object has been created, then attach the compressor as a property for data compression.
        bindCompressorToStream(compressor, streamId);

        return future;
    } catch (Throwable e) {
        promise.tryFailure(e);
    }
    return promise;
}
 
Example 2
Source File: CompressorHttp2ConnectionEncoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture writeHeaders(final ChannelHandlerContext ctx, final int streamId, final Http2Headers headers,
        final int streamDependency, final short weight, final boolean exclusive, final int padding,
        final boolean endOfStream, final ChannelPromise promise) {
    try {
        // Determine if compression is required and sanitize the headers.
        EmbeddedChannel compressor = newCompressor(ctx, headers, endOfStream);

        // Write the headers and create the stream object.
        ChannelFuture future = super.writeHeaders(ctx, streamId, headers, streamDependency, weight, exclusive,
                                                  padding, endOfStream, promise);

        // After the stream object has been created, then attach the compressor as a property for data compression.
        bindCompressorToStream(compressor, streamId);

        return future;
    } catch (Throwable e) {
        promise.tryFailure(e);
    }
    return promise;
}
 
Example 3
Source File: UkcpClientChannel.java    From kcp-netty with MIT License 6 votes vote down vote up
@Override
public void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
    if (!promise.setUncancellable() || !ensureOpen(promise)) {
        return;
    }

    try {
        boolean wasActive = isActive();
        if (doConnect(remoteAddress, localAddress)) {
            fulfillConnectPromise(promise, wasActive);
        } else {
            throw new Error();
        }
    } catch (Throwable t) {
        promise.tryFailure(annotateConnectException(t, remoteAddress));
        closeIfClosed();
    }
}
 
Example 4
Source File: AbstractEpollStreamChannel.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Splice from this {@link AbstractEpollStreamChannel} to another {@link AbstractEpollStreamChannel}.
 * The {@code len} is the number of bytes to splice. If using {@link Integer#MAX_VALUE} it will
 * splice until the {@link ChannelFuture} was canceled or it was failed.
 *
 * Please note:
 * <ul>
 *   <li>both channels need to be registered to the same {@link EventLoop}, otherwise an
 *   {@link IllegalArgumentException} is thrown. </li>
 *   <li>{@link EpollChannelConfig#getEpollMode()} must be {@link EpollMode#LEVEL_TRIGGERED} for this and the
 *   target {@link AbstractEpollStreamChannel}</li>
 * </ul>
 *
 */
public final ChannelFuture spliceTo(final AbstractEpollStreamChannel ch, final int len,
                                    final ChannelPromise promise) {
    if (ch.eventLoop() != eventLoop()) {
        throw new IllegalArgumentException("EventLoops are not the same.");
    }
    if (len < 0) {
        throw new IllegalArgumentException("len: " + len + " (expected: >= 0)");
    }
    if (ch.config().getEpollMode() != EpollMode.LEVEL_TRIGGERED
            || config().getEpollMode() != EpollMode.LEVEL_TRIGGERED) {
        throw new IllegalStateException("spliceTo() supported only when using " + EpollMode.LEVEL_TRIGGERED);
    }
    checkNotNull(promise, "promise");
    if (!isOpen()) {
        promise.tryFailure(SPLICE_TO_CLOSED_CHANNEL_EXCEPTION);
    } else {
        addToSpliceQueue(new SpliceInChannelTask(ch, len, promise));
        failSpliceIfClosed(promise);
    }
    return promise;
}
 
Example 5
Source File: AbstractEpollStreamChannel.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Splice from this {@link AbstractEpollStreamChannel} to another {@link FileDescriptor}.
 * The {@code offset} is the offset for the {@link FileDescriptor} and {@code len} is the
 * number of bytes to splice. If using {@link Integer#MAX_VALUE} it will splice until the
 * {@link ChannelFuture} was canceled or it was failed.
 *
 * Please note:
 * <ul>
 *   <li>{@link EpollChannelConfig#getEpollMode()} must be {@link EpollMode#LEVEL_TRIGGERED} for this
 *   {@link AbstractEpollStreamChannel}</li>
 *   <li>the {@link FileDescriptor} will not be closed after the {@link ChannelPromise} is notified</li>
 *   <li>this channel must be registered to an event loop or {@link IllegalStateException} will be thrown.</li>
 * </ul>
 */
public final ChannelFuture spliceTo(final FileDescriptor ch, final int offset, final int len,
                                    final ChannelPromise promise) {
    if (len < 0) {
        throw new IllegalArgumentException("len: " + len + " (expected: >= 0)");
    }
    if (offset < 0) {
        throw new IllegalArgumentException("offset must be >= 0 but was " + offset);
    }
    if (config().getEpollMode() != EpollMode.LEVEL_TRIGGERED) {
        throw new IllegalStateException("spliceTo() supported only when using " + EpollMode.LEVEL_TRIGGERED);
    }
    checkNotNull(promise, "promise");
    if (!isOpen()) {
        promise.tryFailure(SPLICE_TO_CLOSED_CHANNEL_EXCEPTION);
    } else {
        addToSpliceQueue(new SpliceFdTask(ch, offset, len, promise));
        failSpliceIfClosed(promise);
    }
    return promise;
}
 
Example 6
Source File: HttpClientPipelineConfigurator.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
                    ChannelPromise promise) throws Exception {

    // Remember the requested remote address for later use.
    final InetSocketAddress inetRemoteAddr = (InetSocketAddress) remoteAddress;
    this.remoteAddress = inetRemoteAddr;

    // Configure the pipeline.
    final Channel ch = ctx.channel();
    ChannelUtil.disableWriterBufferWatermark(ch);

    final ChannelPipeline p = ch.pipeline();
    p.addLast(new FlushConsolidationHandler());
    p.addLast(ReadSuppressingAndChannelDeactivatingHandler.INSTANCE);

    try {
        if (sslCtx != null) {
            configureAsHttps(ch, inetRemoteAddr);
        } else {
            configureAsHttp(ch);
        }
    } catch (Throwable t) {
        promise.tryFailure(t);
        ctx.close();
    } finally {
        if (p.context(this) != null) {
            p.remove(this);
        }
    }

    ctx.connect(remoteAddress, localAddress, promise);
}
 
Example 7
Source File: DefaultHttp2ConnectionEncoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelFuture writePushPromise(ChannelHandlerContext ctx, int streamId, int promisedStreamId,
        Http2Headers headers, int padding, ChannelPromise promise) {
    try {
        if (connection.goAwayReceived()) {
            throw connectionError(PROTOCOL_ERROR, "Sending PUSH_PROMISE after GO_AWAY received.");
        }

        Http2Stream stream = requireStream(streamId);
        // Reserve the promised stream.
        connection.local().reservePushStream(promisedStreamId, stream);

        ChannelFuture future = frameWriter.writePushPromise(ctx, streamId, promisedStreamId, headers, padding,
                                                            promise);
        // Writing headers may fail during the encode state if they violate HPACK limits.
        Throwable failureCause = future.cause();
        if (failureCause == null) {
            // This just sets internal stream state which is used elsewhere in the codec and doesn't
            // necessarily mean the write will complete successfully.
            stream.pushPromiseSent();

            if (!future.isSuccess()) {
                // Either the future is not done or failed in the meantime.
                notifyLifecycleManagerOnError(future, ctx);
            }
        } else {
            lifecycleManager.onError(ctx, true, failureCause);
        }
        return future;
    } catch (Throwable t) {
        lifecycleManager.onError(ctx, true, t);
        promise.tryFailure(t);
        return promise;
    }
}
 
Example 8
Source File: AbstractEpollStreamChannel.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
private void fulfillConnectPromise(ChannelPromise promise, Throwable cause) {
    if (promise == null) {
        // Closed via cancellation and the promise has been notified already.
        return;
    }

    // Use tryFailure() instead of setFailure() to avoid the race against cancel().
    promise.tryFailure(cause);
    closeIfClosed();
}
 
Example 9
Source File: AbstractNioChannel.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
private void fulfillConnectPromise(ChannelPromise promise, Throwable cause) {
    if (promise == null) {
        // Closed via cancellation and the promise has been notified already.
        return;
    }

    // Use tryFailure() instead of setFailure() to avoid the race against cancel().
    promise.tryFailure(cause);
    closeIfClosed();
}
 
Example 10
Source File: VirtualChannel.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
protected void doClose() throws Exception {
    final VirtualClientConnection peer = this.virtualConnection;
    State oldState = state;
    try {
        if (oldState != State.CLOSED) {
            // Update all internal state before the closeFuture is notified.
            if (localAddress != null) {
                if (parent() == null) {
                    VirtualChannelRegistry.unregister(localAddress);
                }
                localAddress = null;
            }

            // State change must happen before finishPeerRead to ensure writes are released either in doWrite or
            // channelRead.
            state = State.CLOSED;

            ChannelPromise promise = connectPromise;
            if (promise != null) {
                // Use tryFailure() instead of setFailure() to avoid the race against cancel().
                promise.tryFailure(new ClosedChannelException());
                connectPromise = null;
            }
        }

        if (peer != null) {
            peer.close();
        }
    } finally {
        // Release all buffers if the Channel was already registered in the past and if it was not closed before.
        if (oldState != null && oldState != State.CLOSED) {
            // We need to release all the buffers that may be put into our inbound queue since we closed the Channel
            // to ensure we not leak any memory. This is fine as it basically gives the same guarantees as TCP which
            // means even if the promise was notified before its not really guaranteed that the "remote peer" will
            // see the buffer at all.
            releaseInboundBuffers();
        }
    }
}
 
Example 11
Source File: AbstractWriteTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Override
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise)
        throws Exception {
    if (throwFromNextWrite) {
        throw DELIBERATE_EXCEPTION;
    }
    if (failNextWritePromise) {
        promise.tryFailure(DELIBERATE_EXCEPTION);
    } else {
        super.write(ctx, msg, promise);
    }
}
 
Example 12
Source File: AbstractEpollChannel.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private void fulfillConnectPromise(ChannelPromise promise, Throwable cause) {
    if (promise == null) {
        // Closed via cancellation and the promise has been notified already.
        return;
    }

    // Use tryFailure() instead of setFailure() to avoid the race against cancel().
    promise.tryFailure(cause);
    closeIfClosed();
}
 
Example 13
Source File: AbstractEpollStreamChannel.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private void failSpliceIfClosed(ChannelPromise promise) {
    if (!isOpen()) {
        // Seems like the Channel was closed in the meantime try to fail the promise to prevent any
        // cases where a future may not be notified otherwise.
        if (promise.tryFailure(FAIL_SPLICE_IF_CLOSED_CLOSED_CHANNEL_EXCEPTION)) {
            eventLoop().execute(new Runnable() {
                @Override
                public void run() {
                    // Call this via the EventLoop as it is a MPSC queue.
                    clearSpliceQueue();
                }
            });
        }
    }
}
 
Example 14
Source File: AbstractKQueueChannel.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private void fulfillConnectPromise(ChannelPromise promise, Throwable cause) {
    if (promise == null) {
        // Closed via cancellation and the promise has been notified already.
        return;
    }

    // Use tryFailure() instead of setFailure() to avoid the race against cancel().
    promise.tryFailure(cause);
    closeIfClosed();
}
 
Example 15
Source File: AbstractNioChannel.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void doClose() throws Exception {
    ChannelPromise promise = connectPromise;
    if (promise != null) {
        // Use tryFailure() instead of setFailure() to avoid the race against cancel().使用tryFailure()而不是setFailure()来避免与cancel()的竞争。
        promise.tryFailure(DO_CLOSE_CLOSED_CHANNEL_EXCEPTION);
        connectPromise = null;
    }

    ScheduledFuture<?> future = connectTimeoutFuture;
    if (future != null) {
        future.cancel(false);
        connectTimeoutFuture = null;
    }
}
 
Example 16
Source File: IpmiCodec.java    From ipmi4j with Apache License 2.0 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    try {
        ctx.write(encode(ctx, (Packet) msg), promise);
        // LOG.info("Write: OK");
    } catch (Throwable e) {
        // LOG.info("Write: " + e);
        // https://github.com/netty/netty/issues/3060 - exception not reported by pipeline.
        promise.tryFailure(e);
    } finally {
        // It isn't, but it might become so?
        ReferenceCountUtil.release(msg);
    }
}
 
Example 17
Source File: MockChannelHandlerContext.java    From karyon with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
    try {
        if (null != handler) {
            handler.write(this, msg, promise);
            handler.flush(this);
        }
    } catch (Exception e) {
        promise.tryFailure(e);
    }
    return promise;
}
 
Example 18
Source File: AbstractEpollChannel.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
protected void doClose() throws Exception {
    active = false;
    // Even if we allow half closed sockets we should give up on reading. Otherwise we may allow a read attempt on a
    // socket which has not even been connected yet. This has been observed to block during unit tests.
    inputClosedSeenErrorOnRead = true;
    try {
        ChannelPromise promise = connectPromise;
        if (promise != null) {
            // Use tryFailure() instead of setFailure() to avoid the race against cancel().
            promise.tryFailure(DO_CLOSE_CLOSED_CHANNEL_EXCEPTION);
            connectPromise = null;
        }

        ScheduledFuture<?> future = connectTimeoutFuture;
        if (future != null) {
            future.cancel(false);
            connectTimeoutFuture = null;
        }

        if (isRegistered()) {
            // Need to check if we are on the EventLoop as doClose() may be triggered by the GlobalEventExecutor
            // if SO_LINGER is used.
            //
            // See https://github.com/netty/netty/issues/7159
            EventLoop loop = eventLoop();
            if (loop.inEventLoop()) {
                doDeregister();
            } else {
                loop.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            doDeregister();
                        } catch (Throwable cause) {
                            pipeline().fireExceptionCaught(cause);
                        }
                    }
                });
            }
        }
    } finally {
        socket.close();
    }
}
 
Example 19
Source File: LocalChannel.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
protected void doClose() throws Exception {
    final LocalChannel peer = this.peer;
    State oldState = state;
    try {
        if (oldState != State.CLOSED) {
            // Update all internal state before the closeFuture is notified.
            if (localAddress != null) {
                if (parent() == null) {
                    LocalChannelRegistry.unregister(localAddress);
                }
                localAddress = null;
            }

            // State change must happen before finishPeerRead to ensure writes are released either in doWrite or
            // channelRead.
            state = State.CLOSED;

            // Preserve order of event and force a read operation now before the close operation is processed.
            if (writeInProgress && peer != null) {
                finishPeerRead(peer);
            }

            ChannelPromise promise = connectPromise;
            if (promise != null) {
                // Use tryFailure() instead of setFailure() to avoid the race against cancel().
                promise.tryFailure(DO_CLOSE_CLOSED_CHANNEL_EXCEPTION);
                connectPromise = null;
            }
        }

        if (peer != null) {
            this.peer = null;
            // Always call peer.eventLoop().execute() even if peer.eventLoop().inEventLoop() is true.
            // This ensures that if both channels are on the same event loop, the peer's channelInActive
            // event is triggered *after* this peer's channelInActive event
            EventLoop peerEventLoop = peer.eventLoop();
            final boolean peerIsActive = peer.isActive();
            try {
                peerEventLoop.execute(new Runnable() {
                    @Override
                    public void run() {
                        peer.tryClose(peerIsActive);
                    }
                });
            } catch (Throwable cause) {
                logger.warn("Releasing Inbound Queues for channels {}-{} because exception occurred!",
                        this, peer, cause);
                if (peerEventLoop.inEventLoop()) {
                    peer.releaseInboundBuffers();
                } else {
                    // inboundBuffers is a SPSC so we may leak if the event loop is shutdown prematurely or
                    // rejects the close Runnable but give a best effort.
                    peer.close();
                }
                PlatformDependent.throwException(cause);
            }
        }
    } finally {
        // Release all buffers if the Channel was already registered in the past and if it was not closed before.
        if (oldState != null && oldState != State.CLOSED) {
            // We need to release all the buffers that may be put into our inbound queue since we closed the Channel
            // to ensure we not leak any memory. This is fine as it basically gives the same guarantees as TCP which
            // means even if the promise was notified before its not really guaranteed that the "remote peer" will
            // see the buffer at all.
            releaseInboundBuffers();
        }
    }
}
 
Example 20
Source File: SslHandler.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
private void wrap(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException {
    ByteBuf out = null;
    ChannelPromise promise = null;
    ByteBufAllocator alloc = ctx.alloc();
    boolean needUnwrap = false;
    ByteBuf buf = null;
    try {
        final int wrapDataSize = this.wrapDataSize;
        // Only continue to loop if the handler was not removed in the meantime.
        // See https://github.com/netty/netty/issues/5860
        while (!ctx.isRemoved()) {
            promise = ctx.newPromise();
            buf = wrapDataSize > 0 ?
                    pendingUnencryptedWrites.remove(alloc, wrapDataSize, promise) :
                    pendingUnencryptedWrites.removeFirst(promise);
            if (buf == null) {
                break;
            }

            if (out == null) {
                out = allocateOutNetBuf(ctx, buf.readableBytes(), buf.nioBufferCount());
            }

            SSLEngineResult result = wrap(alloc, engine, buf, out);

            if (result.getStatus() == Status.CLOSED) {
                buf.release();
                buf = null;
                promise.tryFailure(SSLENGINE_CLOSED);
                promise = null;
                // SSLEngine has been closed already.
                // Any further write attempts should be denied.
                pendingUnencryptedWrites.releaseAndFailAll(ctx, SSLENGINE_CLOSED);
                return;
            } else {
                if (buf.isReadable()) {
                    pendingUnencryptedWrites.addFirst(buf, promise);
                    // When we add the buffer/promise pair back we need to be sure we don't complete the promise
                    // later in finishWrap. We only complete the promise if the buffer is completely consumed.
                    promise = null;
                } else {
                    buf.release();
                }
                buf = null;

                switch (result.getHandshakeStatus()) {
                    case NEED_TASK:
                        runDelegatedTasks();
                        break;
                    case FINISHED:
                        setHandshakeSuccess();
                        // deliberate fall-through
                    case NOT_HANDSHAKING:
                        setHandshakeSuccessIfStillHandshaking();
                        // deliberate fall-through
                    case NEED_WRAP:
                        finishWrap(ctx, out, promise, inUnwrap, false);
                        promise = null;
                        out = null;
                        break;
                    case NEED_UNWRAP:
                        needUnwrap = true;
                        return;
                    default:
                        throw new IllegalStateException(
                                "Unknown handshake status: " + result.getHandshakeStatus());
                }
            }
        }
    } finally {
        // Ownership of buffer was not transferred, release it.
        if (buf != null) {
            buf.release();
        }
        finishWrap(ctx, out, promise, inUnwrap, needUnwrap);
    }
}