Use method reference where possible

This commit is contained in:
Stephane Nicoll
2022-04-15 16:41:25 +02:00
parent c9866e3785
commit b70022971b
22 changed files with 204 additions and 412 deletions

View File

@@ -44,13 +44,10 @@ public class PatternMatcher<S> {
this.map = map;
// Sort keys to start with the most specific
this.sorted = new ArrayList<>(map.keySet());
Collections.sort(this.sorted, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String s1 = o1; // .replace('?', '{');
String s2 = o2; // .replace('*', '}');
return s2.compareTo(s1);
}
Collections.sort(this.sorted, (o1, o2) -> {
String s1 = o1; // .replace('?', '{');
String s2 = o2; // .replace('*', '}');
return s2.compareTo(s1);
});
}

View File

@@ -80,14 +80,12 @@ public class AnnotationMethodResolver implements MethodResolver {
public Method findMethod(final Class<?> clazz) {
Assert.notNull(clazz, "class must not be null");
final AtomicReference<Method> annotatedMethod = new AtomicReference<>();
ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Assert.isNull(annotatedMethod.get(), "found more than one method on target class [" + clazz
+ "] with the annotation type [" + annotationType + "]");
annotatedMethod.set(method);
}
ReflectionUtils.doWithMethods(clazz, method -> {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Assert.isNull(annotatedMethod.get(), "found more than one method on target class [" + clazz
+ "] with the annotation type [" + annotationType + "]");
annotatedMethod.set(method);
}
});
return annotatedMethod.get();

View File

@@ -115,21 +115,19 @@ public class MethodInvokerUtils {
final Class<?> targetClass = (target instanceof Advised) ? ((Advised) target).getTargetSource().getTargetClass()
: target.getClass();
if (mi != null) {
ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 0) {
String errorMsg = "The method [" + method.getName() + "] on target class ["
+ targetClass.getSimpleName() + "] is incompatable with the signature ["
+ getParamTypesString(expectedParamTypes) + "] expected for the annotation ["
+ annotationType.getSimpleName() + "].";
ReflectionUtils.doWithMethods(targetClass, method -> {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 0) {
String errorMsg = "The method [" + method.getName() + "] on target class ["
+ targetClass.getSimpleName() + "] is incompatable with the signature ["
+ getParamTypesString(expectedParamTypes) + "] expected for the annotation ["
+ annotationType.getSimpleName() + "].";
Assert.isTrue(paramTypes.length == expectedParamTypes.length, errorMsg);
for (int i = 0; i < paramTypes.length; i++) {
Assert.isTrue(expectedParamTypes[i].isAssignableFrom(paramTypes[i]), errorMsg);
}
Assert.isTrue(paramTypes.length == expectedParamTypes.length, errorMsg);
for (int i = 0; i < paramTypes.length; i++) {
Assert.isTrue(expectedParamTypes[i].isAssignableFrom(paramTypes[i]), errorMsg);
}
}
}
@@ -160,15 +158,13 @@ public class MethodInvokerUtils {
return null;
}
final AtomicReference<Method> annotatedMethod = new AtomicReference<>();
ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Assert.isNull(annotatedMethod.get(),
"found more than one method on target class [" + targetClass.getSimpleName()
+ "] with the annotation type [" + annotationType.getSimpleName() + "].");
annotatedMethod.set(method);
}
ReflectionUtils.doWithMethods(targetClass, method -> {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Assert.isNull(annotatedMethod.get(),
"found more than one method on target class [" + targetClass.getSimpleName()
+ "] with the annotation type [" + annotationType.getSimpleName() + "].");
annotatedMethod.set(method);
}
});
Method method = annotatedMethod.get();
@@ -189,21 +185,19 @@ public class MethodInvokerUtils {
*/
public static <C, T> MethodInvoker getMethodInvokerForSingleArgument(Object target) {
final AtomicReference<Method> methodHolder = new AtomicReference<>();
ReflectionUtils.doWithMethods(target.getClass(), new ReflectionUtils.MethodCallback() {
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
if ((method.getModifiers() & Modifier.PUBLIC) == 0 || method.isBridge()) {
return;
}
if (method.getParameterTypes() == null || method.getParameterTypes().length != 1) {
return;
}
if (method.getReturnType().equals(Void.TYPE) || ReflectionUtils.isEqualsMethod(method)) {
return;
}
Assert.state(methodHolder.get() == null,
"More than one non-void public method detected with single argument.");
methodHolder.set(method);
ReflectionUtils.doWithMethods(target.getClass(), method -> {
if ((method.getModifiers() & Modifier.PUBLIC) == 0 || method.isBridge()) {
return;
}
if (method.getParameterTypes() == null || method.getParameterTypes().length != 1) {
return;
}
if (method.getReturnType().equals(Void.TYPE) || ReflectionUtils.isEqualsMethod(method)) {
return;
}
Assert.state(methodHolder.get() == null,
"More than one non-void public method detected with single argument.");
methodHolder.set(method);
});
Method method = methodHolder.get();
return new SimpleMethodInvoker(target, method);

View File

@@ -80,11 +80,8 @@ public class AnnotationAwareRetryOperationsInterceptor implements IntroductionIn
private static final SpelExpressionParser PARSER = new SpelExpressionParser();
private static final MethodInterceptor NULL_INTERCEPTOR = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
throw new OperationNotSupportedException("Not supported");
}
private static final MethodInterceptor NULL_INTERCEPTOR = methodInvocation -> {
throw new OperationNotSupportedException("Not supported");
};
private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
@@ -298,12 +295,9 @@ public class AnnotationAwareRetryOperationsInterceptor implements IntroductionIn
return (MethodInvocationRecoverer<?>) target;
}
final AtomicBoolean foundRecoverable = new AtomicBoolean(false);
ReflectionUtils.doWithMethods(target.getClass(), new MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
if (AnnotatedElementUtils.findMergedAnnotation(method, Recover.class) != null) {
foundRecoverable.set(true);
}
ReflectionUtils.doWithMethods(target.getClass(), candidate -> {
if (AnnotatedElementUtils.findMergedAnnotation(candidate, Recover.class) != null) {
foundRecoverable.set(true);
}
});

View File

@@ -203,24 +203,21 @@ public class RecoverAnnotationRecoveryHandler<T> implements MethodInvocationReco
if (retryable != null) {
this.recoverMethodName = retryable.recover();
}
ReflectionUtils.doWithMethods(target.getClass(), new MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException {
Recover recover = AnnotationUtils.findAnnotation(method, Recover.class);
if (recover == null) {
recover = findAnnotationOnTarget(target, method);
}
if (recover != null && failingMethod.getGenericReturnType() instanceof ParameterizedType
&& method.getGenericReturnType() instanceof ParameterizedType) {
if (isParameterizedTypeAssignable((ParameterizedType) method.getGenericReturnType(),
(ParameterizedType) failingMethod.getGenericReturnType())) {
putToMethodsMap(method, types);
}
}
else if (recover != null && method.getReturnType().isAssignableFrom(failingMethod.getReturnType())) {
putToMethodsMap(method, types);
ReflectionUtils.doWithMethods(target.getClass(), candidate -> {
Recover recover = AnnotationUtils.findAnnotation(candidate, Recover.class);
if (recover == null) {
recover = findAnnotationOnTarget(target, candidate);
}
if (recover != null && failingMethod.getGenericReturnType() instanceof ParameterizedType
&& candidate.getGenericReturnType() instanceof ParameterizedType) {
if (isParameterizedTypeAssignable((ParameterizedType) candidate.getGenericReturnType(),
(ParameterizedType) failingMethod.getGenericReturnType())) {
putToMethodsMap(candidate, types);
}
}
else if (recover != null && candidate.getReturnType().isAssignableFrom(failingMethod.getReturnType())) {
putToMethodsMap(candidate, types);
}
});
this.classifier.setTypeMap(types);
optionallyFilterMethodsBy(failingMethod.getReturnType());

View File

@@ -250,17 +250,14 @@ public class RetryConfiguration extends AbstractPointcutAdvisor
public boolean hasAnnotatedMethods(Class<?> clazz) {
final AtomicBoolean found = new AtomicBoolean(false);
ReflectionUtils.doWithMethods(clazz, new MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
if (found.get()) {
return;
}
Annotation annotation = AnnotationUtils.findAnnotation(method,
AnnotationMethodsResolver.this.annotationType);
if (annotation != null) {
found.set(true);
}
ReflectionUtils.doWithMethods(clazz, method -> {
if (found.get()) {
return;
}
Annotation annotation = AnnotationUtils.findAnnotation(method,
AnnotationMethodsResolver.this.annotationType);
if (annotation != null) {
found.set(true);
}
});
return found.get();

View File

@@ -84,11 +84,7 @@ public class ClassifierAdapterTests {
@SuppressWarnings({ "serial" })
@Test
public void testClassifierAdapterClassifier() {
adapter = new ClassifierAdapter<>(new org.springframework.classify.Classifier<String, Integer>() {
public Integer classify(String classifiable) {
return Integer.valueOf(classifiable);
}
});
adapter = new ClassifierAdapter<>(Integer::valueOf);
assertEquals(23, adapter.classify("23").intValue());
}
@@ -117,11 +113,7 @@ public class ClassifierAdapterTests {
@SuppressWarnings("serial")
@Test
public void testClassifyWithClassifier() {
adapter.setDelegate(new org.springframework.classify.Classifier<String, Integer>() {
public Integer classify(String classifiable) {
return Integer.valueOf(classifiable);
}
});
adapter.setDelegate(Integer::valueOf);
assertEquals(23, adapter.classify("23").intValue());
}

View File

@@ -299,17 +299,11 @@ public class EnableRetryTests {
if (bean instanceof RecoverableService) {
Advised advised = (Advised) bean;
advised.addAdvice(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
if (invocation.getMethod().getName().equals("recover")) {
((RecoverableService) bean).setOtherAdviceCalled();
}
return invocation.proceed();
advised.addAdvice((MethodInterceptor) invocation -> {
if (invocation.getMethod().getName().equals("recover")) {
((RecoverableService) bean).setOtherAdviceCalled();
}
return invocation.proceed();
});
return bean;
}
@@ -350,10 +344,7 @@ public class EnableRetryTests {
@SuppressWarnings("serial")
@Bean
public Sleeper sleeper() {
return new Sleeper() {
@Override
public void sleep(long period) throws InterruptedException {
}
return period -> {
};
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014 the original author or authors.
* Copyright 2006-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -87,13 +87,9 @@ public class RetryInterceptorBuilderTests {
public void testWithCustomNewMessageIdentifier() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
StatefulRetryOperationsInterceptor interceptor = RetryInterceptorBuilder.stateful().maxAttempts(5)
.newMethodArgumentsIdentifier(new NewMethodArgumentsIdentifier() {
@Override
public boolean isNew(Object[] args) {
latch.countDown();
return false;
}
.newMethodArgumentsIdentifier(args -> {
latch.countDown();
return false;
}).backOffPolicy(new FixedBackOffPolicy()).build();
assertEquals(5, TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts"));
@@ -123,15 +119,10 @@ public class RetryInterceptorBuilderTests {
@Test
public void testWithCustomKeyGenerator() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
StatefulRetryOperationsInterceptor interceptor = RetryInterceptorBuilder.stateful()
.keyGenerator(new MethodArgumentsKeyGenerator() {
@Override
public Object getKey(Object[] item) {
latch.countDown();
return "foo";
}
}).build();
StatefulRetryOperationsInterceptor interceptor = RetryInterceptorBuilder.stateful().keyGenerator(item -> {
latch.countDown();
return "foo";
}).build();
assertEquals(3, TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts"));
final AtomicInteger count = new AtomicInteger();
@@ -148,14 +139,9 @@ public class RetryInterceptorBuilderTests {
}
private Foo createDelegate(MethodInterceptor interceptor, final AtomicInteger count) {
Foo delegate = new Foo() {
@Override
public void onMessage(String s, Object message) {
count.incrementAndGet();
throw new RuntimeException("foo", new RuntimeException("bar"));
}
Foo delegate = (s, message) -> {
count.incrementAndGet();
throw new RuntimeException("foo", new RuntimeException("bar"));
};
ProxyFactory factory = new ProxyFactory();
factory.addAdvisor(new DefaultPointcutAdvisor(Pointcut.TRUE, interceptor));

View File

@@ -160,12 +160,7 @@ public class RetryOperationsInterceptorTests {
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new SimpleRetryPolicy(1));
this.interceptor.setRetryOperations(template);
this.interceptor.setRecoverer(new MethodInvocationRecoverer<Void>() {
@Override
public Void recover(Object[] args, Throwable cause) {
return null;
}
});
this.interceptor.setRecoverer((args, cause) -> null);
((Advised) this.service).addAdvice(this.interceptor);
this.service.service();
assertEquals(1, count);
@@ -175,12 +170,9 @@ public class RetryOperationsInterceptorTests {
public void testInterceptorChainWithRetry() throws Exception {
((Advised) this.service).addAdvice(this.interceptor);
final List<String> list = new ArrayList<>();
((Advised) this.service).addAdvice(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
list.add("chain");
return invocation.proceed();
}
((Advised) this.service).addAdvice((MethodInterceptor) invocation -> {
list.add("chain");
return invocation.proceed();
});
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new SimpleRetryPolicy(2));

View File

@@ -150,12 +150,9 @@ public class StatefulRetryOperationsInterceptorTests {
public void testInterceptorChainWithRetry() throws Exception {
((Advised) service).addAdvice(interceptor);
final List<String> list = new ArrayList<>();
((Advised) service).addAdvice(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
list.add("chain");
return invocation.proceed();
}
((Advised) service).addAdvice((MethodInterceptor) invocation -> {
list.add("chain");
return invocation.proceed();
});
interceptor.setRetryOperations(retryTemplate);
retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2));
@@ -232,12 +229,9 @@ public class StatefulRetryOperationsInterceptorTests {
assertTrue("Wrong message: " + message, message.startsWith("Not enough calls"));
}
assertEquals(1, count);
interceptor.setRecoverer(new MethodInvocationRecoverer<Object>() {
@Override
public Object recover(Object[] data, Throwable cause) {
count++;
return null;
}
interceptor.setRecoverer((data, cause) -> {
count++;
return null;
});
service.service("foo");
assertEquals(2, count);
@@ -261,13 +255,7 @@ public class StatefulRetryOperationsInterceptorTests {
@SuppressWarnings("unchecked")
@Test
public void testKeyGeneratorAndRawKey() throws Throwable {
this.interceptor.setKeyGenerator(new MethodArgumentsKeyGenerator() {
@Override
public Object getKey(Object[] item) {
return "bar";
}
});
this.interceptor.setKeyGenerator(item -> "bar");
this.interceptor.setLabel("foo");
this.interceptor.setUseRawKey(true);
RetryOperations template = mock(RetryOperations.class);
@@ -294,12 +282,9 @@ public class StatefulRetryOperationsInterceptorTests {
assertTrue("Wrong message: " + message, message.startsWith("Not enough calls"));
}
assertEquals(1, count);
interceptor.setRecoverer(new MethodInvocationRecoverer<Collection<String>>() {
@Override
public Collection<String> recover(Object[] data, Throwable cause) {
count++;
return Collections.singleton((String) data[0]);
}
interceptor.setRecoverer((data, cause) -> {
count++;
return Collections.singleton((String) data[0]);
});
Collection<String> result = transformer.transform("foo");
assertEquals(2, count);

View File

@@ -54,11 +54,7 @@ public class RetryListenerTests {
return true;
}
} });
template.execute(new RetryCallback<String, Exception>() {
public String doWithRetry(RetryContext context) throws Exception {
return null;
}
});
template.execute(context -> null);
assertEquals(2, count);
assertEquals(2, list.size());
assertEquals("1:1", list.get(0));
@@ -73,11 +69,9 @@ public class RetryListenerTests {
}
});
try {
template.execute(new RetryCallback<String, Exception>() {
public String doWithRetry(RetryContext context) throws Exception {
count++;
return null;
}
template.execute(context -> {
count++;
return null;
});
fail("Expected TerminatedRetryException");
}
@@ -104,11 +98,7 @@ public class RetryListenerTests {
list.add("2:" + count);
}
} });
template.execute(new RetryCallback<String, Exception>() {
public String doWithRetry(RetryContext context) throws Exception {
return null;
}
});
template.execute(context -> null);
assertEquals(2, count);
assertEquals(2, list.size());
// interceptors are called in reverse order on close...
@@ -130,11 +120,9 @@ public class RetryListenerTests {
}
} });
try {
template.execute(new RetryCallback<String, Exception>() {
public String doWithRetry(RetryContext context) throws Exception {
count++;
throw new IllegalStateException("foo");
}
template.execute(context -> {
count++;
throw new IllegalStateException("foo");
});
fail("Expected IllegalStateException");
}
@@ -159,12 +147,10 @@ public class RetryListenerTests {
assertNull(t);
}
});
template.execute(new RetryCallback<String, Exception>() {
public String doWithRetry(RetryContext context) throws Exception {
if (count++ < 1)
throw new RuntimeException("Retry!");
return null;
}
template.execute(context -> {
if (count++ < 1)
throw new RuntimeException("Retry!");
return null;
});
assertEquals(2, count);
// The close interceptor was only called once:

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2006-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,12 +51,7 @@ public class CircuitBreakerRetryTemplateTests {
@Before
public void init() {
this.callback = new MockRetryCallback();
this.recovery = new RecoveryCallback<Object>() {
@Override
public Object recover(RetryContext context) throws Exception {
return RECOVERED;
}
};
this.recovery = context -> RECOVERED;
this.retryTemplate = new RetryTemplate();
this.callback.setAttemptsBeforeSuccess(1);
// No rollback by default (so exceptions are not rethrown)

View File

@@ -80,13 +80,11 @@ public class ExceptionClassifierRetryPolicyTests {
assertFalse(policy.canRetry(context)); // NeverRetryPolicy is the
// default
policy.setExceptionClassifier(new Classifier<Throwable, RetryPolicy>() {
public RetryPolicy classify(Throwable throwable) {
if (throwable != null) {
return new AlwaysRetryPolicy();
}
return new NeverRetryPolicy();
policy.setExceptionClassifier(throwable -> {
if (throwable != null) {
return new AlwaysRetryPolicy();
}
return new NeverRetryPolicy();
});
// The context saves the classifier, so changing it now has no effect
@@ -107,13 +105,9 @@ public class ExceptionClassifierRetryPolicyTests {
@SuppressWarnings("serial")
@Test
public void testClose() throws Exception {
policy.setExceptionClassifier(new Classifier<Throwable, RetryPolicy>() {
public RetryPolicy classify(Throwable throwable) {
return new MockRetryPolicySupport() {
public void close(RetryContext context) {
count++;
}
};
policy.setExceptionClassifier(throwable -> new MockRetryPolicySupport() {
public void close(RetryContext context) {
count++;
}
});
RetryContext context = policy.open(null);

View File

@@ -46,11 +46,7 @@ public class FatalExceptionRetryPolicyTests {
// ... and allow multiple attempts
SimpleRetryPolicy policy = new SimpleRetryPolicy(3, map);
retryTemplate.setRetryPolicy(policy);
RecoveryCallback<String> recoveryCallback = new RecoveryCallback<String>() {
public String recover(RetryContext context) throws Exception {
return "bar";
}
};
RecoveryCallback<String> recoveryCallback = context -> "bar";
Object result = null;
try {
@@ -79,11 +75,7 @@ public class FatalExceptionRetryPolicyTests {
SimpleRetryPolicy policy = new SimpleRetryPolicy(3, map);
retryTemplate.setRetryPolicy(policy);
RecoveryCallback<String> recoveryCallback = new RecoveryCallback<String>() {
public String recover(RetryContext context) throws Exception {
return "bar";
}
};
RecoveryCallback<String> recoveryCallback = context -> "bar";
Object result = null;
try {

View File

@@ -162,16 +162,10 @@ public class StatefulRetryIntegrationTests {
RetryState retryState = new DefaultRetryState("bar");
for (int i = 0; i < 3; i++) {
try {
template.execute(new RetryCallback<String, Exception>() {
public String doWithRetry(RetryContext context) throws Exception {
times.add(System.currentTimeMillis());
throw new Exception("Fail");
}
}, new RecoveryCallback<String>() {
public String recover(RetryContext context) throws Exception {
return null;
}
}, retryState);
template.execute(context -> {
times.add(System.currentTimeMillis());
throw new Exception("Fail");
}, context -> null, retryState);
}
catch (Exception e) {
assertTrue(e.getMessage().equals("Fail"));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2006-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -63,12 +63,7 @@ public class CircuitBreakerStatisticsTests {
@Before
public void init() {
this.callback = new MockRetryCallback();
this.recovery = new RecoveryCallback<Object>() {
@Override
public Object recover(RetryContext context) throws Exception {
return RECOVERED;
}
};
this.recovery = context -> RECOVERED;
this.retryTemplate = new RetryTemplate();
this.cache = new MapRetryContextCache();
this.retryTemplate.setRetryContextCache(this.cache);
@@ -98,11 +93,8 @@ public class CircuitBreakerStatisticsTests {
@Test
public void testFailedRecoveryCountsAsAbort() throws Throwable {
this.retryTemplate.setRetryPolicy(new CircuitBreakerRetryPolicy(new NeverRetryPolicy()));
this.recovery = new RecoveryCallback<Object>() {
@Override
public Object recover(RetryContext context) throws Exception {
throw new ExhaustedRetryException("Planned exhausted");
}
this.recovery = context -> {
throw new ExhaustedRetryException("Planned exhausted");
};
try {
this.retryTemplate.execute(this.callback, this.recovery, this.state);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2006-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -144,12 +144,7 @@ public class StatisticsListenerTests {
MockRetryCallback callback = new MockRetryCallback();
callback.setAttemptsBeforeSuccess(x + 1);
retryTemplate.setRetryPolicy(new SimpleRetryPolicy(x));
retryTemplate.execute(callback, new RecoveryCallback<Object>() {
@Override
public Object recover(RetryContext context) throws Exception {
return null;
}
});
retryTemplate.execute(callback, context -> null);
assertEquals(x, callback.attempts);
RetryStatistics stats = repository.findOne("test");
// System.err.println(stats);
@@ -171,12 +166,7 @@ public class StatisticsListenerTests {
retryTemplate.setRetryPolicy(new SimpleRetryPolicy(x));
for (int i = 0; i < x + 1; i++) {
try {
retryTemplate.execute(callback, new RecoveryCallback<Object>() {
@Override
public Object recover(RetryContext context) throws Exception {
return null;
}
}, state);
retryTemplate.execute(callback, context -> null, state);
}
catch (Exception e) {
// don't care

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2006-2007 the original author or authors.
* Copyright 2006-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,11 +35,7 @@ public class DefaultRetryStateTests {
@SuppressWarnings("serial")
@Test
public void testDefaultRetryStateObjectBooleanClassifierOfQsuperThrowableBoolean() {
DefaultRetryState state = new DefaultRetryState("foo", true, new Classifier<Throwable, Boolean>() {
public Boolean classify(Throwable classifiable) {
return false;
}
});
DefaultRetryState state = new DefaultRetryState("foo", true, classifiable -> false);
assertEquals("foo", state.getKey());
assertTrue(state.isForceRefresh());
assertFalse(state.rollbackFor(null));
@@ -52,11 +48,7 @@ public class DefaultRetryStateTests {
@SuppressWarnings("serial")
@Test
public void testDefaultRetryStateObjectClassifierOfQsuperThrowableBoolean() {
DefaultRetryState state = new DefaultRetryState("foo", new Classifier<Throwable, Boolean>() {
public Boolean classify(Throwable classifiable) {
return false;
}
});
DefaultRetryState state = new DefaultRetryState("foo", classifiable -> false);
assertEquals("foo", state.getKey());
assertFalse(state.isForceRefresh());
assertFalse(state.rollbackFor(null));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2006-2007 the original author or authors.
* Copyright 2006-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -48,14 +48,11 @@ public class RetrySynchronizationManagerTests {
RetryContext status = RetrySynchronizationManager.getContext();
assertNull(status);
this.template.execute(new RetryCallback<Object, Exception>() {
@Override
public Object doWithRetry(RetryContext status) throws Exception {
RetryContext global = RetrySynchronizationManager.getContext();
assertNotNull(status);
assertEquals(global, status);
return null;
}
this.template.execute(retryContext -> {
RetryContext global = RetrySynchronizationManager.getContext();
assertNotNull(retryContext);
assertEquals(global, retryContext);
return null;
});
status = RetrySynchronizationManager.getContext();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2006-2007 the original author or authors.
* Copyright 2006-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -71,17 +71,14 @@ public class RetryTemplateTests {
for (int x = 1; x <= 10; x++) {
final int attemptsBeforeSuccess = x;
final AtomicInteger attempts = new AtomicInteger(0);
RetryCallback<String, IllegalStateException> callback = new RetryCallback<String, IllegalStateException>() {
@Override
public String doWithRetry(RetryContext context) throws IllegalStateException {
if (attempts.incrementAndGet() < attemptsBeforeSuccess) {
// The parametrized exception type in the callback is really just
// syntactic sugar since rules of erasure mean that the handler
// can't really tell the difference between runtime exceptions.
throw new IllegalArgumentException("Planned");
}
return "foo";
RetryCallback<String, IllegalStateException> callback = context -> {
if (attempts.incrementAndGet() < attemptsBeforeSuccess) {
// The parametrized exception type in the callback is really just
// syntactic sugar since rules of erasure mean that the handler
// can't really tell the difference between runtime exceptions.
throw new IllegalArgumentException("Planned");
}
return "foo";
};
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(new SimpleRetryPolicy(x));
@@ -97,12 +94,7 @@ public class RetryTemplateTests {
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2));
final Object value = new Object();
Object result = retryTemplate.execute(callback, new RecoveryCallback<Object>() {
@Override
public Object recover(RetryContext context) throws Exception {
return value;
}
});
Object result = retryTemplate.execute(callback, context -> value);
assertEquals(2, callback.attempts);
assertEquals(value, result);
}
@@ -211,12 +203,9 @@ public class RetryTemplateTests {
public void testEarlyTermination() throws Throwable {
try {
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.execute(new RetryCallback<Object, Exception>() {
@Override
public Object doWithRetry(RetryContext status) throws Exception {
status.setExhaustedOnly();
throw new IllegalStateException("Retry this operation");
}
retryTemplate.execute(status -> {
status.setExhaustedOnly();
throw new IllegalStateException("Retry this operation");
});
fail("Expected ExhaustedRetryException");
}
@@ -232,12 +221,9 @@ public class RetryTemplateTests {
try {
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setThrowLastExceptionOnExhausted(true);
retryTemplate.execute(new RetryCallback<Object, Throwable>() {
@Override
public Object doWithRetry(RetryContext status) throws Exception {
status.setExhaustedOnly();
throw new IllegalStateException("Retry this operation");
}
retryTemplate.execute(status -> {
status.setExhaustedOnly();
throw new IllegalStateException("Retry this operation");
});
fail("Expected ExhaustedRetryException");
}
@@ -252,25 +238,19 @@ public class RetryTemplateTests {
public void testNestedContexts() throws Throwable {
RetryTemplate outer = new RetryTemplate();
final RetryTemplate inner = new RetryTemplate();
outer.execute(new RetryCallback<Object, Throwable>() {
@Override
public Object doWithRetry(RetryContext status) throws Throwable {
RetryTemplateTests.this.context = status;
outer.execute(status -> {
RetryTemplateTests.this.context = status;
RetryTemplateTests.this.count++;
Object result = inner.execute((RetryCallback<Object, Throwable>) status1 -> {
RetryTemplateTests.this.count++;
Object result = inner.execute(new RetryCallback<Object, Throwable>() {
@Override
public Object doWithRetry(RetryContext status) throws Throwable {
RetryTemplateTests.this.count++;
assertNotNull(RetryTemplateTests.this.context);
assertNotSame(status, RetryTemplateTests.this.context);
assertSame(RetryTemplateTests.this.context, status.getParent());
assertSame("The context should be the child", status, RetrySynchronizationManager.getContext());
return null;
}
});
assertSame("The context should be restored", status, RetrySynchronizationManager.getContext());
return result;
}
assertNotNull(RetryTemplateTests.this.context);
assertNotSame(status1, RetryTemplateTests.this.context);
assertSame(RetryTemplateTests.this.context, status1.getParent());
assertSame("The context should be the child", status1, RetrySynchronizationManager.getContext());
return null;
});
assertSame("The context should be restored", status, RetrySynchronizationManager.getContext());
return result;
});
assertEquals(2, this.count);
}
@@ -280,11 +260,8 @@ public class RetryTemplateTests {
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(new NeverRetryPolicy());
try {
retryTemplate.execute(new RetryCallback<Object, Exception>() {
@Override
public Object doWithRetry(RetryContext context) throws Exception {
throw new Error("Realllly bad!");
}
retryTemplate.execute(context -> {
throw new Error("Realllly bad!");
});
fail("Expected Error");
}
@@ -304,11 +281,8 @@ public class RetryTemplateTests {
}
});
try {
retryTemplate.execute(new RetryCallback<Object, Exception>() {
@Override
public Object doWithRetry(RetryContext context) throws Exception {
throw new RuntimeException("Realllly bad!");
}
retryTemplate.execute(context -> {
throw new RuntimeException("Realllly bad!");
});
fail("Expected Error");
}
@@ -327,11 +301,8 @@ public class RetryTemplateTests {
}
});
try {
retryTemplate.execute(new RetryCallback<Object, Exception>() {
@Override
public Object doWithRetry(RetryContext context) throws Exception {
throw new RuntimeException("Bad!");
}
retryTemplate.execute(context -> {
throw new RuntimeException("Bad!");
});
fail("Expected RuntimeException");
}
@@ -360,13 +331,8 @@ public class RetryTemplateTests {
replay(bop);
try {
tested.execute(new RetryCallback<Object, Exception>() {
@Override
public Object doWithRetry(RetryContext context) throws Exception {
throw new Exception("maybe next time!");
}
tested.execute(context -> {
throw new Exception("maybe next time!");
}, null, new DefaultRetryState(tested) {
@Override

View File

@@ -86,19 +86,13 @@ public class StatefulRecoveryRetryTests {
this.retryTemplate.setRetryPolicy(new SimpleRetryPolicy(1));
final String input = "foo";
RetryState state = new DefaultRetryState(input);
RetryCallback<String, Exception> callback = new RetryCallback<String, Exception>() {
@Override
public String doWithRetry(RetryContext context) throws Exception {
throw new RuntimeException("Barf!");
}
RetryCallback<String, Exception> callback = context -> {
throw new RuntimeException("Barf!");
};
RecoveryCallback<String> recoveryCallback = new RecoveryCallback<String>() {
@Override
public String recover(RetryContext context) {
StatefulRecoveryRetryTests.this.count++;
StatefulRecoveryRetryTests.this.list.add(input);
return input;
}
RecoveryCallback<String> recoveryCallback = context -> {
StatefulRecoveryRetryTests.this.count++;
StatefulRecoveryRetryTests.this.list.add(input);
return input;
};
Object result = null;
try {
@@ -125,19 +119,13 @@ public class StatefulRecoveryRetryTests {
assertFalse(classifier.classify(new RuntimeException()));
final String input = "foo";
RetryState state = new DefaultRetryState(input, classifier);
RetryCallback<String, Exception> callback = new RetryCallback<String, Exception>() {
@Override
public String doWithRetry(RetryContext context) throws Exception {
throw new RuntimeException("Barf!");
}
RetryCallback<String, Exception> callback = context -> {
throw new RuntimeException("Barf!");
};
RecoveryCallback<String> recoveryCallback = new RecoveryCallback<String>() {
@Override
public String recover(RetryContext context) {
StatefulRecoveryRetryTests.this.count++;
StatefulRecoveryRetryTests.this.list.add(input);
return input;
}
RecoveryCallback<String> recoveryCallback = context -> {
StatefulRecoveryRetryTests.this.count++;
StatefulRecoveryRetryTests.this.list.add(input);
return input;
};
Object result = null;
// On the second retry, the recovery path is taken...
@@ -154,11 +142,8 @@ public class StatefulRecoveryRetryTests {
final String input = "foo";
RetryState state = new DefaultRetryState(input);
RetryCallback<String, Exception> callback = new RetryCallback<String, Exception>() {
@Override
public String doWithRetry(RetryContext context) throws Exception {
throw new RuntimeException("Barf!");
}
RetryCallback<String, Exception> callback = context -> {
throw new RuntimeException("Barf!");
};
try {
@@ -190,15 +175,12 @@ public class StatefulRecoveryRetryTests {
final StringHolder item = new StringHolder("bar");
RetryState state = new DefaultRetryState(item);
RetryCallback<StringHolder, Exception> callback = new RetryCallback<StringHolder, Exception>() {
@Override
public StringHolder doWithRetry(RetryContext context) throws Exception {
// This simulates what happens if someone uses a primary key
// for hashCode and equals and then relies on default key
// generator
item.string = item.string + (StatefulRecoveryRetryTests.this.count++);
throw new RuntimeException("Barf!");
}
RetryCallback<StringHolder, Exception> callback = context -> {
// This simulates what happens if someone uses a primary key
// for hashCode and equals and then relies on default key
// generator
item.string = item.string + (StatefulRecoveryRetryTests.this.count++);
throw new RuntimeException("Barf!");
};
try {
@@ -233,12 +215,9 @@ public class StatefulRecoveryRetryTests {
this.retryTemplate.setRetryPolicy(new SimpleRetryPolicy(1));
this.retryTemplate.setRetryContextCache(new MapRetryContextCache(1));
RetryCallback<Object, Exception> callback = new RetryCallback<Object, Exception>() {
@Override
public Object doWithRetry(RetryContext context) throws Exception {
StatefulRecoveryRetryTests.this.count++;
throw new RuntimeException("Barf!");
}
RetryCallback<Object, Exception> callback = context -> {
StatefulRecoveryRetryTests.this.count++;
throw new RuntimeException("Barf!");
};
try {
@@ -268,19 +247,11 @@ public class StatefulRecoveryRetryTests {
final StringHolder item = new StringHolder("foo");
RetryState state = new DefaultRetryState(item);
RetryCallback<Object, Exception> callback = new RetryCallback<Object, Exception>() {
@Override
public Object doWithRetry(RetryContext context) throws Exception {
StatefulRecoveryRetryTests.this.count++;
throw new RuntimeException("Barf!");
}
};
RecoveryCallback<Object> recoveryCallback = new RecoveryCallback<Object>() {
@Override
public Object recover(RetryContext context) throws Exception {
return null;
}
RetryCallback<Object, Exception> callback = context -> {
StatefulRecoveryRetryTests.this.count++;
throw new RuntimeException("Barf!");
};
RecoveryCallback<Object> recoveryCallback = context -> null;
try {
this.retryTemplate.execute(callback, recoveryCallback, state);