Search in sources :

Example 91 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project grpc-java by grpc.

the class AltsProtocolNegotiatorTest method flushShouldFailAllPromises.

@Test
public void flushShouldFailAllPromises() throws Exception {
    doHandshake();
    channel.pipeline().addFirst(new ChannelDuplexHandler() {

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            throw new Exception("Fake exception");
        }
    });
    // Write the message 1 character at a time.
    String message = "hello";
    final AtomicInteger failures = new AtomicInteger();
    for (int ix = 0; ix < message.length(); ++ix) {
        ByteBuf in = Unpooled.copiedBuffer(message, ix, 1, UTF_8);
        // go/futurereturn-lsc
        @SuppressWarnings("unused") Future<?> possiblyIgnoredError = channel.write(in).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    failures.incrementAndGet();
                }
            }
        });
    }
    channel.flush();
    // Verify that the promises fail.
    assertEquals(message.length(), failures.get());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) GeneralSecurityException(java.security.GeneralSecurityException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) Test(org.junit.Test)

Example 92 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project grpc-java by grpc.

the class WriteBufferingAndExceptionHandler method exceptionCaught.

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    assert cause != null;
    Throwable previousFailure = failCause;
    Status status = Utils.statusFromThrowable(cause).augmentDescription("Channel Pipeline: " + ctx.pipeline().names());
    failWrites(status.asRuntimeException());
    // 4d. active, prev!=null[connect]: impossible, channel can't be active after a failed connect.
    if (ctx.channel().isActive() && previousFailure == null) {
        final class LogOnFailure implements ChannelFutureListener {

            @Override
            public void operationComplete(ChannelFuture future) {
                if (!future.isSuccess()) {
                    logger.log(Level.FINE, "Failed closing channel", future.cause());
                }
            }
        }
        ctx.close().addListener(new LogOnFailure());
    }
}
Also used : Status(io.grpc.Status) ChannelFuture(io.netty.channel.ChannelFuture) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 93 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project Glowstone by GlowstoneMC.

the class HttpClient method connect.

/**
 * Opens a URL.
 *
 * @param url       the URL to download
 * @param eventLoop an {@link EventLoop} that will receive the response body
 * @param callback  a callback to handle the response or any error
 */
public void connect(String url, EventLoop eventLoop, HttpCallback callback) {
    URI uri = URI.create(url);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    SslContext sslCtx = null;
    if ("https".equalsIgnoreCase(scheme)) {
        if (port == -1) {
            port = 443;
        }
        try {
            sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } catch (SSLException e) {
            callback.error(e);
            return;
        }
    } else if ("http".equalsIgnoreCase(scheme)) {
        if (port == -1) {
            port = 80;
        }
    } else {
        throw new IllegalArgumentException("Only http(s) is supported!");
    }
    new Bootstrap().group(eventLoop).resolver(resolverGroup).channel(Networking.bestSocketChannel()).handler(new HttpChannelInitializer(sslCtx, callback)).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).connect(InetSocketAddress.createUnresolved(host, port)).addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            String path = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery());
            HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
            request.headers().set(HttpHeaderNames.HOST, host);
            future.channel().writeAndFlush(request);
        } else {
            callback.error(future.cause());
        }
    });
}
Also used : HttpVersion(io.netty.handler.codec.http.HttpVersion) ChannelOption(io.netty.channel.ChannelOption) DnsServerAddressStreamProvider(io.netty.resolver.dns.DnsServerAddressStreamProvider) SequentialDnsServerAddressStreamProvider(io.netty.resolver.dns.SequentialDnsServerAddressStreamProvider) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SocketUtils(io.netty.util.internal.SocketUtils) URI(java.net.URI) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) SslContext(io.netty.handler.ssl.SslContext) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) HttpMethod(io.netty.handler.codec.http.HttpMethod) EventLoop(io.netty.channel.EventLoop) DnsServerAddressStreamProviders(io.netty.resolver.dns.DnsServerAddressStreamProviders) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) Networking(net.glowstone.net.Networking) SSLException(javax.net.ssl.SSLException) List(java.util.List) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) DnsEndpoint(net.glowstone.net.config.DnsEndpoint) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AllArgsConstructor(lombok.AllArgsConstructor) DnsAddressResolverGroup(io.netty.resolver.dns.DnsAddressResolverGroup) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Bootstrap(io.netty.bootstrap.Bootstrap) URI(java.net.URI) SSLException(javax.net.ssl.SSLException) DnsEndpoint(net.glowstone.net.config.DnsEndpoint) SslContext(io.netty.handler.ssl.SslContext)

Example 94 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project mongo-java-driver by mongodb.

the class NettyStream method writeAsync.

@Override
public void writeAsync(final List<ByteBuf> buffers, final AsyncCompletionHandler<Void> handler) {
    CompositeByteBuf composite = PooledByteBufAllocator.DEFAULT.compositeBuffer();
    for (ByteBuf cur : buffers) {
        composite.addComponent(true, ((NettyByteBuf) cur).asByteBuf());
    }
    channel.writeAndFlush(composite).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                handler.failed(future.cause());
            } else {
                handler.completed(null);
            }
        }
    });
}
Also used : CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ChannelFuture(io.netty.channel.ChannelFuture) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(org.bson.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) MongoSocketOpenException(com.mongodb.MongoSocketOpenException) MongoClientException(com.mongodb.MongoClientException) MongoSocketException(com.mongodb.MongoSocketException) MongoException(com.mongodb.MongoException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MongoInternalException(com.mongodb.MongoInternalException) ReadTimeoutException(io.netty.handler.timeout.ReadTimeoutException) MongoInterruptedException(com.mongodb.MongoInterruptedException) IOException(java.io.IOException) MongoSocketReadTimeoutException(com.mongodb.MongoSocketReadTimeoutException)

Example 95 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project vert.x by eclipse.

the class Http2ConnectionBase method close.

@Override
public Future<Void> close() {
    PromiseInternal<Void> promise = context.promise();
    ChannelPromise pr = chctx.newPromise();
    ChannelPromise channelPromise = pr.addListener(promise);
    handlerContext.writeAndFlush(Unpooled.EMPTY_BUFFER, pr);
    channelPromise.addListener((ChannelFutureListener) future -> shutdown(0L));
    return promise.future();
}
Also used : VertxException(io.vertx.core.VertxException) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) ArrayList(java.util.ArrayList) VertxByteBufAllocator(io.vertx.core.buffer.impl.VertxByteBufAllocator) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) Http2Stream(io.netty.handler.codec.http2.Http2Stream) AsyncResult(io.vertx.core.AsyncResult) HttpConnection(io.vertx.core.http.HttpConnection) Logger(io.vertx.core.impl.logging.Logger) io.netty.buffer(io.netty.buffer) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Http2Flags(io.netty.handler.codec.http2.Http2Flags) StreamPriority(io.vertx.core.http.StreamPriority) Promise(io.vertx.core.Promise) GoAway(io.vertx.core.http.GoAway) Http2FrameListener(io.netty.handler.codec.http2.Http2FrameListener) Future(io.vertx.core.Future) ChannelFuture(io.netty.channel.ChannelFuture) Http2Settings(io.netty.handler.codec.http2.Http2Settings) Nullable(io.vertx.codegen.annotations.Nullable) Objects(java.util.Objects) EventLoopContext(io.vertx.core.impl.EventLoopContext) Http2Connection(io.netty.handler.codec.http2.Http2Connection) Buffer(io.vertx.core.buffer.Buffer) Http2Headers(io.netty.handler.codec.http2.Http2Headers) Handler(io.vertx.core.Handler) ArrayDeque(java.util.ArrayDeque) ChannelPromise(io.netty.channel.ChannelPromise)

Aggregations

ChannelFutureListener (io.netty.channel.ChannelFutureListener)223 ChannelFuture (io.netty.channel.ChannelFuture)208 Channel (io.netty.channel.Channel)70 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)57 ByteBuf (io.netty.buffer.ByteBuf)49 Bootstrap (io.netty.bootstrap.Bootstrap)43 Test (org.junit.jupiter.api.Test)41 CountDownLatch (java.util.concurrent.CountDownLatch)36 IOException (java.io.IOException)35 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)33 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)31 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)31 InetSocketAddress (java.net.InetSocketAddress)27 ClosedChannelException (java.nio.channels.ClosedChannelException)25 ChannelPromise (io.netty.channel.ChannelPromise)21 Logger (org.slf4j.Logger)21 LoggerFactory (org.slf4j.LoggerFactory)21 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)20 EventLoopGroup (io.netty.channel.EventLoopGroup)18 List (java.util.List)17