public Statement apply()

in src/main/java/org/apache/sling/commons/testing/junit/RetryRule.java [61:102]


    public Statement apply(final Statement statement, final Description description) {
        return new Statement() {
            
            private Throwable eval(Statement stmt) {
                try {
                    stmt.evaluate();
                } catch(Throwable t) {
                    return t;
                }
                return null;
            }
            
            @Override
            public void evaluate() throws Throwable {
                int retries = 0;
                Throwable t = eval(statement);
                if(t != null) {
                    final Retry r = description.getAnnotation(Retry.class);
                    if(r != null) {
                        final long timeout = System.currentTimeMillis() + getTimeout(r.timeoutMsec());
                        while(System.currentTimeMillis() < timeout) {
                            retries++;
                            t = eval(statement);
                            if(t == null) {
                                break;
                            }
                            Thread.sleep(getInterval(r.intervalMsec()));
                        }
                    }
                }
                if(t != null) {
                    if(retries > 0) {
                        log.debug("{} fails after retrying {} time(s)", statement, retries);
                    }
                    throw t;
                }
                if(retries > 0) {
                    log.debug("{} succeeds after retrying {} time(s)", statement, retries);
                }
            }
        };
    }