Search in sources :

Example 51 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project netty by netty.

the class Http2ConnectionHandlerTest method canSendGoAwayFrame.

@SuppressWarnings("unchecked")
@Test
public void canSendGoAwayFrame() throws Exception {
    ByteBuf data = dummyData();
    long errorCode = Http2Error.INTERNAL_ERROR.code();
    when(future.isDone()).thenReturn(true);
    when(future.isSuccess()).thenReturn(true);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            ((GenericFutureListener) invocation.getArgument(0)).operationComplete(future);
            return null;
        }
    }).when(future).addListener(any(GenericFutureListener.class));
    handler = newHandler();
    handler.goAway(ctx, STREAM_ID, errorCode, data, promise);
    verify(connection).goAwaySent(eq(STREAM_ID), eq(errorCode), eq(data));
    verify(frameWriter).writeGoAway(eq(ctx), eq(STREAM_ID), eq(errorCode), eq(data), eq(promise));
    verify(ctx).close();
    assertEquals(0, data.refCnt());
}
Also used : InvocationOnMock(org.mockito.invocation.InvocationOnMock) ByteBuf(io.netty.buffer.ByteBuf) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 52 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project herddb by diennea.

the class NettyChannel method sendOneWayMessage.

@Override
public void sendOneWayMessage(ByteBuf message, SendResultCallback callback) {
    io.netty.channel.Channel _socket = this.socket;
    if (_socket == null || !_socket.isOpen()) {
        callback.messageSent(new Exception(this + " connection is closed"));
        return;
    }
    if (LOGGER.isLoggable(Level.FINEST)) {
        StringBuilder dumper = new StringBuilder();
        ByteBufUtil.appendPrettyHexDump(dumper, message);
        LOGGER.log(Level.FINEST, "Sending to {}: {}", new Object[] { _socket, dumper });
    }
    _socket.writeAndFlush(message).addListener(new GenericFutureListener() {

        @Override
        public void operationComplete(Future future) throws Exception {
            if (future.isSuccess()) {
                callback.messageSent(null);
            } else {
                LOGGER.log(Level.SEVERE, this + ": error " + future.cause(), future.cause());
                callback.messageSent(future.cause());
                close();
            }
        }
    });
    unflushedWrites.incrementAndGet();
}
Also used : Future(io.netty.util.concurrent.Future) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener)

Example 53 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project micronaut-core by micronaut-projects.

the class RoutingInBoundHandler method writeFinalNettyResponse.

private void writeFinalNettyResponse(MutableHttpResponse<?> message, HttpRequest<?> request, ChannelHandlerContext context) {
    HttpStatus httpStatus = message.status();
    final io.micronaut.http.HttpVersion httpVersion = request.getHttpVersion();
    final boolean isHttp2 = httpVersion == io.micronaut.http.HttpVersion.HTTP_2_0;
    boolean decodeError = request instanceof NettyHttpRequest && ((NettyHttpRequest<?>) request).getNativeRequest().decoderResult().isFailure();
    final Object body = message.body();
    if (body instanceof NettyCustomizableResponseTypeHandlerInvoker) {
        // default Connection header if not set explicitly
        if (!isHttp2) {
            if (!message.getHeaders().contains(HttpHeaders.CONNECTION)) {
                if (!decodeError && (httpStatus.getCode() < 500 || serverConfiguration.isKeepAliveOnServerError())) {
                    message.getHeaders().set(HttpHeaders.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                } else {
                    message.getHeaders().set(HttpHeaders.CONNECTION, HttpHeaderValues.CLOSE);
                }
            }
        }
        NettyCustomizableResponseTypeHandlerInvoker handler = (NettyCustomizableResponseTypeHandlerInvoker) body;
        message.body(null);
        handler.invoke(request, message, context);
    } else {
        io.netty.handler.codec.http.HttpResponse nettyResponse = NettyHttpResponseBuilder.toHttpResponse(message);
        io.netty.handler.codec.http.HttpHeaders nettyHeaders = nettyResponse.headers();
        // default Connection header if not set explicitly
        if (!isHttp2) {
            if (!nettyHeaders.contains(HttpHeaderNames.CONNECTION)) {
                boolean expectKeepAlive = nettyResponse.protocolVersion().isKeepAliveDefault() || request.getHeaders().isKeepAlive();
                if (!decodeError && (expectKeepAlive || httpStatus.getCode() < 500 || serverConfiguration.isKeepAliveOnServerError())) {
                    nettyHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                } else {
                    nettyHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
                }
            }
        }
        // default to Transfer-Encoding: chunked if Content-Length not set or not already set
        if (!nettyHeaders.contains(HttpHeaderNames.CONTENT_LENGTH) && !nettyHeaders.contains(HttpHeaderNames.TRANSFER_ENCODING)) {
            nettyHeaders.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
        }
        // close handled by HttpServerKeepAliveHandler
        final NettyHttpRequest<?> nettyHttpRequest = (NettyHttpRequest<?>) request;
        if (isHttp2) {
            addHttp2StreamHeader(request, nettyResponse);
        }
        io.netty.handler.codec.http.HttpRequest nativeRequest = nettyHttpRequest.getNativeRequest();
        GenericFutureListener<Future<? super Void>> requestCompletor = future -> {
            try {
                if (!future.isSuccess()) {
                    final Throwable throwable = future.cause();
                    if (!(throwable instanceof ClosedChannelException)) {
                        if (throwable instanceof Http2Exception.StreamException) {
                            Http2Exception.StreamException se = (Http2Exception.StreamException) throwable;
                            if (se.error() == Http2Error.STREAM_CLOSED) {
                                // ignore
                                return;
                            }
                        }
                        if (LOG.isErrorEnabled()) {
                            LOG.error("Error writing final response: " + throwable.getMessage(), throwable);
                        }
                    }
                }
            } finally {
                cleanupRequest(context, nettyHttpRequest);
                context.read();
            }
        };
        if (nativeRequest instanceof StreamedHttpRequest && !((StreamedHttpRequest) nativeRequest).isConsumed()) {
            StreamedHttpRequest streamedHttpRequest = (StreamedHttpRequest) nativeRequest;
            // We have to clear the buffer of FlowControlHandler before writing the response
            // If this is a streamed request and there is still content to consume then subscribe
            // and write the buffer is empty.
            // noinspection ReactiveStreamsSubscriberImplementation
            streamedHttpRequest.subscribe(new Subscriber<HttpContent>() {

                private Subscription streamSub;

                @Override
                public void onSubscribe(Subscription s) {
                    streamSub = s;
                    s.request(1);
                }

                @Override
                public void onNext(HttpContent httpContent) {
                    httpContent.release();
                    streamSub.request(1);
                }

                @Override
                public void onError(Throwable t) {
                    syncWriteAndFlushNettyResponse(context, request, nettyResponse, requestCompletor);
                }

                @Override
                public void onComplete() {
                    syncWriteAndFlushNettyResponse(context, request, nettyResponse, requestCompletor);
                }
            });
        } else {
            syncWriteAndFlushNettyResponse(context, request, nettyResponse, requestCompletor);
        }
    }
}
Also used : Publishers(io.micronaut.core.async.publisher.Publishers) HttpRequestTerminatedEvent(io.micronaut.http.context.event.HttpRequestTerminatedEvent) HttpHeaders(io.micronaut.http.HttpHeaders) Internal(io.micronaut.core.annotation.Internal) NettyStreamedFileCustomizableResponseType(io.micronaut.http.server.netty.types.files.NettyStreamedFileCustomizableResponseType) ByteBufHolder(io.netty.buffer.ByteBufHolder) HttpStatus(io.micronaut.http.HttpStatus) IdleState(io.netty.handler.timeout.IdleState) NettySystemFileCustomizableResponseType(io.micronaut.http.server.netty.types.files.NettySystemFileCustomizableResponseType) NettyPartData(io.micronaut.http.server.netty.multipart.NettyPartData) TextPlainCodec(io.micronaut.runtime.http.codec.TextPlainCodec) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) Set(java.util.Set) RequestArgumentSatisfier(io.micronaut.http.server.binding.RequestArgumentSatisfier) SSLException(javax.net.ssl.SSLException) RouteInfo(io.micronaut.web.router.RouteInfo) Writable(io.micronaut.core.io.Writable) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) Body(io.micronaut.http.annotation.Body) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) InternalServerException(io.micronaut.http.server.exceptions.InternalServerException) RouteMatch(io.micronaut.web.router.RouteMatch) NettyByteBufferFactory(io.micronaut.buffer.netty.NettyByteBufferFactory) NettyMutableHttpResponse(io.micronaut.http.netty.NettyMutableHttpResponse) MonoSink(reactor.core.publisher.MonoSink) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) UriRouteMatch(io.micronaut.web.router.UriRouteMatch) HttpData(io.netty.handler.codec.http.multipart.HttpData) Nullable(io.micronaut.core.annotation.Nullable) DuplicateRouteException(io.micronaut.web.router.exceptions.DuplicateRouteException) BiConsumer(java.util.function.BiConsumer) ByteBuffer(io.micronaut.core.io.buffer.ByteBuffer) Argument(io.micronaut.core.type.Argument) HttpRequest(io.micronaut.http.HttpRequest) ConversionService(io.micronaut.core.convert.ConversionService) ServerRequestContext(io.micronaut.http.context.ServerRequestContext) ErrorResponseProcessor(io.micronaut.http.server.exceptions.response.ErrorResponseProcessor) MediaTypeCodecRegistry(io.micronaut.http.codec.MediaTypeCodecRegistry) HttpContent(io.netty.handler.codec.http.HttpContent) FileUpload(io.netty.handler.codec.http.multipart.FileUpload) ClosedChannelException(java.nio.channels.ClosedChannelException) Publisher(org.reactivestreams.Publisher) Mono(reactor.core.publisher.Mono) IOException(java.io.IOException) NettyHttpResponseBuilder(io.micronaut.http.netty.NettyHttpResponseBuilder) File(java.io.File) AbstractNettyHttpRequest(io.micronaut.http.netty.AbstractNettyHttpRequest) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) Flux(reactor.core.publisher.Flux) AtomicLong(java.util.concurrent.atomic.AtomicLong) Paths(java.nio.file.Paths) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Future(io.netty.util.concurrent.Future) RouteExecutor(io.micronaut.http.server.RouteExecutor) Sinks(reactor.core.publisher.Sinks) StreamingFileUpload(io.micronaut.http.multipart.StreamingFileUpload) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) NettyHttpServerConfiguration(io.micronaut.http.server.netty.configuration.NettyHttpServerConfiguration) FileCustomizableResponseType(io.micronaut.http.server.types.files.FileCustomizableResponseType) Unpooled(io.netty.buffer.Unpooled) CompletionAwareSubscriber(io.micronaut.core.async.subscriber.CompletionAwareSubscriber) PartData(io.micronaut.http.multipart.PartData) NettyCustomizableResponseTypeHandler(io.micronaut.http.server.netty.types.NettyCustomizableResponseTypeHandler) StaticResourceResolver(io.micronaut.web.router.resource.StaticResourceResolver) MediaType(io.micronaut.http.MediaType) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ReferenceCounted(io.micronaut.core.io.buffer.ReferenceCounted) HttpResponse(io.micronaut.http.HttpResponse) NettyCompletedFileUpload(io.micronaut.http.server.netty.multipart.NettyCompletedFileUpload) ClassUtils(io.micronaut.core.reflect.ClassUtils) Collection(java.util.Collection) MethodBasedRouteMatch(io.micronaut.web.router.MethodBasedRouteMatch) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MutableHttpResponse(io.micronaut.http.MutableHttpResponse) MutableHttpHeaders(io.micronaut.http.MutableHttpHeaders) NettyCustomizableResponseTypeHandlerRegistry(io.micronaut.http.server.netty.types.NettyCustomizableResponseTypeHandlerRegistry) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Collectors(java.util.stream.Collectors) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) Attribute(io.netty.handler.codec.http.multipart.Attribute) StreamedHttpRequest(io.micronaut.http.netty.stream.StreamedHttpRequest) DecoderResult(io.netty.handler.codec.DecoderResult) List(java.util.List) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) Optional(java.util.Optional) HttpAttributes(io.micronaut.http.HttpAttributes) Pattern(java.util.regex.Pattern) AVAILABLE_HTTP_METHODS(io.micronaut.http.HttpAttributes.AVAILABLE_HTTP_METHODS) HttpVersion(io.netty.handler.codec.http.HttpVersion) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicReference(java.util.concurrent.atomic.AtomicReference) Sharable(io.netty.channel.ChannelHandler.Sharable) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HashSet(java.util.HashSet) ErrorContext(io.micronaut.http.server.exceptions.response.ErrorContext) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Subscriber(org.reactivestreams.Subscriber) ExecutorService(java.util.concurrent.ExecutorService) HttpMethod(io.micronaut.http.HttpMethod) MediaTypeCodec(io.micronaut.http.codec.MediaTypeCodec) Logger(org.slf4j.Logger) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) ApplicationEventPublisher(io.micronaut.context.event.ApplicationEventPublisher) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) NettyStreamingFileUpload(io.micronaut.http.server.netty.multipart.NettyStreamingFileUpload) LongConsumer(java.util.function.LongConsumer) NonNull(io.micronaut.core.annotation.NonNull) CollectionUtils(io.micronaut.core.util.CollectionUtils) Subscription(org.reactivestreams.Subscription) Router(io.micronaut.web.router.Router) Collections(java.util.Collections) JsonSubscriber(io.micronaut.http.netty.stream.JsonSubscriber) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Subscription(org.reactivestreams.Subscription) ClosedChannelException(java.nio.channels.ClosedChannelException) HttpStatus(io.micronaut.http.HttpStatus) StreamedHttpRequest(io.micronaut.http.netty.stream.StreamedHttpRequest) Future(io.netty.util.concurrent.Future) AbstractNettyHttpRequest(io.micronaut.http.netty.AbstractNettyHttpRequest) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent)

Example 54 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project netconf by opendaylight.

the class TcpClientChannelInitializer method initialize.

@Override
public void initialize(final Channel ch, final Promise<NetconfClientSession> promise) {
    final Future<NetconfClientSession> negotiationFuture = promise;
    // We have to add this channel outbound handler to channel pipeline, in order
    // to get notifications from netconf negotiatior. Set connection promise to
    // success only after successful negotiation.
    ch.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {

        ChannelPromise connectPromise;

        GenericFutureListener<Future<NetconfClientSession>> negotiationFutureListener;

        @Override
        public void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise channelPromise) {
            connectPromise = channelPromise;
            ChannelPromise tcpConnectFuture = new DefaultChannelPromise(ch);
            negotiationFutureListener = future -> {
                if (future.isSuccess()) {
                    channelPromise.setSuccess();
                }
            };
            tcpConnectFuture.addListener(future -> {
                if (future.isSuccess()) {
                    // complete connection promise with netconf negotiation future
                    negotiationFuture.addListener(negotiationFutureListener);
                } else {
                    channelPromise.setFailure(future.cause());
                }
            });
            ctx.connect(remoteAddress, localAddress, tcpConnectFuture);
        }

        @Override
        public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
            if (connectPromise == null) {
                return;
            }
            // reconnect logic
            if (connectPromise.isSuccess()) {
                ctx.fireChannelInactive();
            }
            // we must set connection promise to failure
            if (!connectPromise.isDone()) {
                connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
            }
            // Remove listener from negotiation future, we don't want notifications
            // from negotiation anymore
            negotiationFuture.removeListener(negotiationFutureListener);
            super.disconnect(ctx, promise);
            promise.setSuccess();
        }
    });
    super.initialize(ch, promise);
}
Also used : Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelPromise(io.netty.channel.ChannelPromise) Promise(io.netty.util.concurrent.Promise) SocketAddress(java.net.SocketAddress) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Future(io.netty.util.concurrent.Future) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelPromise(io.netty.channel.ChannelPromise) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) Future(io.netty.util.concurrent.Future) SocketAddress(java.net.SocketAddress)

Example 55 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project netconf by opendaylight.

the class NetconfDeviceCommunicatorTest method testSendRequestWithWithSendFailure.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testSendRequestWithWithSendFailure() throws Exception {
    setupSession();
    NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
    QName rpc = QName.create("", "mockRpc");
    ArgumentCaptor<GenericFutureListener> futureListener = ArgumentCaptor.forClass(GenericFutureListener.class);
    ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
    doReturn(mockChannelFuture).when(mockChannelFuture).addListener(futureListener.capture());
    doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message));
    ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest(message, rpc);
    assertNotNull("ListenableFuture is null", resultFuture);
    verify(mockChannelFuture).addListener(futureListener.capture());
    Future<Void> operationFuture = mock(Future.class);
    doReturn(false).when(operationFuture).isSuccess();
    doReturn(new Exception("mock error")).when(operationFuture).cause();
    futureListener.getValue().operationComplete(operationFuture);
    // Should have an immediate result
    RpcResult<NetconfMessage> rpcResult = resultFuture.get(3, TimeUnit.MILLISECONDS);
    RpcError rpcError = verifyErrorRpcResult(rpcResult, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED);
    assertEquals("RpcError message contains \"mock error\"", true, rpcError.getMessage().contains("mock error"));
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NetconfMessage(org.opendaylight.netconf.api.NetconfMessage) QName(org.opendaylight.yangtools.yang.common.QName) RpcResult(org.opendaylight.yangtools.yang.common.RpcResult) RpcError(org.opendaylight.yangtools.yang.common.RpcError) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) TimeoutException(java.util.concurrent.TimeoutException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Test(org.junit.Test)

Aggregations

GenericFutureListener (io.netty.util.concurrent.GenericFutureListener)70 Future (io.netty.util.concurrent.Future)44 ChannelFuture (io.netty.channel.ChannelFuture)32 Channel (io.netty.channel.Channel)19 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)18 IOException (java.io.IOException)18 List (java.util.List)15 InetSocketAddress (java.net.InetSocketAddress)13 ArrayList (java.util.ArrayList)13 Map (java.util.Map)12 ChannelOption (io.netty.channel.ChannelOption)10 Future (io.vertx.core.Future)10 Handler (io.vertx.core.Handler)10 ContextInternal (io.vertx.core.impl.ContextInternal)10 VertxInternal (io.vertx.core.impl.VertxInternal)10 Logger (org.slf4j.Logger)10 LoggerFactory (org.slf4j.LoggerFactory)9 Bootstrap (io.netty.bootstrap.Bootstrap)8 LoggingHandler (io.netty.handler.logging.LoggingHandler)8 AsyncResult (io.vertx.core.AsyncResult)8