Merge branch '5.3.x'

This commit is contained in:
Sam Brannen 2022-02-03 14:58:36 +01:00
commit 54565e95b5
91 changed files with 576 additions and 1059 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-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.
@ -33,7 +33,6 @@ import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ScopeMetadata;
import org.springframework.context.annotation.ScopeMetadataResolver;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
@ -306,12 +305,9 @@ class ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests {
GenericWebApplicationContext context = new GenericWebApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
scanner.setIncludeAnnotationConfig(false);
scanner.setScopeMetadataResolver(new ScopeMetadataResolver() {
@Override
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
scanner.setScopeMetadataResolver(definition -> {
ScopeMetadata metadata = new ScopeMetadata();
if (definition instanceof AnnotatedBeanDefinition) {
AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
if (definition instanceof AnnotatedBeanDefinition annDef) {
for (String type : annDef.getMetadata().getAnnotationTypes()) {
if (type.equals(jakarta.inject.Singleton.class.getName())) {
metadata.setScopeName(BeanDefinition.SCOPE_SINGLETON);
@ -322,13 +318,12 @@ class ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests {
metadata.setScopedProxyMode(scopedProxyMode);
break;
}
else if (type.startsWith("jakarta.inject")) {
else if (type.startsWith("javax.inject")) {
metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
}
}
}
return metadata;
}
});
// Scan twice in order to find errors in the bean definition compatibility check.

View File

@ -125,16 +125,7 @@ public class ConcurrencyThrottleInterceptorTests {
try {
this.proxy.exceptional(this.ex);
}
catch (RuntimeException ex) {
if (ex == this.ex) {
logger.debug("Expected exception thrown", ex);
}
else {
// should never happen
ex.printStackTrace();
}
}
catch (Error err) {
catch (RuntimeException | Error err) {
if (err == this.ex) {
logger.debug("Expected exception thrown", err);
}

View File

@ -43,13 +43,13 @@ public abstract class AbstractPropertyValuesTests {
m.put("forname", "Tony");
m.put("surname", "Blair");
m.put("age", "50");
for (int i = 0; i < ps.length; i++) {
Object val = m.get(ps[i].getName());
for (PropertyValue element : ps) {
Object val = m.get(element.getName());
assertThat(val != null).as("Can't have unexpected value").isTrue();
boolean condition = val instanceof String;
assertThat(condition).as("Val i string").isTrue();
assertThat(val.equals(ps[i].getValue())).as("val matches expected").isTrue();
m.remove(ps[i].getName());
assertThat(val.equals(element.getValue())).as("val matches expected").isTrue();
m.remove(element.getName());
}
assertThat(m.size() == 0).as("Map size is 0").isTrue();
}

View File

@ -483,6 +483,7 @@ public class BeanFactoryUtilsTests {
return TestBean.class;
}
@Override
public TestBean getObject() {
// We don't really care if the actual instance is a singleton or prototype
// for the tests that use this factory.

View File

@ -42,8 +42,6 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.NotWritablePropertyException;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.TypeMismatchException;
@ -78,7 +76,6 @@ import org.springframework.beans.testfixture.beans.factory.DummyFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.core.io.Resource;
@ -983,9 +980,7 @@ class DefaultListableBeanFactoryTests {
@Test
void customConverter() {
GenericConversionService conversionService = new DefaultConversionService();
conversionService.addConverter(new Converter<String, Float>() {
@Override
public Float convert(String source) {
conversionService.addConverter(String.class, Float.class, source -> {
try {
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
return nf.parse(source).floatValue();
@ -993,7 +988,6 @@ class DefaultListableBeanFactoryTests {
catch (ParseException ex) {
throw new IllegalArgumentException(ex);
}
}
});
lbf.setConversionService(conversionService);
MutablePropertyValues pvs = new MutablePropertyValues();
@ -1007,12 +1001,9 @@ class DefaultListableBeanFactoryTests {
@Test
void customEditorWithBeanReference() {
lbf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
lbf.addPropertyEditorRegistrar(registry -> {
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
registry.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, true));
}
});
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("myFloat", new RuntimeBeanReference("myFloat"));
@ -2695,8 +2686,12 @@ class DefaultListableBeanFactoryTests {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConstructorDependency that = (ConstructorDependency) o;
return spouseAge == that.spouseAge &&
Objects.equals(spouse, that.spouse) &&

View File

@ -22,7 +22,6 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
@ -3638,11 +3637,8 @@ public class AutowiredAnnotationBeanPostProcessorTests {
@SuppressWarnings("unchecked")
public <T> T createMock(Class<T> toMock) {
return (T) Proxy.newProxyInstance(AutowiredAnnotationBeanPostProcessorTests.class.getClassLoader(), new Class<?>[] {toMock},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
(InvocationHandler) (proxy, method, args) -> {
throw new UnsupportedOperationException("mocked!");
}
});
}
}

View File

@ -29,7 +29,6 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.propertyeditors.CustomDateEditor;
@ -50,12 +49,7 @@ public class CustomEditorConfigurerTests {
CustomEditorConfigurer cec = new CustomEditorConfigurer();
final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN);
cec.setPropertyEditorRegistrars(new PropertyEditorRegistrar[] {
new PropertyEditorRegistrar() {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
}
}});
registry -> registry.registerCustomEditor(Date.class, new CustomDateEditor(df, true))});
cec.postProcessBeanFactory(bf);
MutablePropertyValues pvs = new MutablePropertyValues();

View File

@ -113,7 +113,7 @@ public class MethodInvokingFactoryBeanTests {
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello");
mcfb.afterPropertiesSet();
mcfb.getObjectType();
@ -184,7 +184,7 @@ public class MethodInvokingFactoryBeanTests {
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello");
// should pass
mcfb.afterPropertiesSet();
}
@ -194,7 +194,7 @@ public class MethodInvokingFactoryBeanTests {
MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello", "bogus");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello", "bogus");
assertThatExceptionOfType(NoSuchMethodException.class).as(
"Matched method with wrong number of args").isThrownBy(
mcfb::afterPropertiesSet);
@ -210,14 +210,14 @@ public class MethodInvokingFactoryBeanTests {
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes2");
mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello", "bogus");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello", "bogus");
mcfb.afterPropertiesSet();
assertThat(mcfb.getObject()).isEqualTo("hello");
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes2");
mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), new Object());
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), new Object());
assertThatExceptionOfType(NoSuchMethodException.class).as(
"Matched method when shouldn't have matched").isThrownBy(
mcfb::afterPropertiesSet);

View File

@ -17,7 +17,6 @@
package org.springframework.beans.factory.support;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URI;
@ -34,8 +33,6 @@ import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.ObjectProvider;
@ -409,12 +406,7 @@ class BeanFactoryGenericsTests {
@Test
void testGenericMapWithCollectionValueConstructor() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
}
});
bf.addPropertyEditorRegistrar(registry -> registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false)));
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Map<String, AbstractCollection<?>> input = new HashMap<>();
@ -568,12 +560,7 @@ class BeanFactoryGenericsTests {
@Test
void testGenericMapWithCollectionValueFactoryMethod() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
}
});
bf.addPropertyEditorRegistrar(registry -> registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false)));
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
@ -1010,11 +997,8 @@ class BeanFactoryGenericsTests {
@SuppressWarnings("unchecked")
public <T> T createMock(Class<T> toMock) {
return (T) Proxy.newProxyInstance(BeanFactoryGenericsTests.class.getClassLoader(), new Class<?>[] {toMock},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
(InvocationHandler) (proxy, method, args) -> {
throw new UnsupportedOperationException("mocked!");
}
});
}
}

View File

@ -18,8 +18,6 @@ package org.springframework.beans.factory.support;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.testfixture.beans.DerivedTestBean;
import org.springframework.beans.testfixture.beans.TestBean;
@ -40,12 +38,7 @@ public class DefaultSingletonBeanRegistryTests {
beanRegistry.registerSingleton("tb", tb);
assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb);
TestBean tb2 = (TestBean) beanRegistry.getSingleton("tb2", new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return new TestBean();
}
});
TestBean tb2 = (TestBean) beanRegistry.getSingleton("tb2", () -> new TestBean());
assertThat(beanRegistry.getSingleton("tb2")).isSameAs(tb2);
assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb);

View File

@ -40,8 +40,9 @@ public class MustBeInitialized implements InitializingBean {
* managed the bean's lifecycle correctly
*/
public void businessMethod() {
if (!this.inited)
if (!this.inited) {
throw new RuntimeException("Factory didn't call afterPropertiesSet() on MustBeInitialized object");
}
}
}

View File

@ -39,12 +39,18 @@ public class Pet {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Pet pet = (Pet) o;
if (name != null ? !name.equals(pet.name) : pet.name != null) return false;
if (name != null ? !name.equals(pet.name) : pet.name != null) {
return false;
}
return true;
}

View File

@ -178,14 +178,11 @@ public class CaffeineCacheManagerTests {
@Test
public void cacheLoaderUseLoadingCache() {
CaffeineCacheManager cm = new CaffeineCacheManager("c1");
cm.setCacheLoader(new CacheLoader<Object, Object>() {
@Override
public Object load(Object key) throws Exception {
cm.setCacheLoader(key -> {
if ("ping".equals(key)) {
return "pong";
}
throw new IllegalArgumentException("I only know ping");
}
});
Cache cache1 = cm.getCache("c1");
Cache.ValueWrapper value = cache1.get("ping");

View File

@ -181,12 +181,9 @@ public class JavaMailSenderTests {
final List<Message> messages = new ArrayList<>();
MimeMessagePreparator preparator = new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws MessagingException {
MimeMessagePreparator preparator = mimeMessage -> {
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("you@mail.org"));
messages.add(mimeMessage);
}
};
sender.send(preparator);
@ -207,19 +204,13 @@ public class JavaMailSenderTests {
final List<Message> messages = new ArrayList<>();
MimeMessagePreparator preparator1 = new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws MessagingException {
MimeMessagePreparator preparator1 = mimeMessage -> {
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("he@mail.org"));
messages.add(mimeMessage);
}
};
MimeMessagePreparator preparator2 = new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws MessagingException {
MimeMessagePreparator preparator2 = mimeMessage -> {
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("she@mail.org"));
messages.add(mimeMessage);
}
};
sender.send(preparator1, preparator2);
@ -322,12 +313,7 @@ public class JavaMailSenderTests {
@Test
public void javaMailSenderWithParseExceptionOnMimeMessagePreparator() {
MockJavaMailSender sender = new MockJavaMailSender();
MimeMessagePreparator preparator = new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws MessagingException {
mimeMessage.setFrom(new InternetAddress(""));
}
};
MimeMessagePreparator preparator = mimeMessage -> mimeMessage.setFrom(new InternetAddress(""));
try {
sender.send(preparator);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-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.
@ -557,12 +557,7 @@ class TestBeanAdvisor extends StaticMethodMatcherPointcutAdvisor {
public int count;
public TestBeanAdvisor() {
setAdvice(new MethodBeforeAdvice() {
@Override
public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
++count;
}
});
setAdvice((MethodBeforeAdvice) (method, args, target) -> ++count);
}
@Override

View File

@ -372,9 +372,7 @@ public abstract class AbstractAopProxyTests {
private void testContext(final boolean context) throws Throwable {
final String s = "foo";
// Test return value
MethodInterceptor mi = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
MethodInterceptor mi = invocation -> {
if (!context) {
assertNoInvocationContext();
}
@ -382,7 +380,6 @@ public abstract class AbstractAopProxyTests {
assertThat(ExposeInvocationInterceptor.currentInvocation()).as("have context").isNotNull();
}
return s;
}
};
AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
if (context) {
@ -422,11 +419,8 @@ public abstract class AbstractAopProxyTests {
public void testDeclaredException() throws Throwable {
final Exception expectedException = new Exception();
// Test return value
MethodInterceptor mi = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
MethodInterceptor mi = invocation -> {
throw expectedException;
}
};
AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
pc.addAdvice(ExposeInvocationInterceptor.INSTANCE);
@ -453,11 +447,8 @@ public abstract class AbstractAopProxyTests {
public void testUndeclaredCheckedException() throws Throwable {
final Exception unexpectedException = new Exception();
// Test return value
MethodInterceptor mi = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
MethodInterceptor mi = invocation -> {
throw unexpectedException;
}
};
AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
pc.addAdvice(ExposeInvocationInterceptor.INSTANCE);
@ -477,11 +468,8 @@ public abstract class AbstractAopProxyTests {
public void testUndeclaredUncheckedException() throws Throwable {
final RuntimeException unexpectedException = new RuntimeException();
// Test return value
MethodInterceptor mi = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
MethodInterceptor mi = invocation -> {
throw unexpectedException;
}
};
AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
pc.addAdvice(ExposeInvocationInterceptor.INSTANCE);
@ -660,12 +648,7 @@ public abstract class AbstractAopProxyTests {
NopInterceptor di = new NopInterceptor();
pc.addAdvice(di);
final long ts = 37;
pc.addAdvice(new DelegatingIntroductionInterceptor(new TimeStamped() {
@Override
public long getTimeStamp() {
return ts;
}
}));
pc.addAdvice(new DelegatingIntroductionInterceptor((TimeStamped) () -> ts));
ITestBean proxied = (ITestBean) createProxy(pc);
assertThat(proxied.getName()).isEqualTo(name);
@ -1039,9 +1022,7 @@ public abstract class AbstractAopProxyTests {
ProxyFactory pc = new ProxyFactory(tb);
pc.addInterface(ITestBean.class);
MethodInterceptor twoBirthdayInterceptor = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
MethodInterceptor twoBirthdayInterceptor = mi -> {
// Clone the invocation to proceed three times
// "The Moor's Last Sigh": this technology can cause premature aging
MethodInvocation clone1 = ((ReflectiveMethodInvocation) mi).invocableClone();
@ -1049,7 +1030,6 @@ public abstract class AbstractAopProxyTests {
clone1.proceed();
clone2.proceed();
return mi.proceed();
}
};
@SuppressWarnings("serial")
StaticMethodMatcherPointcutAdvisor advisor = new StaticMethodMatcherPointcutAdvisor(twoBirthdayInterceptor) {
@ -1082,16 +1062,13 @@ public abstract class AbstractAopProxyTests {
/**
* Changes the name, then changes it back.
*/
MethodInterceptor nameReverter = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
MethodInterceptor nameReverter = mi -> {
MethodInvocation clone = ((ReflectiveMethodInvocation) mi).invocableClone();
String oldName = ((ITestBean) mi.getThis()).getName();
clone.getArguments()[0] = oldName;
// Original method invocation should be unaffected by changes to argument list of clone
mi.proceed();
return clone.proceed();
}
};
class NameSaver implements MethodInterceptor {
@ -1347,9 +1324,10 @@ public abstract class AbstractAopProxyTests {
@Override
public void before(Method m, Object[] args, Object target) throws Throwable {
super.before(m, args, target);
if (m.getName().startsWith("set"))
if (m.getName().startsWith("set")) {
throw rex;
}
}
};
TestBean target = new TestBean();
@ -1563,13 +1541,10 @@ public abstract class AbstractAopProxyTests {
@SuppressWarnings("serial")
protected static class StringSetterNullReplacementAdvice extends DefaultPointcutAdvisor {
private static MethodInterceptor cleaner = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
private static MethodInterceptor cleaner = mi -> {
// We know it can only be invoked if there's a single parameter of type string
mi.getArguments()[0] = "";
return mi.proceed();
}
};
public StringSetterNullReplacementAdvice() {
@ -1601,7 +1576,9 @@ public abstract class AbstractAopProxyTests {
@Override
public boolean matches(Method m, @Nullable Class<?> targetClass, Object... args) {
boolean run = m.getName().contains(pattern);
if (run) ++count;
if (run) {
++count;
}
return run;
}
});
@ -1620,7 +1597,9 @@ public abstract class AbstractAopProxyTests {
@Override
public boolean matches(Method m, @Nullable Class<?> targetClass, Object... args) {
boolean run = m.getName().contains(pattern);
if (run) ++count;
if (run) {
++count;
}
return run;
}
@Override
@ -1924,8 +1903,9 @@ public abstract class AbstractAopProxyTests {
*/
@Override
public void releaseTarget(Object pTarget) throws Exception {
if (pTarget != this.target)
if (pTarget != this.target) {
throw new RuntimeException("Released wrong target");
}
++releases;
}
@ -1934,9 +1914,10 @@ public abstract class AbstractAopProxyTests {
*
*/
public void verify() {
if (gets != releases)
if (gets != releases) {
throw new RuntimeException("Expectation failed: " + gets + " gets and " + releases + " releases");
}
}
/**
* @see org.springframework.aop.TargetSource#isStatic()

View File

@ -198,10 +198,16 @@ public class JdkDynamicProxyTests extends AbstractAopProxyTests implements Seria
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Person person = (Person) o;
if (!name.equals(person.name)) return false;
if (!name.equals(person.name)) {
return false;
}
return true;
}

View File

@ -304,11 +304,8 @@ public class ProxyFactoryBeanTests {
final Exception ex = new UnsupportedOperationException("invoke");
// Add evil interceptor to head of list
config.addAdvice(0, new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
config.addAdvice(0, (MethodInterceptor) invocation -> {
throw ex;
}
});
assertThat(config.getAdvisors().length).as("Have correct advisor count").isEqualTo(2);
@ -691,12 +688,9 @@ public class ProxyFactoryBeanTests {
}
public PointcutForVoid() {
setAdvice(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
setAdvice((MethodInterceptor) invocation -> {
methodNames.add(invocation.getMethod().getName());
return invocation.proceed();
}
});
setPointcut(new DynamicMethodMatcherPointcut() {
@Override

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-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.
@ -17,8 +17,6 @@
package org.springframework.aop.framework.autoproxy;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.aopalliance.intercept.MethodInterceptor;
@ -434,6 +432,7 @@ public class AutoProxyCreatorTests {
@SuppressWarnings("serial")
public static class IntroductionTestAutoProxyCreator extends TestAutoProxyCreator {
@Override
protected Object[] getAdvicesAndAdvisors() {
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(this.testInterceptor);
advisor.addInterface(Serializable.class);
@ -491,12 +490,8 @@ public class AutoProxyCreatorTests {
@Override
public ITestBean getObject() {
return (ITestBean) Proxy.newProxyInstance(CustomProxyFactoryBean.class.getClassLoader(), new Class<?>[]{ITestBean.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return ReflectionUtils.invokeMethod(method, tb, args);
}
});
return (ITestBean) Proxy.newProxyInstance(CustomProxyFactoryBean.class.getClassLoader(), new Class<?>[]{ITestBean.class},
(proxy, method, args) -> ReflectionUtils.invokeMethod(method, tb, args));
}
@Override

View File

@ -158,8 +158,8 @@ class CommonsPool2TargetSourceTests {
pooledInstances[9] = targetSource.getTarget();
// release all objects
for (int i = 0; i < pooledInstances.length; i++) {
targetSource.releaseTarget(pooledInstances[i]);
for (Object element : pooledInstances) {
targetSource.releaseTarget(element);
}
}

View File

@ -33,21 +33,24 @@ public class LifecycleContextBean extends LifecycleBean implements ApplicationCo
@Override
public void setBeanFactory(BeanFactory beanFactory) {
super.setBeanFactory(beanFactory);
if (this.owningContext != null)
if (this.owningContext != null) {
throw new RuntimeException("Factory called setBeanFactory after setApplicationContext");
}
}
@Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
if (this.owningContext == null)
if (this.owningContext == null) {
throw new RuntimeException("Factory didn't call setApplicationContext before afterPropertiesSet on lifecycle bean");
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (this.owningFactory == null)
if (this.owningFactory == null) {
throw new RuntimeException("Factory called setApplicationContext before setBeanFactory");
}
this.owningContext = applicationContext;
}

View File

@ -544,19 +544,24 @@ class TestBean {
@Override
public boolean equals(Object obj) {
if (this == obj)
if (this == obj) {
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TestBean other = (TestBean) obj;
if (name == null) {
if (other.name != null)
}
if (obj == null) {
return false;
}
else if (!name.equals(other.name))
if (getClass() != obj.getClass()) {
return false;
}
TestBean other = (TestBean) obj;
if (name == null) {
if (other.name != null) {
return false;
}
}
else if (!name.equals(other.name)) {
return false;
}
return true;
}

View File

@ -214,12 +214,7 @@ public class CommonAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean4", tbd);
bf.registerResolvableDependency(BeanFactory.class, bf);
bf.registerResolvableDependency(INestedTestBean.class, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return new NestedTestBean();
}
});
bf.registerResolvableDependency(INestedTestBean.class, (ObjectFactory<Object>) () -> new NestedTestBean());
@SuppressWarnings("deprecation")
org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ppc = new org.springframework.beans.factory.config.PropertyPlaceholderConfigurer();

View File

@ -18,10 +18,8 @@ package org.springframework.context.annotation;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.testfixture.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThat;
@ -72,11 +70,8 @@ public class ConfigurationClassAndBFPPTests {
@Bean
public BeanFactoryPostProcessor bfpp() {
return new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
return beanFactory -> {
// no-op
}
};
}
}
@ -88,11 +83,8 @@ public class ConfigurationClassAndBFPPTests {
@Bean
public static final BeanFactoryPostProcessor bfpp() {
return new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
return beanFactory -> {
// no-op
}
};
}
}

View File

@ -291,7 +291,9 @@ public class ConfigurationClassWithConditionTests {
static class ImportsNotCreated {
static {
if (true) throw new RuntimeException();
if (true) {
throw new RuntimeException();
}
}
}
@ -299,14 +301,18 @@ public class ConfigurationClassWithConditionTests {
static class ConfigurationNotCreated {
static {
if (true) throw new RuntimeException();
if (true) {
throw new RuntimeException();
}
}
}
static class RegistrarNotCreated implements ImportBeanDefinitionRegistrar {
static {
if (true) throw new RuntimeException();
if (true) {
throw new RuntimeException();
}
}
@Override
@ -318,7 +324,9 @@ public class ConfigurationClassWithConditionTests {
static class ImportSelectorNotCreated implements ImportSelector {
static {
if (true) throw new RuntimeException();
if (true) {
throw new RuntimeException();
}
}
@Override

View File

@ -136,10 +136,7 @@ public class ConfigurationClassAspectIntegrationTests {
@Bean
Runnable fromInnerClass() {
return new Runnable() {
@Override
public void run() {
}
return () -> {
};
}

View File

@ -38,7 +38,6 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.config.ListFactoryBean;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
@ -558,12 +557,9 @@ public class ConfigurationClassProcessingTests {
// @Bean
public BeanFactoryPostProcessor beanFactoryPostProcessor() {
return new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
return beanFactory -> {
BeanDefinition bd = beanFactory.getBeanDefinition("beanPostProcessor");
bd.getPropertyValues().addPropertyValue("nameSuffix", "-processed-" + myProp);
}
};
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-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.
@ -20,7 +20,6 @@ import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.jupiter.api.Test;
@ -141,12 +140,9 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen
ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext());
SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
smc.setTaskExecutor(new Executor() {
@Override
public void execute(Runnable command) {
smc.setTaskExecutor(command -> {
command.run();
command.run();
}
});
smc.addApplicationListener(listener);
@ -429,12 +425,7 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen
public void anonymousClassAsListener() {
final Set<MyEvent> seenEvents = new HashSet<>();
StaticApplicationContext context = new StaticApplicationContext();
context.addApplicationListener(new ApplicationListener<MyEvent>() {
@Override
public void onApplicationEvent(MyEvent event) {
seenEvents.add(event);
}
});
context.addApplicationListener((MyEvent event) -> seenEvents.add(event));
context.refresh();
MyEvent event1 = new MyEvent(context);

View File

@ -101,7 +101,7 @@ class PayloadApplicationEventTests {
void testProgrammaticPayloadListener() {
List<String> events = new ArrayList<>();
ApplicationListener<PayloadApplicationEvent<String>> listener = ApplicationListener.forPayload(events::add);
ApplicationListener<PayloadApplicationEvent<Integer>> mismatch = ApplicationListener.forPayload(payload -> payload.intValue());
ApplicationListener<PayloadApplicationEvent<Integer>> mismatch = ApplicationListener.forPayload(Integer::intValue);
ConfigurableApplicationContext ac = new GenericApplicationContext();
ac.addApplicationListener(listener);

View File

@ -36,8 +36,12 @@ public abstract class AbstractIdentifiable implements Identifiable {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AbstractIdentifiable that = (AbstractIdentifiable) o;

View File

@ -38,8 +38,12 @@ public class GenericEventPojo<T> implements ResolvableTypeProvider {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GenericEventPojo<?> that = (GenericEventPojo<?>) o;

View File

@ -50,8 +50,12 @@ public abstract class IdentifiableApplicationEvent extends ApplicationEvent impl
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
IdentifiableApplicationEvent that = (IdentifiableApplicationEvent) o;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-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.
@ -99,8 +99,7 @@ public class ConversionServiceFactoryBeanTests {
Set<Object> converters = new HashSet<>();
converters.add("bogus");
factory.setConverters(converters);
assertThatIllegalArgumentException().isThrownBy(
factory::afterPropertiesSet);
assertThatIllegalArgumentException().isThrownBy(factory::afterPropertiesSet);
}
@Test

View File

@ -30,7 +30,6 @@ import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.util.StringValueResolver;
import org.springframework.validation.DataBinder;
import static org.assertj.core.api.Assertions.assertThat;
@ -49,16 +48,13 @@ public class NumberFormattingTests {
@BeforeEach
public void setUp() {
DefaultConversionService.addDefaultConverters(conversionService);
conversionService.setEmbeddedValueResolver(new StringValueResolver() {
@Override
public String resolveStringValue(String strVal) {
conversionService.setEmbeddedValueResolver(strVal -> {
if ("${pattern}".equals(strVal)) {
return "#,##.00";
}
else {
return strVal;
}
}
});
conversionService.addFormatterForFieldType(Number.class, new NumberStyleFormatter());
conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-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.
@ -189,24 +189,14 @@ public class FormattingConversionServiceFactoryBeanTests {
public Printer<?> getPrinter(SpecialInt annotation, Class<?> fieldType) {
assertThat(annotation.value()).isEqualTo("aliased");
assertThat(annotation.alias()).isEqualTo("aliased");
return new Printer<Integer>() {
@Override
public String print(Integer object, Locale locale) {
return ":" + object.toString();
}
};
return (object, locale) -> ":" + object.toString();
}
@Override
public Parser<?> getParser(SpecialInt annotation, Class<?> fieldType) {
assertThat(annotation.value()).isEqualTo("aliased");
assertThat(annotation.alias()).isEqualTo("aliased");
return new Parser<Integer>() {
@Override
public Integer parse(String text, Locale locale) throws ParseException {
return Integer.parseInt(text, 1, text.length(), 10);
}
};
return (text, locale) -> Integer.parseInt(text, 1, text.length(), 10);
}
}

View File

@ -27,7 +27,6 @@ import org.junit.jupiter.api.Test;
import org.springframework.jmx.AbstractMBeanServerTests;
import org.springframework.jmx.JmxTestBean;
import org.springframework.jmx.export.naming.ObjectNamingStrategy;
import org.springframework.jmx.support.ObjectNameManager;
import static org.assertj.core.api.Assertions.assertThat;
@ -74,12 +73,7 @@ class MBeanExporterOperationsTests extends AbstractMBeanServerTests {
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
exporter.setNamingStrategy(new ObjectNamingStrategy() {
@Override
public ObjectName getObjectName(Object managedBean, String beanKey) {
return objectNameTemplate;
}
});
exporter.setNamingStrategy((managedBean, beanKey) -> objectNameTemplate);
JmxTestBean bean1 = new JmxTestBean();
JmxTestBean bean2 = new JmxTestBean();
@ -101,12 +95,7 @@ class MBeanExporterOperationsTests extends AbstractMBeanServerTests {
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
exporter.setEnsureUniqueRuntimeObjectNames(false);
exporter.setNamingStrategy(new ObjectNamingStrategy() {
@Override
public ObjectName getObjectName(Object managedBean, String beanKey) {
return objectNameTemplate;
}
});
exporter.setNamingStrategy((managedBean, beanKey) -> objectNameTemplate);
JmxTestBean bean1 = new JmxTestBean();
JmxTestBean bean2 = new JmxTestBean();

View File

@ -90,11 +90,8 @@ public class MBeanExporterTests extends AbstractMBeanServerTests {
@Test
void testRegisterNotificationListenerForNonExistentMBean() throws Exception {
Map<String, NotificationListener> listeners = new HashMap<>();
NotificationListener dummyListener = new NotificationListener() {
@Override
public void handleNotification(Notification notification, Object handback) {
NotificationListener dummyListener = (notification, handback) -> {
throw new UnsupportedOperationException();
}
};
// the MBean with the supplied object name does not exist...
listeners.put("spring:type=Test", dummyListener);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-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.
@ -23,7 +23,6 @@ import javax.management.Attribute;
import javax.management.AttributeChangeNotification;
import javax.management.MalformedObjectNameException;
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
@ -117,7 +116,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests {
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListeners(new NotificationListenerBean[] { listenerBean });
exporter.setNotificationListeners(listenerBean);
start(exporter);
// update the attribute
@ -145,7 +144,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests {
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListeners(new NotificationListenerBean[] { listenerBean });
exporter.setNotificationListeners(listenerBean);
start(exporter);
// update the attribute
@ -168,9 +167,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests {
NotificationListenerBean listenerBean = new NotificationListenerBean();
listenerBean.setNotificationListener(listener);
listenerBean.setNotificationFilter(new NotificationFilter() {
@Override
public boolean isNotificationEnabled(Notification notification) {
listenerBean.setNotificationFilter(notification -> {
if (notification instanceof AttributeChangeNotification) {
AttributeChangeNotification changeNotification = (AttributeChangeNotification) notification;
return "Name".equals(changeNotification.getAttributeName());
@ -178,13 +175,12 @@ public class NotificationListenerTests extends AbstractMBeanServerTests {
else {
return false;
}
}
});
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListeners(new NotificationListenerBean[] { listenerBean });
exporter.setNotificationListeners(listenerBean);
start(exporter);
// update the attributes

View File

@ -83,9 +83,9 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests {
MBeanAttributeInfo[] inf = info.getAttributes();
assertThat(inf).as("Invalid number of Attributes returned").hasSize(getExpectedAttributeCount());
for (int x = 0; x < inf.length; x++) {
assertThat(inf[x]).as("MBeanAttributeInfo should not be null").isNotNull();
assertThat(inf[x].getDescription()).as("Description for MBeanAttributeInfo should not be null").isNotNull();
for (MBeanAttributeInfo element : inf) {
assertThat(element).as("MBeanAttributeInfo should not be null").isNotNull();
assertThat(element.getDescription()).as("Description for MBeanAttributeInfo should not be null").isNotNull();
}
}
@ -95,9 +95,9 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests {
MBeanOperationInfo[] inf = info.getOperations();
assertThat(inf).as("Invalid number of Operations returned").hasSize(getExpectedOperationCount());
for (int x = 0; x < inf.length; x++) {
assertThat(inf[x]).as("MBeanOperationInfo should not be null").isNotNull();
assertThat(inf[x].getDescription()).as("Description for MBeanOperationInfo should not be null").isNotNull();
for (MBeanOperationInfo element : inf) {
assertThat(element).as("MBeanOperationInfo should not be null").isNotNull();
assertThat(element.getDescription()).as("Description for MBeanOperationInfo should not be null").isNotNull();
}
}

View File

@ -27,7 +27,6 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.Test;
@ -613,16 +612,13 @@ public class AsyncExecutionTests {
public DynamicAsyncInterfaceBean() {
ProxyFactory pf = new ProxyFactory(new HashMap<>());
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor((MethodInterceptor) invocation -> {
boolean condition = !Thread.currentThread().getName().equals(originalThreadName);
assertThat(condition).isTrue();
if (Future.class.equals(invocation.getMethod().getReturnType())) {
return new AsyncResult<>(invocation.getArguments()[0].toString());
}
return null;
}
});
advisor.addInterface(AsyncInterface.class);
pf.addAdvisor(advisor);
@ -686,16 +682,13 @@ public class AsyncExecutionTests {
public DynamicAsyncMethodsInterfaceBean() {
ProxyFactory pf = new ProxyFactory(new HashMap<>());
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor((MethodInterceptor) invocation -> {
boolean condition = !Thread.currentThread().getName().equals(originalThreadName);
assertThat(condition).isTrue();
if (Future.class.equals(invocation.getMethod().getReturnType())) {
return new AsyncResult<>(invocation.getArguments()[0].toString());
}
return null;
}
});
advisor.addInterface(AsyncMethodsInterface.class);
pf.addAdvisor(advisor);

View File

@ -16,7 +16,6 @@
package org.springframework.scheduling.config;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.FutureTask;
@ -59,12 +58,7 @@ public class ExecutorBeanDefinitionParserTests {
assertThat(getKeepAliveSeconds(executor)).isEqualTo(60);
assertThat(getAllowCoreThreadTimeOut(executor)).isFalse();
FutureTask<String> task = new FutureTask<>(new Callable<String>() {
@Override
public String call() throws Exception {
return "foo";
}
});
FutureTask<String> task = new FutureTask<>(() -> "foo");
executor.execute(task);
assertThat(task.get()).isEqualTo("foo");
}

View File

@ -26,7 +26,7 @@ import org.codehaus.groovy.control.BytecodeProcessor;
*/
public class MyBytecodeProcessor implements BytecodeProcessor {
public final Set<String> processed = new HashSet<String>();
public final Set<String> processed = new HashSet<>();
@Override
public byte[] processBytecode(String name, byte[] original) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-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.
@ -17,8 +17,6 @@
package org.springframework.ui;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
@ -281,12 +279,7 @@ public class ModelMapTests {
Object proxy = Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] {Map.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
return "proxy";
}
});
(proxy1, method, args) -> "proxy");
map.addAttribute(proxy);
assertThat(map.get("map")).isSameAs(proxy);
}

View File

@ -61,8 +61,9 @@ public class LockMixin extends DelegatingIntroductionInterceptor implements Lock
*/
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
if (locked() && invocation.getMethod().getName().indexOf("set") == 0)
if (locked() && invocation.getMethod().getName().indexOf("set") == 0) {
throw new LockedException();
}
return super.invoke(invocation);
}

View File

@ -19,7 +19,6 @@ package org.springframework.context.testfixture;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@ -75,8 +74,7 @@ public class SimpleMapScope implements Scope, Serializable {
}
public void close() {
for (Iterator<Runnable> it = this.callbacks.iterator(); it.hasNext();) {
Runnable runnable = it.next();
for (Runnable runnable : this.callbacks) {
runnable.run();
}
}

View File

@ -1699,7 +1699,7 @@ class MergedAnnotationsTests {
assertThat(componentScan).isNotNull();
assertThat(componentScan.value().pattern()).isEqualTo("*Foo");
Map<String, Object> map = MergedAnnotation.from(componentScan).asMap(
annotation -> new LinkedHashMap<String, Object>(),
annotation -> new LinkedHashMap<>(),
Adapt.ANNOTATION_TO_MAP);
Map<String, Object> filterMap = (Map<String, Object>) map.get("value");
assertThat(filterMap.get("pattern")).isEqualTo("*Foo");
@ -1719,7 +1719,7 @@ class MergedAnnotationsTests {
ComponentScan.class);
assertThat(componentScan).isNotNull();
Map<String, Object> map = MergedAnnotation.from(componentScan).asMap(
annotation -> new LinkedHashMap<String, Object>(),
annotation -> new LinkedHashMap<>(),
Adapt.ANNOTATION_TO_MAP);
Map<String, Object>[] filters = (Map[]) map.get("excludeFilters");
List<String> patterns = Arrays.stream(filters).map(

View File

@ -140,7 +140,7 @@ class ConvertingComparatorTests {
assertThat(o2).isInstanceOf(Integer.class);
this.called = true;
return super.compare(o1, o2);
};
}
public void assertCalled() {
assertThat(this.called).isTrue();

View File

@ -48,7 +48,7 @@ class AutoPopulatingListTests {
@Test
void withElementFactoryAndUserSuppliedBackingList() throws Exception {
doTestWithElementFactory(new AutoPopulatingList<Object>(new ArrayList<>(), new MockElementFactory()));
doTestWithElementFactory(new AutoPopulatingList<>(new ArrayList<>(), new MockElementFactory()));
}
private void doTestWithClass(AutoPopulatingList<Object> list) {

View File

@ -51,7 +51,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
*/
class ConcurrentReferenceHashMapTests {
private static final Comparator<? super String> NULL_SAFE_STRING_SORT = new NullSafeComparator<String>(
private static final Comparator<? super String> NULL_SAFE_STRING_SORT = new NullSafeComparator<>(
new ComparableComparator<String>(), true);
private TestWeakConcurrentCache<Integer, String> map = new TestWeakConcurrentCache<>();

View File

@ -391,8 +391,8 @@ class ReflectionUtilsTests {
int add(int... args) {
int sum = 0;
for (int i = 0; i < args.length; i++) {
sum += args[i];
for (int arg : args) {
sum += arg;
}
return sum;
}

View File

@ -608,14 +608,8 @@ class StringUtilsTests {
}
private void doTestCommaDelimitedListToStringArrayLegalMatch(String[] components) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < components.length; i++) {
if (i != 0) {
sb.append(',');
}
sb.append(components[i]);
}
String[] sa = StringUtils.commaDelimitedListToStringArray(sb.toString());
String sb = String.join(String.valueOf(','), components);
String[] sa = StringUtils.commaDelimitedListToStringArray(sb);
assertThat(sa != null).as("String array isn't null with legal match").isTrue();
assertThat(sa.length).as("String array length is correct with legal match").isEqualTo(components.length);
assertThat(Arrays.equals(sa, components)).as("Output equals input").isTrue();

View File

@ -107,7 +107,7 @@ public abstract class AbstractRowMapperTests {
}
protected enum MockType {ONE, TWO, THREE};
protected enum MockType {ONE, TWO, THREE}
protected static class Mock {

View File

@ -22,7 +22,6 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
@ -160,12 +159,7 @@ public class JdbcTemplateQueryTests {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getInt(1)).willReturn(22);
Object o = this.template.queryForObject(sql, new RowMapper<Integer>() {
@Override
public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getInt(1);
}
});
Object o = this.template.queryForObject(sql, (RowMapper<Integer>) (rs, rowNum) -> rs.getInt(1));
assertThat(o instanceof Integer).as("Correct result type").isTrue();
verify(this.resultSet).close();
verify(this.statement).close();

View File

@ -152,12 +152,12 @@ public class JdbcTemplateTests {
@Test
public void testStringsWithStaticSql() throws Exception {
doTestStrings(null, null, null, null, (template, sql, rch) -> template.query(sql, rch));
doTestStrings(null, null, null, null, JdbcTemplate::query);
}
@Test
public void testStringsWithStaticSqlAndFetchSizeAndMaxRows() throws Exception {
doTestStrings(10, 20, 30, null, (template, sql, rch) -> template.query(sql, rch));
doTestStrings(10, 20, 30, null, JdbcTemplate::query);
}
@Test
@ -268,28 +268,22 @@ public class JdbcTemplateTests {
@Test
public void testConnectionCallback() throws Exception {
String result = this.template.execute(new ConnectionCallback<String>() {
@Override
public String doInConnection(Connection con) {
String result = this.template.execute((ConnectionCallback<String>) con -> {
assertThat(con instanceof ConnectionProxy).isTrue();
assertThat(((ConnectionProxy) con).getTargetConnection()).isSameAs(JdbcTemplateTests.this.connection);
return "test";
}
});
assertThat(result).isEqualTo("test");
}
@Test
public void testConnectionCallbackWithStatementSettings() throws Exception {
String result = this.template.execute(new ConnectionCallback<String>() {
@Override
public String doInConnection(Connection con) throws SQLException {
String result = this.template.execute((ConnectionCallback<String>) con -> {
PreparedStatement ps = con.prepareStatement("some SQL");
ps.setFetchSize(10);
ps.setMaxRows(20);
ps.close();
return "test";
}
});
assertThat(result).isEqualTo("test");

View File

@ -20,7 +20,6 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
@ -176,12 +175,7 @@ public class NamedParameterQueryTests {
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("id", 3);
Object o = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID = :id",
params, new RowMapper<Object>() {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getInt(1);
}
});
params, (RowMapper<Object>) (rs, rowNum) -> rs.getInt(1));
boolean condition = o instanceof Integer;
assertThat(condition).as("Correct result type").isTrue();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-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.
@ -46,9 +46,7 @@ import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.SqlReturnResultSet;
import org.springframework.jdbc.core.support.AbstractSqlTypeValue;
import org.springframework.jdbc.datasource.ConnectionHolder;
import org.springframework.jdbc.support.SQLExceptionTranslator;
import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
import org.springframework.lang.Nullable;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import static org.assertj.core.api.Assertions.assertThat;
@ -148,8 +146,7 @@ public class StoredProcedureTests {
given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getObject(3)).willReturn(4);
given(connection.prepareCall("{call " + AddInvoice.SQL + "(?, ?, ?)}")
).willReturn(callableStatement);
given(connection.prepareCall("{call " + AddInvoice.SQL + "(?, ?, ?)}")).willReturn(callableStatement);
TransactionSynchronizationManager.bindResource(dataSource, new ConnectionHolder(connection));
try {
testAddInvoice(1106, 3);
@ -174,8 +171,7 @@ public class StoredProcedureTests {
given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getObject(2)).willReturn(5);
given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}")
).willReturn(callableStatement);
given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}")).willReturn(callableStatement);
class TestJdbcTemplate extends JdbcTemplate {
@ -210,8 +206,7 @@ public class StoredProcedureTests {
given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getObject(2)).willReturn(4);
given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}")
).willReturn(callableStatement);
given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}")).willReturn(callableStatement);
JdbcTemplate t = new JdbcTemplate();
t.setDataSource(dataSource);
StoredProcedureConfiguredViaJdbcTemplate sp = new StoredProcedureConfiguredViaJdbcTemplate(t);
@ -234,28 +229,24 @@ public class StoredProcedureTests {
public void testUnnamedParameter() throws Exception {
this.verifyClosedAfter = false;
// Shouldn't succeed in creating stored procedure with unnamed parameter
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
new UnnamedParameterStoredProcedure(dataSource));
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
.isThrownBy(() -> new UnnamedParameterStoredProcedure(dataSource));
}
@Test
public void testMissingParameter() throws Exception {
this.verifyClosedAfter = false;
MissingParameterStoredProcedure mp = new MissingParameterStoredProcedure(dataSource);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(
mp::execute);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(mp::execute);
}
@Test
public void testStoredProcedureExceptionTranslator() throws Exception {
SQLException sqlException = new SQLException(
"Syntax error or access violation exception", "42000");
SQLException sqlException = new SQLException("Syntax error or access violation exception", "42000");
given(callableStatement.execute()).willThrow(sqlException);
given(connection.prepareCall("{call " + StoredProcedureExceptionTranslator.SQL + "()}")
).willReturn(callableStatement);
given(connection.prepareCall("{call " + StoredProcedureExceptionTranslator.SQL + "()}")).willReturn(callableStatement);
StoredProcedureExceptionTranslator sproc = new StoredProcedureExceptionTranslator(dataSource);
assertThatExceptionOfType(CustomDataException.class).isThrownBy(
sproc::execute);
assertThatExceptionOfType(CustomDataException.class).isThrownBy(sproc::execute);
}
@Test
@ -266,8 +257,7 @@ public class StoredProcedureTests {
given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getResultSet()).willReturn(resultSet);
given(callableStatement.getUpdateCount()).willReturn(-1);
given(connection.prepareCall("{call " + StoredProcedureWithResultSet.SQL + "()}")
).willReturn(callableStatement);
given(connection.prepareCall("{call " + StoredProcedureWithResultSet.SQL + "()}")).willReturn(callableStatement);
StoredProcedureWithResultSet sproc = new StoredProcedureWithResultSet(dataSource);
sproc.execute();
assertThat(sproc.getCount()).isEqualTo(2);
@ -285,14 +275,11 @@ public class StoredProcedureTests {
given(callableStatement.getResultSet()).willReturn(resultSet);
given(callableStatement.getMoreResults()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1);
given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")
).willReturn(callableStatement);
given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")).willReturn(callableStatement);
StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(dataSource);
Map<String, Object> res = sproc.execute();
List<String> rs = (List<String>) res.get("rs");
assertThat(rs.size()).isEqualTo(2);
assertThat(rs.get(0)).isEqualTo("Foo");
assertThat(rs.get(1)).isEqualTo("Bar");
assertThat(rs).containsExactly("Foo", "Bar");
verify(resultSet).close();
}
@ -319,8 +306,7 @@ public class StoredProcedureTests {
given(callableStatement.getResultSet()).willReturn(resultSet1, resultSet2);
given(callableStatement.getMoreResults()).willReturn(true, false, false);
given(callableStatement.getUpdateCount()).willReturn(-1, -1, 0, -1);
given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")
).willReturn(callableStatement);
given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")).willReturn(callableStatement);
StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(dataSource);
Map<String, Object> res = sproc.execute();
@ -328,15 +314,12 @@ public class StoredProcedureTests {
assertThat(res.size()).as("incorrect number of returns").isEqualTo(3);
List<String> rs1 = (List<String>) res.get("rs");
assertThat(rs1.size()).isEqualTo(2);
assertThat(rs1.get(0)).isEqualTo("Foo");
assertThat(rs1.get(1)).isEqualTo("Bar");
assertThat(rs1).containsExactly("Foo", "Bar");
List<Object> rs2 = (List<Object>) res.get("#result-set-2");
assertThat(rs2.size()).isEqualTo(1);
Object o2 = rs2.get(0);
boolean condition = o2 instanceof Map;
assertThat(condition).as("wron type returned for result set 2").isTrue();
assertThat(o2).as("wron type returned for result set 2").isInstanceOf(Map.class);
Map<String, String> m2 = (Map<String, String>) o2;
assertThat(m2.get("spam")).isEqualTo("Spam");
assertThat(m2.get("eggs")).isEqualTo("Eggs");
@ -351,12 +334,10 @@ public class StoredProcedureTests {
public void testStoredProcedureSkippingResultsProcessing() throws Exception {
given(callableStatement.execute()).willReturn(true);
given(callableStatement.getUpdateCount()).willReturn(-1);
given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")
).willReturn(callableStatement);
given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")).willReturn(callableStatement);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.setSkipResultsProcessing(true);
StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(
jdbcTemplate);
StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(jdbcTemplate);
Map<String, Object> res = sproc.execute();
assertThat(res.size()).as("incorrect number of returns").isEqualTo(0);
}
@ -372,13 +353,11 @@ public class StoredProcedureTests {
given(callableStatement.getResultSet()).willReturn(resultSet);
given(callableStatement.getMoreResults()).willReturn(true, false);
given(callableStatement.getUpdateCount()).willReturn(-1, -1);
given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")
).willReturn(callableStatement);
given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")).willReturn(callableStatement);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.setSkipUndeclaredResults(true);
StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(
jdbcTemplate);
StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(jdbcTemplate);
Map<String, Object> res = sproc.execute();
assertThat(res.size()).as("incorrect number of returns").isEqualTo(1);
@ -394,8 +373,7 @@ public class StoredProcedureTests {
given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getObject(2)).willReturn("OK");
given(connection.prepareCall("{call " + ParameterMapperStoredProcedure.SQL + "(?, ?)}")
).willReturn(callableStatement);
given(connection.prepareCall("{call " + ParameterMapperStoredProcedure.SQL + "(?, ?)}")).willReturn(callableStatement);
ParameterMapperStoredProcedure pmsp = new ParameterMapperStoredProcedure(dataSource);
Map<String, Object> out = pmsp.executeTest();
@ -411,8 +389,7 @@ public class StoredProcedureTests {
given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getObject(2)).willReturn("OK");
given(connection.prepareCall("{call " + SqlTypeValueStoredProcedure.SQL + "(?, ?)}")
).willReturn(callableStatement);
given(connection.prepareCall("{call " + SqlTypeValueStoredProcedure.SQL + "(?, ?)}")).willReturn(callableStatement);
SqlTypeValueStoredProcedure stvsp = new SqlTypeValueStoredProcedure(dataSource);
Map<String, Object> out = stvsp.executeTest(testVal);
@ -426,8 +403,7 @@ public class StoredProcedureTests {
given(callableStatement.execute()).willReturn(false);
given(callableStatement.getUpdateCount()).willReturn(-1);
given(callableStatement.getObject(1)).willReturn(new BigDecimal("12345.6789"));
given(connection.prepareCall("{call " + NumericWithScaleStoredProcedure.SQL + "(?)}")
).willReturn(callableStatement);
given(connection.prepareCall("{call " + NumericWithScaleStoredProcedure.SQL + "(?)}")).willReturn(callableStatement);
NumericWithScaleStoredProcedure nwssp = new NumericWithScaleStoredProcedure(dataSource);
Map<String, Object> out = nwssp.executeTest();
assertThat(out.get("out")).isEqualTo(new BigDecimal("12345.6789"));
@ -686,12 +662,7 @@ public class StoredProcedureTests {
public StoredProcedureExceptionTranslator(DataSource ds) {
setDataSource(ds);
setSql(SQL);
getJdbcTemplate().setExceptionTranslator(new SQLExceptionTranslator() {
@Override
public DataAccessException translate(String task, @Nullable String sql, SQLException ex) {
return new CustomDataException(sql, ex);
}
});
getJdbcTemplate().setExceptionTranslator((task, sql, ex) -> new CustomDataException(sql, ex));
compile();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-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,7 +87,7 @@ public class SQLErrorCodeSQLExceptionTranslatorTests {
SQLException dupKeyEx = new SQLException("", "", 10);
DataAccessException dksex = sext.translate("task", "SQL", dupKeyEx);
assertThat(DataIntegrityViolationException.class.isInstance(dksex)).as("Not instance of DataIntegrityViolationException").isTrue();
assertThat(dksex).isInstanceOf(DataIntegrityViolationException.class);
// Test fallback. We assume that no database will ever return this error code,
// but 07xxx will be bad grammar picked up by the fallback SQLState translator

View File

@ -200,12 +200,9 @@ class JmsTemplateTests {
JmsTemplate template = createTemplate();
template.setConnectionFactory(this.connectionFactory);
template.execute(new SessionCallback<Void>() {
@Override
public Void doInJms(Session session) throws JMSException {
template.execute((SessionCallback<Void>) session -> {
session.getTransacted();
return null;
}
});
verify(this.session).close();
@ -220,19 +217,13 @@ class JmsTemplateTests {
TransactionSynchronizationManager.initSynchronization();
try {
template.execute(new SessionCallback<Void>() {
@Override
public Void doInJms(Session session) throws JMSException {
template.execute((SessionCallback<Void>) session -> {
session.getTransacted();
return null;
}
});
template.execute(new SessionCallback<Void>() {
@Override
public Void doInJms(Session session) throws JMSException {
template.execute((SessionCallback<Void>) session -> {
session.getTransacted();
return null;
}
});
assertThat(ConnectionFactoryUtils.getTransactionalSession(scf, null, false)).isSameAs(this.session);
@ -374,29 +365,14 @@ class JmsTemplateTests {
}
if (useDefaultDestination) {
template.send(new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("just testing");
}
});
template.send(session -> session.createTextMessage("just testing"));
}
else {
if (explicitDestination) {
template.send(this.queue, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("just testing");
}
});
template.send(this.queue, (MessageCreator) session -> session.createTextMessage("just testing"));
}
else {
template.send(destinationName, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("just testing");
}
});
template.send(destinationName, (MessageCreator) session -> session.createTextMessage("just testing"));
}
}

View File

@ -30,7 +30,6 @@ import jakarta.jms.Session;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.task.TaskExecutor;
import org.springframework.jms.StubQueue;
import org.springframework.lang.Nullable;
import org.springframework.util.ErrorHandler;
@ -182,9 +181,7 @@ public class SimpleMessageListenerContainerTests {
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new SessionAwareMessageListener<Message>() {
@Override
public void onMessage(Message message, @Nullable Session sess) {
this.container.setMessageListener((SessionAwareMessageListener<Message>) (Message message, @Nullable Session sess) -> {
try {
// Check correct Session passed into SessionAwareMessageListener.
assertThat(session).isSameAs(sess);
@ -192,7 +189,6 @@ public class SimpleMessageListenerContainerTests {
catch (Throwable ex) {
failure.add("MessageListener execution failed: " + ex);
}
}
});
this.container.afterPropertiesSet();
@ -231,14 +227,11 @@ public class SimpleMessageListenerContainerTests {
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(listener);
this.container.setTaskExecutor(new TaskExecutor() {
@Override
public void execute(Runnable task) {
this.container.setTaskExecutor(task -> {
listener.executorInvoked = true;
assertThat(listener.listenerInvoked).isFalse();
task.run();
assertThat(listener.listenerInvoked).isTrue();
}
});
this.container.afterPropertiesSet();
this.container.start();
@ -278,11 +271,8 @@ public class SimpleMessageListenerContainerTests {
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new SessionAwareMessageListener<Message>() {
@Override
public void onMessage(Message message, @Nullable Session session) throws JMSException {
this.container.setMessageListener((SessionAwareMessageListener<Message>) (Message message, @Nullable Session session1) -> {
throw theException;
}
});
ExceptionListener exceptionListener = mock(ExceptionListener.class);
@ -328,11 +318,8 @@ public class SimpleMessageListenerContainerTests {
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new SessionAwareMessageListener<Message>() {
@Override
public void onMessage(Message message, @Nullable Session session) throws JMSException {
this.container.setMessageListener((SessionAwareMessageListener<Message>) (Message message, @Nullable Session session1) -> {
throw theException;
}
});
ErrorHandler errorHandler = mock(ErrorHandler.class);
@ -374,11 +361,8 @@ public class SimpleMessageListenerContainerTests {
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
this.container.setMessageListener((MessageListener) message -> {
throw new UnsupportedOperationException();
}
});
this.container.afterPropertiesSet();
this.container.start();
@ -418,11 +402,8 @@ public class SimpleMessageListenerContainerTests {
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
this.container.setMessageListener((MessageListener) message -> {
throw new UnsupportedOperationException();
}
});
this.container.afterPropertiesSet();
this.container.start();

View File

@ -431,8 +431,8 @@ public class MessagingMessageListenerAdapterTests {
}
}
interface Summary {};
interface Full extends Summary {};
interface Summary {}
interface Full extends Summary {}
@SuppressWarnings("unused")
private static class SampleResponse {

View File

@ -29,8 +29,6 @@ import jakarta.jms.ObjectMessage;
import jakarta.jms.Session;
import jakarta.jms.TextMessage;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.SimpleMessageConverter;
@ -76,12 +74,7 @@ public class SimpleMessageConverterTests {
given(session.createBytesMessage()).willReturn(message);
given(message.getBodyLength()).willReturn((long) content.length);
given(message.readBytes(any(byte[].class))).willAnswer(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
return byteArrayInputStream.read((byte[]) invocation.getArguments()[0]);
}
});
given(message.readBytes(any(byte[].class))).willAnswer(invocation -> byteArrayInputStream.read((byte[]) invocation.getArguments()[0]));
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);

View File

@ -299,9 +299,9 @@ class MappingJackson2MessageConverterTests {
}
private interface Summary {};
private interface Summary {}
private interface Full extends Summary {};
private interface Full extends Summary {}
@SuppressWarnings("unused")

View File

@ -319,9 +319,9 @@ public class MappingJackson2MessageConverterTests {
}
public interface MyJacksonView1 {};
public interface MyJacksonView1 {}
public interface MyJacksonView2 {};
public interface MyJacksonView2 {}
public static class JacksonViewBean {

View File

@ -29,7 +29,6 @@ import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageDeliveryException;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.StubMessageChannel;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.support.ExecutorSubscribableChannel;
@ -112,12 +111,9 @@ public class GenericMessagingTemplateTests {
@Test
public void sendAndReceive() {
SubscribableChannel channel = new ExecutorSubscribableChannel(this.executor);
channel.subscribe(new MessageHandler() {
@Override
public void handleMessage(Message<?> message) throws MessagingException {
channel.subscribe(message -> {
MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
replyChannel.send(new GenericMessage<>("response"));
}
});
String actual = this.template.convertSendAndReceive(channel, "request", String.class);
@ -126,7 +122,7 @@ public class GenericMessagingTemplateTests {
@Test
public void sendAndReceiveTimeout() throws InterruptedException {
final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
final AtomicReference<Throwable> failure = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
this.template.setReceiveTimeout(1);
@ -152,7 +148,7 @@ public class GenericMessagingTemplateTests {
@Test
public void sendAndReceiveVariableTimeout() throws InterruptedException {
final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
final AtomicReference<Throwable> failure = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
this.template.setSendTimeout(20_000);
@ -182,7 +178,7 @@ public class GenericMessagingTemplateTests {
@Test
public void sendAndReceiveVariableTimeoutCustomHeaders() throws InterruptedException {
final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
final AtomicReference<Throwable> failure = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
this.template.setSendTimeout(20_000);

View File

@ -151,7 +151,7 @@ public class MessageMappingMessageHandlerTests {
}
private Message<?> message(String destination, String... content) {
Flux<DataBuffer> payload = Flux.fromIterable(Arrays.asList(content)).map(parts -> toDataBuffer(parts));
Flux<DataBuffer> payload = Flux.fromIterable(Arrays.asList(content)).map(this::toDataBuffer);
MessageHeaderAccessor headers = new MessageHeaderAccessor();
headers.setLeaveMutable(true);
headers.setHeader(DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER,

View File

@ -28,7 +28,6 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.support.StaticListableBeanFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.messaging.Message;
import org.springframework.messaging.converter.ByteArrayMessageConverter;
@ -59,12 +58,7 @@ public class DefaultMessageHandlerMethodFactoryTests {
public void customConversion() throws Exception {
DefaultMessageHandlerMethodFactory instance = createInstance();
GenericConversionService conversionService = new GenericConversionService();
conversionService.addConverter(SampleBean.class, String.class, new Converter<SampleBean, String>() {
@Override
public String convert(SampleBean source) {
return "foo bar";
}
});
conversionService.addConverter(SampleBean.class, String.class, source -> "foo bar");
instance.setConversionService(conversionService);
instance.afterPropertiesSet();

View File

@ -131,8 +131,7 @@ public class SimpAttributesContextHolderTests {
@Test
public void currentAttributesNone() {
assertThatIllegalStateException().isThrownBy(() ->
SimpAttributesContextHolder.currentAttributes())
assertThatIllegalStateException().isThrownBy(SimpAttributesContextHolder::currentAttributes)
.withMessageStartingWith("No thread-bound SimpAttributes found");
}

View File

@ -224,8 +224,8 @@ public class SubscriptionMethodReturnValueHandlerTests {
}
private interface MyJacksonView1 {};
private interface MyJacksonView2 {};
private interface MyJacksonView1 {}
private interface MyJacksonView2 {}
private static class JacksonViewBean {

View File

@ -19,7 +19,6 @@ package org.springframework.messaging.simp.stomp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -286,12 +285,7 @@ class StompBrokerRelayMessageHandlerTests {
private static ListenableFutureTask<Void> getVoidFuture() {
ListenableFutureTask<Void> futureTask = new ListenableFutureTask<>(new Callable<Void>() {
@Override
public Void call() {
return null;
}
});
ListenableFutureTask<Void> futureTask = new ListenableFutureTask<>(() -> null);
futureTask.run();
return futureTask;
}

View File

@ -31,7 +31,6 @@ import org.springframework.transaction.InvalidIsolationLevelException;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
@ -99,13 +98,10 @@ public class JpaTransactionManagerTests {
boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition2).isTrue();
Object result = tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Object result = tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
return l;
}
});
assertThat(result).isSameAs(l);
@ -134,13 +130,10 @@ public class JpaTransactionManagerTests {
assertThat(condition2).isTrue();
try {
Object result = tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Object result = tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
return l;
}
});
assertThat(result).isSameAs(l);
}
@ -173,13 +166,10 @@ public class JpaTransactionManagerTests {
assertThat(condition2).isTrue();
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
throw new RuntimeException("some exception");
}
})).withMessage("some exception");
boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
@ -204,13 +194,10 @@ public class JpaTransactionManagerTests {
assertThat(condition2).isTrue();
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
throw new RuntimeException("some exception");
}
}));
boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
@ -234,16 +221,13 @@ public class JpaTransactionManagerTests {
boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition2).isTrue();
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
status.setRollbackOnly();
return l;
}
});
boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
@ -268,19 +252,13 @@ public class JpaTransactionManagerTests {
boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition2).isTrue();
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
return tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
return tt.execute(status1 -> {
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
return l;
}
});
}
});
boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
@ -307,18 +285,12 @@ public class JpaTransactionManagerTests {
assertThat(condition2).isTrue();
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
return tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
return tt.execute(status1 -> {
EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
throw new RuntimeException("some exception");
}
});
}
}));
boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
@ -347,20 +319,14 @@ public class JpaTransactionManagerTests {
assertThat(condition2).isTrue();
assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() ->
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
return tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
return tt.execute(status1 -> {
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
status.setRollbackOnly();
status1.setRollbackOnly();
return null;
}
});
}
}))
.withCauseInstanceOf(RollbackException.class);
@ -390,18 +356,12 @@ public class JpaTransactionManagerTests {
boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition2).isTrue();
Object result = tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Object result = tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
return tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
return tt.execute(status1 -> {
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
return l;
}
});
}
});
assertThat(result).isSameAs(l);
@ -432,20 +392,14 @@ public class JpaTransactionManagerTests {
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
try {
Object result = tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Object result = tt.execute(status -> {
EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
return tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
return tt.execute(status1 -> {
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
return l;
}
});
}
});
assertThat(result).isSameAs(l);
}
@ -478,20 +432,14 @@ public class JpaTransactionManagerTests {
boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition2).isTrue();
Object result = tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Object result = tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
TransactionTemplate tt2 = new TransactionTemplate(tm);
tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
return tt2.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
return tt2.execute(status1 -> {
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
return l;
}
});
}
});
assertThat(result).isSameAs(l);
@ -521,22 +469,16 @@ public class JpaTransactionManagerTests {
boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition2).isTrue();
Object result = tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Object result = tt.execute(status -> {
EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
TransactionTemplate tt2 = new TransactionTemplate(tm);
tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
return tt2.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
return tt2.execute(status1 -> {
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
return l;
}
});
}
});
assertThat(result).isSameAs(l);
@ -567,24 +509,18 @@ public class JpaTransactionManagerTests {
boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition2).isTrue();
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
tt.execute(status -> {
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCompletion(int status) {
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
tt.execute(status1 -> {
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
return null;
}
});
}
});
return null;
}
});
boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
@ -615,9 +551,7 @@ public class JpaTransactionManagerTests {
boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition2).isTrue();
Object result = tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Object result = tt.execute(status -> {
boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
assertThat(condition1).isTrue();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
@ -625,7 +559,6 @@ public class JpaTransactionManagerTests {
assertThat(condition).isTrue();
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
return l;
}
});
assertThat(result).isSameAs(l);
@ -649,9 +582,7 @@ public class JpaTransactionManagerTests {
boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition2).isTrue();
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
tt.execute(status -> {
boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
assertThat(condition1).isTrue();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
@ -660,7 +591,6 @@ public class JpaTransactionManagerTests {
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
status.setRollbackOnly();
return null;
}
});
boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
@ -686,14 +616,11 @@ public class JpaTransactionManagerTests {
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
try {
Object result = tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Object result = tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
return l;
}
});
assertThat(result).isSameAs(l);
@ -721,15 +648,12 @@ public class JpaTransactionManagerTests {
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
try {
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
status.setRollbackOnly();
return null;
}
});
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
@ -759,16 +683,13 @@ public class JpaTransactionManagerTests {
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
try {
Object result = tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Object result = tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
boolean condition = !status.isNewTransaction();
assertThat(condition).isTrue();
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
return l;
}
});
assertThat(result).isSameAs(l);
@ -794,9 +715,7 @@ public class JpaTransactionManagerTests {
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
try {
tt.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
tt.execute(status -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
boolean condition = !status.isNewTransaction();
@ -804,7 +723,6 @@ public class JpaTransactionManagerTests {
EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
status.setRollbackOnly();
return null;
}
});
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-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.
@ -72,13 +72,7 @@ public class InterceptingClientHttpRequestFactoryTests {
@Test
public void noExecution() throws Exception {
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
return responseMock;
}
});
interceptors.add((request, body, execution) -> responseMock);
interceptors.add(new NoOpInterceptor());
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, interceptors);
@ -97,14 +91,10 @@ public class InterceptingClientHttpRequestFactoryTests {
final String headerValue = "Bar";
final String otherValue = "Baz";
ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
HttpRequestWrapper wrapper = new HttpRequestWrapper(request);
wrapper.getHeaders().add(headerName, otherValue);
return execution.execute(wrapper, body);
}
};
requestMock = new RequestMock() {
@ -119,8 +109,7 @@ public class InterceptingClientHttpRequestFactoryTests {
};
requestMock.getHeaders().add(headerName, headerValue);
requestFactory =
new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
request.execute();
@ -130,19 +119,13 @@ public class InterceptingClientHttpRequestFactoryTests {
public void changeURI() throws Exception {
final URI changedUri = new URI("https://example.com/2");
ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
return execution.execute(new HttpRequestWrapper(request) {
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> execution.execute(new HttpRequestWrapper(request) {
@Override
public URI getURI() {
return changedUri;
}
}, body);
}
};
requestFactoryMock = new RequestFactoryMock() {
@Override
@ -152,8 +135,7 @@ public class InterceptingClientHttpRequestFactoryTests {
}
};
requestFactory =
new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
request.execute();
@ -163,19 +145,13 @@ public class InterceptingClientHttpRequestFactoryTests {
public void changeMethod() throws Exception {
final HttpMethod changedMethod = HttpMethod.POST;
ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
return execution.execute(new HttpRequestWrapper(request) {
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> execution.execute(new HttpRequestWrapper(request) {
@Override
public HttpMethod getMethod() {
return changedMethod;
}
}, body);
}
};
requestFactoryMock = new RequestFactoryMock() {
@Override
@ -185,8 +161,7 @@ public class InterceptingClientHttpRequestFactoryTests {
}
};
requestFactory =
new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
request.execute();
@ -196,16 +171,9 @@ public class InterceptingClientHttpRequestFactoryTests {
public void changeBody() throws Exception {
final byte[] changedBody = "Foo".getBytes();
ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
return execution.execute(request, changedBody);
}
};
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> execution.execute(request, changedBody);
requestFactory =
new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
request.execute();

View File

@ -271,9 +271,9 @@ public class MappingJackson2XmlHttpMessageConverterTests {
}
private interface MyJacksonView1 {};
private interface MyJacksonView1 {}
private interface MyJacksonView2 {};
private interface MyJacksonView2 {}
@SuppressWarnings("unused")

View File

@ -249,13 +249,13 @@ public class ServletRequestDataBinderTests {
m.put("forname", "Tony");
m.put("surname", "Blair");
m.put("age", "50");
for (int i = 0; i < ps.length; i++) {
Object val = m.get(ps[i].getName());
for (PropertyValue element : ps) {
Object val = m.get(element.getName());
assertThat(val != null).as("Can't have unexpected value").isTrue();
boolean condition = val instanceof String;
assertThat(condition).as("Val i string").isTrue();
assertThat(val.equals(ps[i].getValue())).as("val matches expected").isTrue();
m.remove(ps[i].getName());
assertThat(val.equals(element.getValue())).as("val matches expected").isTrue();
m.remove(element.getName());
}
assertThat(m.size() == 0).as("Map size is 0").isTrue();
}

View File

@ -16,8 +16,6 @@
package org.springframework.web.context.request.async;
import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
import org.springframework.web.context.request.async.DeferredResult.DeferredResultHandler;
@ -127,12 +125,7 @@ public class DeferredResultTests {
DeferredResult<String> result = new DeferredResult<>(null, "error result");
result.setResultHandler(handler);
Exception e = new Exception();
result.onError(new Consumer<Throwable>() {
@Override
public void accept(Throwable t) {
sb.append("error event");
}
});
result.onError(t -> sb.append("error event"));
result.getInterceptor().handleError(null, null, e);

View File

@ -17,7 +17,6 @@
package org.springframework.web.context.request.async;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import jakarta.servlet.AsyncEvent;
import org.junit.jupiter.api.BeforeEach;
@ -95,12 +94,7 @@ public class WebAsyncManagerErrorTests {
StubCallable callable = new StubCallable();
WebAsyncTask<Object> webAsyncTask = new WebAsyncTask<>(callable);
webAsyncTask.onError(new Callable<Object>() {
@Override
public Object call() throws Exception {
return 7;
}
});
webAsyncTask.onError(() -> 7);
this.asyncManager.startCallableProcessing(webAsyncTask);
@ -201,12 +195,7 @@ public class WebAsyncManagerErrorTests {
public void startDeferredResultProcessingErrorAndResumeThroughCallback() throws Exception {
final DeferredResult<Throwable> deferredResult = new DeferredResult<>();
deferredResult.onError(new Consumer<Throwable>() {
@Override
public void accept(Throwable t) {
deferredResult.setResult(t);
}
});
deferredResult.onError(t -> deferredResult.setResult(t));
this.asyncManager.startDeferredResultProcessing(deferredResult);

View File

@ -96,12 +96,7 @@ public class WebAsyncManagerTimeoutTests {
StubCallable callable = new StubCallable();
WebAsyncTask<Object> webAsyncTask = new WebAsyncTask<>(callable);
webAsyncTask.onTimeout(new Callable<Object>() {
@Override
public Object call() throws Exception {
return 7;
}
});
webAsyncTask.onTimeout(() -> 7);
this.asyncManager.startCallableProcessing(webAsyncTask);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-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.
@ -20,8 +20,6 @@ import java.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
@ -67,14 +65,9 @@ public class HiddenHttpMethodFilterTests {
}
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = new FilterChain() {
@Override
public void doFilter(ServletRequest filterRequest,
ServletResponse filterResponse) throws IOException, ServletException {
assertThat(((HttpServletRequest) filterRequest).getMethod()).as("Invalid method").isEqualTo(expectedMethod);
}
};
FilterChain filterChain = (filterRequest, filterResponse) ->
assertThat(((HttpServletRequest) filterRequest).getMethod())
.as("Invalid method").isEqualTo(expectedMethod);
this.filter.doFilter(request, response, filterChain);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-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.
@ -54,27 +54,24 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Rossen Stoyanchev
*/
public class ModelFactoryOrderingTests {
class ModelFactoryOrderingTests {
private static final Log logger = LogFactory.getLog(ModelFactoryOrderingTests.class);
private NativeWebRequest webRequest;
private final NativeWebRequest webRequest = new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse());
private ModelAndViewContainer mavContainer;
private final ModelAndViewContainer mavContainer = new ModelAndViewContainer();
private SessionAttributeStore sessionAttributeStore;
private final SessionAttributeStore sessionAttributeStore = new DefaultSessionAttributeStore();
@BeforeEach
public void setup() {
this.sessionAttributeStore = new DefaultSessionAttributeStore();
this.webRequest = new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse());
this.mavContainer = new ModelAndViewContainer();
void setup() {
this.mavContainer.addAttribute("methods", new ArrayList<String>());
}
@Test
public void straightLineDependency() throws Exception {
void straightLineDependency() throws Exception {
runTest(new StraightLineDependencyController());
assertInvokedBefore("getA", "getB1", "getB2", "getC1", "getC2", "getC3", "getC4");
assertInvokedBefore("getB1", "getB2", "getC1", "getC2", "getC3", "getC4");
@ -85,7 +82,7 @@ public class ModelFactoryOrderingTests {
}
@Test
public void treeDependency() throws Exception {
void treeDependency() throws Exception {
runTest(new TreeDependencyController());
assertInvokedBefore("getA", "getB1", "getB2", "getC1", "getC2", "getC3", "getC4");
assertInvokedBefore("getB1", "getC1", "getC2");
@ -93,7 +90,7 @@ public class ModelFactoryOrderingTests {
}
@Test
public void InvertedTreeDependency() throws Exception {
void InvertedTreeDependency() throws Exception {
runTest(new InvertedTreeDependencyController());
assertInvokedBefore("getC1", "getA", "getB1");
assertInvokedBefore("getC2", "getA", "getB1");
@ -104,7 +101,7 @@ public class ModelFactoryOrderingTests {
}
@Test
public void unresolvedDependency() throws Exception {
void unresolvedDependency() throws Exception {
runTest(new UnresolvedDependencyController());
assertInvokedBefore("getA", "getC1", "getC2", "getC3", "getC4");
@ -133,19 +130,16 @@ public class ModelFactoryOrderingTests {
ModelFactory factory = new ModelFactory(modelMethods, dataBinderFactory, sessionHandler);
factory.initModel(this.webRequest, this.mavContainer, new HandlerMethod(controller, "handle"));
if (logger.isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
for (String name : getInvokedMethods()) {
sb.append(" >> ").append(name);
}
logger.debug(sb);
logger.debug(String.join(" >> ", getInvokedMethods()));
}
}
private void assertInvokedBefore(String beforeMethod, String... afterMethods) {
List<String> actual = getInvokedMethods();
for (String afterMethod : afterMethods) {
assertThat(actual.indexOf(beforeMethod) < actual.indexOf(afterMethod)).as(beforeMethod + " should be before " + afterMethod + ". Actual order: " +
actual.toString()).isTrue();
assertThat(actual.indexOf(beforeMethod) < actual.indexOf(afterMethod))
.as(beforeMethod + " should be before " + afterMethod + ". Actual order: " + actual.toString())
.isTrue();
}
}
@ -321,13 +315,8 @@ public class ModelFactoryOrderingTests {
private static class C4 { }
private static final ReflectionUtils.MethodFilter METHOD_FILTER = new ReflectionUtils.MethodFilter() {
@Override
public boolean matches(Method method) {
return ((AnnotationUtils.findAnnotation(method, RequestMapping.class) == null) &&
private static final ReflectionUtils.MethodFilter METHOD_FILTER = method ->
((AnnotationUtils.findAnnotation(method, RequestMapping.class) == null) &&
(AnnotationUtils.findAnnotation(method, ModelAttribute.class) != null));
}
};
}

View File

@ -111,7 +111,7 @@ public class BodyExtractorsTests {
return hints;
}
};
this.hints = new HashMap<String, Object>();
this.hints = new HashMap<>();
}

View File

@ -36,7 +36,6 @@ import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest;
import org.springframework.web.testfixture.http.server.reactive.MockServerHttpResponse;
import org.springframework.web.testfixture.server.MockServerWebExchange;
@ -295,12 +294,9 @@ public class RouterFunctionsTests {
public void toHttpHandlerWebFilter() {
AtomicBoolean filterInvoked = new AtomicBoolean();
WebFilter webFilter = new WebFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
WebFilter webFilter = (exchange, chain) -> {
filterInvoked.set(true);
return chain.filter(exchange);
}
};
HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.accepted().build();

View File

@ -164,7 +164,7 @@ public class ResourceUrlProviderTests {
private Condition<PathPattern> pathPatternStringOf(String expected) {
return new Condition<PathPattern>(
return new Condition<>(
actual -> actual != null && actual.getPatternString().equals(expected),
"Pattern %s", expected);
}

View File

@ -33,21 +33,24 @@ public class LifecycleContextBean extends LifecycleBean implements ApplicationCo
@Override
public void setBeanFactory(BeanFactory beanFactory) {
super.setBeanFactory(beanFactory);
if (this.owningContext != null)
if (this.owningContext != null) {
throw new RuntimeException("Factory called setBeanFactory after setApplicationContext");
}
}
@Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
if (this.owningContext == null)
if (this.owningContext == null) {
throw new RuntimeException("Factory didn't call setApplicationContext before afterPropertiesSet on lifecycle bean");
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (this.owningFactory == null)
if (this.owningFactory == null) {
throw new RuntimeException("Factory called setApplicationContext before setBeanFactory");
}
this.owningContext = applicationContext;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-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.
@ -24,9 +24,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.testfixture.beans.TestBean;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.NoSuchMessageException;
@ -55,10 +53,7 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes
MockServletContext sc = new MockServletContext("");
root.setServletContext(sc);
root.setConfigLocations("/org/springframework/web/context/WEB-INF/applicationContext.xml");
root.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
root.addBeanFactoryPostProcessor(beanFactory -> beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
@Override
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
if (bean instanceof TestBean) {
@ -66,13 +61,7 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
return bean;
}
});
}
});
}));
root.refresh();
XmlWebApplicationContext wac = new XmlWebApplicationContext();
wac.getEnvironment().addActiveProfile("wacProfile1");
@ -108,7 +97,7 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes
@Test
@Override
public void count() {
assertThat(this.applicationContext.getBeanDefinitionCount() == 14).as("should have 14 beans, not "+ this.applicationContext.getBeanDefinitionCount()).isTrue();
assertThat(this.applicationContext.getBeanDefinitionCount()).as("should have 14 beans").isEqualTo(14);
}
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-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.
@ -20,8 +20,6 @@ import java.io.IOException;
import jakarta.servlet.Servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.springframework.web.HttpRequestHandler;
@ -45,13 +43,11 @@ public class HttpRequestHandlerTests {
@Test
public void testHttpRequestHandlerServletPassThrough() throws Exception {
MockServletContext servletContext = new MockServletContext();
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.getBeanFactory().registerSingleton("myHandler", new HttpRequestHandler() {
@Override
public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
wac.getBeanFactory().registerSingleton("myHandler", (HttpRequestHandler) (req, res) -> {
assertThat(req).isSameAs(request);
assertThat(res).isSameAs(response);
String exception = request.getParameter("exception");
@ -62,7 +58,6 @@ public class HttpRequestHandlerTests {
throw new IOException("test");
}
res.getWriter().write("myResponse");
}
});
wac.setServletContext(servletContext);
wac.refresh();
@ -75,13 +70,13 @@ public class HttpRequestHandlerTests {
assertThat(response.getContentAsString()).isEqualTo("myResponse");
request.setParameter("exception", "ServletException");
assertThatExceptionOfType(ServletException.class).isThrownBy(() ->
servlet.service(request, response))
assertThatExceptionOfType(ServletException.class)
.isThrownBy(() -> servlet.service(request, response))
.withMessage("test");
request.setParameter("exception", "IOException");
assertThatIOException().isThrownBy(() ->
servlet.service(request, response))
assertThatIOException()
.isThrownBy(() -> servlet.service(request, response))
.withMessage("test");
}

View File

@ -29,7 +29,6 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.testfixture.beans.TestBean;
import org.springframework.core.Ordered;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.io.FileSystemResourceLoader;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.HttpStatus;
@ -360,12 +359,7 @@ public class WebMvcConfigurationSupportExtensionTests {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new Converter<TestBean, String>() {
@Override
public String convert(TestBean source) {
return "converted";
}
});
registry.addConverter(TestBean.class, String.class, testBean -> "converted");
}
@Override

View File

@ -34,7 +34,6 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.servlet.ModelAndView;
@ -48,13 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class DefaultEntityResponseBuilderTests {
static final ServerResponse.Context EMPTY_CONTEXT = new ServerResponse.Context() {
@Override
public List<HttpMessageConverter<?>> messageConverters() {
return Collections.emptyList();
}
};
static final ServerResponse.Context EMPTY_CONTEXT = () -> Collections.emptyList();
@Test
public void fromObject() {

View File

@ -20,7 +20,6 @@ import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.Cookie;
@ -28,7 +27,6 @@ import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.servlet.ModelAndView;
@ -42,13 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class DefaultRenderingResponseTests {
static final ServerResponse.Context EMPTY_CONTEXT = new ServerResponse.Context() {
@Override
public List<HttpMessageConverter<?>> messageConverters() {
return Collections.emptyList();
}
};
static final ServerResponse.Context EMPTY_CONTEXT = () -> Collections.emptyList();
@Test
public void create() throws Exception {

View File

@ -317,12 +317,7 @@ class DefaultServerRequestTests {
@Test
void principal() {
MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
Principal principal = new Principal() {
@Override
public String getName() {
return "foo";
}
};
Principal principal = () -> "foo";
servletRequest.setUserPrincipal(principal);
DefaultServerRequest request = new DefaultServerRequest(servletRequest,

View File

@ -38,7 +38,6 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
@ -54,14 +53,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class DefaultServerResponseBuilderTests {
static final ServerResponse.Context EMPTY_CONTEXT = new ServerResponse.Context() {
@Override
public List<HttpMessageConverter<?>> messageConverters() {
return Collections.emptyList();
}
};
static final ServerResponse.Context EMPTY_CONTEXT = () -> Collections.emptyList();
@Test
public void status() {

View File

@ -22,7 +22,6 @@ import java.io.StringReader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
@ -948,12 +947,7 @@ public class SelectTagTests extends AbstractFormTagTests {
}
private Map getCountryToLocaleMap() {
Map map = new TreeMap(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((Country)o1).getName().compareTo(((Country)o2).getName());
}
});
Map map = new TreeMap((o1, o2) -> ((Country)o1).getName().compareTo(((Country)o2).getName()));
map.put(Country.COUNTRY_AT, LOCALE_AT);
map.put(Country.COUNTRY_NL, LOCALE_NL);
map.put(Country.COUNTRY_US, Locale.US);

View File

@ -28,7 +28,6 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.user.SimpSubscription;
import org.springframework.messaging.simp.user.SimpSubscriptionMatcher;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.socket.CloseStatus;
@ -143,12 +142,7 @@ public class DefaultSimpUserRegistryTests {
subscribeEvent = new SessionSubscribeEvent(this, message, user);
registry.onApplicationEvent(subscribeEvent);
Set<SimpSubscription> matches = registry.findSubscriptions(new SimpSubscriptionMatcher() {
@Override
public boolean match(SimpSubscription subscription) {
return subscription.getDestination().equals("/match");
}
});
Set<SimpSubscription> matches = registry.findSubscriptions(subscription -> subscription.getDestination().equals("/match"));
assertThat(matches.size()).isEqualTo(2);