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:com.allanbank.mongodb.netty.NettyChannelInit.java

License:Apache License

/**
 * {@inheritDoc}/*from   w  w w.  jav  a 2s .  c o m*/
 * <p>
 * Overridden to initialize the channel's processing pipeline.
 * </p>
 */
@Override
public void initChannel(final SocketChannel ch) throws Exception {

    final ChannelPipeline pipeline = ch.pipeline();

    // Make sure we know when the connection gets closed.
    ch.closeFuture().addListener(new NettyCloseListener(myResponseListener));

    SSLEngine engine = null;
    final SocketFactory socketFactory = myClientConfig.getSocketFactory();
    if (socketFactory instanceof SslEngineFactory) {

        final SslEngineFactory factory = (SslEngineFactory) socketFactory;
        engine = factory.createSSLEngine();

    } else if (socketFactory instanceof SSLSocketFactory) {
        engine = createVanillaEngine((SSLSocketFactory) socketFactory);
    }

    if (engine != null) {
        engine.setUseClientMode(true);

        final SslHandler handler = new SslHandler(engine, false /* startTLS */);
        pipeline.addLast("ssl", handler);

        if (socketFactory instanceof SocketConnectionListener) {
            handler.handshakeFuture().addListener(new NettyTlsConnectionCompletedListener(
                    (SocketConnectionListener) socketFactory, engine, ch));
        }
    }

    // Read side.
    pipeline.addLast("readTimeoutHandler",
            new ReadTimeoutHandler(myClientConfig.getReadTimeout(), TimeUnit.MILLISECONDS));
    pipeline.addLast("bufToMessageHandler", new ByteToMessageDecoder(myDecoderCache));
    pipeline.addLast("replyHandler", new NettyReplyHandler(myResponseListener));
}

From source file:com.codeabovelab.dm.platform.http.async.NettyRequestFactory.java

License:Apache License

private Bootstrap getBootstrap() {
    if (this.bootstrap == null) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(this.eventLoopGroup).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override// w  w  w  .  j a va2s.  c o m
                    protected void initChannel(SocketChannel channel) throws Exception {
                        configureChannel(channel.config());
                        ChannelPipeline pipeline = channel.pipeline();
                        if (sslContext != null) {
                            pipeline.addLast(sslContext.newHandler(channel.alloc()));
                        }
                        pipeline.addLast(new HttpClientCodec());
                        //pipeline.addLast(new HttpObjectAggregator(maxResponseSize));
                        if (readTimeout > 0) {
                            pipeline.addLast(new ReadTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS));
                        }
                    }
                });
        this.bootstrap = bootstrap;
    }
    return this.bootstrap;
}

From source file:com.codebullets.external.party.simulator.connections.websocket.inbound.WebSocketServerInitializer.java

License:Apache License

@Override
public void initChannel(final SocketChannel ch) throws Exception {
    long timeoutVal = connectionConfig.getTimeout() > 0 ? connectionConfig.getTimeout() : DEFAULT_TIMEOUT;

    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("codec-http", new HttpServerCodec());
    pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(timeoutVal, TimeUnit.MILLISECONDS));
    pipeline.addLast("aggregator", new HttpObjectAggregator(Integer.MAX_VALUE));
    pipeline.addLast("handler", new NettyWebSocketServerHandler(endpoint, connectionMonitor,
            connectionConfig.getName(), connectedChannels));
}

From source file:com.mongodb.connection.netty.NettyStream.java

License:Apache License

@Override
public void openAsync(final AsyncCompletionHandler<Void> handler) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup);//from w ww.  j a v a  2s . co m
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, settings.getConnectTimeout(MILLISECONDS));
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, settings.isKeepAlive());

    if (settings.getReceiveBufferSize() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, settings.getReceiveBufferSize());
    }
    if (settings.getSendBufferSize() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, settings.getSendBufferSize());
    }
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(final SocketChannel ch) throws Exception {
            if (sslSettings.isEnabled()) {
                SSLEngine engine = SSLContext.getDefault().createSSLEngine(address.getHost(),
                        address.getPort());
                engine.setUseClientMode(true);
                if (!sslSettings.isInvalidHostNameAllowed()) {
                    engine.setSSLParameters(enableHostNameVerification(engine.getSSLParameters()));
                }
                ch.pipeline().addFirst("ssl", new SslHandler(engine, false));
            }
            ch.pipeline().addLast("readTimeoutHandler",
                    new ReadTimeoutHandler(settings.getReadTimeout(MILLISECONDS), MILLISECONDS));
            ch.pipeline().addLast(new InboundBufferHandler());
        }
    });
    final ChannelFuture channelFuture = bootstrap.connect(address.getHost(), address.getPort());
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = channelFuture.channel();
                handler.completed(null);
            } else {
                handler.failed(future.cause());
            }
        }
    });
}

From source file:com.relayrides.pushy.apns.FeedbackServiceClient.java

License:Open Source License

/**
 * <p>Retrieves a list of expired tokens from the APNs feedback service. Be warned that this is a
 * <strong>destructive operation</strong>. According to Apple's documentation:</p>
 *
 * <blockquote>The feedback service's list is cleared after you read it. Each time you connect to the feedback
 * service, the information it returns lists only the failures that have happened since you last
 * connected.</blockquote>// w w  w .  jav  a 2 s . c om
 *
 * @param timeout the time after the last received data after which the connection to the feedback service should
 * be closed
 * @param timeoutUnit the unit of time in which the given {@code timeout} is measured
 *
 * @return a list of tokens that have expired since the last connection to the feedback service
 *
 * @throws InterruptedException if interrupted while waiting for a response from the feedback service
 * @throws FeedbackConnectionException if the connection to the feedback service failed for any reason
 */
public synchronized List<ExpiredToken> getExpiredTokens(final long timeout, final TimeUnit timeoutUnit)
        throws InterruptedException, FeedbackConnectionException {

    this.expiredTokens.clear();

    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(this.eventLoopGroup);
    bootstrap.channel(NioSocketChannel.class);

    final FeedbackServiceClient feedbackClient = this;
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();

            final SSLEngine sslEngine = feedbackClient.sslContext.createSSLEngine();
            sslEngine.setUseClientMode(true);

            pipeline.addLast("ssl", new SslHandler(sslEngine));
            pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(timeout, timeoutUnit));
            pipeline.addLast("decoder", new ExpiredTokenDecoder());
            pipeline.addLast("handler", new FeedbackClientHandler(feedbackClient));
        }

    });

    final ChannelFuture connectFuture = bootstrap
            .connect(this.environment.getFeedbackHost(), this.environment.getFeedbackPort()).await();

    if (connectFuture.isSuccess()) {
        log.debug("Connected to feedback service.");

        final SslHandler sslHandler = connectFuture.channel().pipeline().get(SslHandler.class);

        if (sslHandler != null) {
            final Future<Channel> handshakeFuture = sslHandler.handshakeFuture().await();

            if (handshakeFuture.isSuccess()) {
                log.debug("Completed TLS handshake with feedback service.");

                // The feedback service will send us a list of device tokens as soon as we complete the SSL
                // handshake, then hang up. While we're waiting to sync with the connection closure, we'll be
                // receiving messages from the feedback service from another thread.
                connectFuture.channel().closeFuture().await();
            } else {
                log.debug("Failed to complete TLS handshake with feedback service.", handshakeFuture.cause());

                connectFuture.channel().close().await();
                throw new FeedbackConnectionException(handshakeFuture.cause());
            }
        } else {
            log.warn("Feedback client failed to get SSL handler and could not wait for TLS handshake.");

            connectFuture.channel().close().await();
            throw new FeedbackConnectionException(null);
        }
    } else {
        log.debug("Failed to connect to feedback service.", connectFuture.cause());
        throw new FeedbackConnectionException(connectFuture.cause());
    }

    return new ArrayList<ExpiredToken>(this.expiredTokens);
}

From source file:de.codecentric.boot.admin.server.web.client.InstanceWebClient.java

License:Apache License

private static WebClient createDefaultWebClient(Duration connectTimeout, Duration readTimeout,
        WebClientCustomizer customizer) {
    ReactorClientHttpConnector connector = new ReactorClientHttpConnector(
            options -> options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout.toMillis())
                    .compression(true).afterNettyContextInit(ctx -> {
                        ctx.addHandlerLast(
                                new ReadTimeoutHandler(readTimeout.toMillis(), TimeUnit.MILLISECONDS));
                    }));//w  w  w . jav a 2s. c  o  m

    WebClient.Builder builder = WebClient.builder().clientConnector(connector).defaultHeader(HttpHeaders.ACCEPT,
            ActuatorMediaType.V2_JSON, ActuatorMediaType.V1_JSON, MediaType.APPLICATION_JSON_VALUE);
    customizer.customize(builder);
    return builder.build();
}

From source file:io.werval.server.netty.HttpServerChannelInitializer.java

License:Apache License

@Override
public void initChannel(Channel channel) {
    ChannelPipeline pipeline = channel.pipeline();

    // Connection Events
    String remoteHostString = ((InetSocketAddress) channel.remoteAddress()).getHostString();
    app.events().emit(new ConnectionEvent.Opened(remoteHostString));
    channel.closeFuture()//from w w  w  .j  a  v  a  2  s.  c  o  m
            .addListener(future -> app.events().emit(new ConnectionEvent.Closed(remoteHostString)));

    if (app.config().bool(WERVAL_HTTP_LOG_LOWLEVEL_ENABLED)) {
        // Log Netty Bytes
        LogLevel level = LogLevel.valueOf(app.config().string(WERVAL_HTTP_LOG_LOWLEVEL_LEVEL).toUpperCase(US));
        pipeline.addLast("byte-logging", new LoggingHandler("io.werval.server.netty.LowLevelLogger", level));
    }

    // Read/Write Timeout
    long readTimeout = app.config().seconds(WERVAL_HTTP_TIMEOUT_READ);
    long writeTimeout = app.config().seconds(WERVAL_HTTP_TIMEOUT_WRITE);
    pipeline.addLast("read-timeout", new ReadTimeoutHandler(readTimeout, SECONDS));
    pipeline.addLast("write-timeout", new WriteTimeoutHandler(writeTimeout, SECONDS));

    // HTTP Decoding / Encoding
    // HTTP decoders always generates multiple message objects per a single HTTP message:
    //
    //  1       * HttpRequest / HttpResponse
    //  0 - n   * HttpContent
    //  1       * LastHttpContent
    //
    // or a single FullHttpRequest if a handler ask for it
    pipeline.addLast("http-codec", new HttpServerCodec());

    // GZip decompression support
    pipeline.addLast("http-decompressor", new HttpContentDecompressor());

    // Allow to send chunked data
    pipeline.addLast("chunked-write-handler", new ChunkedWriteHandler());

    // Protocol Switching Handler
    pipeline.addLast("subprotocol-switcher", new SubProtocolSwitchHandler(allChannels, app, devSpi));
}

From source file:me.bigteddy98.movingmotd.ClientSideConnectionInitialization.java

License:Open Source License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipe = ch.pipeline();
    pipe.addLast("clientside_timout_handler", new ReadTimeoutHandler(30, TimeUnit.SECONDS));
    pipe.addLast("proxy_handler_clientside",
            new ClientSideConnection(this.networkManager, this.hostname, this.toPort));
}

From source file:me.bigteddy98.movingmotd.ServerSideConnectionInitialization.java

License:Open Source License

@Override
protected void initChannel(SocketChannel channel) throws Exception {
    ChannelPipeline pipe = channel.pipeline();
    pipe.addLast("serverside_timout_handler", new ReadTimeoutHandler(30, TimeUnit.SECONDS));
    pipe.addLast("proxy_handler_serverside", new ServerSideConnection(this.networkManager));
}

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

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();/*ww  w  . jav  a2  s  .  c  o m*/
    //p.addLast(new LoggingHandler(LogLevel.INFO));
    p.addLast("timeoutHandler", new ReadTimeoutHandler(60, TimeUnit.SECONDS));
    p.addLast("bytesEncoder", new ByteArrayEncoder());
    p.addLast("handshakeHandler", new InboundHandshakeHandler(client));
    p.addLast("lengthFrameDecoder", new LengthFieldBasedFrameDecoder(65535, 0, 4));
    p.addLast("peerRequestDecoder", new PeerRequestDecoder());
}