Example usage for io.netty.handler.timeout ReadTimeoutHandler ReadTimeoutHandler

List of usage examples for io.netty.handler.timeout ReadTimeoutHandler ReadTimeoutHandler

Introduction

In this page you can find the example usage for io.netty.handler.timeout ReadTimeoutHandler ReadTimeoutHandler.

Prototype

public ReadTimeoutHandler(long timeout, TimeUnit unit) 

Source Link

Document

Creates a new instance.

Usage

From source file:org.aotorrent.client.OutboundChannelInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();/*from   w  w w.  ja  v a2 s.com*/
    //p.addLast(new LoggingHandler(LogLevel.INFO));
    p.addLast("trafficCounter", torrentEngine.getCounter());
    p.addLast("timeoutHandler", new ReadTimeoutHandler(60, TimeUnit.SECONDS));
    p.addLast("bytesEncoder", new ByteArrayEncoder());
    p.addLast("handshakeHandler", new OutboundHandshakeHandler(torrentEngine));
    p.addLast("lengthFrameDecoder", new LengthFieldBasedFrameDecoder(65535, 0, 4));
    p.addLast("peerRequestDecoder", new PeerRequestDecoder());
}

From source file:org.apache.camel.component.netty4.DefaultClientInitializerFactory.java

License:Apache License

protected void initChannel(Channel ch) throws Exception {
    // create a new pipeline
    ChannelPipeline channelPipeline = ch.pipeline();

    SslHandler sslHandler = configureClientSSLOnDemand();
    if (sslHandler != null) {
        //TODO  must close on SSL exception
        //sslHandler.setCloseOnSSLException(true);
        LOG.debug("Client SSL handler configured and added to the ChannelPipeline: {}", sslHandler);
        addToPipeline("ssl", channelPipeline, sslHandler);
    }/*from   w  w w  .  j av  a  2 s  .  c  om*/

    List<ChannelHandler> decoders = producer.getConfiguration().getDecoders();
    for (int x = 0; x < decoders.size(); x++) {
        ChannelHandler decoder = decoders.get(x);
        if (decoder instanceof ChannelHandlerFactory) {
            // use the factory to create a new instance of the channel as it may not be shareable
            decoder = ((ChannelHandlerFactory) decoder).newChannelHandler();
        }
        addToPipeline("decoder-" + x, channelPipeline, decoder);
    }

    List<ChannelHandler> encoders = producer.getConfiguration().getEncoders();
    for (int x = 0; x < encoders.size(); x++) {
        ChannelHandler encoder = encoders.get(x);
        if (encoder instanceof ChannelHandlerFactory) {
            // use the factory to create a new instance of the channel as it may not be shareable
            encoder = ((ChannelHandlerFactory) encoder).newChannelHandler();
        }
        addToPipeline("encoder-" + x, channelPipeline, encoder);
    }

    // do we use request timeout?
    if (producer.getConfiguration().getRequestTimeout() > 0) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using request timeout {} millis", producer.getConfiguration().getRequestTimeout());
        }
        ChannelHandler timeout = new ReadTimeoutHandler(producer.getConfiguration().getRequestTimeout(),
                TimeUnit.MILLISECONDS);
        addToPipeline("timeout", channelPipeline, timeout);
    }

    // our handler must be added last
    addToPipeline("handler", channelPipeline, new ClientChannelHandler(producer));

    LOG.trace("Created ChannelPipeline: {}", channelPipeline);

}

From source file:org.apache.camel.component.netty4.http.HttpClientInitializerFactory.java

License:Apache License

@Override
protected void initChannel(Channel ch) throws Exception {
    // create a new pipeline
    ChannelPipeline pipeline = ch.pipeline();

    SslHandler sslHandler = configureClientSSLOnDemand();
    if (sslHandler != null) {
        //TODO must close on SSL exception
        //sslHandler.setCloseOnSSLException(true);
        LOG.debug("Client SSL handler configured and added as an interceptor against the ChannelPipeline: {}",
                sslHandler);//from   w ww  .  j av a  2 s.co  m
        pipeline.addLast("ssl", sslHandler);
    }

    pipeline.addLast("http", new HttpClientCodec());

    List<ChannelHandler> encoders = producer.getConfiguration().getEncoders();
    for (int x = 0; x < encoders.size(); x++) {
        ChannelHandler encoder = encoders.get(x);
        if (encoder instanceof ChannelHandlerFactory) {
            // use the factory to create a new instance of the channel as it may not be shareable
            encoder = ((ChannelHandlerFactory) encoder).newChannelHandler();
        }
        pipeline.addLast("encoder-" + x, encoder);
    }

    List<ChannelHandler> decoders = producer.getConfiguration().getDecoders();
    for (int x = 0; x < decoders.size(); x++) {
        ChannelHandler decoder = decoders.get(x);
        if (decoder instanceof ChannelHandlerFactory) {
            // use the factory to create a new instance of the channel as it may not be shareable
            decoder = ((ChannelHandlerFactory) decoder).newChannelHandler();
        }
        pipeline.addLast("decoder-" + x, decoder);
    }
    pipeline.addLast("aggregator", new HttpObjectAggregator(configuration.getChunkedMaxContentLength()));

    if (producer.getConfiguration().getRequestTimeout() > 0) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using request timeout {} millis", producer.getConfiguration().getRequestTimeout());
        }
        ChannelHandler timeout = new ReadTimeoutHandler(producer.getConfiguration().getRequestTimeout(),
                TimeUnit.MILLISECONDS);
        pipeline.addLast("timeout", timeout);
    }

    // handler to route Camel messages
    pipeline.addLast("handler", new HttpClientChannelHandler(producer));

}

From source file:org.apache.hadoop.hbase.ipc.NettyRpcConnection.java

License:Apache License

private void saslNegotiate(final Channel ch) {
    UserGroupInformation ticket = getUGI();
    if (ticket == null) {
        failInit(ch, new FatalConnectionException("ticket/user is null"));
        return;/* ww  w  . j a  v a  2  s. c  o  m*/
    }
    Promise<Boolean> saslPromise = ch.eventLoop().newPromise();
    final NettyHBaseSaslRpcClientHandler saslHandler;
    try {
        saslHandler = new NettyHBaseSaslRpcClientHandler(saslPromise, ticket, authMethod, token,
                serverPrincipal, rpcClient.fallbackAllowed, this.rpcClient.conf);
    } catch (IOException e) {
        failInit(ch, e);
        return;
    }
    ch.pipeline().addFirst(new SaslChallengeDecoder(), saslHandler);
    saslPromise.addListener(new FutureListener<Boolean>() {

        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            if (future.isSuccess()) {
                ChannelPipeline p = ch.pipeline();
                p.remove(SaslChallengeDecoder.class);
                p.remove(NettyHBaseSaslRpcClientHandler.class);

                // check if negotiate with server for connection header is necessary
                if (saslHandler.isNeedProcessConnectionHeader()) {
                    Promise<Boolean> connectionHeaderPromise = ch.eventLoop().newPromise();
                    // create the handler to handle the connection header
                    ChannelHandler chHandler = new NettyHBaseRpcConnectionHeaderHandler(connectionHeaderPromise,
                            conf, connectionHeaderWithLength);

                    // add ReadTimeoutHandler to deal with server doesn't response connection header
                    // because of the different configuration in client side and server side
                    p.addFirst(new ReadTimeoutHandler(RpcClient.DEFAULT_SOCKET_TIMEOUT_READ,
                            TimeUnit.MILLISECONDS));
                    p.addLast(chHandler);
                    connectionHeaderPromise.addListener(new FutureListener<Boolean>() {
                        @Override
                        public void operationComplete(Future<Boolean> future) throws Exception {
                            if (future.isSuccess()) {
                                ChannelPipeline p = ch.pipeline();
                                p.remove(ReadTimeoutHandler.class);
                                p.remove(NettyHBaseRpcConnectionHeaderHandler.class);
                                // don't send connection header, NettyHbaseRpcConnectionHeaderHandler
                                // sent it already
                                established(ch);
                            } else {
                                final Throwable error = future.cause();
                                scheduleRelogin(error);
                                failInit(ch, toIOE(error));
                            }
                        }
                    });
                } else {
                    // send the connection header to server
                    ch.write(connectionHeaderWithLength.retainedDuplicate());
                    established(ch);
                }
            } else {
                final Throwable error = future.cause();
                scheduleRelogin(error);
                failInit(ch, toIOE(error));
            }
        }
    });
}

From source file:org.apache.jackrabbit.oak.plugins.segment.standby.client.StandbyClient.java

License:Apache License

public void run() {
    if (!isRunning()) {
        // manually stopped
        return;/*from   www.j a  v a2s .c  o m*/
    }

    Bootstrap b;
    synchronized (this.sync) {
        if (this.active) {
            return;
        }
        state = STATUS_STARTING;
        handler = new StandbyClientHandler(this.store, observer, running, readTimeoutMs, autoClean);
        group = new NioEventLoopGroup();

        b = new Bootstrap();
        b.group(group);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, readTimeoutMs);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_REUSEADDR, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);

        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslContext != null) {
                    p.addLast(sslContext.newHandler(ch.alloc()));
                }
                p.addLast("readTimeoutHandler", new ReadTimeoutHandler(readTimeoutMs, TimeUnit.MILLISECONDS));
                p.addLast(new StringEncoder(CharsetUtil.UTF_8));
                p.addLast(new SnappyFramedDecoder(true));
                p.addLast(new RecordIdDecoder(store));
                p.addLast(handler);
            }
        });
        state = STATUS_RUNNING;
        this.active = true;
    }

    try {
        long startTimestamp = System.currentTimeMillis();
        // Start the client.
        ChannelFuture f = b.connect(host, port).sync();
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
        this.failedRequests = 0;
        this.syncStartTimestamp = startTimestamp;
        this.syncEndTimestamp = System.currentTimeMillis();
        this.lastSuccessfulRequest = syncEndTimestamp / 1000;
    } catch (Exception e) {
        this.failedRequests++;
        log.error("Failed synchronizing state.", e);
    } finally {
        synchronized (this.sync) {
            this.active = false;
            shutdownNetty();
        }
    }
}

From source file:org.enderstone.server.packet.ConnectionInitializer.java

License:Open Source License

@Override
protected void initChannel(SocketChannel channel) throws Exception {
    ChannelPipeline line = channel.pipeline();
    NetworkManager manager = new NetworkManager(connectionThrottlingMap, 5000); // TODO Add config option for this
    line.addLast("packet_r_timeout", new ReadTimeoutHandler(30, TimeUnit.SECONDS));
    line.addLast("packet_rw_converter", manager.createCodex());
    line.addLast("packet_rw_reader", manager);
}

From source file:org.evilco.network.rcon.common.protocol.RconChannelInitializer.java

License:Apache License

/**
 * {@inheritDoc}/*from www.jav a2s.com*/
 */
@Override
protected void initChannel(Channel serverChannel) throws Exception {
    // read timeout
    serverChannel.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(120, TimeUnit.SECONDS));

    // add frame codec
    serverChannel.pipeline().addLast("frameCodec", FrameCodec.getInstance());

    // add protocol codec
    serverChannel.pipeline().addLast("protocol", new RconCodec(this.codecConfiguration, this.eventBus));

    // add handler
    serverChannel.pipeline().addLast("handler", this.getHandler());
}

From source file:org.graylog2.inputs.transports.HttpTransport.java

License:Open Source License

@Override
protected LinkedHashMap<String, Callable<? extends ChannelHandler>> getCustomChildChannelHandlers(
        MessageInput input) {/*  w w w .  ja va2  s .  c  o m*/
    final LinkedHashMap<String, Callable<? extends ChannelHandler>> handlers = new LinkedHashMap<>();

    if (idleWriterTimeout > 0) {
        // Install read timeout handler to close idle connections after a timeout.
        // This avoids dangling HTTP connections when the HTTP client does not close the connection properly.
        // For details see: https://github.com/Graylog2/graylog2-server/issues/3223#issuecomment-270350500
        handlers.put("read-timeout-handler", () -> new ReadTimeoutHandler(idleWriterTimeout, TimeUnit.SECONDS));
    }

    handlers.put("decoder", () -> new HttpRequestDecoder(DEFAULT_MAX_INITIAL_LINE_LENGTH,
            DEFAULT_MAX_HEADER_SIZE, maxChunkSize));
    handlers.put("aggregator", () -> new HttpObjectAggregator(maxChunkSize));
    handlers.put("encoder", HttpResponseEncoder::new);
    handlers.put("decompressor", HttpContentDecompressor::new);
    handlers.put("http-handler", () -> new HttpHandler(enableCors));
    handlers.putAll(super.getCustomChildChannelHandlers(input));

    return handlers;
}

From source file:org.restnext.server.ServerInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    if (isSslConfigured()) {
        pipeline.addLast("ssl", sslCtx.newHandler(ch.alloc()));
    }//from  ww w  .ja v  a2s. c  o m
    pipeline.addLast("http", new HttpServerCodec());
    pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
    if (compressor != null) {
        pipeline.addLast("compressor",
                new CustomHttpContentCompressor(compressor.level, compressor.contentLength, compressor.types));
    }
    pipeline.addLast("streamer", new ChunkedWriteHandler());
    pipeline.addLast("timeout", new ReadTimeoutHandler(timeout.getSeconds(), TimeUnit.SECONDS));
    // Tell the pipeline to run MyBusinessLogicHandler's event handler methods in a different
    // thread than an I/O thread so that the I/O thread is not blocked by a time-consuming task.
    // If your business logic is fully asynchronous or finished very quickly, you don't need to
    // specify a group.
    if (group != null) {
        pipeline.addLast(group, "handler", ServerHandler.INSTANCE);
    } else {
        pipeline.addLast("handler", ServerHandler.INSTANCE);
    }
}

From source file:ratpack.http.client.internal.RequestActionSupport.java

License:Apache License

public void execute(final Fulfiller<? super T> fulfiller) throws Exception {
    final AtomicBoolean redirecting = new AtomicBoolean();

    final Bootstrap b = new Bootstrap();
    b.group(this.execution.getEventLoop()).channel(ChannelImplDetector.getSocketChannelImpl())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from  ww  w.  ja  v a  2  s.c o m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();

                    if (finalUseSsl) {
                        SSLEngine engine = SSLContext.getDefault().createSSLEngine();
                        engine.setUseClientMode(true);
                        p.addLast("ssl", new SslHandler(engine));
                    }

                    p.addLast("codec", new HttpClientCodec());
                    p.addLast("readTimeout",
                            new ReadTimeoutHandler(requestParams.readTimeoutNanos, TimeUnit.NANOSECONDS));

                    p.addLast("redirectHandler", new SimpleChannelInboundHandler<HttpObject>(false) {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
                                throws Exception {
                            if (msg instanceof HttpResponse) {
                                final HttpResponse response = (HttpResponse) msg;
                                final Headers headers = new NettyHeadersBackedHeaders(response.headers());
                                final Status status = new DefaultStatus(response.status());
                                int maxRedirects = requestSpecBacking.getMaxRedirects();
                                String locationValue = headers.get("Location");

                                //Check for redirect and location header if it is follow redirect if we have request forwarding left
                                if (shouldRedirect(status) && maxRedirects > 0 && locationValue != null) {
                                    redirecting.compareAndSet(false, true);

                                    Action<? super RequestSpec> redirectRequestConfig = Action
                                            .join(requestConfigurer, s -> {
                                                if (status.getCode() == 301 || status.getCode() == 302) {
                                                    s.method("GET");
                                                }

                                                s.redirects(maxRedirects - 1);
                                            });

                                    URI locationUrl;
                                    if (ABSOLUTE_PATTERN.matcher(locationValue).matches()) {
                                        locationUrl = new URI(locationValue);
                                    } else {
                                        locationUrl = new URI(uri.getScheme(), null, uri.getHost(),
                                                uri.getPort(), locationValue, null, null);
                                    }

                                    buildRedirectRequestAction(redirectRequestConfig, locationUrl)
                                            .execute(fulfiller);
                                } else {
                                    p.remove(this);
                                }
                            }

                            if (!redirecting.get()) {
                                ctx.fireChannelRead(msg);
                            }
                        }
                    });

                    addResponseHandlers(p, fulfiller);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    ctx.close();
                    error(fulfiller, cause);
                }
            });

    ChannelFuture connectFuture = b.connect(host, port);
    connectFuture.addListener(f1 -> {
        if (connectFuture.isSuccess()) {
            String fullPath = getFullPath(uri);
            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(requestSpecBacking.getMethod()), fullPath, requestSpecBacking.getBody());
            if (headers.get(HttpHeaderConstants.HOST) == null) {
                headers.set(HttpHeaderConstants.HOST, host);
            }
            headers.set(HttpHeaderConstants.CONNECTION, HttpHeaderValues.CLOSE);
            int contentLength = request.content().readableBytes();
            if (contentLength > 0) {
                headers.set(HttpHeaderConstants.CONTENT_LENGTH, Integer.toString(contentLength, 10));
            }

            HttpHeaders requestHeaders = request.headers();

            for (String name : headers.getNames()) {
                requestHeaders.set(name, headers.getAll(name));
            }

            ChannelFuture writeFuture = connectFuture.channel().writeAndFlush(request);
            writeFuture.addListener(f2 -> {
                if (!writeFuture.isSuccess()) {
                    writeFuture.channel().close();
                    error(fulfiller, writeFuture.cause());
                }
            });
        } else {
            connectFuture.channel().close();
            error(fulfiller, connectFuture.cause());
        }
    });
}