package pt.fccn.saw.selenium;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by mehmetgerceker on 12/7/15.
 */
public class RetryRule implements TestRule {

    private AtomicInteger retryCount;

    public RetryRule(int retries){
        super();
        this.retryCount = new AtomicInteger(retries);
    }

    @Override
    public Statement apply(final Statement base, final Description description) {
        //statement is a private method which will return a new statement
        //here Statement is taken as abstract for your test which includes test method and before/after methods )
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                System.out.println("Evaluating retry ...");
                Throwable caughtThrowable = null;

                // implement retry logic here
                while (retryCount.getAndDecrement() > 0) {
                    try {
                        base.evaluate();
                        return;
                    } catch (Throwable t) {
                    	t.printStackTrace();

                        if (retryCount.get() > 0 && description.getAnnotation(Retry.class)!= null) {
                            caughtThrowable = t;
                            System.err.println(description.getDisplayName() +
                                    ": Failed, " +
                                    retryCount.toString() +
                                    " retries remain");
                        } else {
                            throw caughtThrowable;
                        }
                    }
                }
            }
        };
    }
}

@@ -914,17 +914,22 @@
 rowable 
-c
+firstC
 aughtThr
@@ -1233,16 +1233,166 @@
 Trace();
+%0A                    %09%0A                    %09if (firstCaughtThrowable == null) %7B%0A                    %09%09firstCaughtThrowable = t;%0A                    %09%7D
 %0A%0A      
@@ -1490,57 +1490,8 @@
 ) %7B%0A
-                            caughtThrowable = t;%0A
     
@@ -1798,17 +1798,22 @@
   throw 
-c
+firstC
 aughtThr

Fix NPE on retry rule.