Voci le code :

package com.gisgraphy;

public abstract class RetryOnErrorTemplate {

    private int alreadyTry = 0;

    private int numberOfTimesToRetry = 1;
    private T returnvalue = null;

    private RetryOnErrorTemplate retry() throws Exception {
    try {
        returnvalue = tryThat();
        alreadyTry++;
        return this;
    } catch (Exception e) {
        numberOfTimesToRetry--;
        alreadyTry++;
        if (numberOfTimesToRetry == 0) {
        throw e;
        } else {
        return retry();
        }
    }
    }

   
    public abstract T tryThat() throws Exception;

    public T times(int numberOfTry) throws Exception {
    this.numberOfTimesToRetry = numberOfTry;
    retry();
    return returnvalue;

    }


    /**
     * @return The number of times the code has already been try
     */
    public int getAlreadyTry() {
        return alreadyTry;
    }


    /**
     * @return The number of times the code should be try  
     */
    public int getNumberOfTimesToRetry() {
        return numberOfTimesToRetry;
    }


}

Voci le test JUnit 4:

package com.gisgraphy;

import junit.framework.Assert;

import org.junit.Test;

import com.gisgraphy.domain.geoloc.service.geoloc.GisgraphyCommunicationException;

public class RetryOnErrorTemplateTest {

    private static final String THE_RETURNED_VALUE = "The returned value";

    @Test
    public void testRetryWhenCodeThrows() throws Exception {
        RetryOnErrorTemplate<String> retryOnError = new RetryOnErrorTemplate<String>() {
            @Override
            public String tryThat() throws Exception {

                if (true) {
                    throw new GisgraphyCommunicationException();
                }
                return "will never be return";
            }
        };
        try {
            retryOnError.times(3);
            Assert.fail("the code should have throws");
        } catch (GisgraphyCommunicationException ignore) {
        }
        Assert.assertEquals("The number of retry is not the expected one",3, retryOnError.getAlreadyTry());
    }

    @Test
    public void testRetryWhenCodeDoesnTThrows() throws Exception {
        RetryOnErrorTemplate<String> retryOnError = new RetryOnErrorTemplate<String>() {
            @Override
            public String tryThat() throws Exception {
                return THE_RETURNED_VALUE;
            }
        };
        Assert.assertEquals("The returned value is not the expected one",THE_RETURNED_VALUE, retryOnError.times(3));
        Assert.assertEquals("Only one try should have been done",1, retryOnError.getAlreadyTry());
    }

}