io.netty.handler.timeout.ReadTimeoutHandler Java Examples

The following examples show how to use io.netty.handler.timeout.ReadTimeoutHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServerChannelInitializer.java    From Velocity with MIT License 6 votes vote down vote up
@Override
protected void initChannel(final Channel ch) {
  ch.pipeline()
      .addLast(READ_TIMEOUT,
          new ReadTimeoutHandler(this.server.getConfiguration().getReadTimeout(),
              TimeUnit.MILLISECONDS))
      .addLast(LEGACY_PING_DECODER, new LegacyPingDecoder())
      .addLast(FRAME_DECODER, new MinecraftVarintFrameDecoder())
      .addLast(LEGACY_PING_ENCODER, LegacyPingEncoder.INSTANCE)
      .addLast(FRAME_ENCODER, MinecraftVarintLengthEncoder.INSTANCE)
      .addLast(MINECRAFT_DECODER, new MinecraftDecoder(ProtocolUtils.Direction.SERVERBOUND))
      .addLast(MINECRAFT_ENCODER, new MinecraftEncoder(ProtocolUtils.Direction.CLIENTBOUND));

  final MinecraftConnection connection = new MinecraftConnection(ch, this.server);
  connection.setSessionHandler(new HandshakeSessionHandler(connection, this.server));
  ch.pipeline().addLast(Connections.HANDLER, connection);

  if (this.server.getConfiguration().isProxyProtocol()) {
    ch.pipeline().addFirst(new HAProxyMessageDecoder());
  }
}
 
Example #2
Source File: InstanceWebClient.java    From Moss with Apache License 2.0 6 votes vote down vote up
private static WebClient.Builder createDefaultWebClient(Duration connectTimeout, Duration readTimeout) {
    HttpClient httpClient = HttpClient.create()
                                      .compress(true)
                                      .tcpConfiguration(tcp -> tcp.bootstrap(bootstrap -> bootstrap.option(
                                          ChannelOption.CONNECT_TIMEOUT_MILLIS,
                                          (int) connectTimeout.toMillis()
                                      )).observe((connection, newState) -> {
                                          if (ConnectionObserver.State.CONNECTED.equals(newState)) {
                                              connection.addHandlerLast(new ReadTimeoutHandler(readTimeout.toMillis(),
                                                  TimeUnit.MILLISECONDS
                                              ));
                                          }
                                      }));
    ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
    return WebClient.builder().clientConnector(connector);
}
 
Example #3
Source File: OvsdbChannelInitializer.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel channel) throws Exception {

    ChannelPipeline pipeline = channel.pipeline();
    if (sslContext != null) {
        log.info("OVSDB SSL enabled.");
        SSLEngine sslEngine = sslContext.createSSLEngine();

        sslEngine.setNeedClientAuth(true);
        sslEngine.setUseClientMode(false);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);

        SslHandler sslHandler = new SslHandler(sslEngine);
        pipeline.addLast("ssl", sslHandler);
    } else {
        log.info("OVSDB SSL disabled.");
    }
    pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
    pipeline.addLast(new MessageDecoder());

    pipeline.addLast(new IdleStateHandler(READER_IDLE_TIME, WRITER_IDLE_TIME, ALL_IDLE_TIME));
    pipeline.addLast(new ReadTimeoutHandler(TIMEOUT));
    controller.handleNewNodeConnection(channel);
}
 
Example #4
Source File: NettyHttpClientPipelineFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    SslHandler sslHandler = configureClientSSLOnDemand();
    if (sslHandler != null) {
        LOG.log(Level.FINE,
                "Server SSL handler configured and added as an interceptor against the ChannelPipeline: {}",
                sslHandler);
        pipeline.addLast("ssl", sslHandler);
    }


    pipeline.addLast("decoder", new HttpResponseDecoder());
    // TODO need to configure the aggregator size
    pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
    pipeline.addLast("encoder", new HttpRequestEncoder());
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
    if (readTimeout > 0) {
        pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS));
    }
    pipeline.addLast("client", new NettyHttpClientHandler());
}
 
Example #5
Source File: TimeoutLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
private ReactorClientHttpConnector getConnector() throws SSLException {
    SslContext sslContext = SslContextBuilder
            .forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .build();

    TcpClient tcpClient = TcpClient
      .create()
      .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT_MILLIS)
      .doOnConnected(connection -> {
          connection.addHandlerLast(new ReadTimeoutHandler(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
          connection.addHandlerLast(new WriteTimeoutHandler(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
      });

    HttpClient httpClient = HttpClient.from(tcpClient).secure(t -> t.sslContext(sslContext));
    return new ReactorClientHttpConnector(httpClient);
}
 
Example #6
Source File: ServerChannelInitializer.java    From ThinkMap with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline = socketChannel.pipeline();
    pipeline.addLast("timeout", new ReadTimeoutHandler(15));
    pipeline.addLast("codec-http", new HttpServerCodec());
    pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
    pipeline.addLast("handler", new HTTPHandler(plugin));
    pipeline.addLast("websocket", new WebSocketServerProtocolHandler("/server"));
    pipeline.addLast("packet-decoder", new PacketDecoder());
    pipeline.addLast("packet-encoder", new PacketEncoder());
    pipeline.addLast("packet-handler", new ClientHandler(socketChannel, plugin));

    socketChannel.config().setAllocator(PooledByteBufAllocator.DEFAULT);

    plugin.getWebHandler().getChannelGroup().add(socketChannel);
}
 
Example #7
Source File: NettyPistachioClientInitializer.java    From Pistachio with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc(), NettyPistachioClient.HOST, NettyPistachioClient.PORT));
    }

    LogLevel level = LogLevel.DEBUG;


    p.addLast(new LoggingHandler(level));
    p.addLast(new ReadTimeoutHandler(ConfigurationManager.getConfiguration().getInt("Network.Netty.ClientReadTimeoutMillis",10000), TimeUnit.MILLISECONDS));
    p.addLast(new ProtobufVarint32FrameDecoder());
    p.addLast(new ProtobufDecoder(NettyPistachioProtocol.Response.getDefaultInstance()));

    p.addLast(new ProtobufVarint32LengthFieldPrepender());
    p.addLast(new ProtobufEncoder());

    p.addLast(new NettyPistachioClientHandler());
}
 
Example #8
Source File: BaseNet.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static Channel connect(ByteToMessageDecoder decoder) throws InterruptedException {
  NioEventLoopGroup group = new NioEventLoopGroup(1);
  Bootstrap b = new Bootstrap();
  b.group(group).channel(NioSocketChannel.class)
      .handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
          ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(256 * 1024));
          ch.config().setOption(ChannelOption.SO_RCVBUF, 256 * 1024);
          ch.config().setOption(ChannelOption.SO_BACKLOG, 1024);
          ch.pipeline()
              .addLast("readTimeoutHandler", new ReadTimeoutHandler(600, TimeUnit.SECONDS))
              .addLast("writeTimeoutHandler", new WriteTimeoutHandler(600, TimeUnit.SECONDS));
          ch.pipeline().addLast("protoPender", new ProtobufVarint32LengthFieldPrepender());
          ch.pipeline().addLast("lengthDecode", new ProtobufVarint32FrameDecoder());
          ch.pipeline().addLast("handshakeHandler", decoder);
          ch.closeFuture();
        }
      }).option(ChannelOption.SO_KEEPALIVE, true)
      .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60000)
      .option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
  return b.connect("127.0.0.1", port).sync().channel();
}
 
Example #9
Source File: EtcdNettyClient.java    From etcd4j with Apache License 2.0 6 votes vote down vote up
/**
 * Modify the pipeline for the request
 *
 * @param req      to process
 * @param pipeline to modify
 * @param <R>      Type of Response
 */
private <R> void modifyPipeLine(final EtcdRequest<R> req, final ChannelPipeline pipeline) {
  final EtcdResponseHandler<R> handler = new EtcdResponseHandler<>(this, req);

  if (req.hasTimeout()) {
    pipeline.addFirst(new ReadTimeoutHandler(req.getTimeout(), req.getTimeoutUnit()));
  }

  pipeline.addLast(handler);
  pipeline.addLast(new ChannelHandlerAdapter() {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
      handler.retried(true);
      req.getPromise().handleRetry(cause);
    }
  });
}
 
Example #10
Source File: HttpClient.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
private Bootstrap bootstrap(ClientHandler handler) {
    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup(1))
            .channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10 * 1000)
            .handler(
                    new ChannelInitializer<Channel>() {
                        @Override
                        public void initChannel(Channel ch) {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new ReadTimeoutHandler(10 * 60 * 1000));
                            p.addLast(new HttpClientCodec());
                            p.addLast(new HttpContentDecompressor());
                            p.addLast(new ChunkedWriteHandler());
                            p.addLast(new HttpObjectAggregator(6553600));
                            p.addLast(handler);
                        }
                    });
    return b;
}
 
Example #11
Source File: HttpServerInitializer.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
	ChannelPipeline pipeline = ch.pipeline();
	if (sslCtx != null) {
		pipeline.addLast(sslCtx.newHandler(ch.alloc()));
	}
	pipeline.addLast(new HttpResponseEncoder());
	pipeline.addLast(new HttpRequestDecoder());
	// Uncomment the following line if you don't want to handle HttpChunks.
	//pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
	//p.addLast(new HttpObjectAggregator(1048576));
	// Remove the following line if you don't want automatic content compression.
	//pipeline.addLast(new HttpContentCompressor());
	
	// Uncomment the following line if you don't want to handle HttpContents.
	pipeline.addLast(new HttpObjectAggregator(65536));
	pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(READ_TIMEOUT));
	pipeline.addLast("myHandler", new MyHandler());
	
	pipeline.addLast("handler", new HttpServerHandler(listener));
}
 
Example #12
Source File: HandlerRemovingChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void removePerRequestHandlers(Channel channel) {
    channel.attr(IN_USE).set(false);

    // Only remove per request handler if the channel is registered
    // or open since DefaultChannelPipeline would remove handlers if
    // channel is closed and unregistered
    // See DefaultChannelPipeline.java#L1403
    if (channel.isOpen() || channel.isRegistered()) {
        removeIfExists(channel.pipeline(),
                       HttpStreamsClientHandler.class,
                       LastHttpContentHandler.class,
                       FlushOnReadHandler.class,
                       ResponseHandler.class,
                       ReadTimeoutHandler.class,
                       WriteTimeoutHandler.class);
    }
}
 
Example #13
Source File: ChannelUtilsTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void removeIfExists() throws Exception {
    MockChannel channel = null;

    try {
        channel = new MockChannel();
        ChannelPipeline pipeline = channel.pipeline();
        pipeline.addLast(new ReadTimeoutHandler(1));
        pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));

        ChannelUtils.removeIfExists(pipeline, ReadTimeoutHandler.class, LoggingHandler.class);
        assertThat(pipeline.get(ReadTimeoutHandler.class)).isNull();
        assertThat(pipeline.get(LoggingHandler.class)).isNull();
    } finally {
        Optional.ofNullable(channel).ifPresent(Channel::close);
    }

}
 
Example #14
Source File: HandlerRemovingChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    mockChannel = new MockChannel();
    pipeline = mockChannel.pipeline();
    pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
    nioEventLoopGroup = new NioEventLoopGroup();
    nioEventLoopGroup.register(mockChannel);
    RequestContext requestContext = new RequestContext(channelPool,
                                                       nioEventLoopGroup,
                                                       AsyncExecuteRequest.builder().responseHandler(responseHandler).build(),
                                                       null);

    mockChannel.attr(IN_USE).set(true);
    mockChannel.attr(REQUEST_CONTEXT_KEY).set(requestContext);
    mockChannel.attr(RESPONSE_COMPLETE_KEY).set(true);

    pipeline.addLast(new HttpStreamsClientHandler());
    pipeline.addLast(ResponseHandler.getInstance());
    pipeline.addLast(new ReadTimeoutHandler(10));
    pipeline.addLast(new WriteTimeoutHandler(10));
    handlerRemovingChannelPool = new HandlerRemovingChannelPool(channelPool);
}
 
Example #15
Source File: EppProtocolModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Provides
@EppProtocol
static ImmutableList<Provider<? extends ChannelHandler>> provideHandlerProviders(
    Provider<ProxyProtocolHandler> proxyProtocolHandlerProvider,
    @EppProtocol Provider<SslServerInitializer<NioSocketChannel>> sslServerInitializerProvider,
    @EppProtocol Provider<ReadTimeoutHandler> readTimeoutHandlerProvider,
    Provider<LengthFieldBasedFrameDecoder> lengthFieldBasedFrameDecoderProvider,
    Provider<LengthFieldPrepender> lengthFieldPrependerProvider,
    Provider<EppServiceHandler> eppServiceHandlerProvider,
    Provider<FrontendMetricsHandler> frontendMetricsHandlerProvider,
    Provider<EppQuotaHandler> eppQuotaHandlerProvider,
    Provider<FullHttpRequestRelayHandler> relayHandlerProvider) {
  return ImmutableList.of(
      proxyProtocolHandlerProvider,
      sslServerInitializerProvider,
      readTimeoutHandlerProvider,
      lengthFieldBasedFrameDecoderProvider,
      lengthFieldPrependerProvider,
      eppServiceHandlerProvider,
      frontendMetricsHandlerProvider,
      eppQuotaHandlerProvider,
      relayHandlerProvider);
}
 
Example #16
Source File: WhoisProtocolModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Provides
@WhoisProtocol
static ImmutableList<Provider<? extends ChannelHandler>> provideHandlerProviders(
    Provider<ProxyProtocolHandler> proxyProtocolHandlerProvider,
    @WhoisProtocol Provider<ReadTimeoutHandler> readTimeoutHandlerProvider,
    Provider<LineBasedFrameDecoder> lineBasedFrameDecoderProvider,
    Provider<WhoisServiceHandler> whoisServiceHandlerProvider,
    Provider<FrontendMetricsHandler> frontendMetricsHandlerProvider,
    Provider<WhoisQuotaHandler> whoisQuotaHandlerProvider,
    Provider<FullHttpRequestRelayHandler> relayHandlerProvider) {
  return ImmutableList.of(
      proxyProtocolHandlerProvider,
      readTimeoutHandlerProvider,
      lineBasedFrameDecoderProvider,
      whoisServiceHandlerProvider,
      frontendMetricsHandlerProvider,
      whoisQuotaHandlerProvider,
      relayHandlerProvider);
}
 
Example #17
Source File: HttpBlobStore.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
private void releaseDownloadChannel(Channel ch) {
  if (ch.isOpen()) {
    // The channel might have been closed due to an error, in which case its pipeline
    // has already been cleared. Closed channels can't be reused.
    try {
      ch.pipeline().remove(ReadTimeoutHandler.class);
      ch.pipeline().remove(HttpClientCodec.class);
      ch.pipeline().remove(HttpDownloadHandler.class);
    } catch (NoSuchElementException e) {
      // If the channel is in the process of closing but not yet closed, some handlers could have
      // been removed and would cause NoSuchElement exceptions to be thrown. Because handlers are
      // removed in reverse-order, if we get a NoSuchElement exception, the following handlers
      // should have been removed.
    }
  }
  channelPool.release(ch);
}
 
Example #18
Source File: HttpServerInitializer.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
	ChannelPipeline pipeline = ch.pipeline();
	if (sslCtx != null) {
		pipeline.addLast(sslCtx.newHandler(ch.alloc()));
	}
	pipeline.addLast(new HttpResponseEncoder());
	pipeline.addLast(new HttpRequestDecoder());
	// Uncomment the following line if you don't want to handle HttpChunks.
	//pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
	//p.addLast(new HttpObjectAggregator(1048576));
	// Remove the following line if you don't want automatic content compression.
	//pipeline.addLast(new HttpContentCompressor());
	
	// Uncomment the following line if you don't want to handle HttpContents.
	pipeline.addLast(new HttpObjectAggregator(65536));
	pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(READ_TIMEOUT));
	pipeline.addLast("myHandler", new MyHandler());
	
	pipeline.addLast("handler", new HttpServerHandler(listener));
}
 
Example #19
Source File: OvsdbConnectionService.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void initChannel(final SocketChannel channel) throws Exception {
    channel.pipeline().addLast(
        //new LoggingHandler(LogLevel.INFO),
        new JsonRpcDecoder(jsonRpcDecoderMaxFrameLength),
        UTF8_ENCODER,
        new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
        new ReadTimeoutHandler(READ_TIMEOUT),
        new ExceptionHandler(OvsdbConnectionService.this));
}
 
Example #20
Source File: LocalFetcher.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(Channel channel) throws Exception {
  ChannelPipeline pipeline = channel.pipeline();

  int maxChunkSize = conf.getIntVar(ConfVars.SHUFFLE_FETCHER_CHUNK_MAX_SIZE);
  int readTimeout = conf.getIntVar(ConfVars.SHUFFLE_FETCHER_READ_TIMEOUT);

  pipeline.addLast("codec", new HttpClientCodec(4096, 8192, maxChunkSize));
  pipeline.addLast("inflater", new HttpContentDecompressor());
  pipeline.addLast("timeout", new ReadTimeoutHandler(readTimeout, TimeUnit.SECONDS));
  pipeline.addLast("handler", new HttpClientHandler());
}
 
Example #21
Source File: OvsdbConnectionService.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
void initChannelImpl(final SocketChannel channel) {
    channel.pipeline().addLast(
        new JsonRpcDecoder(jsonRpcDecoderMaxFrameLength),
        UTF8_ENCODER,
        new IdleStateHandler(IDLE_READER_TIMEOUT, 0, 0),
        new ReadTimeoutHandler(READ_TIMEOUT),
        new ExceptionHandler(OvsdbConnectionService.this));
    handleNewPassiveConnection(channel);
}
 
Example #22
Source File: ReactorClientHttpConnectorCreator.java    From charon-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpConnector createConnector(TimeoutConfiguration configuration) {
    return new ReactorClientHttpConnector(httpClient.tcpConfiguration(client ->
            client.option(CONNECT_TIMEOUT_MILLIS, toMillis(configuration.getConnection()))
                    .doOnConnected(connection -> connection
                            .addHandlerLast(new ReadTimeoutHandler(configuration.getRead().toMillis(), MILLISECONDS))
                            .addHandlerLast(new WriteTimeoutHandler(configuration.getWrite().toMillis(), MILLISECONDS)))));
}
 
Example #23
Source File: EthereumChannelInitializer.java    From ethereumj with MIT License 5 votes vote down vote up
public void initChannel(NioSocketChannel ch) throws Exception {

        MessageQueue msgQueue;
        P2pHandler p2pHandler;
        EthHandler ethHandler;
        ShhHandler shhHandler;

        msgQueue = new MessageQueue(null);

        logger.info("Incoming connection from: {}", ch.toString());

        ch.remoteAddress();

        p2pHandler = new P2pHandler(msgQueue, null, false);
        p2pHandler.activate();

        ethHandler = new EthHandler(msgQueue, null, false);
        shhHandler = new ShhHandler(msgQueue, null);


        ch.pipeline().addLast("readTimeoutHandler",
                new ReadTimeoutHandler(CONFIG.peerChannelReadTimeout(), TimeUnit.SECONDS));
        ch.pipeline().addLast("out encoder", new MessageEncoder());
        ch.pipeline().addLast("in  encoder", new MessageDecoder());
        ch.pipeline().addLast(Capability.P2P, p2pHandler);
        ch.pipeline().addLast(Capability.ETH, ethHandler);
        ch.pipeline().addLast(Capability.SHH, shhHandler);

        // limit the size of receiving buffer to 1024
        ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(32368));
        ch.config().setOption(ChannelOption.SO_RCVBUF, 32368);

        peerServer.addChannel(new Channel(msgQueue, p2pHandler, ethHandler, shhHandler));

        // todo: check if have or not active peer if not set this one
    }
 
Example #24
Source File: OFChannelInitializer.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ch.pipeline().addLast(new OFMessageDecoder())
            .addLast(new OFMessageEncoder())
            .addLast(new ReadTimeoutHandler(READ_TIMEOUT))
            .addLast(new OFChannelHandler(ofSwitch));
}
 
Example #25
Source File: ITSpringConfiguredReactorClient.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
static HttpClient testHttpClient(URI baseUrl) {
	return HttpClient.create().baseUrl(baseUrl.toString())
			.tcpConfiguration(tcpClient -> tcpClient
					.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
					.doOnConnected(conn -> conn
							.addHandler(new ReadTimeoutHandler(3, TimeUnit.SECONDS))))
			.disableRetry(true).followRedirect(true);
}
 
Example #26
Source File: ProxyForwardingVoteSource.java    From NuVotifier with GNU General Public License v3.0 5 votes vote down vote up
private void forwardVote(final BackendServer server, final Vote v, final int tries) {
    nettyBootstrap.get()
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel channel) {
                    channel.pipeline().addLast(new DelimiterBasedFrameDecoder(256, true, Delimiters.lineDelimiter()));
                    channel.pipeline().addLast(new ReadTimeoutHandler(5, TimeUnit.SECONDS));
                    channel.pipeline().addLast(STRING_DECODER);
                    channel.pipeline().addLast(new VotifierProtocol2Encoder(server.key));
                    channel.pipeline().addLast(new VotifierProtocol2HandshakeHandler(v, new VotifierResponseHandler() {
                        @Override
                        public void onSuccess() {
                            if (plugin.isDebug()) {
                                plugin.getPluginLogger().info("Successfully forwarded vote " + v + " to " + server.address + ".");
                            }
                        }

                        @Override
                        public void onFailure(Throwable error) {
                            handleFailure(server, v, error, tries);
                        }
                    }, plugin));
                }
            })
            .connect(server.address)
            .addListener((ChannelFutureListener) future -> {
                if (!future.isSuccess()) {
                    handleFailure(server, v, future.cause(), tries);
                }
            });
}
 
Example #27
Source File: NettyClientServer.java    From rapid with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(final SocketChannel channel) {
    final ChannelPipeline pipeline = channel.pipeline();
    pipeline.addLast(
            new ReadTimeoutHandler(30, TimeUnit.SECONDS),
            new ObjectEncoder(),
            new ObjectDecoder(ClassResolvers.softCachingConcurrentResolver(null)),
            clientHandler);
}
 
Example #28
Source File: TcpSession.java    From PacketLib with MIT License 5 votes vote down vote up
protected void refreshReadTimeoutHandler(Channel channel) {
    if(channel != null) {
        if(this.readTimeout <= 0) {
            if(channel.pipeline().get("readTimeout") != null) {
                channel.pipeline().remove("readTimeout");
            }
        } else {
            if(channel.pipeline().get("readTimeout") == null) {
                channel.pipeline().addFirst("readTimeout", new ReadTimeoutHandler(this.readTimeout));
            } else {
                channel.pipeline().replace("readTimeout", "readTimeout", new ReadTimeoutHandler(this.readTimeout));
            }
        }
    }
}
 
Example #29
Source File: NetworkManager.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
    ch.pipeline()
            .addLast("logger", MinecraftProtocol.LOGGER_HANDLER)
            .addLast("timeout", new ReadTimeoutHandler(30))
            .addLast("legacy", new LegacyClientHandler())
            .addLast("frame_decoder", new Varint21FrameDecoder())
            .addLast("packet_decoder", new MinecraftDecoder())
            .addLast("length_prepender", MinecraftProtocol.LENGTH_PREPENDER)
            .addLast("packet_encoder", MinecraftProtocol.PACKET_ENCODER)
            .addLast("packet_handler", new ClientHandler());
}
 
Example #30
Source File: Netty4HttpServerTransport.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(Channel ch) throws Exception {
    ch.pipeline().addLast("openChannels", transport.serverOpenChannels);
    ch.pipeline().addLast("read_timeout", new ReadTimeoutHandler(transport.readTimeoutMillis, TimeUnit.MILLISECONDS));
    final HttpRequestDecoder decoder = new HttpRequestDecoder(
        Math.toIntExact(transport.maxInitialLineLength.getBytes()),
        Math.toIntExact(transport.maxHeaderSize.getBytes()),
        Math.toIntExact(transport.maxChunkSize.getBytes()));
    decoder.setCumulator(ByteToMessageDecoder.COMPOSITE_CUMULATOR);
    ch.pipeline().addLast("decoder", decoder);
    ch.pipeline().addLast("decoder_compress", new HttpContentDecompressor());
    ch.pipeline().addLast("encoder", new HttpResponseEncoder());
    final HttpObjectAggregator aggregator = new HttpObjectAggregator(Math.toIntExact(transport.maxContentLength.getBytes()));
    aggregator.setMaxCumulationBufferComponents(transport.maxCompositeBufferComponents);
    ch.pipeline().addLast("aggregator", aggregator);
    if (transport.compression) {
        ch.pipeline().addLast("encoder_compress", new HttpContentCompressor(transport.compressionLevel));
    }
    ch.pipeline().addLast("handler", new MainAndStaticFileHandler(
        nodeName,
        home,
        nodeClient,
        transport.getCorsConfig()
    ));
    pipelineRegistry.registerItems(ch.pipeline(), transport.getCorsConfig());
    if (SETTING_CORS_ENABLED.get(transport.settings())) {
        ch.pipeline().addAfter("encoder", "cors", new Netty4CorsHandler(transport.getCorsConfig()));
    }
}