|
| 1 | +/* |
| 2 | + * Copyright 2020 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.translate; |
| 18 | + |
| 19 | +import java.util.Objects; |
| 20 | +import org.junit.rules.TestRule; |
| 21 | +import org.junit.runner.Description; |
| 22 | +import org.junit.runners.model.Statement; |
| 23 | + |
| 24 | +public class Retry implements TestRule { |
| 25 | + private int maxAttempts; |
| 26 | + |
| 27 | + public Retry(int maxAttempts) { |
| 28 | + this.maxAttempts = maxAttempts; |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + public Statement apply(Statement base, Description description) { |
| 33 | + return statement(base, description); |
| 34 | + } |
| 35 | + |
| 36 | + private Statement statement(final Statement base, final Description description) { |
| 37 | + return new Statement() { |
| 38 | + @Override |
| 39 | + public void evaluate() throws Throwable { |
| 40 | + Throwable caughtThrowable = null; |
| 41 | + |
| 42 | + // implement retry logic here |
| 43 | + int factor = 1; |
| 44 | + for (int attempt = 0; attempt < maxAttempts; attempt++) { |
| 45 | + try { |
| 46 | + base.evaluate(); |
| 47 | + return; |
| 48 | + } catch (Throwable t) { |
| 49 | + caughtThrowable = t; |
| 50 | + |
| 51 | + // random_number_milliseconds that is less than or equal to 1000. |
| 52 | + int randomNumberMilliseconds = (int) Math.floor(Math.random() * 1000) + 1; |
| 53 | + Thread.sleep(1300 * factor + randomNumberMilliseconds); |
| 54 | + System.out.println(description.getDisplayName() + ": run " + (attempt + 1) + " failed"); |
| 55 | + factor += 1; |
| 56 | + |
| 57 | + } |
| 58 | + } |
| 59 | + System.out.println( |
| 60 | + description.getDisplayName() + ": giving up after " + maxAttempts + " failures"); |
| 61 | + throw Objects.requireNonNull(caughtThrowable); |
| 62 | + } |
| 63 | + }; |
| 64 | + } |
| 65 | +} |
0 commit comments