Search in sources :

Example 11 with ChannelPromise

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPromise in project pravega by pravega.

the class ClientConnectionInboundHandler method sendAsync.

@Override
public void sendAsync(List<Append> appends, CompletedCallback callback) {
    recentMessage.set(true);
    Channel ch;
    try {
        ch = getChannel();
    } catch (ConnectionFailedException e) {
        callback.complete(new ConnectionFailedException("Connection to " + connectionName + " is not established."));
        return;
    }
    PromiseCombiner combiner = new PromiseCombiner();
    for (Append append : appends) {
        batchSizeTracker.recordAppend(append.getEventNumber(), append.getData().readableBytes());
        combiner.add(ch.write(append));
    }
    ch.flush();
    ChannelPromise promise = ch.newPromise();
    promise.addListener(new GenericFutureListener<Future<? super Void>>() {

        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
            Throwable cause = future.cause();
            callback.complete(cause == null ? null : new ConnectionFailedException(cause));
        }
    });
    combiner.finish(promise);
}
Also used : PromiseCombiner(io.netty.util.concurrent.PromiseCombiner) Append(io.pravega.shared.protocol.netty.Append) Channel(io.netty.channel.Channel) ScheduledFuture(io.netty.util.concurrent.ScheduledFuture) CompletableFuture(java.util.concurrent.CompletableFuture) Future(io.netty.util.concurrent.Future) ChannelPromise(io.netty.channel.ChannelPromise) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException)

Example 12 with ChannelPromise

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPromise in project reactor-netty by reactor.

the class ChannelOperationsHandler method drain.

@SuppressWarnings("unchecked")
void drain() {
    if (WIP.getAndIncrement(this) == 0) {
        for (; ; ) {
            if (removed) {
                discard();
                return;
            }
            if (pendingWrites == null || innerActive || !ctx.channel().isWritable()) {
                if (!ctx.channel().isWritable() && hasPendingWriteBytes()) {
                    ctx.flush();
                }
                if (WIP.decrementAndGet(this) == 0) {
                    break;
                }
                continue;
            }
            ChannelFuture future;
            Object v = pendingWrites.poll();
            try {
                future = (ChannelFuture) v;
            } catch (Throwable e) {
                ctx.fireExceptionCaught(e);
                return;
            }
            boolean empty = future == null;
            if (empty) {
                if (WIP.decrementAndGet(this) == 0) {
                    break;
                }
                continue;
            }
            v = pendingWrites.poll();
            if (!innerActive && v == PublisherSender.PENDING_WRITES) {
                boolean last = pendingWrites.isEmpty();
                if (!future.isDone() && hasPendingWriteBytes()) {
                    ctx.flush();
                    if (!future.isDone() && hasPendingWriteBytes()) {
                        pendingWriteOffer.test(future, v);
                    }
                }
                if (last && WIP.decrementAndGet(this) == 0) {
                    break;
                }
            } else if (future instanceof ChannelPromise) {
                ChannelPromise promise = (ChannelPromise) future;
                if (v instanceof Publisher) {
                    Publisher<?> p = (Publisher<?>) v;
                    if (p instanceof Callable) {
                        @SuppressWarnings("unchecked") Callable<?> supplier = (Callable<?>) p;
                        Object vr;
                        try {
                            vr = supplier.call();
                        } catch (Throwable e) {
                            promise.setFailure(e);
                            continue;
                        }
                        if (vr == null) {
                            promise.setSuccess();
                            continue;
                        }
                        if (inner.unbounded) {
                            doWrite(vr, promise, null);
                        } else {
                            innerActive = true;
                            inner.promise = promise;
                            inner.onSubscribe(Operators.scalarSubscription(inner, vr));
                        }
                    } else {
                        innerActive = true;
                        inner.promise = promise;
                        p.subscribe(inner);
                    }
                } else {
                    doWrite(v, promise, null);
                }
            }
        }
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelPromise(io.netty.channel.ChannelPromise) Publisher(org.reactivestreams.Publisher) Callable(java.util.concurrent.Callable)

Example 13 with ChannelPromise

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPromise in project activemq-artemis by apache.

the class NettyConnection method writeNotInEventLoop.

private void writeNotInEventLoop(ActiveMQBuffer buffer, final boolean flush, final boolean batched, final ChannelFutureListener futureListener) {
    final Channel channel = this.channel;
    final ChannelPromise promise;
    if (flush || (futureListener != null)) {
        promise = channel.newPromise();
    } else {
        promise = channel.voidPromise();
    }
    final ChannelFuture future;
    final ByteBuf bytes = buffer.byteBuf();
    final int readableBytes = bytes.readableBytes();
    assert readableBytes >= 0;
    final int writeBatchSize = this.batchLimit;
    final boolean batchingEnabled = this.batchingEnabled;
    if (batchingEnabled && batched && !flush && readableBytes < writeBatchSize) {
        future = writeBatch(bytes, readableBytes, promise);
    } else {
        future = channel.writeAndFlush(bytes, promise);
    }
    if (futureListener != null) {
        future.addListener(futureListener);
    }
    if (flush) {
        // NOTE: this code path seems used only on RemotingConnection::disconnect
        waitFor(promise, DEFAULT_WAIT_MILLIS);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) ChannelPromise(io.netty.channel.ChannelPromise) ByteBuf(io.netty.buffer.ByteBuf)

Example 14 with ChannelPromise

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPromise in project riposte by Nike-Inc.

the class VerifyCornerCasesComponentTest method invalid_http_call_that_causes_Netty_DecoderFailure_should_result_in_expected_400_error.

@Test
public void invalid_http_call_that_causes_Netty_DecoderFailure_should_result_in_expected_400_error() throws Exception {
    // given
    // Normal request, but fiddle with the first chunk as it's going out to remove the HTTP version and make it an
    // invalid HTTP call. This will cause Netty to mark the HttpRequest with a DecoderFailure.
    NettyHttpClientRequestBuilder request = request().withMethod(HttpMethod.GET).withUri(BasicEndpoint.MATCHING_PATH).withPipelineAdjuster(p -> p.addFirst(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            String msgAsString = ((ByteBuf) msg).toString(CharsetUtil.UTF_8);
            if (msgAsString.contains("HTTP/1.1")) {
                msg = Unpooled.copiedBuffer(msgAsString.replace("HTTP/1.1", ""), CharsetUtil.UTF_8);
            }
            super.write(ctx, msg, promise);
        }
    }));
    // when
    NettyHttpClientResponse response = request.execute(downstreamServerConfig.endpointsPort(), 3000);
    // then
    verifyErrorReceived(response.payload, response.statusCode, new ApiErrorWithMetadata(SampleCoreApiError.MALFORMED_REQUEST, Pair.of("cause", "Invalid HTTP request")));
}
Also used : ApiErrorWithMetadata(com.nike.backstopper.apierror.ApiErrorWithMetadata) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) NettyHttpClientResponse(com.nike.riposte.server.testutils.ComponentTestUtils.NettyHttpClientResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ByteBuf(io.netty.buffer.ByteBuf) NettyHttpClientRequestBuilder(com.nike.riposte.server.testutils.ComponentTestUtils.NettyHttpClientRequestBuilder) Test(org.junit.Test)

Example 15 with ChannelPromise

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPromise in project hono by eclipse.

the class CommandAndControlMqttIT method injectMqttClientPubAckBlocker.

private Future<Void> injectMqttClientPubAckBlocker(final AtomicBoolean outboundPubAckBlocked) {
    // Therefore the underlying NetSocket pipeline is used here to filter out the outbound PubAck messages.
    try {
        final Method connectionMethod = MqttClientImpl.class.getDeclaredMethod("connection");
        connectionMethod.setAccessible(true);
        final NetSocketInternal connection = (NetSocketInternal) connectionMethod.invoke(mqttClient);
        connection.channelHandlerContext().pipeline().addBefore("handler", "OutboundPubAckBlocker", new ChannelOutboundHandlerAdapter() {

            @Override
            public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception {
                if (outboundPubAckBlocked.get() && msg instanceof io.netty.handler.codec.mqtt.MqttPubAckMessage) {
                    LOGGER.debug("suppressing PubAck, message id: {}", ((MqttPubAckMessage) msg).variableHeader().messageId());
                } else {
                    super.write(ctx, msg, promise);
                }
            }
        });
        return Future.succeededFuture();
    } catch (final Exception e) {
        LOGGER.error("failed to inject PubAck blocking handler");
        return Future.failedFuture(new Exception("failed to inject PubAck blocking handler", e));
    }
}
Also used : MqttPubAckMessage(io.netty.handler.codec.mqtt.MqttPubAckMessage) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) Method(java.lang.reflect.Method) IllegalStateException(javax.jms.IllegalStateException) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServerErrorException(org.eclipse.hono.client.ServerErrorException) SendMessageTimeoutException(org.eclipse.hono.client.SendMessageTimeoutException) NetSocketInternal(io.vertx.core.net.impl.NetSocketInternal)

Aggregations

ChannelPromise (io.netty.channel.ChannelPromise)223 Test (org.junit.jupiter.api.Test)88 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)63 ChannelFuture (io.netty.channel.ChannelFuture)62 DefaultChannelPromise (io.netty.channel.DefaultChannelPromise)58 ByteBuf (io.netty.buffer.ByteBuf)56 ChannelOutboundHandlerAdapter (io.netty.channel.ChannelOutboundHandlerAdapter)30 Test (org.junit.Test)25 Channel (io.netty.channel.Channel)23 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)22 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)22 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)21 ClosedChannelException (java.nio.channels.ClosedChannelException)20 ChannelFutureListener (io.netty.channel.ChannelFutureListener)19 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)18 InvocationOnMock (org.mockito.invocation.InvocationOnMock)18 AsciiString (io.netty.util.AsciiString)15 IOException (java.io.IOException)14 CountDownLatch (java.util.concurrent.CountDownLatch)13 Bootstrap (io.netty.bootstrap.Bootstrap)12