com.evanlennick.retry4j.exception.UnexpectedException Java Examples

The following examples show how to use com.evanlennick.retry4j.exception.UnexpectedException. 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: CallExecutorTest.java    From retry4j with MIT License 6 votes vote down vote up
@Test(expectedExceptions = {UnexpectedException.class})
public void shouldThrowUnexpectedIfThrownExceptionCauseDoesNotMatchRetryExceptions() throws Exception {
    Callable<Boolean> callable = () -> {
        throw new Exception(new CustomTestException("message", 3));
    };

    RetryConfig retryConfig = retryConfigBuilder
            .retryOnCausedBy()
            .retryOnSpecificExceptions(IOException.class)
            .withMaxNumberOfTries(1)
            .withDelayBetweenTries(0, ChronoUnit.SECONDS)
            .withFixedBackoff()
            .build();

    new CallExecutorBuilder().config(retryConfig).build().execute(callable);
}
 
Example #2
Source File: TcpTransport.java    From bender with Apache License 2.0 6 votes vote down vote up
@Override
public void sendBatch(TransportBuffer buffer) throws TransportException {

  Buffer internalBuffer = ((TcpTransportBuffer) buffer).getInternalBuffer();

  Callable<Boolean> write = () -> {
    try {
      sink.write(internalBuffer, internalBuffer.size());
      return true;
    } catch (IOException ex) {
      throw new TransportException("Error while sending in tcp transport", ex);
    }
  };

  try {
    new CallExecutor(retryConfig).execute(write);
  } catch (RetriesExhaustedException | UnexpectedException ue) {
    throw new TransportException(ue);
  }

}
 
Example #3
Source File: CallExecutorTest_RetryOnAnyExcludingTest.java    From retry4j with MIT License 5 votes vote down vote up
@Test(expectedExceptions = {UnexpectedException.class})
public void verifyRetryOnAnyExcludingThrowsCallFailureException() {
    Callable<Boolean> callable = () -> {
        throw new UnsupportedOperationException();
    };

    RetryConfig retryConfig = retryConfigBuilder
            .retryOnAnyExceptionExcluding(UnsupportedOperationException.class)
            .withMaxNumberOfTries(1)
            .withDelayBetweenTries(0, ChronoUnit.SECONDS)
            .withFixedBackoff()
            .build();

    new CallExecutorBuilder().config(retryConfig).build().execute(callable);
}
 
Example #4
Source File: CallExecutorTest.java    From retry4j with MIT License 5 votes vote down vote up
@Test(expectedExceptions = {UnexpectedException.class})
public void verifyUnspecifiedExceptionCausesUnexpectedCallFailureException() throws Exception {
    Callable<Boolean> callable = () -> {
        throw new IllegalArgumentException();
    };

    RetryConfig retryConfig = retryConfigBuilder
            .retryOnSpecificExceptions(UnsupportedOperationException.class)
            .withMaxNumberOfTries(1)
            .withDelayBetweenTries(0, ChronoUnit.SECONDS)
            .withFixedBackoff()
            .build();

    new CallExecutorBuilder().config(retryConfig).build().execute(callable);
}
 
Example #5
Source File: CallExecutorTest.java    From retry4j with MIT License 5 votes vote down vote up
@Test(expectedExceptions = {UnexpectedException.class})
public void verifySpecificSuperclassExceptionThrowsUnexpectedException() throws Exception {
    Callable<Boolean> callable = () -> {
        throw new Exception();
    };

    RetryConfig retryConfig = retryConfigBuilder
            .retryOnSpecificExceptions(IOException.class)
            .withMaxNumberOfTries(1)
            .withDelayBetweenTries(0, ChronoUnit.SECONDS)
            .withFixedBackoff()
            .build();

    new CallExecutorBuilder().config(retryConfig).build().execute(callable);
}
 
Example #6
Source File: AsyncCallExecutorTest.java    From retry4j with MIT License 5 votes vote down vote up
@Test
public void verifyOneCall_failDueToUnexpectedException_withExecutorService() throws Exception {
    Callable<Boolean> callable = () -> { throw new RuntimeException(); };

    AsyncCallExecutor<Boolean> executor = new CallExecutorBuilder().config(failOnAnyExceptionConfig)
            .buildAsync(executorService);

    CompletableFuture<Status<Boolean>> future = executor.execute(callable);

    assertThatThrownBy(future::get)
            .isExactlyInstanceOf(ExecutionException.class)
            .hasCauseExactlyInstanceOf(UnexpectedException.class);
}
 
Example #7
Source File: AsyncCallExecutorTest.java    From retry4j with MIT License 5 votes vote down vote up
@Test
public void verifyOneCall_failDueToUnexpectedException_noExecutorService() throws Exception {
    Callable<Boolean> callable = () -> { throw new RuntimeException(); };

    AsyncCallExecutor<Boolean> executor = new CallExecutorBuilder().config(failOnAnyExceptionConfig).buildAsync();

    CompletableFuture<Status<Boolean>> future = executor.execute(callable);

    assertThatThrownBy(future::get)
            .isExactlyInstanceOf(ExecutionException.class)
            .hasCauseExactlyInstanceOf(UnexpectedException.class);
}
 
Example #8
Source File: CallExecutorTest_RetryOnAnyExcludingTest.java    From retry4j with MIT License 5 votes vote down vote up
@Test(expectedExceptions = {UnexpectedException.class})
public void verifyMultipleExceptions_throwSecondExcludedException() {
    Callable<Boolean> callable = () -> {
        throw new UnsupportedOperationException();
    };

    RetryConfig retryConfig = retryConfigBuilder
            .retryOnAnyExceptionExcluding(IllegalArgumentException.class, UnsupportedOperationException.class)
            .withMaxNumberOfTries(5)
            .withNoWaitBackoff()
            .build();

    new CallExecutorBuilder().config(retryConfig).build().execute(callable);
}
 
Example #9
Source File: CallExecutorTest_RetryOnAnyExcludingTest.java    From retry4j with MIT License 5 votes vote down vote up
@Test(expectedExceptions = {UnexpectedException.class})
public void verifyMultipleExceptions_throwFirstExcludedException() {
    Callable<Boolean> callable = () -> {
        throw new IllegalArgumentException();
    };

    RetryConfig retryConfig = retryConfigBuilder
            .retryOnAnyExceptionExcluding(IllegalArgumentException.class, UnsupportedOperationException.class)
            .withMaxNumberOfTries(5)
            .withNoWaitBackoff()
            .build();

    new CallExecutorBuilder().config(retryConfig).build().execute(callable);
}
 
Example #10
Source File: CallExecutorTest_RetryOnAnyExcludingTest.java    From retry4j with MIT License 5 votes vote down vote up
@Test(expectedExceptions = UnexpectedException.class)
public void verifySubclassOfExcludedExceptionThrowsUnexpectedException() {
    Callable<Boolean> callable = () -> {
        throw new FileNotFoundException();
    };

    RetryConfig retryConfig = retryConfigBuilder
            .retryOnAnyExceptionExcluding(IOException.class)
            .withMaxNumberOfTries(1)
            .withDelayBetweenTries(0, ChronoUnit.SECONDS)
            .withFixedBackoff()
            .build();

    new CallExecutorBuilder().config(retryConfig).build().execute(callable);
}
 
Example #11
Source File: CallExecutorTest_RetryOnCustomLogicTest.java    From retry4j with MIT License 5 votes vote down vote up
@Test(expectedExceptions = UnexpectedException.class)
public void verifyShouldNotRetryOnCustomException() {
    RetryConfig config = new RetryConfigBuilder()
            .retryOnCustomExceptionLogic(ex -> ((CustomTestException) ex).getSomeValue() > 0)
            .withFixedBackoff()
            .withDelayBetweenTries(Duration.ofMillis(1))
            .withMaxNumberOfTries(3)
            .build();

    new CallExecutorBuilder().config(config).build()
            .execute(() -> {
                throw new CustomTestException("test message", -100);
            });
}
 
Example #12
Source File: CallExecutorTest_RetryOnCustomLogicTest.java    From retry4j with MIT License 5 votes vote down vote up
@Test(expectedExceptions = UnexpectedException.class)
public void verifyShouldNotRetryOnExceptionMessage() {
    RetryConfig config = new RetryConfigBuilder()
            .retryOnCustomExceptionLogic(ex -> ex.getMessage().contains("should retry!"))
            .withFixedBackoff()
            .withDelayBetweenTries(Duration.ofMillis(1))
            .withMaxNumberOfTries(3)
            .build();

    new CallExecutorBuilder().config(config)
            .build()
            .execute(() -> {
                throw new RuntimeException("should NOT retry!");
            });
}
 
Example #13
Source File: CallExecutor.java    From retry4j with MIT License 5 votes vote down vote up
private AttemptStatus<T> tryCall(Callable<T> callable) throws UnexpectedException {
    AttemptStatus attemptStatus = new AttemptStatus();

    try {
        T callResult = callable.call();

        boolean shouldRetryOnThisResult = config.shouldRetryOnValue() && (
                (config.getValuesToExpect() != null && !isOneOfValuesToExpect(callResult))
                        || isOneOfValuesToRetryOn(callResult));
        if (shouldRetryOnThisResult) {
            attemptStatus.setSuccessful(false);
        } else {
            attemptStatus.setResult(callResult);
            attemptStatus.setSuccessful(true);
        }
    } catch (Exception e) {
        if (shouldThrowException(e)) {
            logger.trace("Throwing expected exception {}", e);
            throw new UnexpectedException("Unexpected exception thrown during retry execution!", e);
        } else {
            lastKnownExceptionThatCausedRetry = e;
            attemptStatus.setSuccessful(false);
        }
    }

    return attemptStatus;
}
 
Example #14
Source File: S3EventIterator.java    From bender with Apache License 2.0 5 votes vote down vote up
@Override
public InternalEvent next() {
  updateCursor();

  /*
   * Wrap reading next row in retry logic. This is because there is intermittent socket timeouts
   * when reading from S3 that cause the function to hang/fail.
   */
  Callable<String> callable = () -> {
    return this.lineIterator.next();
  };

  String nextRow;
  try {
    CallResults<Object> results = new CallExecutor(this.config).execute(callable);
    nextRow = (String) results.getResult();
  } catch (RetriesExhaustedException ree) {
    throw new RuntimeException(ree.getCallResults().getLastExceptionThatCausedRetry());
  } catch (UnexpectedException ue) {
    throw ue;
  }

  /*
   * Construct the internal event
   */
  return new S3InternalEvent(nextRow, this.context, this.arrivalTime,
      currentS3Entity.getObject().getKey(), currentS3Entity.getBucket().getName(),
      currentS3Entity.getObject().getVersionId());
}
 
Example #15
Source File: HttpTransport.java    From bender with Apache License 2.0 4 votes vote down vote up
public void sendBatch(byte[] raw) throws TransportException {
  /*
   * Wrap the call with retry logic to avoid intermittent ES issues.
   */
  Callable<HttpResponse> callable = () -> {
    HttpResponse resp;
    String responseString = null;
    HttpPost httpPost = new HttpPost(this.url);

    /*
     * Do the call, read response, release connection so it is available for use again, and
     * finally check the response.
     */
    try {
      if (this.useGzip) {
        resp = sendBatchCompressed(httpPost, raw);
      } else {
        resp = sendBatchUncompressed(httpPost, raw);
      }

      try {
        responseString = EntityUtils.toString(resp.getEntity());
      } catch (ParseException | IOException e) {
        throw new TransportException(
            "http transport call failed because " + resp.getStatusLine().getReasonPhrase());
      }
    } finally {
      /*
       * Always release connection otherwise it blocks future requests.
       */
      httpPost.releaseConnection();
    }

    checkResponse(resp, responseString);
    return resp;
  };

  RetryConfig config = new RetryConfigBuilder()
      .retryOnSpecificExceptions(TransportException.class).withMaxNumberOfTries(this.retries + 1)
      .withDelayBetweenTries(this.retryDelayMs, ChronoUnit.MILLIS).withExponentialBackoff()
      .build();

  try {
    new CallExecutor(config).execute(callable);
  } catch (RetriesExhaustedException ree) {
    logger.warn("transport failed after " + ree.getCallResults().getTotalTries() + " tries.");
    throw new TransportException(ree.getCallResults().getLastExceptionThatCausedRetry());
  } catch (UnexpectedException ue) {
    throw new TransportException(ue);
  }
}
 
Example #16
Source File: RetryExecutor.java    From retry4j with MIT License votes vote down vote up
S execute(Callable<T> callable, String callName) throws RetriesExhaustedException, UnexpectedException; 
Example #17
Source File: RetryExecutor.java    From retry4j with MIT License votes vote down vote up
S execute(Callable<T> callable) throws RetriesExhaustedException, UnexpectedException;