Replace relevant code with lambda

See gh-1454
This commit is contained in:
diguage 2017-06-08 00:07:34 +08:00 committed by Stephane Nicoll
parent 738160538e
commit 4b1478d830
52 changed files with 522 additions and 845 deletions

View File

@ -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;

View File

@ -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
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);

View File

@ -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);
}

View File

@ -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());

View File

@ -139,12 +139,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());
}
});
Collections.sort(matches, (m1, m2) -> m2.toString().compareTo(m1.toString()));
return matches;
}

View File

@ -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);

View File

@ -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,50 +411,44 @@ 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;
}
boolean required = determineRequiredStatus(ann);
currElements.add(new AutowiredFieldElement(field, required));
}
}
});
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);
}
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)) {
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);
}
}
boolean required = determineRequiredStatus(ann);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new AutowiredMethodElement(method, required, pd));
}
}
});
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;
}
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));
}
});
elements.addAll(0, currElements);
targetClass = targetClass.getSuperclass();

View File

@ -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);
}
}
}

View File

@ -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);
}

View File

@ -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);
}
};

View File

@ -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));
}
/**

View File

@ -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);
}
};

View File

@ -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));
}
}
}

View File

@ -280,13 +280,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;
}
Collections.sort(configCandidates, (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

View File

@ -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");
}
});
}

View File

@ -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
* 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));
}
/**

View File

@ -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> {
* @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());
}

View File

@ -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));
}
/**

View File

@ -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));
}
/**

View File

@ -47,6 +47,12 @@ import org.springframework.lang.Nullable;
*/
public abstract class ReflectionUtils {
/**
* Pre-built FieldFilter that matches all non-static, non-final fields.
*/
public static final FieldFilter COPYABLE_FIELDS =
field -> !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()));
/**
* Naming prefix for CGLIB-renamed methods.
* @see #isCglibRenamedMethod
@ -845,18 +851,6 @@ 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()));
}
};
/**
* Pre-built MethodFilter that matches all non-bridge methods.
*/

View File

@ -53,18 +53,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, exception) -> {
if (exception != null) {
callbacks.failure(exception);
}
else {
callbacks.success(result);
}
return null;
});
}

View File

@ -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");
};

View File

@ -137,17 +137,10 @@ 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.registerNewField((cw, codeflow1)
-> 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.registerNewClinit((mv1, codeflow12) -> generateClinitCode(className, constantFieldName, mv1, codeflow12, false));
mv.visitFieldInsn(GETSTATIC, className, constantFieldName, "Ljava/util/List;");
codeflow.pushDescriptor("Ljava/util/List");

View File

@ -121,25 +121,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;
}
Collections.sort(methods, (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));
});
}

View File

@ -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;
}

View File

@ -77,15 +77,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) {

View File

@ -105,15 +105,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, resultSet -> {
String beanName = resultSet.getString(1);
String property = resultSet.getString(2);
String value = resultSet.getString(3);
// Make a properties entry by combining bean name and property.
props.setProperty(beanName + '.' + property, value);
});
this.propReader.registerBeanDefinitions(props);
}

View File

@ -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

View File

@ -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

View File

@ -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 (tcpConnection != null && !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()));
@ -701,32 +698,24 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
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);
}
});
}
this.tcpConnection.onWriteInactivity(() -> {
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);
}
});
}
}, 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);
}
}

View File

@ -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

View File

@ -350,12 +350,7 @@ 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();

View File

@ -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));
}
});

View File

@ -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 {
* 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 {
* 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 {
* 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 {
* 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 {
* @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));
};
}

View File

@ -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;
@ -55,11 +54,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 +64,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 +74,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 +84,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 +94,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 +102,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 +115,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 +145,12 @@ 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) {
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]);
}
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,13 @@ 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) {
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));
}
Assert.state(headerValues != null, "No header values");for (int i = 0 ; i < expectedValues.length; i++) {
assertEquals("Request header [" + name + "]",
expectedValues[i], headerValues.get(i));
}
};
}

View File

@ -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);
}
});
}

View File

@ -59,12 +59,7 @@ 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>) bootstrapContext::getWorkManager);
}
}

View File

@ -303,34 +303,26 @@ 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) {

View File

@ -290,6 +290,43 @@ public class MediaType extends MimeType implements Serializable {
*/
public final static String APPLICATION_PROBLEM_XML_VALUE = "application/problem+xml";
/**
* Comparator used by {@link #sortByQualityValue(List)}.
*/
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.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
}
}
};
private static final String PARAM_QUALITY_FACTOR = "q";
@ -650,48 +687,6 @@ 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/*
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.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
}
}
}
};
/**
* Comparator used by {@link #sortBySpecificity(List)}.
*/

View File

@ -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,32 @@ 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(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(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(asyncWebRequest, callable);
result = callable.call();
}
catch (Throwable ex) {
result = ex;
}
finally {
result = interceptorChain.applyPostProcess(asyncWebRequest, callable, result);
}
setConcurrentResultAndDispatch(result);
});
}
catch (RejectedExecutionException ex) {
@ -388,36 +373,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(asyncWebRequest, deferredResult);
}
catch (Throwable ex) {
setConcurrentResultAndDispatch(ex);
}
});
this.asyncWebRequest.addCompletionHandler(new Runnable() {
@Override
public void run() {
interceptorChain.triggerAfterCompletion(asyncWebRequest, deferredResult);
}
});
this.asyncWebRequest.addCompletionHandler(()
-> interceptorChain.triggerAfterCompletion(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(asyncWebRequest, deferredResult, result);
setConcurrentResultAndDispatch(result);
});
}
catch (Throwable ex) {

View File

@ -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.

View File

@ -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) {

View File

@ -117,6 +117,19 @@ import org.springframework.web.util.WebUtils;
public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter
implements BeanFactoryAware, InitializingBean {
/**
* MethodFilter that matches {@link InitBinder @InitBinder} methods.
*/
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 =
method -> ((AnnotationUtils.findAnnotation(method, RequestMapping.class) == null)
&& (AnnotationUtils.findAnnotation(method, ModelAttribute.class) != null));
private List<HandlerMethodArgumentResolver> customArgumentResolvers;
private HandlerMethodArgumentResolverComposite argumentResolvers;
@ -981,26 +994,4 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter
return mav;
}
/**
* 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;
}
};
/**
* 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));
}
};
}

View File

@ -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) {

View File

@ -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);
}
});
}

View File

@ -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);
}
});
}

View File

@ -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) {

View File

@ -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;
}

View File

@ -401,21 +401,18 @@ 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);
}
}
}
}
}, duration / 2));
this.inactivityTasks.add(getTaskScheduler().scheduleWithFixedDelay(() -> {
if (System.currentTimeMillis() - lastReadTime > duration) {
try {
runnable.run();
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("ReadInactivityTask failure", ex);
}
}
}
}, duration / 2));
}
@Override

View File

@ -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

View File

@ -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;
}
}
});

View File

@ -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());
}
}