All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.rholder.retry.RetryerBuilder Maven / Gradle / Ivy

Go to download

This is a small extension to Google's Guava library to allow for the creation of configurable retrying strategies for an arbitrary function call, such as something that talks to a remote service with flaky uptime.

There is a newer version: 2.0.0
Show newest version
/*
 * Copyright 2012-2013 Ray Holder
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.rholder.retry;

import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;

import javax.annotation.Nonnull;

/**
 * A builder used to configure and create a {@link Retryer}.
 * @author JB
 * @author Jason Dunkelberger (dirkraft)
 *
 * @param  the type of the retryer return value
 */
public class RetryerBuilder {
    private AttemptTimeLimiter attemptTimeLimiter;
    private StopStrategy stopStrategy;
    private WaitStrategy waitStrategy;
    private Predicate> rejectionPredicate = Predicates.alwaysFalse();

    private RetryerBuilder() {
    }

    /**
     * Constructs a new builder
     * @return the new builder
     */
    public static  RetryerBuilder newBuilder() {
        return new RetryerBuilder();
    }

    /**
     * Sets the wait strategy used to decide how long to sleep between failed attempts.
     * The default strategy is to retry immediately after a failed attempt.
     * @param waitStrategy the strategy used to sleep between failed attempts
     * @return this
     * @throws IllegalStateException if a wait strategy has already been set.
     */
    public RetryerBuilder withWaitStrategy(@Nonnull WaitStrategy waitStrategy) throws IllegalStateException {
        Preconditions.checkNotNull(waitStrategy, "waitStrategy may not be null");
        Preconditions.checkState(this.waitStrategy == null, "a wait strategy has already been set %s", this.waitStrategy);
        this.waitStrategy = waitStrategy;
        return this;
    }

    /**
     * Sets the wait strategy used to decide . The default strategy
     * is to not sleep at all between attempts.
     * @param stopStrategy the strategy used to sleep between failed attempts
     * @return this
     * @throws IllegalStateException if a stop strategy has already been set.
     */
    public RetryerBuilder withStopStrategy(StopStrategy stopStrategy) {
        Preconditions.checkNotNull(stopStrategy, "stopStrategy may not be null");
        Preconditions.checkState(this.stopStrategy == null, "a stop strategy has already been set %s", this.stopStrategy);
        this.stopStrategy = stopStrategy;
        return this;
    }

    /**
     * Configures the retryer to limit the duration of any particular attempt by the given duration.
     * @param attemptTimeLimiter to apply to each attempt
     * @return this
     */
    public RetryerBuilder withAttemptTimeLimiter(@Nonnull AttemptTimeLimiter attemptTimeLimiter) {
        Preconditions.checkNotNull(attemptTimeLimiter);
        this.attemptTimeLimiter = attemptTimeLimiter;
        return this;
    }

    /**
     * Configures the retryer to retry if an exception (i.e. any Exception or subclass
     * of Exception) is thrown by the call.
     * @return this
     */
    public RetryerBuilder retryIfException() {
        rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate(Exception.class));
        return this;
    }

    /**
     * Configures the retryer to retry if a runtime exception (i.e. any RuntimeException or subclass
     * of RuntimeException) is thrown by the call.
     * @return this
     */
    public RetryerBuilder retryIfRuntimeException() {
        rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate(RuntimeException.class));
        return this;
    }

    /**
     * Configures the retryer to retry if an exception of the given class (or subclass of the given class) is
     * thrown by the call.
     * @param exceptionClass the type of the exception which should cause the retryer to retry
     * @return this
     */
    public RetryerBuilder retryIfExceptionOfType(@Nonnull Class exceptionClass) {
        Preconditions.checkNotNull(exceptionClass, "exceptionClass may not be null");
        rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate(exceptionClass));
        return this;
    }

    /**
     * Configures the retryer to retry if an exception satisfying the given predicate is
     * thrown by the call.
     * @param exceptionPredicate the predicate which causes a retry if satisfied
     * @return this
     */
    public RetryerBuilder retryIfException(@Nonnull Predicate exceptionPredicate) {
        Preconditions.checkNotNull(exceptionPredicate, "exceptionPredicate may not be null");
        rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionPredicate(exceptionPredicate));
        return this;
    }

    /**
     * Configures the retryer to retry if the result satisfies the given predicate.
     * @param resultPredicate a predicate applied to the result, and which causes the retryer
     * to retry if the predicate is satisfied
     * @return this
     */
    public RetryerBuilder retryIfResult(@Nonnull Predicate resultPredicate) {
        Preconditions.checkNotNull(resultPredicate, "resultPredicate may not be null");
        rejectionPredicate = Predicates.or(rejectionPredicate, new ResultPredicate(resultPredicate));
        return this;
    }

    /**
     * Builds the retryer.
     * @return the built retryer.
     */
    public Retryer build() {
        AttemptTimeLimiter theAttemptTimeLimiter = attemptTimeLimiter == null ? AttemptTimeLimiters.noTimeLimit() : attemptTimeLimiter;
        StopStrategy theStopStrategy = stopStrategy == null ? StopStrategies.neverStop() : stopStrategy;
        WaitStrategy theWaitStrategy = waitStrategy == null ? WaitStrategies.noWait() : waitStrategy;

        return new Retryer(theAttemptTimeLimiter, theStopStrategy, theWaitStrategy, rejectionPredicate);
    }

    private static final class ExceptionClassPredicate implements Predicate> {

        private Class exceptionClass;

        public ExceptionClassPredicate(Class exceptionClass) {
            this.exceptionClass = exceptionClass;
        }

        @Override
        public boolean apply(Attempt attempt) {
            if (!attempt.hasException()) {
                return false;
            }
            return exceptionClass.isAssignableFrom(attempt.getExceptionCause().getClass());
        }
    }

    private static final class ResultPredicate implements Predicate> {

        private Predicate delegate;

        public ResultPredicate(Predicate delegate) {
            this.delegate = delegate;
        }

        @Override
        public boolean apply(Attempt attempt) {
            if (!attempt.hasResult()) {
                return false;
            }
            V result = attempt.getResult();
            return delegate.apply(result);
        }
    }

    private static final class ExceptionPredicate implements Predicate> {

        private Predicate delegate;

        public ExceptionPredicate(Predicate delegate) {
            this.delegate = delegate;
        }

        @Override
        public boolean apply(Attempt attempt) {
            if (!attempt.hasException()) {
                return false;
            }
            return delegate.apply(attempt.getExceptionCause());
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy