Browse Source

Merge pull request #1454 from diguage:lambda

* pr/1454:
  Polish "Replace relevant code with lambda"
  Replace relevant code with lambda
pull/1459/head
Stephane Nicoll 8 years ago
parent
commit
40df48fd95
  1. 9
      spring-aop/src/main/java/org/springframework/aop/aspectj/DeclareParentsAdvisor.java
  2. 30
      spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/ReflectiveAspectJAdvisorFactory.java
  3. 15
      spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java
  4. 27
      spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionInterceptor.java
  5. 10
      spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java
  6. 11
      spring-beans/src/main/java/org/springframework/beans/PropertyMatches.java
  7. 85
      spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java
  8. 31
      spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java
  9. 23
      spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
  10. 17
      spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/JCacheInterceptor.java
  11. 17
      spring-context/src/main/java/org/springframework/cache/annotation/AnnotationCacheOperationSource.java
  12. 17
      spring-context/src/main/java/org/springframework/cache/interceptor/CacheInterceptor.java
  13. 108
      spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java
  14. 13
      spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java
  15. 13
      spring-context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java
  16. 14
      spring-context/src/main/java/org/springframework/jmx/export/MBeanExporter.java
  17. 14
      spring-core/src/main/java/org/springframework/core/convert/converter/ConvertingComparator.java
  18. 7
      spring-core/src/main/java/org/springframework/core/env/AbstractPropertyResolver.java
  19. 7
      spring-core/src/main/java/org/springframework/util/PropertyPlaceholderHelper.java
  20. 9
      spring-core/src/main/java/org/springframework/util/ReflectionUtils.java
  21. 21
      spring-core/src/main/java/org/springframework/util/concurrent/CompletableToListenableFutureAdapter.java
  22. 7
      spring-core/src/main/java/org/springframework/util/concurrent/SettableListenableFuture.java
  23. 17
      spring-expression/src/main/java/org/springframework/expression/spel/ast/InlineList.java
  24. 33
      spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveMethodResolver.java
  25. 7
      spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java
  26. 18
      spring-jdbc/src/main/java/org/springframework/jdbc/config/SortedResourcesFactoryBean.java
  27. 18
      spring-jdbc/src/main/java/org/springframework/jdbc/core/support/JdbcBeanDefinitionReader.java
  28. 7
      spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandler.java
  29. 7
      spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/DefaultStompSession.java
  30. 48
      spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java
  31. 8
      spring-orm/src/main/java/org/springframework/orm/hibernate5/LocalSessionFactoryBuilder.java
  32. 9
      spring-orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java
  33. 46
      spring-orm/src/main/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.java
  34. 84
      spring-test/src/main/java/org/springframework/test/web/client/match/ContentRequestMatchers.java
  35. 97
      spring-test/src/main/java/org/springframework/test/web/client/match/MockRestRequestMatchers.java
  36. 18
      spring-tx/src/main/java/org/springframework/jca/cci/core/CciTemplate.java
  37. 10
      spring-tx/src/main/java/org/springframework/jca/context/ResourceAdapterApplicationContext.java
  38. 51
      spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java
  39. 52
      spring-web/src/main/java/org/springframework/http/MediaType.java
  40. 88
      spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java
  41. 8
      spring-web/src/main/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolver.java
  42. 11
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java
  43. 19
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java
  44. 13
      spring-websocket/src/main/java/org/springframework/web/socket/client/jetty/JettyWebSocketClient.java
  45. 25
      spring-websocket/src/main/java/org/springframework/web/socket/client/standard/AnnotatedEndpointConnectionManager.java
  46. 27
      spring-websocket/src/main/java/org/springframework/web/socket/client/standard/EndpointConnectionManager.java
  47. 9
      spring-websocket/src/main/java/org/springframework/web/socket/client/standard/StandardWebSocketClient.java
  48. 11
      spring-websocket/src/main/java/org/springframework/web/socket/config/WebSocketMessageBrokerStats.java
  49. 19
      spring-websocket/src/main/java/org/springframework/web/socket/messaging/WebSocketStompClient.java
  50. 7
      spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/AbstractClientSockJsSession.java
  51. 49
      spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/RestTemplateXhrTransport.java
  52. 31
      spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java

9
spring-aop/src/main/java/org/springframework/aop/aspectj/DeclareParentsAdvisor.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 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.
@ -76,12 +76,7 @@ public class DeclareParentsAdvisor implements IntroductionAdvisor { @@ -76,12 +76,7 @@ public class DeclareParentsAdvisor implements IntroductionAdvisor {
ClassFilter typePatternFilter = new TypePatternClassFilter(typePattern);
// Excludes methods implemented.
ClassFilter exclusion = new ClassFilter() {
@Override
public boolean matches(Class<?> clazz) {
return !(introducedInterface.isAssignableFrom(clazz));
}
};
ClassFilter exclusion = clazz -> !(introducedInterface.isAssignableFrom(clazz));
this.typePatternClassFilter = ClassFilters.intersection(typePatternFilter, exclusion);
this.advice = advice;

30
spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/ReflectiveAspectJAdvisorFactory.java

@ -76,21 +76,12 @@ public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto @@ -76,21 +76,12 @@ public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto
Comparator<Method> adviceKindComparator = new ConvertingComparator<>(
new InstanceComparator<>(
Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class),
new Converter<Method, Annotation>() {
@Override
public Annotation convert(Method method) {
AspectJAnnotation<?> annotation =
AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(method);
return (annotation != null ? annotation.getAnnotation() : null);
}
});
Comparator<Method> methodNameComparator = new ConvertingComparator<>(
new Converter<Method, String>() {
@Override
public String convert(Method method) {
return method.getName();
}
(Converter<Method, Annotation>) method -> {
AspectJAnnotation<?> annotation =
AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(method);
return (annotation != null ? annotation.getAnnotation() : null);
});
Comparator<Method> methodNameComparator = new ConvertingComparator<>(Method::getName);
METHOD_COMPARATOR = adviceKindComparator.thenComparing(methodNameComparator);
}
@ -157,13 +148,10 @@ public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto @@ -157,13 +148,10 @@ public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto
private List<Method> getAdvisorMethods(Class<?> aspectClass) {
final List<Method> methods = new LinkedList<>();
ReflectionUtils.doWithMethods(aspectClass, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException {
// Exclude pointcuts
if (AnnotationUtils.getAnnotation(method, Pointcut.class) == null) {
methods.add(method);
}
ReflectionUtils.doWithMethods(aspectClass, method -> {
// Exclude pointcuts
if (AnnotationUtils.getAnnotation(method, Pointcut.class) == null) {
methods.add(method);
}
});
Collections.sort(methods, METHOD_COMPARATOR);

15
spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java

@ -264,15 +264,12 @@ public abstract class AsyncExecutionAspectSupport implements BeanFactoryAware { @@ -264,15 +264,12 @@ public abstract class AsyncExecutionAspectSupport implements BeanFactoryAware {
@Nullable
protected Object doSubmit(Callable<Object> task, AsyncTaskExecutor executor, Class<?> returnType) {
if (CompletableFuture.class.isAssignableFrom(returnType)) {
return CompletableFuture.supplyAsync(new Supplier<Object>() {
@Override
public Object get() {
try {
return task.call();
}
catch (Throwable ex) {
throw new CompletionException(ex);
}
return CompletableFuture.supplyAsync(() -> {
try {
return task.call();
}
catch (Throwable ex) {
throw new CompletionException(ex);
}
}, executor);
}

27
spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionInterceptor.java

@ -109,23 +109,20 @@ public class AsyncExecutionInterceptor extends AsyncExecutionAspectSupport imple @@ -109,23 +109,20 @@ public class AsyncExecutionInterceptor extends AsyncExecutionAspectSupport imple
"No executor specified and no default executor set on AsyncExecutionInterceptor either");
}
Callable<Object> task = new Callable<Object>() {
@Override
public Object call() throws Exception {
try {
Object result = invocation.proceed();
if (result instanceof Future) {
return ((Future<?>) result).get();
}
Callable<Object> task = () -> {
try {
Object result = invocation.proceed();
if (result instanceof Future) {
return ((Future<?>) result).get();
}
catch (ExecutionException ex) {
handleError(ex.getCause(), userDeclaredMethod, invocation.getArguments());
}
catch (Throwable ex) {
handleError(ex, userDeclaredMethod, invocation.getArguments());
}
return null;
}
catch (ExecutionException ex) {
handleError(ex.getCause(), userDeclaredMethod, invocation.getArguments());
}
catch (Throwable ex) {
handleError(ex, userDeclaredMethod, invocation.getArguments());
}
return null;
};
return doSubmit(task, executor, invocation.getMethod().getReturnType());

10
spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@ -28,7 +28,6 @@ import java.beans.PropertyDescriptor; @@ -28,7 +28,6 @@ import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
@ -139,12 +138,7 @@ class ExtendedBeanInfo implements BeanInfo { @@ -139,12 +138,7 @@ class ExtendedBeanInfo implements BeanInfo {
// Sort non-void returning write methods to guard against the ill effects of
// non-deterministic sorting of methods returned from Class#getDeclaredMethods
// under JDK 7. See http://bugs.sun.com/view_bug.do?bug_id=7023180
Collections.sort(matches, new Comparator<Method>() {
@Override
public int compare(Method m1, Method m2) {
return m2.toString().compareTo(m1.toString());
}
});
matches.sort((m1, m2) -> m2.toString().compareTo(m1.toString()));
return matches;
}

11
spring-beans/src/main/java/org/springframework/beans/PropertyMatches.java

@ -245,13 +245,10 @@ public abstract class PropertyMatches { @@ -245,13 +245,10 @@ public abstract class PropertyMatches {
private static String[] calculateMatches(final String propertyName, Class<?> beanClass, final int maxDistance) {
final List<String> candidates = new ArrayList<>();
ReflectionUtils.doWithFields(beanClass, new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
String possibleAlternative = field.getName();
if (calculateStringDistance(propertyName, possibleAlternative) <= maxDistance) {
candidates.add(possibleAlternative);
}
ReflectionUtils.doWithFields(beanClass, field -> {
String possibleAlternative = field.getName();
if (calculateStringDistance(propertyName, possibleAlternative) <= maxDistance) {
candidates.add(possibleAlternative);
}
});
Collections.sort(candidates);

85
spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java

@ -239,20 +239,17 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean @@ -239,20 +239,17 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean
// Let's check for lookup methods here..
if (!this.lookupMethodsChecked.contains(beanName)) {
try {
ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
Lookup lookup = method.getAnnotation(Lookup.class);
if (lookup != null) {
LookupOverride override = new LookupOverride(method, lookup.value());
try {
RootBeanDefinition mbd = (RootBeanDefinition) beanFactory.getMergedBeanDefinition(beanName);
mbd.getMethodOverrides().addOverride(override);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(beanName,
"Cannot apply @Lookup to beans without corresponding bean definition");
}
ReflectionUtils.doWithMethods(beanClass, method -> {
Lookup lookup = method.getAnnotation(Lookup.class);
if (lookup != null) {
LookupOverride override = new LookupOverride(method, lookup.value());
try {
RootBeanDefinition mbd = (RootBeanDefinition) beanFactory.getMergedBeanDefinition(beanName);
mbd.getMethodOverrides().addOverride(override);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(beanName,
"Cannot apply @Lookup to beans without corresponding bean definition");
}
}
});
@ -414,48 +411,42 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean @@ -414,48 +411,42 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean
do {
final LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<>();
ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
AnnotationAttributes ann = findAutowiredAnnotation(field);
if (ann != null) {
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static fields: " + field);
}
return;
ReflectionUtils.doWithLocalFields(targetClass, field -> {
AnnotationAttributes ann = findAutowiredAnnotation(field);
if (ann != null) {
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static fields: " + field);
}
boolean required = determineRequiredStatus(ann);
currElements.add(new AutowiredFieldElement(field, required));
return;
}
boolean required = determineRequiredStatus(ann);
currElements.add(new AutowiredFieldElement(field, required));
}
});
ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
}
AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static methods: " + method);
}
return;
}
AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static methods: " + method);
}
return;
}
if (method.getParameterCount() == 0) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation should only be used on methods with parameters: " +
method);
}
if (method.getParameterCount() == 0) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation should only be used on methods with parameters: " +
method);
}
boolean required = determineRequiredStatus(ann);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new AutowiredMethodElement(method, required, pd));
}
boolean required = determineRequiredStatus(ann);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new AutowiredMethodElement(method, required, pd));
}
});

31
spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@ -201,24 +201,21 @@ public class InitDestroyAnnotationBeanPostProcessor @@ -201,24 +201,21 @@ public class InitDestroyAnnotationBeanPostProcessor
final LinkedList<LifecycleElement> currInitMethods = new LinkedList<>();
final LinkedList<LifecycleElement> currDestroyMethods = new LinkedList<>();
ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
if (initAnnotationType != null) {
if (method.getAnnotation(initAnnotationType) != null) {
LifecycleElement element = new LifecycleElement(method);
currInitMethods.add(element);
if (debug) {
logger.debug("Found init method on class [" + clazz.getName() + "]: " + method);
}
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
if (initAnnotationType != null) {
if (method.getAnnotation(initAnnotationType) != null) {
LifecycleElement element = new LifecycleElement(method);
currInitMethods.add(element);
if (debug) {
logger.debug("Found init method on class [" + clazz.getName() + "]: " + method);
}
}
if (destroyAnnotationType != null) {
if (method.getAnnotation(destroyAnnotationType) != null) {
currDestroyMethods.add(new LifecycleElement(method));
if (debug) {
logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method);
}
}
if (destroyAnnotationType != null) {
if (method.getAnnotation(destroyAnnotationType) != null) {
currDestroyMethods.add(new LifecycleElement(method));
if (debug) {
logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method);
}
}
}

23
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java

@ -877,20 +877,15 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac @@ -877,20 +877,15 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
// Find the given factory method, taking into account that in the case of
// @Bean methods, there may be parameters present.
ReflectionUtils.doWithMethods(fbClass,
new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) {
if (method.getName().equals(factoryMethodName) &&
FactoryBean.class.isAssignableFrom(method.getReturnType())) {
Class<?> currentType = GenericTypeResolver.resolveReturnTypeArgument(
method, FactoryBean.class);
if (currentType != null) {
objectType.value = ClassUtils.determineCommonAncestor(currentType, objectType.value);
}
}
}
});
ReflectionUtils.doWithMethods(fbClass, method -> {
if (method.getName().equals(factoryMethodName) &&
FactoryBean.class.isAssignableFrom(method.getReturnType())) {
Class<?> currentType = GenericTypeResolver.resolveReturnTypeArgument(method, FactoryBean.class);
if (currentType != null) {
objectType.value = ClassUtils.determineCommonAncestor(currentType, objectType.value);
}
}
});
return (objectType.value != null && Object.class != objectType.value ? objectType.value : null);
}

17
spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/JCacheInterceptor.java vendored

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2017 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.
@ -45,15 +45,12 @@ public class JCacheInterceptor extends JCacheAspectSupport implements MethodInte @@ -45,15 +45,12 @@ public class JCacheInterceptor extends JCacheAspectSupport implements MethodInte
public Object invoke(final MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
CacheOperationInvoker aopAllianceInvoker = new CacheOperationInvoker() {
@Override
public Object invoke() {
try {
return invocation.proceed();
}
catch (Throwable ex) {
throw new ThrowableWrapper(ex);
}
CacheOperationInvoker aopAllianceInvoker = () -> {
try {
return invocation.proceed();
}
catch (Throwable ex) {
throw new CacheOperationInvoker.ThrowableWrapper(ex);
}
};

17
spring-context/src/main/java/org/springframework/cache/annotation/AnnotationCacheOperationSource.java vendored

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@ -107,23 +107,12 @@ public class AnnotationCacheOperationSource extends AbstractFallbackCacheOperati @@ -107,23 +107,12 @@ public class AnnotationCacheOperationSource extends AbstractFallbackCacheOperati
@Override
protected Collection<CacheOperation> findCacheOperations(final Class<?> clazz) {
return determineCacheOperations(new CacheOperationProvider() {
@Override
public Collection<CacheOperation> getCacheOperations(CacheAnnotationParser parser) {
return parser.parseCacheAnnotations(clazz);
}
});
return determineCacheOperations(parser -> parser.parseCacheAnnotations(clazz));
}
@Override
protected Collection<CacheOperation> findCacheOperations(final Method method) {
return determineCacheOperations(new CacheOperationProvider() {
@Override
public Collection<CacheOperation> getCacheOperations(CacheAnnotationParser parser) {
return parser.parseCacheAnnotations(method);
}
});
return determineCacheOperations(parser -> parser.parseCacheAnnotations(method));
}
/**

17
spring-context/src/main/java/org/springframework/cache/interceptor/CacheInterceptor.java vendored

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 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.
@ -45,15 +45,12 @@ public class CacheInterceptor extends CacheAspectSupport implements MethodInterc @@ -45,15 +45,12 @@ public class CacheInterceptor extends CacheAspectSupport implements MethodInterc
public Object invoke(final MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
CacheOperationInvoker aopAllianceInvoker = new CacheOperationInvoker() {
@Override
public Object invoke() {
try {
return invocation.proceed();
}
catch (Throwable ex) {
throw new ThrowableWrapper(ex);
}
CacheOperationInvoker aopAllianceInvoker = () -> {
try {
return invocation.proceed();
}
catch (Throwable ex) {
throw new CacheOperationInvoker.ThrowableWrapper(ex);
}
};

108
spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java

@ -351,72 +351,66 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean @@ -351,72 +351,66 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
final LinkedList<InjectionMetadata.InjectedElement> currElements =
new LinkedList<>();
ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
if (webServiceRefClass != null && field.isAnnotationPresent(webServiceRefClass)) {
if (Modifier.isStatic(field.getModifiers())) {
throw new IllegalStateException("@WebServiceRef annotation is not supported on static fields");
}
currElements.add(new WebServiceRefElement(field, field, null));
ReflectionUtils.doWithLocalFields(targetClass, field -> {
if (webServiceRefClass != null && field.isAnnotationPresent(webServiceRefClass)) {
if (Modifier.isStatic(field.getModifiers())) {
throw new IllegalStateException("@WebServiceRef annotation is not supported on static fields");
}
else if (ejbRefClass != null && field.isAnnotationPresent(ejbRefClass)) {
if (Modifier.isStatic(field.getModifiers())) {
throw new IllegalStateException("@EJB annotation is not supported on static fields");
}
currElements.add(new EjbRefElement(field, field, null));
currElements.add(new WebServiceRefElement(field, field, null));
}
else if (ejbRefClass != null && field.isAnnotationPresent(ejbRefClass)) {
if (Modifier.isStatic(field.getModifiers())) {
throw new IllegalStateException("@EJB annotation is not supported on static fields");
}
else if (field.isAnnotationPresent(Resource.class)) {
if (Modifier.isStatic(field.getModifiers())) {
throw new IllegalStateException("@Resource annotation is not supported on static fields");
}
if (!ignoredResourceTypes.contains(field.getType().getName())) {
currElements.add(new ResourceElement(field, field, null));
}
currElements.add(new EjbRefElement(field, field, null));
}
else if (field.isAnnotationPresent(Resource.class)) {
if (Modifier.isStatic(field.getModifiers())) {
throw new IllegalStateException("@Resource annotation is not supported on static fields");
}
if (!ignoredResourceTypes.contains(field.getType().getName())) {
currElements.add(new ResourceElement(field, field, null));
}
}
});
ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
}
if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (webServiceRefClass != null && bridgedMethod.isAnnotationPresent(webServiceRefClass)) {
if (Modifier.isStatic(method.getModifiers())) {
throw new IllegalStateException("@WebServiceRef annotation is not supported on static methods");
}
if (method.getParameterCount() != 1) {
throw new IllegalStateException("@WebServiceRef annotation requires a single-arg method: " + method);
}
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new WebServiceRefElement(method, bridgedMethod, pd));
}
if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (webServiceRefClass != null && bridgedMethod.isAnnotationPresent(webServiceRefClass)) {
if (Modifier.isStatic(method.getModifiers())) {
throw new IllegalStateException("@WebServiceRef annotation is not supported on static methods");
}
if (method.getParameterCount() != 1) {
throw new IllegalStateException("@WebServiceRef annotation requires a single-arg method: " + method);
}
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new WebServiceRefElement(method, bridgedMethod, pd));
else if (ejbRefClass != null && bridgedMethod.isAnnotationPresent(ejbRefClass)) {
if (Modifier.isStatic(method.getModifiers())) {
throw new IllegalStateException("@EJB annotation is not supported on static methods");
}
else if (ejbRefClass != null && bridgedMethod.isAnnotationPresent(ejbRefClass)) {
if (Modifier.isStatic(method.getModifiers())) {
throw new IllegalStateException("@EJB annotation is not supported on static methods");
}
if (method.getParameterCount() != 1) {
throw new IllegalStateException("@EJB annotation requires a single-arg method: " + method);
}
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new EjbRefElement(method, bridgedMethod, pd));
if (method.getParameterCount() != 1) {
throw new IllegalStateException("@EJB annotation requires a single-arg method: " + method);
}
else if (bridgedMethod.isAnnotationPresent(Resource.class)) {
if (Modifier.isStatic(method.getModifiers())) {
throw new IllegalStateException("@Resource annotation is not supported on static methods");
}
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length != 1) {
throw new IllegalStateException("@Resource annotation requires a single-arg method: " + method);
}
if (!ignoredResourceTypes.contains(paramTypes[0].getName())) {
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new ResourceElement(method, bridgedMethod, pd));
}
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new EjbRefElement(method, bridgedMethod, pd));
}
else if (bridgedMethod.isAnnotationPresent(Resource.class)) {
if (Modifier.isStatic(method.getModifiers())) {
throw new IllegalStateException("@Resource annotation is not supported on static methods");
}
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length != 1) {
throw new IllegalStateException("@Resource annotation requires a single-arg method: " + method);
}
if (!ignoredResourceTypes.contains(paramTypes[0].getName())) {
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new ResourceElement(method, bridgedMethod, pd));
}
}
}

13
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java

@ -19,8 +19,6 @@ package org.springframework.context.annotation; @@ -19,8 +19,6 @@ package org.springframework.context.annotation;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
@ -280,13 +278,10 @@ public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPo @@ -280,13 +278,10 @@ public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPo
}
// Sort by previously determined @Order value, if applicable
Collections.sort(configCandidates, new Comparator<BeanDefinitionHolder>() {
@Override
public int compare(BeanDefinitionHolder bd1, BeanDefinitionHolder bd2) {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
}
configCandidates.sort((bd1, bd2) -> {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
});
// Detect any custom bean name generation strategy supplied through the enclosing application context

13
spring-context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java

@ -226,14 +226,11 @@ public class DefaultLifecycleProcessor implements LifecycleProcessor, BeanFactor @@ -226,14 +226,11 @@ public class DefaultLifecycleProcessor implements LifecycleProcessor, BeanFactor
logger.debug("Asking bean '" + beanName + "' of type [" + bean.getClass() + "] to stop");
}
countDownBeanNames.add(beanName);
((SmartLifecycle) bean).stop(new Runnable() {
@Override
public void run() {
latch.countDown();
countDownBeanNames.remove(beanName);
if (logger.isDebugEnabled()) {
logger.debug("Bean '" + beanName + "' completed its stop procedure");
}
((SmartLifecycle) bean).stop(() -> {
latch.countDown();
countDownBeanNames.remove(beanName);
if (logger.isDebugEnabled()) {
logger.debug("Bean '" + beanName + "' completed its stop procedure");
}
});
}

14
spring-context/src/main/java/org/springframework/jmx/export/MBeanExporter.java

@ -872,12 +872,7 @@ public class MBeanExporter extends MBeanRegistrationSupport implements MBeanExpo @@ -872,12 +872,7 @@ public class MBeanExporter extends MBeanRegistrationSupport implements MBeanExpo
* certain internal classes from being registered automatically.
*/
private void autodetectBeans(final AutodetectCapableMBeanInfoAssembler assembler) {
autodetect(new AutodetectCallback() {
@Override
public boolean include(Class<?> beanClass, String beanName) {
return assembler.includeBean(beanClass, beanName);
}
});
autodetect((beanClass, beanName) -> assembler.includeBean(beanClass, beanName));
}
/**
@ -885,12 +880,7 @@ public class MBeanExporter extends MBeanRegistrationSupport implements MBeanExpo @@ -885,12 +880,7 @@ public class MBeanExporter extends MBeanRegistrationSupport implements MBeanExpo
* valid MBeans and registers them automatically with the {@code MBeanServer}.
*/
private void autodetectMBeans() {
autodetect(new AutodetectCallback() {
@Override
public boolean include(Class<?> beanClass, String beanName) {
return isMBean(beanClass);
}
});
autodetect((beanClass, beanName) -> isMBean(beanClass));
}
/**

14
spring-core/src/main/java/org/springframework/core/convert/converter/ConvertingComparator.java

@ -87,12 +87,7 @@ public class ConvertingComparator<S, T> implements Comparator<S> { @@ -87,12 +87,7 @@ public class ConvertingComparator<S, T> implements Comparator<S> {
* @return a new {@link ConvertingComparator} instance
*/
public static <K, V> ConvertingComparator<Map.Entry<K, V>, K> mapEntryKeys(Comparator<K> comparator) {
return new ConvertingComparator<>(comparator, new Converter<Map.Entry<K, V>, K>() {
@Override
public K convert(Map.Entry<K, V> source) {
return source.getKey();
}
});
return new ConvertingComparator<>(comparator, source -> source.getKey());
}
/**
@ -102,12 +97,7 @@ public class ConvertingComparator<S, T> implements Comparator<S> { @@ -102,12 +97,7 @@ public class ConvertingComparator<S, T> implements Comparator<S> {
* @return a new {@link ConvertingComparator} instance
*/
public static <K, V> ConvertingComparator<Map.Entry<K, V>, V> mapEntryValues(Comparator<V> comparator) {
return new ConvertingComparator<>(comparator, new Converter<Map.Entry<K, V>, V>() {
@Override
public V convert(Map.Entry<K, V> source) {
return source.getValue();
}
});
return new ConvertingComparator<>(comparator, source -> source.getValue());
}

7
spring-core/src/main/java/org/springframework/core/env/AbstractPropertyResolver.java vendored

@ -226,12 +226,7 @@ public abstract class AbstractPropertyResolver implements ConfigurablePropertyRe @@ -226,12 +226,7 @@ public abstract class AbstractPropertyResolver implements ConfigurablePropertyRe
}
private String doResolvePlaceholders(String text, PropertyPlaceholderHelper helper) {
return helper.replacePlaceholders(text, new PropertyPlaceholderHelper.PlaceholderResolver() {
@Override
public String resolvePlaceholder(String placeholderName) {
return getPropertyAsRawString(placeholderName);
}
});
return helper.replacePlaceholders(text, placeholderName -> getPropertyAsRawString(placeholderName));
}
/**

7
spring-core/src/main/java/org/springframework/util/PropertyPlaceholderHelper.java

@ -108,12 +108,7 @@ public class PropertyPlaceholderHelper { @@ -108,12 +108,7 @@ public class PropertyPlaceholderHelper {
*/
public String replacePlaceholders(String value, final Properties properties) {
Assert.notNull(properties, "'properties' must not be null");
return replacePlaceholders(value, new PlaceholderResolver() {
@Override
public String resolvePlaceholder(String placeholderName) {
return properties.getProperty(placeholderName);
}
});
return replacePlaceholders(value, placeholderName -> properties.getProperty(placeholderName));
}
/**

9
spring-core/src/main/java/org/springframework/util/ReflectionUtils.java

@ -848,13 +848,8 @@ public abstract class ReflectionUtils { @@ -848,13 +848,8 @@ public abstract class ReflectionUtils {
/**
* Pre-built FieldFilter that matches all non-static, non-final fields.
*/
public static final FieldFilter COPYABLE_FIELDS = new FieldFilter() {
@Override
public boolean matches(Field field) {
return !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()));
}
};
public static final FieldFilter COPYABLE_FIELDS =
field -> !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()));
/**

21
spring-core/src/main/java/org/springframework/util/concurrent/CompletableToListenableFutureAdapter.java

@ -21,9 +21,6 @@ import java.util.concurrent.CompletionStage; @@ -21,9 +21,6 @@ import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiFunction;
import org.springframework.lang.Nullable;
/**
* Adapts a {@link CompletableFuture} or {@link CompletionStage} into a
@ -53,18 +50,14 @@ public class CompletableToListenableFutureAdapter<T> implements ListenableFuture @@ -53,18 +50,14 @@ public class CompletableToListenableFutureAdapter<T> implements ListenableFuture
*/
public CompletableToListenableFutureAdapter(CompletableFuture<T> completableFuture) {
this.completableFuture = completableFuture;
this.completableFuture.handle(new BiFunction<T, Throwable, Object>() {
@Override
@Nullable
public Object apply(T result, @Nullable Throwable ex) {
if (ex != null) {
callbacks.failure(ex);
}
else {
callbacks.success(result);
}
return null;
this.completableFuture.handle((result, ex) -> {
if (ex != null) {
callbacks.failure(ex);
}
else {
callbacks.success(result);
}
return null;
});
}

7
spring-core/src/main/java/org/springframework/util/concurrent/SettableListenableFuture.java

@ -37,11 +37,8 @@ import org.springframework.util.Assert; @@ -37,11 +37,8 @@ import org.springframework.util.Assert;
*/
public class SettableListenableFuture<T> implements ListenableFuture<T> {
private static final Callable<Object> DUMMY_CALLABLE = new Callable<Object>() {
@Override
public Object call() throws Exception {
throw new IllegalStateException("Should never be called");
}
private static final Callable<Object> DUMMY_CALLABLE = () -> {
throw new IllegalStateException("Should never be called");
};

17
spring-expression/src/main/java/org/springframework/expression/spel/ast/InlineList.java

@ -20,7 +20,6 @@ import java.util.ArrayList; @@ -20,7 +20,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.asm.ClassWriter;
import org.springframework.asm.MethodVisitor;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.TypedValue;
@ -137,17 +136,11 @@ public class InlineList extends SpelNodeImpl { @@ -137,17 +136,11 @@ public class InlineList extends SpelNodeImpl {
final String constantFieldName = "inlineList$" + codeflow.nextFieldId();
final String className = codeflow.getClassName();
codeflow.registerNewField(new CodeFlow.FieldAdder() {
public void generateField(ClassWriter cw, CodeFlow codeflow) {
cw.visitField(ACC_PRIVATE|ACC_STATIC|ACC_FINAL, constantFieldName, "Ljava/util/List;", null, null);
}
});
codeflow.registerNewClinit(new CodeFlow.ClinitAdder() {
public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
generateClinitCode(className, constantFieldName, mv, codeflow, false);
}
});
codeflow.registerNewField((cw, cflow) ->
cw.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, constantFieldName, "Ljava/util/List;", null, null));
codeflow.registerNewClinit((mVisitor, cflow) ->
generateClinitCode(className, constantFieldName, mVisitor, cflow, false));
mv.visitFieldInsn(GETSTATIC, className, constantFieldName, "Ljava/util/List;");
codeflow.pushDescriptor("Ljava/util/List");

33
spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveMethodResolver.java

@ -21,8 +21,6 @@ import java.lang.reflect.Modifier; @@ -21,8 +21,6 @@ import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
@ -121,25 +119,22 @@ public class ReflectiveMethodResolver implements MethodResolver { @@ -121,25 +119,22 @@ public class ReflectiveMethodResolver implements MethodResolver {
// Sort methods into a sensible order
if (methods.size() > 1) {
Collections.sort(methods, new Comparator<Method>() {
@Override
public int compare(Method m1, Method m2) {
int m1pl = m1.getParameterCount();
int m2pl = m2.getParameterCount();
// varargs methods go last
if (m1pl == m2pl) {
if (!m1.isVarArgs() && m2.isVarArgs()) {
return -1;
}
else if (m1.isVarArgs() && !m2.isVarArgs()) {
return 1;
}
else {
return 0;
}
methods.sort((m1, m2) -> {
int m1pl = m1.getParameterCount();
int m2pl = m2.getParameterCount();
// varargs methods go last
if (m1pl == m2pl) {
if (!m1.isVarArgs() && m2.isVarArgs()) {
return -1;
}
else if (m1.isVarArgs() && !m2.isVarArgs()) {
return 1;
}
else {
return 0;
}
return (m1pl < m2pl ? -1 : (m1pl > m2pl ? 1 : 0));
}
return (m1pl < m2pl ? -1 : (m1pl > m2pl ? 1 : 0));
});
}

7
spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java

@ -391,12 +391,7 @@ public class ReflectivePropertyAccessor implements PropertyAccessor { @@ -391,12 +391,7 @@ public class ReflectivePropertyAccessor implements PropertyAccessor {
*/
private Method[] getSortedClassMethods(Class<?> clazz) {
Method[] methods = clazz.getMethods();
Arrays.sort(methods, new Comparator<Method>() {
@Override
public int compare(Method o1, Method o2) {
return (o1.isBridge() == o2.isBridge()) ? 0 : (o1.isBridge() ? 1 : -1);
}
});
Arrays.sort(methods, (o1, o2) -> (o1.isBridge() == o2.isBridge()) ? 0 : (o1.isBridge() ? 1 : -1));
return methods;
}

18
spring-jdbc/src/main/java/org/springframework/jdbc/config/SortedResourcesFactoryBean.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.io.IOException; @@ -20,7 +20,6 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.springframework.beans.factory.FactoryBean;
@ -77,15 +76,12 @@ public class SortedResourcesFactoryBean extends AbstractFactoryBean<Resource[]> @@ -77,15 +76,12 @@ public class SortedResourcesFactoryBean extends AbstractFactoryBean<Resource[]>
for (String location : this.locations) {
List<Resource> resources = new ArrayList<>(
Arrays.asList(this.resourcePatternResolver.getResources(location)));
Collections.sort(resources, new Comparator<Resource>() {
@Override
public int compare(Resource r1, Resource r2) {
try {
return r1.getURL().toString().compareTo(r2.getURL().toString());
}
catch (IOException ex) {
return 0;
}
Collections.sort(resources, (r1, r2) -> {
try {
return r1.getURL().toString().compareTo(r2.getURL().toString());
}
catch (IOException ex) {
return 0;
}
});
for (Resource resource : resources) {

18
spring-jdbc/src/main/java/org/springframework/jdbc/core/support/JdbcBeanDefinitionReader.java

@ -16,15 +16,12 @@ @@ -16,15 +16,12 @@
package org.springframework.jdbc.core.support;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.util.Assert;
/**
@ -105,15 +102,12 @@ public class JdbcBeanDefinitionReader { @@ -105,15 +102,12 @@ public class JdbcBeanDefinitionReader {
public void loadBeanDefinitions(String sql) {
Assert.notNull(this.jdbcTemplate, "Not fully configured - specify DataSource or JdbcTemplate");
final Properties props = new Properties();
this.jdbcTemplate.query(sql, new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
String beanName = rs.getString(1);
String property = rs.getString(2);
String value = rs.getString(3);
// Make a properties entry by combining bean name and property.
props.setProperty(beanName + '.' + property, value);
}
this.jdbcTemplate.query(sql, rs -> {
String beanName = rs.getString(1);
String property = rs.getString(2);
String value = rs.getString(3);
// Make a properties entry by combining bean name and property.
props.setProperty(beanName + '.' + property, value);
});
this.propReader.registerBeanDefinitions(props);
}

7
spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandler.java

@ -462,12 +462,7 @@ public class SimpAnnotationMethodMessageHandler extends AbstractMethodMessageHan @@ -462,12 +462,7 @@ public class SimpAnnotationMethodMessageHandler extends AbstractMethodMessageHan
@Override
protected Comparator<SimpMessageMappingInfo> getMappingComparator(final Message<?> message) {
return new Comparator<SimpMessageMappingInfo>() {
@Override
public int compare(SimpMessageMappingInfo info1, SimpMessageMappingInfo info2) {
return info1.compareTo(info2, message);
}
};
return (info1, info2) -> info1.compareTo(info2, message);
}
@Override

7
spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/DefaultStompSession.java

@ -535,12 +535,7 @@ public class DefaultStompSession implements ConnectionHandlingStompSession { @@ -535,12 +535,7 @@ public class DefaultStompSession implements ConnectionHandlingStompSession {
Assert.notNull(getTaskScheduler(), "To track receipts, a TaskScheduler must be configured");
DefaultStompSession.this.receiptHandlers.put(this.receiptId, this);
Date startTime = new Date(System.currentTimeMillis() + getReceiptTimeLimit());
this.future = getTaskScheduler().schedule(new Runnable() {
@Override
public void run() {
handleReceiptNotReceived();
}
}, startTime);
this.future = getTaskScheduler().schedule(this::handleReceiptNotReceived, startTime);
}
@Override

48
spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java

@ -585,13 +585,10 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler @@ -585,13 +585,10 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
logger.debug("TCP connection opened in session=" + getSessionId());
}
this.tcpConnection = connection;
this.tcpConnection.onReadInactivity(new Runnable() {
@Override
public void run() {
if (tcpConnection != null && !isStompConnected) {
handleTcpConnectionFailure("No CONNECTED frame received in " +
MAX_TIME_TO_CONNECTED_FRAME + " ms.", null);
}
this.tcpConnection.onReadInactivity(() -> {
if (this.tcpConnection != null && !this.isStompConnected) {
handleTcpConnectionFailure("No CONNECTED frame received in " +
MAX_TIME_TO_CONNECTED_FRAME + " ms.", null);
}
}, MAX_TIME_TO_CONNECTED_FRAME);
connection.send(MessageBuilder.createMessage(EMPTY_PAYLOAD, this.connectHeaders.getMessageHeaders()));
@ -700,33 +697,26 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler @@ -700,33 +697,26 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
long serverReceiveInterval = connectedHeaders.getHeartbeat()[1];
if (clientSendInterval > 0 && serverReceiveInterval > 0) {
long interval = Math.max(clientSendInterval, serverReceiveInterval);
this.tcpConnection.onWriteInactivity(new Runnable() {
@Override
public void run() {
TcpConnection<byte[]> conn = tcpConnection;
if (conn != null) {
conn.send(HEARTBEAT_MESSAGE).addCallback(
new ListenableFutureCallback<Void>() {
public void onSuccess(Void result) {
}
public void onFailure(Throwable ex) {
handleTcpConnectionFailure(
"Failed to forward heartbeat: " + ex.getMessage(), ex);
}
});
}
long interval = Math.max(clientSendInterval, serverReceiveInterval);
this.tcpConnection.onWriteInactivity(() -> {
TcpConnection<byte[]> conn = this.tcpConnection;
if (conn != null) {
conn.send(HEARTBEAT_MESSAGE).addCallback(
new ListenableFutureCallback<Void>() {
public void onSuccess(Void result) {
}
public void onFailure(Throwable ex) {
handleTcpConnectionFailure("Failed to forward heartbeat: " + ex.getMessage(), ex);
}
});
}
}, interval);
}
if (clientReceiveInterval > 0 && serverSendInterval > 0) {
final long interval = Math.max(clientReceiveInterval, serverSendInterval) * HEARTBEAT_MULTIPLIER;
this.tcpConnection.onReadInactivity(new Runnable() {
@Override
public void run() {
handleTcpConnectionFailure("No messages received in " + interval + " ms.", null);
}
}, interval);
this.tcpConnection.onReadInactivity(()
-> handleTcpConnectionFailure("No messages received in " + interval + " ms.", null), interval);
}
}

8
spring-orm/src/main/java/org/springframework/orm/hibernate5/LocalSessionFactoryBuilder.java

@ -384,12 +384,8 @@ public class LocalSessionFactoryBuilder extends Configuration { @@ -384,12 +384,8 @@ public class LocalSessionFactoryBuilder extends Configuration {
private final Future<SessionFactory> sessionFactoryFuture;
public BootstrapSessionFactoryInvocationHandler(AsyncTaskExecutor bootstrapExecutor) {
this.sessionFactoryFuture = bootstrapExecutor.submit(new Callable<SessionFactory>() {
@Override
public SessionFactory call() throws Exception {
return buildSessionFactory();
}
});
this.sessionFactoryFuture = bootstrapExecutor.submit(
(Callable<SessionFactory>) LocalSessionFactoryBuilder.this::buildSessionFactory);
}
@Override

9
spring-orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java

@ -30,7 +30,6 @@ import java.util.LinkedHashSet; @@ -30,7 +30,6 @@ import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.persistence.EntityManager;
@ -350,12 +349,8 @@ public abstract class AbstractEntityManagerFactoryBean implements @@ -350,12 +349,8 @@ public abstract class AbstractEntityManagerFactoryBean implements
}
if (this.bootstrapExecutor != null) {
this.nativeEntityManagerFactoryFuture = this.bootstrapExecutor.submit(new Callable<EntityManagerFactory>() {
@Override
public EntityManagerFactory call() {
return buildNativeEntityManagerFactory();
}
});
this.nativeEntityManagerFactoryFuture = this.bootstrapExecutor.submit(
this::buildNativeEntityManagerFactory);
}
else {
this.nativeEntityManagerFactory = buildNativeEntityManagerFactory();

46
spring-orm/src/main/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.java

@ -404,38 +404,32 @@ public class PersistenceAnnotationBeanPostProcessor @@ -404,38 +404,32 @@ public class PersistenceAnnotationBeanPostProcessor
final LinkedList<InjectionMetadata.InjectedElement> currElements =
new LinkedList<>();
ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
if (field.isAnnotationPresent(PersistenceContext.class) ||
field.isAnnotationPresent(PersistenceUnit.class)) {
if (Modifier.isStatic(field.getModifiers())) {
throw new IllegalStateException("Persistence annotations are not supported on static fields");
}
currElements.add(new PersistenceElement(field, field, null));
ReflectionUtils.doWithLocalFields(targetClass, field -> {
if (field.isAnnotationPresent(PersistenceContext.class) ||
field.isAnnotationPresent(PersistenceUnit.class)) {
if (Modifier.isStatic(field.getModifiers())) {
throw new IllegalStateException("Persistence annotations are not supported on static fields");
}
currElements.add(new PersistenceElement(field, field, null));
}
});
ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
}
if ((bridgedMethod.isAnnotationPresent(PersistenceContext.class) ||
bridgedMethod.isAnnotationPresent(PersistenceUnit.class)) &&
method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
throw new IllegalStateException("Persistence annotations are not supported on static methods");
}
if ((bridgedMethod.isAnnotationPresent(PersistenceContext.class) ||
bridgedMethod.isAnnotationPresent(PersistenceUnit.class)) &&
method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
throw new IllegalStateException("Persistence annotations are not supported on static methods");
}
if (method.getParameterCount() != 1) {
throw new IllegalStateException("Persistence annotation requires a single-arg method: " + method);
}
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new PersistenceElement(method, bridgedMethod, pd));
if (method.getParameterCount() != 1) {
throw new IllegalStateException("Persistence annotation requires a single-arg method: " + method);
}
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new PersistenceElement(method, bridgedMethod, pd));
}
});

84
spring-test/src/main/java/org/springframework/test/web/client/match/ContentRequestMatchers.java

@ -70,13 +70,10 @@ public class ContentRequestMatchers { @@ -70,13 +70,10 @@ public class ContentRequestMatchers {
* Assert the request content type as a {@link MediaType}.
*/
public RequestMatcher contentType(final MediaType expectedContentType) {
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) throws IOException, AssertionError {
MediaType actualContentType = request.getHeaders().getContentType();
assertTrue("Content type not set", actualContentType != null);
assertEquals("Content type", expectedContentType, actualContentType);
}
return request -> {
MediaType actualContentType = request.getHeaders().getContentType();
assertTrue("Content type not set", actualContentType != null);
assertEquals("Content type", expectedContentType, actualContentType);
};
}
@ -93,15 +90,12 @@ public class ContentRequestMatchers { @@ -93,15 +90,12 @@ public class ContentRequestMatchers {
* content type as defined by {@link MediaType#isCompatibleWith(MediaType)}.
*/
public RequestMatcher contentTypeCompatibleWith(final MediaType contentType) {
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) throws IOException, AssertionError {
MediaType actualContentType = request.getHeaders().getContentType();
assertTrue("Content type not set", actualContentType != null);
if (actualContentType != null) {
assertTrue("Content type [" + actualContentType + "] is not compatible with [" + contentType + "]",
actualContentType.isCompatibleWith(contentType));
}
return request -> {
MediaType actualContentType = request.getHeaders().getContentType();
assertTrue("Content type not set", actualContentType != null);
if (actualContentType != null) {
assertTrue("Content type [" + actualContentType + "] is not compatible with [" + contentType + "]",
actualContentType.isCompatibleWith(contentType));
}
};
}
@ -110,12 +104,9 @@ public class ContentRequestMatchers { @@ -110,12 +104,9 @@ public class ContentRequestMatchers {
* Get the body of the request as a UTF-8 string and appply the given {@link Matcher}.
*/
public RequestMatcher string(final Matcher<? super String> matcher) {
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) throws IOException, AssertionError {
MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
assertThat("Request content", mockRequest.getBodyAsString(), matcher);
}
return request -> {
MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
assertThat("Request content", mockRequest.getBodyAsString(), matcher);
};
}
@ -123,12 +114,9 @@ public class ContentRequestMatchers { @@ -123,12 +114,9 @@ public class ContentRequestMatchers {
* Get the body of the request as a UTF-8 string and compare it to the given String.
*/
public RequestMatcher string(final String expectedContent) {
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) throws IOException, AssertionError {
MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
assertEquals("Request content", expectedContent, mockRequest.getBodyAsString());
}
return request -> {
MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
assertEquals("Request content", expectedContent, mockRequest.getBodyAsString());
};
}
@ -136,12 +124,9 @@ public class ContentRequestMatchers { @@ -136,12 +124,9 @@ public class ContentRequestMatchers {
* Compare the body of the request to the given byte array.
*/
public RequestMatcher bytes(final byte[] expectedContent) {
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) throws IOException, AssertionError {
MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
assertEquals("Request content", expectedContent, mockRequest.getBodyAsBytes());
}
return request -> {
MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
assertEquals("Request content", expectedContent, mockRequest.getBodyAsBytes());
};
}
@ -150,23 +135,20 @@ public class ContentRequestMatchers { @@ -150,23 +135,20 @@ public class ContentRequestMatchers {
* @since 4.3
*/
public RequestMatcher formData(final MultiValueMap<String, String> expectedContent) {
return new RequestMatcher() {
@Override
public void match(final ClientHttpRequest request) throws IOException, AssertionError {
HttpInputMessage inputMessage = new HttpInputMessage() {
@Override
public InputStream getBody() throws IOException {
MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
return new ByteArrayInputStream(mockRequest.getBodyAsBytes());
}
@Override
public HttpHeaders getHeaders() {
return request.getHeaders();
}
};
FormHttpMessageConverter converter = new FormHttpMessageConverter();
assertEquals("Request content", expectedContent, converter.read(null, inputMessage));
}
return request -> {
HttpInputMessage inputMessage = new HttpInputMessage() {
@Override
public InputStream getBody() throws IOException {
MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
return new ByteArrayInputStream(mockRequest.getBodyAsBytes());
}
@Override
public HttpHeaders getHeaders() {
return request.getHeaders();
}
};
FormHttpMessageConverter converter = new FormHttpMessageConverter();
assertEquals("Request content", expectedContent, converter.read(null, inputMessage));
};
}

97
spring-test/src/main/java/org/springframework/test/web/client/match/MockRestRequestMatchers.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@ -16,7 +16,6 @@ @@ -16,7 +16,6 @@
package org.springframework.test.web.client.match;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;
@ -26,7 +25,6 @@ import org.hamcrest.Matcher; @@ -26,7 +25,6 @@ import org.hamcrest.Matcher;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.test.util.AssertionErrors;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.client.RequestMatcher;
import org.springframework.util.Assert;
@ -55,11 +53,7 @@ public abstract class MockRestRequestMatchers { @@ -55,11 +53,7 @@ public abstract class MockRestRequestMatchers {
* Match to any request.
*/
public static RequestMatcher anything() {
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) throws AssertionError {
}
};
return request -> {};
}
/**
@ -69,12 +63,7 @@ public abstract class MockRestRequestMatchers { @@ -69,12 +63,7 @@ public abstract class MockRestRequestMatchers {
*/
public static RequestMatcher method(final HttpMethod method) {
Assert.notNull(method, "'method' must not be null");
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) throws AssertionError {
AssertionErrors.assertEquals("Unexpected HttpMethod", method, request.getMethod());
}
};
return request -> assertEquals("Unexpected HttpMethod", method, request.getMethod());
}
/**
@ -84,12 +73,7 @@ public abstract class MockRestRequestMatchers { @@ -84,12 +73,7 @@ public abstract class MockRestRequestMatchers {
*/
public static RequestMatcher requestTo(final Matcher<String> matcher) {
Assert.notNull(matcher, "'matcher' must not be null");
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) throws IOException, AssertionError {
assertThat("Request URI", request.getURI().toString(), matcher);
}
};
return request -> assertThat("Request URI", request.getURI().toString(), matcher);
}
/**
@ -99,12 +83,7 @@ public abstract class MockRestRequestMatchers { @@ -99,12 +83,7 @@ public abstract class MockRestRequestMatchers {
*/
public static RequestMatcher requestTo(final String expectedUri) {
Assert.notNull(expectedUri, "'uri' must not be null");
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) throws IOException, AssertionError {
assertEquals("Request URI", expectedUri, request.getURI().toString());
}
};
return request -> assertEquals("Request URI", expectedUri, request.getURI().toString());
}
/**
@ -114,12 +93,7 @@ public abstract class MockRestRequestMatchers { @@ -114,12 +93,7 @@ public abstract class MockRestRequestMatchers {
*/
public static RequestMatcher requestTo(final URI uri) {
Assert.notNull(uri, "'uri' must not be null");
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) throws IOException, AssertionError {
AssertionErrors.assertEquals("Unexpected request", uri, request.getURI());
}
};
return request -> assertEquals("Unexpected request", uri, request.getURI());
}
/**
@ -127,14 +101,11 @@ public abstract class MockRestRequestMatchers { @@ -127,14 +101,11 @@ public abstract class MockRestRequestMatchers {
*/
@SafeVarargs
public static RequestMatcher queryParam(final String name, final Matcher<? super String>... matchers) {
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) {
MultiValueMap<String, String> params = getQueryParams(request);
assertValueCount("query param", name, params, matchers.length);
for (int i = 0 ; i < matchers.length; i++) {
assertThat("Query param", params.get(name).get(i), matchers[i]);
}
return request -> {
MultiValueMap<String, String> params = getQueryParams(request);
assertValueCount("query param", name, params, matchers.length);
for (int i = 0 ; i < matchers.length; i++) {
assertThat("Query param", params.get(name).get(i), matchers[i]);
}
};
}
@ -143,14 +114,11 @@ public abstract class MockRestRequestMatchers { @@ -143,14 +114,11 @@ public abstract class MockRestRequestMatchers {
* Assert request query parameter values.
*/
public static RequestMatcher queryParam(final String name, final String... expectedValues) {
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) {
MultiValueMap<String, String> params = getQueryParams(request);
assertValueCount("query param", name, params, expectedValues.length);
for (int i = 0 ; i < expectedValues.length; i++) {
assertEquals("Query param + [" + name + "]", expectedValues[i], params.get(name).get(i));
}
return request -> {
MultiValueMap<String, String> params = getQueryParams(request);
assertValueCount("query param", name, params, expectedValues.length);
for (int i = 0 ; i < expectedValues.length; i++) {
assertEquals("Query param + [" + name + "]", expectedValues[i], params.get(name).get(i));
}
};
}
@ -176,15 +144,13 @@ public abstract class MockRestRequestMatchers { @@ -176,15 +144,13 @@ public abstract class MockRestRequestMatchers {
*/
@SafeVarargs
public static RequestMatcher header(final String name, final Matcher<? super String>... matchers) {
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) {
assertValueCount("header", name, request.getHeaders(), matchers.length);
List<String> headerValues = request.getHeaders().get(name);
Assert.state(headerValues != null, "No header values");
for (int i = 0; i < matchers.length; i++) {
assertThat("Request header [" + name + "]", headerValues.get(i), matchers[i]);
}
return request -> {
assertValueCount("header", name, request.getHeaders(), matchers.length);
List<String> headerValues = request.getHeaders().get(name);
Assert.state(headerValues != null, "No header values");
for (int i = 0; i < matchers.length; i++) {
assertThat("Request header[" + name + "]", headerValues.get(i), matchers[i]);
}
};
}
@ -193,15 +159,14 @@ public abstract class MockRestRequestMatchers { @@ -193,15 +159,14 @@ public abstract class MockRestRequestMatchers {
* Assert request header values.
*/
public static RequestMatcher header(final String name, final String... expectedValues) {
return new RequestMatcher() {
@Override
public void match(ClientHttpRequest request) {
assertValueCount("header", name, request.getHeaders(), expectedValues.length);
List<String> headerValues = request.getHeaders().get(name);
Assert.state(headerValues != null, "No header values");
for (int i = 0 ; i < expectedValues.length; i++) {
assertEquals("Request header [" + name + "]", expectedValues[i], headerValues.get(i));
}
return request -> {
assertValueCount("header", name, request.getHeaders(), expectedValues.length);
List<String> headerValues = request.getHeaders().get(name);
Assert.state(headerValues != null, "No header values");
for (int i = 0; i < expectedValues.length; i++) {
assertEquals("Request header [" + name + "]",
expectedValues[i], headerValues.get(i));
}
};
}

18
spring-tx/src/main/java/org/springframework/jca/cci/core/CciTemplate.java

@ -222,17 +222,13 @@ public class CciTemplate implements CciOperations { @@ -222,17 +222,13 @@ public class CciTemplate implements CciOperations {
@Override
public <T> T execute(final InteractionCallback<T> action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
return execute(new ConnectionCallback<T>() {
@Override
public T doInConnection(Connection connection, ConnectionFactory connectionFactory)
throws ResourceException, SQLException, DataAccessException {
Interaction interaction = connection.createInteraction();
try {
return action.doInInteraction(interaction, connectionFactory);
}
finally {
closeInteraction(interaction);
}
return execute((ConnectionCallback<T>) (connection, connectionFactory) -> {
Interaction interaction = connection.createInteraction();
try {
return action.doInInteraction(interaction, connectionFactory);
}
finally {
closeInteraction(interaction);
}
});
}

10
spring-tx/src/main/java/org/springframework/jca/context/ResourceAdapterApplicationContext.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 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.
@ -59,12 +59,8 @@ public class ResourceAdapterApplicationContext extends GenericApplicationContext @@ -59,12 +59,8 @@ public class ResourceAdapterApplicationContext extends GenericApplicationContext
beanFactory.registerResolvableDependency(BootstrapContext.class, this.bootstrapContext);
// JCA WorkManager resolved lazily - may not be available.
beanFactory.registerResolvableDependency(WorkManager.class, new ObjectFactory<WorkManager>() {
@Override
public WorkManager getObject() {
return bootstrapContext.getWorkManager();
}
});
beanFactory.registerResolvableDependency(WorkManager.class,
(ObjectFactory<WorkManager>) this.bootstrapContext::getWorkManager);
}
}

51
spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java

@ -34,7 +34,6 @@ import org.springframework.transaction.PlatformTransactionManager; @@ -34,7 +34,6 @@ import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.support.CallbackPreferringPlatformTransactionManager;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ConcurrentReferenceHashMap;
@ -303,34 +302,30 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init @@ -303,34 +302,30 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
else {
// It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
try {
Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr,
new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
try {
return invocation.proceedWithInvocation();
}
catch (Throwable ex) {
if (txAttr.rollbackOn(ex)) {
// A RuntimeException: will lead to a rollback.
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
else {
throw new ThrowableHolderException(ex);
}
}
else {
// A normal return value: will lead to a commit.
return new ThrowableHolder(ex);
}
}
finally {
cleanupTransactionInfo(txInfo);
}
Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr, status -> {
TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
try {
return invocation.proceedWithInvocation();
}
catch (Throwable ex) {
if (txAttr.rollbackOn(ex)) {
// A RuntimeException: will lead to a rollback.
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
});
else {
throw new ThrowableHolderException(ex);
}
}
else {
// A normal return value: will lead to a commit.
return new ThrowableHolder(ex);
}
}
finally {
cleanupTransactionInfo(txInfo);
}
});
// Check result: It might indicate a Throwable to rethrow.
if (result instanceof ThrowableHolder) {

52
spring-web/src/main/java/org/springframework/http/MediaType.java

@ -653,40 +653,36 @@ public class MediaType extends MimeType implements Serializable { @@ -653,40 +653,36 @@ public class MediaType extends MimeType implements Serializable {
/**
* Comparator used by {@link #sortByQualityValue(List)}.
*/
public static final Comparator<MediaType> QUALITY_VALUE_COMPARATOR = new Comparator<MediaType>() {
@Override
public int compare(MediaType mediaType1, MediaType mediaType2) {
double quality1 = mediaType1.getQualityValue();
double quality2 = mediaType2.getQualityValue();
int qualityComparison = Double.compare(quality2, quality1);
if (qualityComparison != 0) {
return qualityComparison; // audio/*;q=0.7 < audio/*;q=0.3
}
else if (mediaType1.isWildcardType() && !mediaType2.isWildcardType()) { // */* < audio/*
public static final Comparator<MediaType> QUALITY_VALUE_COMPARATOR = (mediaType1, mediaType2) -> {
double quality1 = mediaType1.getQualityValue();
double quality2 = mediaType2.getQualityValue();
int qualityComparison = Double.compare(quality2, quality1);
if (qualityComparison != 0) {
return qualityComparison; // audio/*;q=0.7 < audio/*;q=0.3
}
else if (mediaType1.isWildcardType() && !mediaType2.isWildcardType()) { // */* < audio/*
return 1;
}
else if (mediaType2.isWildcardType() && !mediaType1.isWildcardType()) { // audio/* > */*
return -1;
}
else if (!mediaType1.getType().equals(mediaType2.getType())) { // audio/basic == text/html
return 0;
}
else { // mediaType1.getType().equals(mediaType2.getType())
if (mediaType1.isWildcardSubtype() && !mediaType2.isWildcardSubtype()) { // audio/* < audio/basic
return 1;
}
else if (mediaType2.isWildcardType() && !mediaType1.isWildcardType()) { // audio/* > */*
else if (mediaType2.isWildcardSubtype() && !mediaType1.isWildcardSubtype()) { // audio/basic > audio/*
return -1;
}
else if (!mediaType1.getType().equals(mediaType2.getType())) { // audio/basic == text/html
else if (!mediaType1.getSubtype().equals(mediaType2.getSubtype())) { // audio/basic == audio/wave
return 0;
}
else { // mediaType1.getType().equals(mediaType2.getType())
if (mediaType1.isWildcardSubtype() && !mediaType2.isWildcardSubtype()) { // audio/* < audio/basic
return 1;
}
else if (mediaType2.isWildcardSubtype() && !mediaType1.isWildcardSubtype()) { // audio/basic > audio/*
return -1;
}
else if (!mediaType1.getSubtype().equals(mediaType2.getSubtype())) { // audio/basic == audio/wave
return 0;
}
else {
int paramsSize1 = mediaType1.getParameters().size();
int paramsSize2 = mediaType2.getParameters().size();
return (paramsSize2 < paramsSize1 ? -1 : (paramsSize2 == paramsSize1 ? 0 : 1)); // audio/basic;level=1 < audio/basic
}
else {
int paramsSize1 = mediaType1.getParameters().size();
int paramsSize2 = mediaType2.getParameters().size();
return (paramsSize2 < paramsSize1 ? -1 : (paramsSize2 == paramsSize1 ? 0 : 1)); // audio/basic;level=1 < audio/basic
}
}
};

88
spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java

@ -107,12 +107,8 @@ public final class WebAsyncManager { @@ -107,12 +107,8 @@ public final class WebAsyncManager {
public void setAsyncWebRequest(final AsyncWebRequest asyncWebRequest) {
Assert.notNull(asyncWebRequest, "AsyncWebRequest must not be null");
this.asyncWebRequest = asyncWebRequest;
this.asyncWebRequest.addCompletionHandler(new Runnable() {
@Override
public void run() {
asyncWebRequest.removeAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
}
});
this.asyncWebRequest.addCompletionHandler(() -> asyncWebRequest.removeAttribute(
WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST));
}
/**
@ -289,43 +285,33 @@ public final class WebAsyncManager { @@ -289,43 +285,33 @@ public final class WebAsyncManager {
final Callable<?> callable = webAsyncTask.getCallable();
final CallableInterceptorChain interceptorChain = new CallableInterceptorChain(interceptors);
this.asyncWebRequest.addTimeoutHandler(new Runnable() {
@Override
public void run() {
logger.debug("Processing timeout");
Object result = interceptorChain.triggerAfterTimeout(asyncWebRequest, callable);
if (result != CallableProcessingInterceptor.RESULT_NONE) {
setConcurrentResultAndDispatch(result);
}
this.asyncWebRequest.addTimeoutHandler(() -> {
logger.debug("Processing timeout");
Object result = interceptorChain.triggerAfterTimeout(this.asyncWebRequest, callable);
if (result != CallableProcessingInterceptor.RESULT_NONE) {
setConcurrentResultAndDispatch(result);
}
});
this.asyncWebRequest.addCompletionHandler(new Runnable() {
@Override
public void run() {
interceptorChain.triggerAfterCompletion(asyncWebRequest, callable);
}
});
this.asyncWebRequest.addCompletionHandler(() ->
interceptorChain.triggerAfterCompletion(this.asyncWebRequest, callable));
interceptorChain.applyBeforeConcurrentHandling(this.asyncWebRequest, callable);
startAsyncProcessing(processingContext);
try {
this.taskExecutor.submit(new Runnable() {
@Override
public void run() {
Object result = null;
try {
interceptorChain.applyPreProcess(asyncWebRequest, callable);
result = callable.call();
}
catch (Throwable ex) {
result = ex;
}
finally {
result = interceptorChain.applyPostProcess(asyncWebRequest, callable, result);
}
setConcurrentResultAndDispatch(result);
this.taskExecutor.submit(() -> {
Object result = null;
try {
interceptorChain.applyPreProcess(this.asyncWebRequest, callable);
result = callable.call();
}
catch (Throwable ex) {
result = ex;
}
finally {
result = interceptorChain.applyPostProcess(this.asyncWebRequest, callable, result);
}
setConcurrentResultAndDispatch(result);
});
}
catch (RejectedExecutionException ex) {
@ -388,36 +374,26 @@ public final class WebAsyncManager { @@ -388,36 +374,26 @@ public final class WebAsyncManager {
final DeferredResultInterceptorChain interceptorChain = new DeferredResultInterceptorChain(interceptors);
this.asyncWebRequest.addTimeoutHandler(new Runnable() {
@Override
public void run() {
try {
interceptorChain.triggerAfterTimeout(asyncWebRequest, deferredResult);
}
catch (Throwable ex) {
setConcurrentResultAndDispatch(ex);
}
this.asyncWebRequest.addTimeoutHandler(() -> {
try {
interceptorChain.triggerAfterTimeout(this.asyncWebRequest, deferredResult);
}
});
this.asyncWebRequest.addCompletionHandler(new Runnable() {
@Override
public void run() {
interceptorChain.triggerAfterCompletion(asyncWebRequest, deferredResult);
catch (Throwable ex) {
setConcurrentResultAndDispatch(ex);
}
});
this.asyncWebRequest.addCompletionHandler(()
-> interceptorChain.triggerAfterCompletion(this.asyncWebRequest, deferredResult));
interceptorChain.applyBeforeConcurrentHandling(this.asyncWebRequest, deferredResult);
startAsyncProcessing(processingContext);
try {
interceptorChain.applyPreProcess(this.asyncWebRequest, deferredResult);
deferredResult.setResultHandler(new DeferredResultHandler() {
@Override
public void handleResult(Object result) {
result = interceptorChain.applyPostProcess(asyncWebRequest, deferredResult, result);
setConcurrentResultAndDispatch(result);
}
deferredResult.setResultHandler(result -> {
result = interceptorChain.applyPostProcess(this.asyncWebRequest, deferredResult, result);
setConcurrentResultAndDispatch(result);
});
}
catch (Throwable ex) {

8
spring-web/src/main/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolver.java

@ -47,12 +47,8 @@ public class ExceptionHandlerMethodResolver { @@ -47,12 +47,8 @@ public class ExceptionHandlerMethodResolver {
/**
* A filter for selecting {@code @ExceptionHandler} methods.
*/
public static final MethodFilter EXCEPTION_HANDLER_METHODS = new MethodFilter() {
@Override
public boolean matches(Method method) {
return (AnnotationUtils.findAnnotation(method, ExceptionHandler.class) != null);
}
};
public static final MethodFilter EXCEPTION_HANDLER_METHODS = method ->
(AnnotationUtils.findAnnotation(method, ExceptionHandler.class) != null);
/**
* Arbitrary {@link Method} reference, indicating no method found in the cache.

11
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java

@ -470,13 +470,10 @@ public class MvcUriComponentsBuilder { @@ -470,13 +470,10 @@ public class MvcUriComponentsBuilder {
}
private static Method getMethod(Class<?> controllerType, final String methodName, final Object... args) {
MethodFilter selector = new MethodFilter() {
@Override
public boolean matches(Method method) {
String name = method.getName();
int argLength = method.getParameterCount();
return (name.equals(methodName) && argLength == args.length);
}
MethodFilter selector = method -> {
String name = method.getName();
int argLength = method.getParameterCount();
return (name.equals(methodName) && argLength == args.length);
};
Set<Method> methods = MethodIntrospector.selectMethods(controllerType, selector);
if (methods.size() == 1) {

19
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java

@ -21,7 +21,6 @@ import java.util.ArrayList; @@ -21,7 +21,6 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
@ -985,22 +984,14 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter @@ -985,22 +984,14 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter
/**
* MethodFilter that matches {@link InitBinder @InitBinder} methods.
*/
public static final MethodFilter INIT_BINDER_METHODS = new MethodFilter() {
@Override
public boolean matches(Method method) {
return AnnotationUtils.findAnnotation(method, InitBinder.class) != null;
}
};
public static final MethodFilter INIT_BINDER_METHODS = method ->
AnnotationUtils.findAnnotation(method, InitBinder.class) != null;
/**
* MethodFilter that matches {@link ModelAttribute @ModelAttribute} methods.
*/
public static final MethodFilter MODEL_ATTRIBUTE_METHODS = new MethodFilter() {
@Override
public boolean matches(Method method) {
return ((AnnotationUtils.findAnnotation(method, RequestMapping.class) == null) &&
(AnnotationUtils.findAnnotation(method, ModelAttribute.class) != null));
}
};
public static final MethodFilter MODEL_ATTRIBUTE_METHODS = method ->
((AnnotationUtils.findAnnotation(method, RequestMapping.class) == null) &&
(AnnotationUtils.findAnnotation(method, ModelAttribute.class) != null));
}

13
spring-websocket/src/main/java/org/springframework/web/socket/client/jetty/JettyWebSocketClient.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@ -170,13 +170,10 @@ public class JettyWebSocketClient extends AbstractWebSocketClient implements Lif @@ -170,13 +170,10 @@ public class JettyWebSocketClient extends AbstractWebSocketClient implements Lif
final JettyWebSocketSession wsSession = new JettyWebSocketSession(attributes, user);
final JettyWebSocketHandlerAdapter listener = new JettyWebSocketHandlerAdapter(wsHandler, wsSession);
Callable<WebSocketSession> connectTask = new Callable<WebSocketSession>() {
@Override
public WebSocketSession call() throws Exception {
Future<Session> future = client.connect(listener, uri, request);
future.get();
return wsSession;
}
Callable<WebSocketSession> connectTask = () -> {
Future<Session> future = client.connect(listener, uri, request);
future.get();
return wsSession;
};
if (this.taskExecutor != null) {

25
spring-websocket/src/main/java/org/springframework/web/socket/client/standard/AnnotatedEndpointConnectionManager.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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,20 +99,17 @@ public class AnnotatedEndpointConnectionManager extends ConnectionManagerSupport @@ -99,20 +99,17 @@ public class AnnotatedEndpointConnectionManager extends ConnectionManagerSupport
@Override
protected void openConnection() {
this.taskExecutor.execute(new Runnable() {
@Override
public void run() {
try {
if (logger.isInfoEnabled()) {
logger.info("Connecting to WebSocket at " + getUri());
}
Object endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler();
session = webSocketContainer.connectToServer(endpointToUse, getUri());
logger.info("Successfully connected to WebSocket");
}
catch (Throwable ex) {
logger.error("Failed to connect to WebSocket", ex);
this.taskExecutor.execute(() -> {
try {
if (logger.isInfoEnabled()) {
logger.info("Connecting to WebSocket at " + getUri());
}
Object endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler();
session = webSocketContainer.connectToServer(endpointToUse, getUri());
logger.info("Successfully connected to WebSocket");
}
catch (Throwable ex) {
logger.error("Failed to connect to WebSocket", ex);
}
});
}

27
spring-websocket/src/main/java/org/springframework/web/socket/client/standard/EndpointConnectionManager.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@ -130,21 +130,18 @@ public class EndpointConnectionManager extends ConnectionManagerSupport implemen @@ -130,21 +130,18 @@ public class EndpointConnectionManager extends ConnectionManagerSupport implemen
@Override
protected void openConnection() {
this.taskExecutor.execute(new Runnable() {
@Override
public void run() {
try {
if (logger.isInfoEnabled()) {
logger.info("Connecting to WebSocket at " + getUri());
}
Endpoint endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler();
ClientEndpointConfig endpointConfig = configBuilder.build();
session = getWebSocketContainer().connectToServer(endpointToUse, endpointConfig, getUri());
logger.info("Successfully connected to WebSocket");
}
catch (Throwable ex) {
logger.error("Failed to connect to WebSocket", ex);
this.taskExecutor.execute(() -> {
try {
if (logger.isInfoEnabled()) {
logger.info("Connecting to WebSocket at " + getUri());
}
Endpoint endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler();
ClientEndpointConfig endpointConfig = configBuilder.build();
session = getWebSocketContainer().connectToServer(endpointToUse, endpointConfig, getUri());
logger.info("Successfully connected to WebSocket");
}
catch (Throwable ex) {
logger.error("Failed to connect to WebSocket", ex);
}
});
}

9
spring-websocket/src/main/java/org/springframework/web/socket/client/standard/StandardWebSocketClient.java

@ -144,12 +144,9 @@ public class StandardWebSocketClient extends AbstractWebSocketClient { @@ -144,12 +144,9 @@ public class StandardWebSocketClient extends AbstractWebSocketClient {
final Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler, session);
Callable<WebSocketSession> connectTask = new Callable<WebSocketSession>() {
@Override
public WebSocketSession call() throws Exception {
webSocketContainer.connectToServer(endpoint, endpointConfig, uri);
return session;
}
Callable<WebSocketSession> connectTask = () -> {
webSocketContainer.connectToServer(endpoint, endpointConfig, uri);
return session;
};
if (this.taskExecutor != null) {

11
spring-websocket/src/main/java/org/springframework/web/socket/config/WebSocketMessageBrokerStats.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 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.
@ -110,12 +110,9 @@ public class WebSocketMessageBrokerStats { @@ -110,12 +110,9 @@ public class WebSocketMessageBrokerStats {
@Nullable
private ScheduledFuture<?> initLoggingTask(long initialDelay) {
if (logger.isInfoEnabled() && this.loggingPeriod > 0) {
return this.sockJsTaskScheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
logger.info(WebSocketMessageBrokerStats.this.toString());
}
}, initialDelay, this.loggingPeriod, TimeUnit.MILLISECONDS);
return this.sockJsTaskScheduler.scheduleAtFixedRate(() ->
logger.info(WebSocketMessageBrokerStats.this.toString()),
initialDelay, this.loggingPeriod, TimeUnit.MILLISECONDS);
}
return null;
}

19
spring-websocket/src/main/java/org/springframework/web/socket/messaging/WebSocketStompClient.java

@ -401,17 +401,14 @@ public class WebSocketStompClient extends StompClientSupport implements SmartLif @@ -401,17 +401,14 @@ public class WebSocketStompClient extends StompClientSupport implements SmartLif
public void onReadInactivity(final Runnable runnable, final long duration) {
Assert.state(getTaskScheduler() != null, "No TaskScheduler configured");
this.lastReadTime = System.currentTimeMillis();
this.inactivityTasks.add(getTaskScheduler().scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
if (System.currentTimeMillis() - lastReadTime > duration) {
try {
runnable.run();
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("ReadInactivityTask failure", ex);
}
this.inactivityTasks.add(getTaskScheduler().scheduleWithFixedDelay(() -> {
if (System.currentTimeMillis() - lastReadTime > duration) {
try {
runnable.run();
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("ReadInactivityTask failure", ex);
}
}
}

7
spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/AbstractClientSockJsSession.java

@ -116,12 +116,7 @@ public abstract class AbstractClientSockJsSession implements WebSocketSession { @@ -116,12 +116,7 @@ public abstract class AbstractClientSockJsSession implements WebSocketSession {
* request.
*/
Runnable getTimeoutTask() {
return new Runnable() {
@Override
public void run() {
closeInternal(new CloseStatus(2007, "Transport timed out"));
}
};
return () -> closeInternal(new CloseStatus(2007, "Transport timed out"));
}
@Override

49
spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/RestTemplateXhrTransport.java

@ -99,35 +99,32 @@ public class RestTemplateXhrTransport extends AbstractXhrTransport { @@ -99,35 +99,32 @@ public class RestTemplateXhrTransport extends AbstractXhrTransport {
final URI receiveUrl, final HttpHeaders handshakeHeaders, final XhrClientSockJsSession session,
final SettableListenableFuture<WebSocketSession> connectFuture) {
getTaskExecutor().execute(new Runnable() {
@Override
public void run() {
HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
XhrRequestCallback requestCallback = new XhrRequestCallback(handshakeHeaders);
XhrRequestCallback requestCallbackAfterHandshake = new XhrRequestCallback(httpHeaders);
XhrReceiveExtractor responseExtractor = new XhrReceiveExtractor(session);
while (true) {
if (session.isDisconnected()) {
session.afterTransportClosed(null);
break;
getTaskExecutor().execute(() -> {
HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
XhrRequestCallback requestCallback = new XhrRequestCallback(handshakeHeaders);
XhrRequestCallback requestCallbackAfterHandshake = new XhrRequestCallback(httpHeaders);
XhrReceiveExtractor responseExtractor = new XhrReceiveExtractor(session);
while (true) {
if (session.isDisconnected()) {
session.afterTransportClosed(null);
break;
}
try {
if (logger.isTraceEnabled()) {
logger.trace("Starting XHR receive request, url=" + receiveUrl);
}
try {
if (logger.isTraceEnabled()) {
logger.trace("Starting XHR receive request, url=" + receiveUrl);
}
getRestTemplate().execute(receiveUrl, HttpMethod.POST, requestCallback, responseExtractor);
requestCallback = requestCallbackAfterHandshake;
getRestTemplate().execute(receiveUrl, HttpMethod.POST, requestCallback, responseExtractor);
requestCallback = requestCallbackAfterHandshake;
}
catch (Throwable ex) {
if (!connectFuture.isDone()) {
connectFuture.setException(ex);
}
catch (Throwable ex) {
if (!connectFuture.isDone()) {
connectFuture.setException(ex);
}
else {
session.handleTransportError(ex);
session.afterTransportClosed(new CloseStatus(1006, ex.getMessage()));
}
break;
else {
session.handleTransportError(ex);
session.afterTransportClosed(new CloseStatus(1006, ex.getMessage()));
}
break;
}
}
});

31
spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java

@ -368,27 +368,24 @@ public class TransportHandlingSockJsService extends AbstractSockJsService implem @@ -368,27 +368,24 @@ public class TransportHandlingSockJsService extends AbstractSockJsService implem
if (this.sessionCleanupTask != null) {
return;
}
this.sessionCleanupTask = getTaskScheduler().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
List<String> removedIds = new ArrayList<>();
for (SockJsSession session : sessions.values()) {
try {
if (session.getTimeSinceLastActive() > getDisconnectDelay()) {
sessions.remove(session.getId());
removedIds.add(session.getId());
session.close();
}
}
catch (Throwable ex) {
// Could be part of normal workflow (e.g. browser tab closed)
logger.debug("Failed to close " + session, ex);
this.sessionCleanupTask = getTaskScheduler().scheduleAtFixedRate(() -> {
List<String> removedIds = new ArrayList<>();
for (SockJsSession session : sessions.values()) {
try {
if (session.getTimeSinceLastActive() > getDisconnectDelay()) {
sessions.remove(session.getId());
removedIds.add(session.getId());
session.close();
}
}
if (logger.isDebugEnabled() && !removedIds.isEmpty()) {
logger.debug("Closed " + removedIds.size() + " sessions: " + removedIds);
catch (Throwable ex) {
// Could be part of normal workflow (e.g. browser tab closed)
logger.debug("Failed to close " + session, ex);
}
}
if (logger.isDebugEnabled() && !removedIds.isEmpty()) {
logger.debug("Closed " + removedIds.size() + " sessions: " + removedIds);
}
}, getDisconnectDelay());
}
}

Loading…
Cancel
Save