Search in sources :

Example 31 with RetryPolicy

use of net.jodah.failsafe.RetryPolicy in project failsafe by jhalterman.

the class Issue36 method retryListener_WithExceptions_ShouldBeCalled.

@Test
public void retryListener_WithExceptions_ShouldBeCalled() throws Exception {
    RetryPolicy policy = new RetryPolicy().retryIf((Boolean response) -> response != null && !response).retryOn(Exception.class).withMaxRetries(3);
    AtomicInteger listenerCallbacks = new AtomicInteger();
    try {
        Failsafe.<Boolean>with(policy).onRetry((failedResponse, exception, context) -> listenerCallbacks.incrementAndGet()).get(() -> {
            throw new RuntimeException();
        });
    } catch (RuntimeException e) {
    }
    assertEquals(listenerCallbacks.get(), 3);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Assert.fail(org.testng.Assert.fail) BeforeMethod(org.testng.annotations.BeforeMethod) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) RetryPolicy(net.jodah.failsafe.RetryPolicy) Failsafe(net.jodah.failsafe.Failsafe) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RetryPolicy(net.jodah.failsafe.RetryPolicy) Test(org.testng.annotations.Test)

Example 32 with RetryPolicy

use of net.jodah.failsafe.RetryPolicy in project failsafe by jhalterman.

the class Issue55 method shouldOnlyFallbackOnFailure.

public void shouldOnlyFallbackOnFailure() throws Throwable {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    AtomicInteger counter = new AtomicInteger();
    Failsafe.with(new RetryPolicy()).with(executor).withFallback(() -> counter.incrementAndGet()).get(() -> null);
    Thread.sleep(100);
    assertEquals(counter.get(), 0);
    Failsafe.with(new RetryPolicy().withMaxRetries(1)).with(executor).withFallback(() -> counter.incrementAndGet()).run(() -> {
        throw new RuntimeException();
    });
    Thread.sleep(100);
    assertEquals(counter.get(), 1);
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RetryPolicy(net.jodah.failsafe.RetryPolicy)

Example 33 with RetryPolicy

use of net.jodah.failsafe.RetryPolicy in project ddf by codice.

the class HttpSolrClientFactory method getHttpSolrClient.

/**
     * Creates a new {@link HttpSolrClient} using the URL, core name and configuration file name
     * provided.
     *
     * @param url        Solr server URL. If {@code null}, defaults to the system's base URL
     *                   followed by {@code /solr}.
     * @param coreName   name of the Solr core to create
     * @param configFile configuration file name. If {@code null}, defaults to
     *                   {@value #DEFAULT_SOLRCONFIG_XML}.
     * @return {@code Future} used to retrieve the new {@link HttpSolrClient} instance
     */
public static Future<SolrClient> getHttpSolrClient(@Nullable String url, String coreName, @Nullable String configFile) {
    String solrUrl = StringUtils.defaultIfBlank(url, SystemBaseUrl.constructUrl("/solr"));
    String coreUrl = url + "/" + coreName;
    if (System.getProperty("solr.data.dir") != null) {
        ConfigurationStore.getInstance().setDataDirectoryPath(System.getProperty("solr.data.dir"));
    }
    RetryPolicy retryPolicy = new RetryPolicy().withBackoff(10, TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS);
    return Failsafe.with(retryPolicy).with(executor).onRetry((c, failure, ctx) -> LOGGER.debug("Attempt {} failed to create HTTP Solr client ({}). Retrying again.", ctx.getExecutions(), coreName)).onFailedAttempt(failure -> LOGGER.debug("Attempt failed to create HTTP Solr client (" + coreName + ")", failure)).onSuccess(client -> LOGGER.debug("Successfully created HTTP Solr client ({})", coreName)).onFailure(failure -> LOGGER.warn("All attempts failed to create HTTP Solr client (" + coreName + ")", failure)).get(() -> createSolrHttpClient(solrUrl, coreName, configFile, coreUrl));
}
Also used : Arrays(java.util.Arrays) SSLContext(javax.net.ssl.SSLContext) StringUtils(org.apache.commons.lang.StringUtils) HttpHead(org.apache.http.client.methods.HttpHead) SolrClientFactory(org.codice.solr.factory.SolrClientFactory) CoreAdminResponse(org.apache.solr.client.solrj.response.CoreAdminResponse) LoggerFactory(org.slf4j.LoggerFactory) KeyStoreException(java.security.KeyStoreException) SolrServerException(org.apache.solr.client.solrj.SolrServerException) Future(java.util.concurrent.Future) HttpClient(org.apache.http.client.HttpClient) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) Nullable(javax.annotation.Nullable) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Logger(org.slf4j.Logger) SystemBaseUrl(org.codice.ddf.configuration.SystemBaseUrl) SSLContexts(org.apache.http.conn.ssl.SSLContexts) IOException(java.io.IOException) KeyStore(java.security.KeyStore) RetryPolicy(net.jodah.failsafe.RetryPolicy) FileInputStream(java.io.FileInputStream) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) Executors(java.util.concurrent.Executors) SolrClient(org.apache.solr.client.solrj.SolrClient) Failsafe(net.jodah.failsafe.Failsafe) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Paths(java.nio.file.Paths) HttpSolrClient(org.apache.solr.client.solrj.impl.HttpSolrClient) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) Collections(java.util.Collections) CoreAdminRequest(org.apache.solr.client.solrj.request.CoreAdminRequest) HttpClients(org.apache.http.impl.client.HttpClients) RetryPolicy(net.jodah.failsafe.RetryPolicy)

Example 34 with RetryPolicy

use of net.jodah.failsafe.RetryPolicy in project ddf by codice.

the class TemporaryFileBackedOutputStream method reset.

/**
     * Reset fileBackedOutputStream and retry if it fails.
     */
@SuppressWarnings("unchecked")
private void reset() {
    RetryPolicy retryPolicy = new RetryPolicy().retryOn(IOException.class).withBackoff(INITIAL_RETRY_SLEEP, MAX_DELAY, INITIAL_RETRY_SLEEP_UNIT).withMaxRetries(MAX_RETRY_ATTEMPTS);
    Failsafe.with(retryPolicy).onFailedAttempt(throwable -> LOGGER.debug("failed to delete temporary file, will retry", throwable)).onFailure(throwable -> LOGGER.debug("failed to delete temporary file", throwable)).run(fileBackedOutputStream::reset);
}
Also used : OutputStream(java.io.OutputStream) TimeUnit(java.util.concurrent.TimeUnit) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) RetryPolicy(net.jodah.failsafe.RetryPolicy) ByteSource(com.google.common.io.ByteSource) FileBackedOutputStream(com.google.common.io.FileBackedOutputStream) Failsafe(net.jodah.failsafe.Failsafe) RetryPolicy(net.jodah.failsafe.RetryPolicy)

Aggregations

RetryPolicy (net.jodah.failsafe.RetryPolicy)34 Failsafe (net.jodah.failsafe.Failsafe)12 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 IOException (java.io.IOException)7 Test (org.testng.annotations.Test)7 Executors (java.util.concurrent.Executors)6 Assert.assertEquals (org.testng.Assert.assertEquals)6 ConnectException (java.net.ConnectException)5 Assert.fail (org.testng.Assert.fail)5 Future (java.util.concurrent.Future)4 TimeUnit (java.util.concurrent.TimeUnit)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4 BeforeMethod (org.testng.annotations.BeforeMethod)4 Waiter (net.jodah.concurrentunit.Waiter)3 Paths (java.nio.file.Paths)2 List (java.util.List)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 ExecutionException (java.util.concurrent.ExecutionException)2