io.netty.handler.timeout.ReadTimeoutException Java Examples

The following examples show how to use io.netty.handler.timeout.ReadTimeoutException. 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: InstanceWebClientTest.java    From Moss with Apache License 2.0 8 votes vote down vote up
@Test
public void should_error_on_timeout() {
    InstanceWebClient fastTimeoutClient = InstanceWebClient.builder()
                                                           .connectTimeout(Duration.ofMillis(10L))
                                                           .readTimeout(Duration.ofMillis(10L))
                                                           .build();

    wireMock.stubFor(get("/foo").willReturn(ok().withFixedDelay(100)));

    Mono<ClientResponse> exchange = fastTimeoutClient.instance(Mono.empty())
                                                     .get()
                                                     .uri(wireMock.url("/foo"))
                                                     .exchange();

    StepVerifier.create(exchange).verifyError(ReadTimeoutException.class);
}
 
Example #2
Source File: SimpleReadTimeoutHandler.java    From ProtocolSupport with GNU Affero General Public License v3.0 6 votes vote down vote up
private void initialize(final ChannelHandlerContext ctx) {
	this.lastReadTime = System.nanoTime();
	this.timeoutTask = ctx.executor().schedule(new Runnable() {
		@Override
		public void run() {
			if (ctx.channel().isOpen()) {
				long untilTimeout = timeoutTime - (Utils.currentTimeMillisFromNanoTime() - lastReadTime);
				if (untilTimeout <= 0) {
					ctx.fireExceptionCaught(ReadTimeoutException.INSTANCE);
				} else {
					ctx.executor().schedule(this, untilTimeout, TimeUnit.MILLISECONDS);
				}
			}
		}
	}, this.timeoutTime, TimeUnit.MILLISECONDS);
}
 
Example #3
Source File: ResponseHandler.java    From NioSmtpClient with Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  if (cause instanceof ReadTimeoutException) {
    LOG.warn("[{}] The channel was closed because a read timed out", connectionId);
  }

  ResponseCollector collector = responseCollector.getAndSet(null);
  if (collector != null) {
    collector.completeExceptionally(cause);
  } else {
    // this exception can't get back to the client via a future,
    // use the connection exception handler if possible
    if (exceptionHandler.isPresent()) {
      exceptionHandler.get().accept(cause);
    } else {
      super.exceptionCaught(ctx, cause);
    }
  }
}
 
Example #4
Source File: FanOutRecordsPublisherTest.java    From amazon-kinesis-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadTimeoutExceptionForShard() {
    FanOutRecordsPublisher source = new FanOutRecordsPublisher(kinesisClient, SHARD_ID, CONSUMER_ARN);

    ArgumentCaptor<FanOutRecordsPublisher.RecordFlow> flowCaptor = ArgumentCaptor
            .forClass(FanOutRecordsPublisher.RecordFlow.class);

    source.subscribe(subscriber);

    verify(kinesisClient).subscribeToShard(any(SubscribeToShardRequest.class), flowCaptor.capture());
    FanOutRecordsPublisher.RecordFlow recordFlow = flowCaptor.getValue();
    recordFlow.exceptionOccurred(new RuntimeException(ReadTimeoutException.INSTANCE));

    verify(subscriber).onSubscribe(any());
    verify(subscriber).onError(any(RetryableRetrievalException.class));
    verify(subscriber, never()).onNext(any());
    verify(subscriber, never()).onComplete();
}
 
Example #5
Source File: HttpClient.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    if (cause instanceof IOException) {
        content = "Failed to connect to MMS";
    } else if (cause instanceof ReadTimeoutException) {
        content = "Request to MMS timeout.";
    } else {
        content = cause.getMessage();
        if (content == null) {
            content = "NullPointException";
        }
        logger.error("Unknown exception", cause);
    }
    statusCode = 500;
    ctx.close();
}
 
Example #6
Source File: OFChannelHandler.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    if (cause instanceof ReadTimeoutException) {
        log.error("Connection closed because of ReadTimeoutException {}", cause.getMessage());
    } else if (cause instanceof ClosedChannelException) {
        log.error("ClosedChannelException occurred");
        return;
    } else if (cause instanceof RejectedExecutionException) {
        log.error("Could not process message: queue full");
    } else if (cause instanceof IOException) {
        log.error("IOException occurred");
    } else {
        log.error("Error while processing message from switch {}", cause.getMessage());
    }
    channel.close();
}
 
Example #7
Source File: ServerNotRespondingTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void connectionNotRespond_newRequestShouldUseNewConnection() throws Exception {
    server.ackPingOnFirstChannel = true;
    server.notRespondOnFirstChannel = true;

    // The first request picks up a non-responding channel and should fail. Channel 1
    CompletableFuture<Void> firstRequest = sendGetRequest();

    assertThatThrownBy(() -> firstRequest.join()).hasRootCauseInstanceOf(ReadTimeoutException.class);

    // The second request should pick up a new healthy channel - Channel 2
    sendGetRequest().join();

    assertThat(server.h2ConnectionCount.get()).isEqualTo(2);
    assertThat(server.closedByClientH2ConnectionCount.get()).isEqualTo(1);
}
 
Example #8
Source File: ClientRetryPolicyTest.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
@Test(groups = "unit")
public void onBeforeSendRequestNotInvoked() {
    RetryOptions retryOptions = new RetryOptions();
    GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class);

    Mockito.doReturn(Completable.complete()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false));
    ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(endpointManager, true, retryOptions);

    Exception exception = ReadTimeoutException.INSTANCE;

    RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName(
            OperationType.Create, "/dbs/db/colls/col/docs/docId", ResourceType.Document);
    dsr.requestContext = Mockito.mock(DocumentServiceRequestContext.class);

    Single<IRetryPolicy.ShouldRetryResult> shouldRetry = clientRetryPolicy.shouldRetry(exception);
    validateSuccess(shouldRetry, ShouldRetryValidator.builder()
            .withException(exception)
            .shouldRetry(false)
            .build());

    Mockito.verifyZeroInteractions(endpointManager);
}
 
Example #9
Source File: ExceptionHandler.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    if (ctx.channel().isActive()) {
        LOG.error("Exception occurred while processing connection pipeline", cause);
        if ((cause instanceof InvalidEncodingException)
                || (cause instanceof TooLongFrameException || (cause instanceof DecoderException))) {
            LOG.info("Disconnecting channel to ovsdb {}", ctx.channel());
            ctx.channel().disconnect();
            return;
        }

    /* In cases where a connection is quickly established and the closed
    Catch the IOException and close the channel. Similarly if the peer is
    powered off, Catch the read time out exception and close the channel
     */
        if ((cause instanceof IOException) || (cause instanceof ReadTimeoutException)) {
            LOG.info("Closing channel to ovsdb {}", ctx.channel());
            ctx.channel().close();
            return;
        }

        LOG.error("Exception was not handled by the exception handler, re-throwing it for next handler");
        ctx.fireExceptionCaught(cause);
    }
}
 
Example #10
Source File: InstanceWebProxy.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
public Mono<ClientResponse> forward(Instance instance, URI uri, HttpMethod method, HttpHeaders headers,
		BodyInserter<?, ? super ClientHttpRequest> bodyInserter) {
	log.trace("Proxy-Request for instance {} with URL '{}'", instance.getId(), uri);
	WebClient.RequestBodySpec bodySpec = this.instanceWebClient.instance(instance).method(method).uri(uri)
			.headers((h) -> h.addAll(headers));

	WebClient.RequestHeadersSpec<?> headersSpec = bodySpec;
	if (requiresBody(method)) {
		headersSpec = bodySpec.body(bodyInserter);
	}

	return headersSpec.exchange()
			.onErrorResume((ex) -> ex instanceof ReadTimeoutException || ex instanceof TimeoutException,
					(ex) -> Mono.fromSupplier(() -> {
						log.trace("Timeout for Proxy-Request for instance {} with URL '{}'", instance.getId(), uri);
						return ClientResponse.create(HttpStatus.GATEWAY_TIMEOUT, this.strategies).build();
					}))
			.onErrorResume(ResolveEndpointException.class, (ex) -> Mono.fromSupplier(() -> {
				log.trace("No Endpoint found for Proxy-Request for instance {} with URL '{}'", instance.getId(),
						uri);
				return ClientResponse.create(HttpStatus.NOT_FOUND, this.strategies).build();
			})).onErrorResume(IOException.class, (ex) -> Mono.fromSupplier(() -> {
				log.trace("Proxy-Request for instance {} with URL '{}' errored", instance.getId(), uri, ex);
				return ClientResponse.create(HttpStatus.BAD_GATEWAY, this.strategies).build();
			}));
}
 
Example #11
Source File: ProxyOutboundHandler.java    From JLilyPad with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext context, Throwable cause) throws Exception {
	Channel channel = context.channel();
	if(cause instanceof IOException && cause.getMessage().equals("Connection reset by peer")) {
		// ignore
	} else if(cause instanceof ReadTimeoutException) {
		// ignore
	} else if(cause instanceof DecoderException) {
		// ignore
	} else {
		cause.printStackTrace();
	}
	if(channel.isOpen()) {
		channel.close();
	}
}
 
Example #12
Source File: MinecraftConnection.java    From Velocity with MIT License 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  if (ctx.channel().isActive()) {
    if (sessionHandler != null) {
      try {
        sessionHandler.exception(cause);
      } catch (Exception ex) {
        logger.error("{}: exception handling exception in {}",
            (association != null ? association : channel.remoteAddress()), sessionHandler, cause);
      }
    }

    if (association != null) {
      if (cause instanceof ReadTimeoutException) {
        logger.error("{}: read timed out", association);
      } else {
        logger.error("{}: exception encountered in {}", association, sessionHandler, cause);
      }
    }

    installDiscardHandler(ctx);
    ctx.close();
  }
}
 
Example #13
Source File: ProxyInboundHandler.java    From JLilyPad with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext context, Throwable cause) throws Exception {
	Channel channel = context.channel();
	if(cause instanceof IOException && cause.getMessage().equals("Connection reset by peer")) {
		// ignore
	} else if(cause instanceof ReadTimeoutException) {
		// ignore
	} else if(cause instanceof DecoderException) {
		// ignore
	} else {
		cause.printStackTrace();
	}
	if(channel.isOpen()) {
		channel.close();
	}
}
 
Example #14
Source File: Channel.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void processException(Throwable throwable) {
    Throwable baseThrowable = throwable;
    while (baseThrowable.getCause() != null) {
        baseThrowable = baseThrowable.getCause();
    }
    SocketAddress address = ctx.channel().remoteAddress();
    if (throwable instanceof ReadTimeoutException ||
            throwable instanceof IOException) {
        logger.warn("Close peer {}, reason: {}", address, throwable.getMessage());
    } else if (baseThrowable instanceof P2pException) {
        logger.warn("Close peer {}, type: {}, info: {}",
                address, ((P2pException) baseThrowable).getType(), baseThrowable.getMessage());
    } else {
        logger.error("Close peer {}, exception caught", address, throwable);
    }
    close();
}
 
Example #15
Source File: RequestAttempt.java    From zuul with Apache License 2.0 5 votes vote down vote up
public void setException(Throwable t) {
    if (t != null) {
        if (t instanceof ReadTimeoutException) {
            error = "READ_TIMEOUT";
            exceptionType = t.getClass().getSimpleName();
        }
        else if (t instanceof OriginConnectException) {
            OriginConnectException oce = (OriginConnectException) t;
            if (oce.getErrorType() != null) {
                error = oce.getErrorType().toString();
            }
            else {
                error = "ORIGIN_CONNECT_ERROR";
            }

            final Throwable cause = t.getCause();
            if (cause != null) {
                exceptionType = t.getCause().getClass().getSimpleName();
            }
            else {
                exceptionType = t.getClass().getSimpleName();
            }
        }
        else if (t instanceof OutboundException) {
            OutboundException obe = (OutboundException) t;
            error = obe.getOutboundErrorType().toString();
            exceptionType = OutboundException.class.getSimpleName();
        }
        else if (t instanceof SSLHandshakeException) {
            error = t.getMessage();
            exceptionType = t.getClass().getSimpleName();
            cause = t.getCause().getMessage();
        }
        else {
            error = t.getMessage();
            exceptionType = t.getClass().getSimpleName();
            cause = Throwables.getStackTraceAsString(t);
        }
    }
}
 
Example #16
Source File: LocalFetcher.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
    throws Exception {
  if (cause instanceof ReadTimeoutException) {
    LOG.warn(cause.getMessage(), cause);
  } else {
    LOG.error("Fetch failed :", cause);
  }

  // this fetching will be retry
  finishTime = System.currentTimeMillis();
  state = TajoProtos.FetcherState.FETCH_FAILED;
  ctx.close();
}
 
Example #17
Source File: HttpDownloadHandler.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) {
  if (t instanceof ReadTimeoutException) {
    super.exceptionCaught(ctx, new DownloadTimeoutException(path, bytesReceived, contentLength));
  } else {
    super.exceptionCaught(ctx, t);
  }
}
 
Example #18
Source File: NettyHttpClientHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (cause instanceof ReadTimeoutException) {
        final NettyHttpClientRequest request = sendedQueue.poll();
        request.getCxfResponseCallback().error(new IOException(cause));
    } else {
        cause.printStackTrace();
        ctx.close();
    }
}
 
Example #19
Source File: TcpSession.java    From PacketLib with MIT License 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    String message = null;
    if(cause instanceof ConnectTimeoutException || (cause instanceof ConnectException && cause.getMessage().contains("connection timed out"))) {
        message = "Connection timed out.";
    } else if(cause instanceof ReadTimeoutException) {
        message = "Read timed out.";
    } else if(cause instanceof WriteTimeoutException) {
        message = "Write timed out.";
    } else {
        message = cause.toString();
    }

    this.disconnect(message, cause);
}
 
Example #20
Source File: RemoteFetcher.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
    throws Exception {
  if (cause instanceof ReadTimeoutException) {
    LOG.warn(cause.getMessage(), cause);
  } else {
    LOG.error("Fetch failed :", cause);
  }

  // this fetching will be retry
  IOUtils.cleanup(LOG, fc, raf);
  endFetch(FetcherState.FETCH_FAILED);
  ctx.close();
}
 
Example #21
Source File: LunaUpstreamHandler.java    From luna with MIT License 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
    Client<?> client = getClient(ctx);
    boolean isReadTimeout = e instanceof ReadTimeoutException;
    boolean isIgnoredMessage = IGNORED.contains(e.getMessage());

    if (!isReadTimeout && !isIgnoredMessage) {
        logger.warn("Disconnecting " + client + ", upstream exception thrown.", e);
    }
    client.onException(e);
    ctx.channel().close();
}
 
Example #22
Source File: TimeoutLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void shouldTimeout() {
    exception.expect(ReadTimeoutException.class);
    webTestClient.get()
      .uri("/timeout/{timeout}", 3)
      .exchange();
}
 
Example #23
Source File: NettyClientServer.java    From rapid with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
    if (cause instanceof ReadTimeoutException) {
        // do something
        LOG.info("Read timeout exception");
    } else {
        LOG.info("Exception caught at client {}", cause);
        ctx.close().addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
    }
}
 
Example #24
Source File: OriginResponseReceiver.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (edgeProxy != null) {
        LOG.error("Error from Origin connection", cause);
        if (cause instanceof ReadTimeoutException) {
            edgeProxy.getPassport().add(PassportState.ORIGIN_CH_READ_TIMEOUT);
        }
        else if (cause instanceof IOException) {
            edgeProxy.getPassport().add(PassportState.ORIGIN_CH_IO_EX);
        }
        edgeProxy.errorFromOrigin(cause);
    }
    ctx.fireExceptionCaught(cause);
}
 
Example #25
Source File: ClientResponseWriter.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    int status = 500;
    final String errorMsg = "ClientResponseWriter caught exception in client connection pipeline: " +
            ChannelUtils.channelInfoForLogging(ctx.channel());

    if (cause instanceof ZuulException) {
        final ZuulException ze = (ZuulException) cause;
        status = ze.getStatusCode();
        LOG.error(errorMsg, cause);
    }
    else if (cause instanceof ReadTimeoutException) {
        LOG.error(errorMsg + ", Read timeout fired");
        status = 504;
    }
    else {
        LOG.error(errorMsg, cause);
    }

    if (isHandlingRequest && !startedSendingResponseToClient && ctx.channel().isActive()) {
        final HttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(status));
        ctx.writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
        startedSendingResponseToClient = true;
    }
    else {
        ctx.close();
    }
}
 
Example #26
Source File: NettyRequestAttemptFactory.java    From zuul with Apache License 2.0 5 votes vote down vote up
public ErrorType mapNettyToOutboundErrorType(final Throwable t) {
    if (t instanceof ReadTimeoutException) {
        return READ_TIMEOUT;
    }

    if (t instanceof OriginConcurrencyExceededException) {
        return ORIGIN_CONCURRENCY_EXCEEDED;
    }

    if (t instanceof OriginConnectException) {
        return ((OriginConnectException) t).getErrorType();
    }

    if (t instanceof OutboundException) {
        return ((OutboundException) t).getOutboundErrorType();
    }

    if (t instanceof Errors.NativeIoException && Errors.ERRNO_ECONNRESET_NEGATIVE == ((Errors.NativeIoException) t).expectedErr()) {
        // This is a "Connection reset by peer" which we see fairly often happening when Origin servers are overloaded.
        LOG.warn("ERRNO_ECONNRESET_NEGATIVE mapped to RESET_CONNECTION", t);
        return RESET_CONNECTION;
    }

    if (t instanceof ClosedChannelException) {
        return RESET_CONNECTION;
    }

    final Throwable cause = t.getCause();
    if (cause instanceof IllegalStateException && cause.getMessage().contains("server")) {
        LOG.warn("IllegalStateException mapped to NO_AVAILABLE_SERVERS", cause);
        return NO_AVAILABLE_SERVERS;
    }

    return OTHER;
}
 
Example #27
Source File: ConnectNetworkHandler.java    From JLilyPad with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext context, Throwable cause) throws Exception {
	Channel channel = context.channel();
	if(cause instanceof IOException) {
		if(!cause.getMessage().equals("Connection reset by peer")) {
			cause.printStackTrace();
		}
	} else if (!(cause instanceof ReadTimeoutException)) {
		cause.printStackTrace();
	}
	if(channel.isOpen()) {
		channel.close();
	}
}
 
Example #28
Source File: NodeHandler.java    From JLilyPad with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext context, Throwable cause) throws Exception {
	Channel channel = context.channel();
	if(cause instanceof IOException) {
		if(!cause.getMessage().equals("Connection reset by peer")) {
			cause.printStackTrace();
		}
	} else if (!(cause instanceof ReadTimeoutException)) {
		cause.printStackTrace();
	}
	if(channel.isOpen()) {
		channel.close();
	}
}
 
Example #29
Source File: QueryUdpHandler.java    From JLilyPad with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext context, Throwable cause) throws Exception {
	if(cause instanceof IOException) {
		if(!cause.getMessage().equals("Connection reset by peer")) {
			cause.printStackTrace();
		}
	} else if (!(cause instanceof ReadTimeoutException)) {
		cause.printStackTrace();
	}
}
 
Example #30
Source File: QueryTcpHandler.java    From JLilyPad with GNU General Public License v3.0 5 votes vote down vote up
public void exceptionCaught(ChannelHandlerContext context, Throwable cause) throws Exception {
	Channel channel = context.channel();
	if(cause instanceof IOException) {
		if(!cause.getMessage().equals("Connection reset by peer")) {
			cause.printStackTrace();
		}
	} else if (!(cause instanceof ReadTimeoutException)) {
		cause.printStackTrace();
	}
	if(channel.isOpen()) {
		channel.close();
	}
}