diff --git a/spring-aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.java index 049a21c0350..be38c90a816 100644 --- a/spring-aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.java +++ b/spring-aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -224,6 +224,9 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence } + /** + * Set the name of the aspect (bean) in which the advice was declared. + */ public void setAspectName(String name) { this.aspectName = name; } @@ -234,7 +237,7 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence } /** - * Sets the declaration order of this advice within the aspect + * Set the declaration order of this advice within the aspect. */ public void setDeclarationOrder(int order) { this.declarationOrder = order; diff --git a/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJPointcutAdvisor.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJPointcutAdvisor.java index 7160354b800..b4adec46c17 100644 --- a/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJPointcutAdvisor.java +++ b/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJPointcutAdvisor.java @@ -57,6 +57,16 @@ public class AspectJPointcutAdvisor implements PointcutAdvisor, Ordered { this.order = order; } + @Override + public int getOrder() { + if (this.order != null) { + return this.order; + } + else { + return this.advice.getOrder(); + } + } + @Override public boolean isPerInstance() { return true; @@ -72,14 +82,13 @@ public class AspectJPointcutAdvisor implements PointcutAdvisor, Ordered { return this.pointcut; } - @Override - public int getOrder() { - if (this.order != null) { - return this.order; - } - else { - return this.advice.getOrder(); - } + /** + * Return the name of the aspect (bean) in which the advice was declared. + * @since 4.3.15 + * @see AbstractAspectJAdvice#getAspectName() + */ + public String getAspectName() { + return this.advice.getAspectName(); } diff --git a/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJPrecedenceInformation.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJPrecedenceInformation.java index cd90ba6d194..cb859d5cf58 100644 --- a/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJPrecedenceInformation.java +++ b/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJPrecedenceInformation.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2018 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. @@ -36,12 +36,12 @@ public interface AspectJPrecedenceInformation extends Ordered { // its advice for aspects with non-singleton instantiation models. /** - * The name of the aspect (bean) in which the advice was declared. + * Return the name of the aspect (bean) in which the advice was declared. */ String getAspectName(); /** - * The declaration order of the advice member within the aspect. + * Return the declaration order of the advice member within the aspect. */ int getDeclarationOrder(); diff --git a/spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java index fbfaaa00220..d6032bf1bcf 100644 --- a/spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java +++ b/spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2018 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. @@ -67,14 +67,12 @@ public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProx @Override @SuppressWarnings("unchecked") protected List sortAdvisors(List advisors) { - List partiallyComparableAdvisors = - new ArrayList<>(advisors.size()); + List partiallyComparableAdvisors = new ArrayList<>(advisors.size()); for (Advisor element : advisors) { partiallyComparableAdvisors.add( new PartiallyComparableAdvisorHolder(element, DEFAULT_PRECEDENCE_COMPARATOR)); } - List sorted = - PartialOrder.sort(partiallyComparableAdvisors); + List sorted = PartialOrder.sort(partiallyComparableAdvisors); if (sorted != null) { List result = new ArrayList<>(advisors.size()); for (PartiallyComparableAdvisorHolder pcAdvisor : sorted) { @@ -102,10 +100,9 @@ public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProx // TODO: Consider optimization by caching the list of the aspect names List candidateAdvisors = findCandidateAdvisors(); for (Advisor advisor : candidateAdvisors) { - if (advisor instanceof AspectJPointcutAdvisor) { - if (((AbstractAspectJAdvice) advisor.getAdvice()).getAspectName().equals(beanName)) { - return true; - } + if (advisor instanceof AspectJPointcutAdvisor && + ((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)) { + return true; } } return super.shouldSkip(beanClass, beanName); diff --git a/spring-beans/src/main/java/org/springframework/beans/PropertyEditorRegistrySupport.java b/spring-beans/src/main/java/org/springframework/beans/PropertyEditorRegistrySupport.java index 1344e194e34..34d9f71e826 100644 --- a/spring-beans/src/main/java/org/springframework/beans/PropertyEditorRegistrySupport.java +++ b/spring-beans/src/main/java/org/springframework/beans/PropertyEditorRegistrySupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -349,10 +349,9 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry { public boolean hasCustomEditorForElement(@Nullable Class elementType, @Nullable String propertyPath) { if (propertyPath != null && this.customEditorsForPath != null) { for (Map.Entry entry : this.customEditorsForPath.entrySet()) { - if (PropertyAccessorUtils.matchesProperty(entry.getKey(), propertyPath)) { - if (entry.getValue().getPropertyEditor(elementType) != null) { - return true; - } + if (PropertyAccessorUtils.matchesProperty(entry.getKey(), propertyPath) && + entry.getValue().getPropertyEditor(elementType) != null) { + return true; } } } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java index 86ade366988..c2a44deb427 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java @@ -593,11 +593,10 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean registerDependentBeans(beanName, autowiredBeanNames); if (autowiredBeanNames.size() == 1) { String autowiredBeanName = autowiredBeanNames.iterator().next(); - if (beanFactory.containsBean(autowiredBeanName)) { - if (beanFactory.isTypeMatch(autowiredBeanName, field.getType())) { - this.cachedFieldValue = new ShortcutDependencyDescriptor( - desc, autowiredBeanName, field.getType()); - } + if (beanFactory.containsBean(autowiredBeanName) && + beanFactory.isTypeMatch(autowiredBeanName, field.getType())) { + this.cachedFieldValue = new ShortcutDependencyDescriptor( + desc, autowiredBeanName, field.getType()); } } } @@ -678,11 +677,10 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean Iterator it = autowiredBeans.iterator(); for (int i = 0; i < paramTypes.length; i++) { String autowiredBeanName = it.next(); - if (beanFactory.containsBean(autowiredBeanName)) { - if (beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) { - cachedMethodArguments[i] = new ShortcutDependencyDescriptor( - descriptors[i], autowiredBeanName, paramTypes[i]); - } + if (beanFactory.containsBean(autowiredBeanName) && + beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) { + cachedMethodArguments[i] = new ShortcutDependencyDescriptor( + descriptors[i], autowiredBeanName, paramTypes[i]); } } } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java index f5bf27a64f1..422e61f57a5 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -205,21 +205,17 @@ public class InitDestroyAnnotationBeanPostProcessor final LinkedList currDestroyMethods = new LinkedList<>(); 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 (initAnnotationType != null && method.isAnnotationPresent(initAnnotationType)) { + 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 && method.isAnnotationPresent(destroyAnnotationType)) { + currDestroyMethods.add(new LifecycleElement(method)); + if (debug) { + logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method); } } }); diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/groovy/GroovyBeanDefinitionReader.java b/spring-beans/src/main/java/org/springframework/beans/factory/groovy/GroovyBeanDefinitionReader.java index 39a2383391f..1fb3c223c2b 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/groovy/GroovyBeanDefinitionReader.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/groovy/GroovyBeanDefinitionReader.java @@ -381,10 +381,8 @@ public class GroovyBeanDefinitionReader extends AbstractBeanDefinitionReader imp refName = args[0].toString(); } boolean parentRef = false; - if (args.length > 1) { - if (args[1] instanceof Boolean) { - parentRef = (Boolean) args[1]; - } + if (args.length > 1 && args[1] instanceof Boolean) { + parentRef = (Boolean) args[1]; } return new RuntimeBeanReference(refName, parentRef); } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index 02ca3d3adb4..41589161abd 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -1556,15 +1556,13 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac return; } + if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) { + ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext()); + } + MutablePropertyValues mpvs = null; List original; - if (System.getSecurityManager() != null) { - if (bw instanceof BeanWrapperImpl) { - ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext()); - } - } - if (pvs instanceof MutablePropertyValues) { mpvs = (MutablePropertyValues) pvs; if (mpvs.isConverted()) { diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConditionEvaluator.java b/spring-context/src/main/java/org/springframework/context/annotation/ConditionEvaluator.java index ea9bdba8bb9..59fd688de82 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConditionEvaluator.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConditionEvaluator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -105,10 +105,8 @@ class ConditionEvaluator { if (condition instanceof ConfigurationCondition) { requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase(); } - if (requiredPhase == null || requiredPhase == phase) { - if (!condition.matches(this.context, metadata)) { - return true; - } + if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) { + return true; } } diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java index 6969ee02313..496136f1586 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -351,10 +351,8 @@ public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPo while (!candidates.isEmpty()); // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes - if (sbr != null) { - if (!sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) { - sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry()); - } + if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) { + sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry()); } if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) { diff --git a/spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java b/spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java index 2ad09f1f21e..2d38c021b62 100644 --- a/spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java +++ b/spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -362,10 +362,9 @@ public class ApplicationListenerMethodAdapter implements GenericApplicationListe } for (ResolvableType declaredEventType : this.declaredEventTypes) { Class eventClass = declaredEventType.getRawClass(); - if ((eventClass == null || !ApplicationEvent.class.isAssignableFrom(eventClass)) && payloadType != null) { - if (declaredEventType.isAssignableFrom(payloadType)) { - return declaredEventType; - } + if ((eventClass == null || !ApplicationEvent.class.isAssignableFrom(eventClass)) && + payloadType != null && declaredEventType.isAssignableFrom(payloadType)) { + return declaredEventType; } if (declaredEventType.getRawClass().isInstance(event)) { return declaredEventType; diff --git a/spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java b/spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java index 0475e6bb74a..4ce31e218c6 100644 --- a/spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java +++ b/spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java @@ -363,25 +363,23 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean ModelMBeanOperationInfo info = null; PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method); - if (pd != null) { - if ((method.equals(pd.getReadMethod()) && includeReadAttribute(method, beanKey)) || - (method.equals(pd.getWriteMethod()) && includeWriteAttribute(method, beanKey))) { - // Attributes need to have their methods exposed as - // operations to the JMX server as well. - info = createModelMBeanOperationInfo(method, pd.getName(), beanKey); - Descriptor desc = info.getDescriptor(); - if (method.equals(pd.getReadMethod())) { - desc.setField(FIELD_ROLE, ROLE_GETTER); - } - else { - desc.setField(FIELD_ROLE, ROLE_SETTER); - } - desc.setField(FIELD_VISIBILITY, ATTRIBUTE_OPERATION_VISIBILITY); - if (isExposeClassDescriptor()) { - desc.setField(FIELD_CLASS, getClassForDescriptor(managedBean).getName()); - } - info.setDescriptor(desc); + if (pd != null && ((method.equals(pd.getReadMethod()) && includeReadAttribute(method, beanKey)) || + (method.equals(pd.getWriteMethod()) && includeWriteAttribute(method, beanKey)))) { + // Attributes need to have their methods exposed as + // operations to the JMX server as well. + info = createModelMBeanOperationInfo(method, pd.getName(), beanKey); + Descriptor desc = info.getDescriptor(); + if (method.equals(pd.getReadMethod())) { + desc.setField(FIELD_ROLE, ROLE_GETTER); } + else { + desc.setField(FIELD_ROLE, ROLE_SETTER); + } + desc.setField(FIELD_VISIBILITY, ATTRIBUTE_OPERATION_VISIBILITY); + if (isExposeClassDescriptor()) { + desc.setField(FIELD_CLASS, getClassForDescriptor(managedBean).getName()); + } + info.setDescriptor(desc); } // allow getters and setters to be marked as operations directly diff --git a/spring-context/src/main/java/org/springframework/jmx/export/assembler/MetadataMBeanInfoAssembler.java b/spring-context/src/main/java/org/springframework/jmx/export/assembler/MetadataMBeanInfoAssembler.java index 620843f3fda..b3a3adeaf8d 100644 --- a/spring-context/src/main/java/org/springframework/jmx/export/assembler/MetadataMBeanInfoAssembler.java +++ b/spring-context/src/main/java/org/springframework/jmx/export/assembler/MetadataMBeanInfoAssembler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -158,12 +158,7 @@ public class MetadataMBeanInfoAssembler extends AbstractReflectiveMBeanInfoAssem @Override protected boolean includeOperation(Method method, String beanKey) { PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method); - if (pd != null) { - if (hasManagedAttribute(method)) { - return true; - } - } - return hasManagedOperation(method); + return (pd != null && hasManagedAttribute(method)) || hasManagedOperation(method); } /** diff --git a/spring-core/src/main/java/org/springframework/core/codec/DataBufferEncoder.java b/spring-core/src/main/java/org/springframework/core/codec/DataBufferEncoder.java index 46d01f893cc..5e25ddd1eaf 100644 --- a/spring-core/src/main/java/org/springframework/core/codec/DataBufferEncoder.java +++ b/spring-core/src/main/java/org/springframework/core/codec/DataBufferEncoder.java @@ -56,7 +56,8 @@ public class DataBufferEncoder extends AbstractEncoder { } @Override - public Long getContentLength(DataBuffer dataBuffer, MimeType mimeType) { + public Long getContentLength(DataBuffer dataBuffer, @Nullable MimeType mimeType) { return (long) dataBuffer.readableByteCount(); } + } diff --git a/spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java b/spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java index 1752b241b2f..502e9867fdd 100644 --- a/spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java +++ b/spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java @@ -493,14 +493,12 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol for (Resource rootDirResource : rootDirResources) { rootDirResource = resolveRootDirResource(rootDirResource); URL rootDirUrl = rootDirResource.getURL(); - if (equinoxResolveMethod != null) { - if (rootDirUrl.getProtocol().startsWith("bundle")) { - URL resolvedUrl = (URL) ReflectionUtils.invokeMethod(equinoxResolveMethod, null, rootDirUrl); - if (resolvedUrl != null) { - rootDirUrl = resolvedUrl; - } - rootDirResource = new UrlResource(rootDirUrl); + if (equinoxResolveMethod != null && rootDirUrl.getProtocol().startsWith("bundle")) { + URL resolvedUrl = (URL) ReflectionUtils.invokeMethod(equinoxResolveMethod, null, rootDirUrl); + if (resolvedUrl != null) { + rootDirUrl = resolvedUrl; } + rootDirResource = new UrlResource(rootDirUrl); } if (rootDirUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) { result.addAll(VfsResourceMatchingDelegate.findMatchingResources(rootDirUrl, subPattern, getPathMatcher())); diff --git a/spring-core/src/main/java/org/springframework/util/xml/AbstractStaxXMLReader.java b/spring-core/src/main/java/org/springframework/util/xml/AbstractStaxXMLReader.java index 71488be71ee..f89af72589a 100644 --- a/spring-core/src/main/java/org/springframework/util/xml/AbstractStaxXMLReader.java +++ b/spring-core/src/main/java/org/springframework/util/xml/AbstractStaxXMLReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -184,13 +184,10 @@ abstract class AbstractStaxXMLReader extends AbstractXMLReader { * @see org.xml.sax.ContentHandler#startPrefixMapping(String, String) */ protected void startPrefixMapping(@Nullable String prefix, String namespace) throws SAXException { - if (getContentHandler() != null) { + if (getContentHandler() != null && StringUtils.hasLength(namespace)) { if (prefix == null) { prefix = ""; } - if (!StringUtils.hasLength(namespace)) { - return; - } if (!namespace.equals(this.namespaces.get(prefix))) { getContentHandler().startPrefixMapping(prefix, namespace); this.namespaces.put(prefix, namespace); @@ -203,11 +200,9 @@ abstract class AbstractStaxXMLReader extends AbstractXMLReader { * @see org.xml.sax.ContentHandler#endPrefixMapping(String) */ protected void endPrefixMapping(String prefix) throws SAXException { - if (getContentHandler() != null) { - if (this.namespaces.containsKey(prefix)) { - getContentHandler().endPrefixMapping(prefix); - this.namespaces.remove(prefix); - } + if (getContentHandler() != null && this.namespaces.containsKey(prefix)) { + getContentHandler().endPrefixMapping(prefix); + this.namespaces.remove(prefix); } } diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpModulus.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpModulus.java index cab9be98732..8be68cbbe8c 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpModulus.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpModulus.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -92,12 +92,12 @@ public class OpModulus extends Operator { if (!getLeftOperand().isCompilable()) { return false; } - if (this.children.length>1) { + if (this.children.length > 1) { if (!getRightOperand().isCompilable()) { return false; } } - return this.exitTypeDescriptor!=null; + return (this.exitTypeDescriptor != null); } @Override diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/VariableReference.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/VariableReference.java index 06d642a74e7..92b82f0b652 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/VariableReference.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/VariableReference.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -104,43 +104,9 @@ public class VariableReference extends SpelNodeImpl { return !(this.name.equals(THIS) || this.name.equals(ROOT)); } - - class VariableRef implements ValueRef { - - private final String name; - - private final TypedValue value; - - private final EvaluationContext evaluationContext; - - - public VariableRef(String name, TypedValue value, - EvaluationContext evaluationContext) { - this.name = name; - this.value = value; - this.evaluationContext = evaluationContext; - } - - - @Override - public TypedValue getValue() { - return this.value; - } - - @Override - public void setValue(@Nullable Object newValue) { - this.evaluationContext.setVariable(this.name, newValue); - } - - @Override - public boolean isWritable() { - return true; - } - } - @Override public boolean isCompilable() { - return this.exitTypeDescriptor!=null; + return (this.exitTypeDescriptor != null); } @Override @@ -158,4 +124,34 @@ public class VariableReference extends SpelNodeImpl { } + private static class VariableRef implements ValueRef { + + private final String name; + + private final TypedValue value; + + private final EvaluationContext evaluationContext; + + public VariableRef(String name, TypedValue value, EvaluationContext evaluationContext) { + this.name = name; + this.value = value; + this.evaluationContext = evaluationContext; + } + + @Override + public TypedValue getValue() { + return this.value; + } + + @Override + public void setValue(@Nullable Object newValue) { + this.evaluationContext.setVariable(this.name, newValue); + } + + @Override + public boolean isWritable() { + return true; + } + } + } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataContext.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataContext.java index 09b8b3b198f..929800f37f1 100755 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataContext.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataContext.java @@ -348,15 +348,13 @@ public class CallMetaDataContext { declaredParams.put(paramNameToMatch, param); if (param instanceof SqlOutParameter) { outParamNames.add(paramName); - if (isFunction() && !metaDataParamNames.contains(paramNameToMatch)) { - if (!returnDeclared) { - if (logger.isDebugEnabled()) { - logger.debug("Using declared out parameter '" + paramName + - "' for function return value"); - } - setFunctionReturnName(paramName); - returnDeclared = true; + if (isFunction() && !metaDataParamNames.contains(paramNameToMatch) && !returnDeclared) { + if (logger.isDebugEnabled()) { + logger.debug("Using declared out parameter '" + paramName + + "' for function return value"); } + setFunctionReturnName(paramName); + returnDeclared = true; } } } @@ -365,7 +363,6 @@ public class CallMetaDataContext { List workParams = new ArrayList<>(); workParams.addAll(declaredReturnParams); - if (!provider.isProcedureColumnMetaDataUsed()) { workParams.addAll(declaredParams.values()); return workParams; diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/object/StoredProcedure.java b/spring-jdbc/src/main/java/org/springframework/jdbc/object/StoredProcedure.java index cf89a282217..ab0a9fde222 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/object/StoredProcedure.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/object/StoredProcedure.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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,16 +28,14 @@ import org.springframework.jdbc.core.SqlParameter; /** * Superclass for object abstractions of RDBMS stored procedures. - * This class is abstract and it is intended that subclasses will provide - * a typed method for invocation that delegates to the supplied - * {@link #execute} method. + * This class is abstract and it is intended that subclasses will provide a typed + * method for invocation that delegates to the supplied {@link #execute} method. * - *

The inherited {@code sql} property is the name of the stored - * procedure in the RDBMS. + *

The inherited {@link #setSql sql} property is the name of the stored procedure + * in the RDBMS. * * @author Rod Johnson * @author Thomas Risberg - * @see #setSql */ public abstract class StoredProcedure extends SqlCall { @@ -113,10 +111,8 @@ public abstract class StoredProcedure extends SqlCall { validateParameters(inParams); int i = 0; for (SqlParameter sqlParameter : getDeclaredParameters()) { - if (sqlParameter.isInputValueProvided()) { - if (i < inParams.length) { - paramsToUse.put(sqlParameter.getName(), inParams[i++]); - } + if (sqlParameter.isInputValueProvided() && i < inParams.length) { + paramsToUse.put(sqlParameter.getName(), inParams[i++]); } } return getJdbcTemplate().call(newCallableStatementCreator(paramsToUse), getDeclaredParameters()); diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslator.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslator.java index 5cc996c1d1b..3cbdef779ee 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslator.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -217,14 +217,13 @@ public class SQLErrorCodeSQLExceptionTranslator extends AbstractFallbackSQLExcep CustomSQLErrorCodesTranslation[] customTranslations = this.sqlErrorCodes.getCustomTranslations(); if (customTranslations != null) { for (CustomSQLErrorCodesTranslation customTranslation : customTranslations) { - if (Arrays.binarySearch(customTranslation.getErrorCodes(), errorCode) >= 0) { - if (customTranslation.getExceptionClass() != null) { - DataAccessException customException = createCustomException( - task, sql, sqlEx, customTranslation.getExceptionClass()); - if (customException != null) { - logTranslation(task, sql, sqlEx, true); - return customException; - } + if (Arrays.binarySearch(customTranslation.getErrorCodes(), errorCode) >= 0 && + customTranslation.getExceptionClass() != null) { + DataAccessException customException = createCustomException( + task, sql, sqlEx, customTranslation.getExceptionClass()); + if (customException != null) { + logTranslation(task, sql, sqlEx, true); + return customException; } } } @@ -321,35 +320,35 @@ public class SQLErrorCodeSQLExceptionTranslator extends AbstractFallbackSQLExcep protected DataAccessException createCustomException( String task, @Nullable String sql, SQLException sqlEx, Class exceptionClass) { - // find appropriate constructor + // Find appropriate constructor for the given exception class try { int constructorType = 0; Constructor[] constructors = exceptionClass.getConstructors(); for (Constructor constructor : constructors) { Class[] parameterTypes = constructor.getParameterTypes(); - if (parameterTypes.length == 1 && String.class == parameterTypes[0]) { - if (constructorType < MESSAGE_ONLY_CONSTRUCTOR) - constructorType = MESSAGE_ONLY_CONSTRUCTOR; + if (parameterTypes.length == 1 && String.class == parameterTypes[0] && + constructorType < MESSAGE_ONLY_CONSTRUCTOR) { + constructorType = MESSAGE_ONLY_CONSTRUCTOR; } if (parameterTypes.length == 2 && String.class == parameterTypes[0] && - Throwable.class == parameterTypes[1]) { - if (constructorType < MESSAGE_THROWABLE_CONSTRUCTOR) - constructorType = MESSAGE_THROWABLE_CONSTRUCTOR; + Throwable.class == parameterTypes[1] && + constructorType < MESSAGE_THROWABLE_CONSTRUCTOR) { + constructorType = MESSAGE_THROWABLE_CONSTRUCTOR; } if (parameterTypes.length == 2 && String.class == parameterTypes[0] && - SQLException.class == parameterTypes[1]) { - if (constructorType < MESSAGE_SQLEX_CONSTRUCTOR) - constructorType = MESSAGE_SQLEX_CONSTRUCTOR; + SQLException.class == parameterTypes[1] && + constructorType < MESSAGE_SQLEX_CONSTRUCTOR) { + constructorType = MESSAGE_SQLEX_CONSTRUCTOR; } if (parameterTypes.length == 3 && String.class == parameterTypes[0] && - String.class == parameterTypes[1] && Throwable.class == parameterTypes[2]) { - if (constructorType < MESSAGE_SQL_THROWABLE_CONSTRUCTOR) - constructorType = MESSAGE_SQL_THROWABLE_CONSTRUCTOR; + String.class == parameterTypes[1] && Throwable.class == parameterTypes[2] && + constructorType < MESSAGE_SQL_THROWABLE_CONSTRUCTOR) { + constructorType = MESSAGE_SQL_THROWABLE_CONSTRUCTOR; } if (parameterTypes.length == 3 && String.class == parameterTypes[0] && - String.class == parameterTypes[1] && SQLException.class == parameterTypes[2]) { - if (constructorType < MESSAGE_SQL_SQLEX_CONSTRUCTOR) - constructorType = MESSAGE_SQL_SQLEX_CONSTRUCTOR; + String.class == parameterTypes[1] && SQLException.class == parameterTypes[2] && + constructorType < MESSAGE_SQL_SQLEX_CONSTRUCTOR) { + constructorType = MESSAGE_SQL_SQLEX_CONSTRUCTOR; } } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/handler/DestinationPatternsMessageCondition.java b/spring-messaging/src/main/java/org/springframework/messaging/handler/DestinationPatternsMessageCondition.java index f99566e62b9..ce8cb7dd500 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/handler/DestinationPatternsMessageCondition.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/handler/DestinationPatternsMessageCondition.java @@ -33,8 +33,8 @@ import org.springframework.util.PathMatcher; import org.springframework.util.StringUtils; /** - * A {@link MessageCondition} for matching the destination of a Message against one or - * more destination patterns using a {@link PathMatcher}. + * A {@link MessageCondition} for matching the destination of a Message + * against one or more destination patterns using a {@link PathMatcher}. * * @author Rossen Stoyanchev * @since 4.0 @@ -78,10 +78,8 @@ public class DestinationPatternsMessageCondition boolean slashSeparator = pathMatcher.combine("a", "a").equals("a/a"); Set result = new LinkedHashSet<>(patterns.size()); for (String pattern : patterns) { - if (slashSeparator) { - if (StringUtils.hasLength(pattern) && !pattern.startsWith("/")) { - pattern = "/" + pattern; - } + if (slashSeparator && StringUtils.hasLength(pattern) && !pattern.startsWith("/")) { + pattern = "/" + pattern; } result.add(pattern); } @@ -152,7 +150,6 @@ public class DestinationPatternsMessageCondition if (destination == null) { return null; } - if (this.patterns.isEmpty()) { return this; } @@ -163,7 +160,6 @@ public class DestinationPatternsMessageCondition matches.add(pattern); } } - if (matches.isEmpty()) { return null; } @@ -179,9 +175,8 @@ public class DestinationPatternsMessageCondition * If all compared patterns match equally, but one instance has more patterns, * it is considered a closer match. *

It is assumed that both instances have been obtained via - * {@link #getMatchingCondition(Message)} to ensure they - * contain only patterns that match the request and are sorted with - * the best matches on top. + * {@link #getMatchingCondition(Message)} to ensure they contain only patterns + * that match the request and are sorted with the best matches on top. */ @Override public int compareTo(DestinationPatternsMessageCondition other, Message message) { @@ -189,8 +184,8 @@ public class DestinationPatternsMessageCondition if (destination == null) { return 0; } - Comparator patternComparator = this.pathMatcher.getPatternComparator(destination); + Comparator patternComparator = this.pathMatcher.getPatternComparator(destination); Iterator iterator = this.patterns.iterator(); Iterator iteratorOther = other.patterns.iterator(); while (iterator.hasNext() && iteratorOther.hasNext()) { @@ -199,6 +194,7 @@ public class DestinationPatternsMessageCondition return result; } } + if (iterator.hasNext()) { return -1; } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/BufferingStompDecoder.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/BufferingStompDecoder.java index 49492511f71..481b09e84e8 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/BufferingStompDecoder.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/BufferingStompDecoder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -140,12 +140,10 @@ public class BufferingStompDecoder { private void checkBufferLimits() { Integer contentLength = this.expectedContentLength; - if (contentLength != null) { - if (contentLength > this.bufferSizeLimit) { - throw new StompConversionException( - "STOMP 'content-length' header value " + this.expectedContentLength + - " exceeds configured buffer size limit " + this.bufferSizeLimit); - } + if (contentLength != null && contentLength > this.bufferSizeLimit) { + throw new StompConversionException( + "STOMP 'content-length' header value " + this.expectedContentLength + + " exceeds configured buffer size limit " + this.bufferSizeLimit); } if (getBufferSize() > this.bufferSizeLimit) { throw new StompConversionException("The configured STOMP buffer size limit of " + diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate5/support/OpenSessionInViewInterceptor.java b/spring-orm/src/main/java/org/springframework/orm/hibernate5/support/OpenSessionInViewInterceptor.java index 840f9559f75..fd86449c998 100644 --- a/spring-orm/src/main/java/org/springframework/orm/hibernate5/support/OpenSessionInViewInterceptor.java +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate5/support/OpenSessionInViewInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -112,18 +112,15 @@ public class OpenSessionInViewInterceptor implements AsyncWebRequestInterceptor */ @Override public void preHandle(WebRequest request) throws DataAccessException { - String participateAttributeName = getParticipateAttributeName(); - + String key = getParticipateAttributeName(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); - if (asyncManager.hasConcurrentResult()) { - if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) { - return; - } + if (asyncManager.hasConcurrentResult() && applySessionBindingInterceptor(asyncManager, key)) { + return; } if (TransactionSynchronizationManager.hasResource(obtainSessionFactory())) { // Do not modify the Session: just mark the request accordingly. - Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); + Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST); int newCount = (count != null ? count + 1 : 1); request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST); } @@ -135,8 +132,8 @@ public class OpenSessionInViewInterceptor implements AsyncWebRequestInterceptor AsyncRequestInterceptor asyncRequestInterceptor = new AsyncRequestInterceptor(obtainSessionFactory(), sessionHolder); - asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor); - asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor); + asyncManager.registerCallableInterceptor(key, asyncRequestInterceptor); + asyncManager.registerDeferredResultInterceptor(key, asyncRequestInterceptor); } } diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryUtils.java b/spring-orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryUtils.java index ebeb108d4dc..2c004faf36d 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryUtils.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -106,10 +106,9 @@ public abstract class EntityManagerFactoryUtils { BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, EntityManagerFactory.class); for (String candidateName : candidateNames) { EntityManagerFactory emf = (EntityManagerFactory) beanFactory.getBean(candidateName); - if (emf instanceof EntityManagerFactoryInfo) { - if (unitName.equals(((EntityManagerFactoryInfo) emf).getPersistenceUnitName())) { - return emf; - } + if (emf instanceof EntityManagerFactoryInfo && + unitName.equals(((EntityManagerFactoryInfo) emf).getPersistenceUnitName())) { + return emf; } } // No matching persistence unit found - simply take the EntityManagerFactory diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java b/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java index 37b6630e206..4f89f0ae4ff 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -69,18 +69,16 @@ public class OpenEntityManagerInViewInterceptor extends EntityManagerFactoryAcce @Override public void preHandle(WebRequest request) throws DataAccessException { - String participateAttributeName = getParticipateAttributeName(); + String key = getParticipateAttributeName(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); - if (asyncManager.hasConcurrentResult()) { - if (applyEntityManagerBindingInterceptor(asyncManager, participateAttributeName)) { - return; - } + if (asyncManager.hasConcurrentResult() && applyEntityManagerBindingInterceptor(asyncManager, key)) { + return; } EntityManagerFactory emf = obtainEntityManagerFactory(); if (TransactionSynchronizationManager.hasResource(emf)) { // Do not modify the EntityManager: just mark the request accordingly. - Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); + Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST); int newCount = (count != null ? count + 1 : 1); request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST); } @@ -92,8 +90,8 @@ public class OpenEntityManagerInViewInterceptor extends EntityManagerFactoryAcce TransactionSynchronizationManager.bindResource(emf, emHolder); AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder); - asyncManager.registerCallableInterceptor(participateAttributeName, interceptor); - asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor); + asyncManager.registerCallableInterceptor(key, interceptor); + asyncManager.registerDeferredResultInterceptor(key, interceptor); } catch (PersistenceException ex) { throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); diff --git a/spring-test/src/main/java/org/springframework/test/web/client/match/MockRestRequestMatchers.java b/spring-test/src/main/java/org/springframework/test/web/client/match/MockRestRequestMatchers.java index 36670ba013d..3a2c739bfd0 100644 --- a/spring-test/src/main/java/org/springframework/test/web/client/match/MockRestRequestMatchers.java +++ b/spring-test/src/main/java/org/springframework/test/web/client/match/MockRestRequestMatchers.java @@ -31,9 +31,8 @@ import org.springframework.util.Assert; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.springframework.test.util.AssertionErrors.assertEquals; -import static org.springframework.test.util.AssertionErrors.assertTrue; +import static org.hamcrest.MatcherAssert.*; +import static org.springframework.test.util.AssertionErrors.*; /** * Static factory methods for {@link RequestMatcher} classes. Typically used to @@ -142,16 +141,17 @@ public abstract class MockRestRequestMatchers { return UriComponentsBuilder.fromUri(request.getURI()).build().getQueryParams(); } - private static void assertValueCount(String valueType, final String name, - MultiValueMap map, int count) { + private static void assertValueCount( + String valueType, final String name, MultiValueMap map, int count) { List values = map.get(name); - String message = "Expected " + valueType + " <" + name + ">"; - assertTrue(message + " to exist but was null", values != null); - - assertTrue(message + " to have at least <" + count + "> values but found " + values, - count <= values.size()); + if (values == null) { + fail(message + " to exist but was null"); + } + if (count > values.size()) { + fail(message + " to have at least <" + count + "> values but found " + values); + } } /** @@ -178,8 +178,7 @@ public abstract class MockRestRequestMatchers { List 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)); + assertEquals("Request header [" + name + "]", expectedValues[i], headerValues.get(i)); } }; } diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java b/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java index cac1ad5d33f..50bc86b0ad2 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -127,15 +127,13 @@ public final class MockMvc { * @param requestBuilder used to prepare the request to execute; * see static factory methods in * {@link org.springframework.test.web.servlet.request.MockMvcRequestBuilders} - * @return an instance of {@link ResultActions}; never {@code null} + * @return an instance of {@link ResultActions} (never {@code null}) * @see org.springframework.test.web.servlet.request.MockMvcRequestBuilders * @see org.springframework.test.web.servlet.result.MockMvcResultMatchers */ public ResultActions perform(RequestBuilder requestBuilder) throws Exception { - if (this.defaultRequestBuilder != null) { - if (requestBuilder instanceof Mergeable) { - requestBuilder = (RequestBuilder) ((Mergeable) requestBuilder).merge(this.defaultRequestBuilder); - } + if (this.defaultRequestBuilder != null && requestBuilder instanceof Mergeable) { + requestBuilder = (RequestBuilder) ((Mergeable) requestBuilder).merge(this.defaultRequestBuilder); } MockHttpServletRequest request = requestBuilder.buildRequest(this.servletContext); @@ -199,9 +197,7 @@ public final class MockMvc { return (MockHttpServletResponse) servletResponse; } - private void applyDefaultResultActions(MvcResult mvcResult) throws Exception { - for (ResultMatcher matcher : this.defaultResultMatchers) { matcher.match(mvcResult); } diff --git a/spring-test/src/test/java/org/springframework/test/web/client/match/MockRestRequestMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/client/match/MockRestRequestMatchersTests.java index 84772793424..dfd13294ed9 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/match/MockRestRequestMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/match/MockRestRequestMatchersTests.java @@ -48,7 +48,7 @@ public class MockRestRequestMatchersTests { MockRestRequestMatchers.requestTo("http://foo.com/bar").match(this.request); } - @Test // SPR-15819 + @Test // SPR-15819 public void requestToUriTemplate() throws Exception { this.request.setURI(new URI("http://foo.com/bar")); diff --git a/spring-tx/src/main/java/org/springframework/jca/endpoint/AbstractMessageEndpointFactory.java b/spring-tx/src/main/java/org/springframework/jca/endpoint/AbstractMessageEndpointFactory.java index 0f7f05077f8..0cd6d234cb6 100644 --- a/spring-tx/src/main/java/org/springframework/jca/endpoint/AbstractMessageEndpointFactory.java +++ b/spring-tx/src/main/java/org/springframework/jca/endpoint/AbstractMessageEndpointFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -325,11 +325,10 @@ public abstract class AbstractMessageEndpointFactory implements MessageEndpointF private boolean rollbackOnly; public TransactionDelegate(@Nullable XAResource xaResource) { - if (xaResource == null) { - if (transactionFactory != null && !transactionFactory.supportsResourceAdapterManagedTransactions()) { - throw new IllegalStateException("ResourceAdapter-provided XAResource is required for " + - "transaction management. Check your ResourceAdapter's configuration."); - } + if (xaResource == null && transactionFactory != null && + !transactionFactory.supportsResourceAdapterManagedTransactions()) { + throw new IllegalStateException("ResourceAdapter-provided XAResource is required for " + + "transaction management. Check your ResourceAdapter's configuration."); } this.xaResource = xaResource; } diff --git a/spring-web/src/main/java/org/springframework/http/codec/ResourceHttpMessageWriter.java b/spring-web/src/main/java/org/springframework/http/codec/ResourceHttpMessageWriter.java index 1ea802c0631..c227d8431ea 100644 --- a/spring-web/src/main/java/org/springframework/http/codec/ResourceHttpMessageWriter.java +++ b/spring-web/src/main/java/org/springframework/http/codec/ResourceHttpMessageWriter.java @@ -144,17 +144,15 @@ public class ResourceHttpMessageWriter implements HttpMessageWriter { private static Optional> zeroCopy(Resource resource, @Nullable ResourceRegion region, ReactiveHttpOutputMessage message) { - if (message instanceof ZeroCopyHttpOutputMessage) { - if (resource.isFile()) { - try { - File file = resource.getFile(); - long pos = region != null ? region.getPosition() : 0; - long count = region != null ? region.getCount() : file.length(); - return Optional.of(((ZeroCopyHttpOutputMessage) message).writeWith(file, pos, count)); - } - catch (IOException ex) { - // should not happen - } + if (message instanceof ZeroCopyHttpOutputMessage && resource.isFile()) { + try { + File file = resource.getFile(); + long pos = region != null ? region.getPosition() : 0; + long count = region != null ? region.getCount() : file.length(); + return Optional.of(((ZeroCopyHttpOutputMessage) message).writeWith(file, pos, count)); + } + catch (IOException ex) { + // should not happen } } return Optional.empty(); diff --git a/spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMapMethodArgumentResolver.java b/spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMapMethodArgumentResolver.java index 08778fc4dc3..7c4d9e09ee1 100644 --- a/spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMapMethodArgumentResolver.java +++ b/spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMapMethodArgumentResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,12 +51,8 @@ public class RequestParamMapMethodArgumentResolver implements HandlerMethodArgum @Override public boolean supportsParameter(MethodParameter parameter) { RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class); - if (requestParam != null) { - if (Map.class.isAssignableFrom(parameter.getParameterType())) { - return !StringUtils.hasText(requestParam.name()); - } - } - return false; + return (requestParam != null && Map.class.isAssignableFrom(parameter.getParameterType()) && + !StringUtils.hasText(requestParam.name())); } @Override diff --git a/spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolver.java b/spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolver.java index 3bb5126388a..658619526b7 100644 --- a/spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolver.java +++ b/spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolver.java @@ -220,10 +220,9 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod Assert.state(name != null, "Unresolvable parameter name"); if (value == null) { - if (requestParam != null) { - if (!requestParam.required() || !requestParam.defaultValue().equals(ValueConstants.DEFAULT_NONE)) { - return; - } + if (requestParam != null && + (!requestParam.required() || !requestParam.defaultValue().equals(ValueConstants.DEFAULT_NONE))) { + return; } builder.queryParam(name); } diff --git a/spring-web/src/main/java/org/springframework/web/method/support/CompositeUriComponentsContributor.java b/spring-web/src/main/java/org/springframework/web/method/support/CompositeUriComponentsContributor.java index 8cd0d899ed1..a3a6dab9bb5 100644 --- a/spring-web/src/main/java/org/springframework/web/method/support/CompositeUriComponentsContributor.java +++ b/spring-web/src/main/java/org/springframework/web/method/support/CompositeUriComponentsContributor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -98,15 +98,14 @@ public class CompositeUriComponentsContributor implements UriComponentsContribut @Override public boolean supportsParameter(MethodParameter parameter) { - for (Object c : this.contributors) { - if (c instanceof UriComponentsContributor) { - UriComponentsContributor contributor = (UriComponentsContributor) c; - if (contributor.supportsParameter(parameter)) { + for (Object contributor : this.contributors) { + if (contributor instanceof UriComponentsContributor) { + if (((UriComponentsContributor) contributor).supportsParameter(parameter)) { return true; } } - else if (c instanceof HandlerMethodArgumentResolver) { - if (((HandlerMethodArgumentResolver) c).supportsParameter(parameter)) { + else if (contributor instanceof HandlerMethodArgumentResolver) { + if (((HandlerMethodArgumentResolver) contributor).supportsParameter(parameter)) { return false; } } diff --git a/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerComposite.java b/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerComposite.java index 9dd36d74a36..c1a0ce1e19b 100644 --- a/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerComposite.java +++ b/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerComposite.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -98,10 +98,9 @@ public class HandlerMethodReturnValueHandlerComposite implements HandlerMethodRe private boolean isAsyncReturnValue(@Nullable Object value, MethodParameter returnType) { for (HandlerMethodReturnValueHandler handler : this.returnValueHandlers) { - if (handler instanceof AsyncHandlerMethodReturnValueHandler) { - if (((AsyncHandlerMethodReturnValueHandler) handler).isAsyncReturnValue(value, returnType)) { - return true; - } + if (handler instanceof AsyncHandlerMethodReturnValueHandler && + ((AsyncHandlerMethodReturnValueHandler) handler).isAsyncReturnValue(value, returnType)) { + return true; } } return false; @@ -122,9 +121,7 @@ public class HandlerMethodReturnValueHandlerComposite implements HandlerMethodRe @Nullable List handlers) { if (handlers != null) { - for (HandlerMethodReturnValueHandler handler : handlers) { - this.returnValueHandlers.add(handler); - } + this.returnValueHandlers.addAll(handlers); } return this; } diff --git a/spring-web/src/main/java/org/springframework/web/util/pattern/InternalPathPatternParser.java b/spring-web/src/main/java/org/springframework/web/util/pattern/InternalPathPatternParser.java index 6c0e1d3972c..36e54df0f85 100644 --- a/spring-web/src/main/java/org/springframework/web/util/pattern/InternalPathPatternParser.java +++ b/spring-web/src/main/java/org/springframework/web/util/pattern/InternalPathPatternParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -157,10 +157,8 @@ class InternalPathPatternParser { } } else if (ch == '*') { - if (this.insideVariableCapture) { - if (this.variableCaptureStart == pos - 1) { - this.isCaptureTheRestVariable = true; - } + if (this.insideVariableCapture && this.variableCaptureStart == this.pos - 1) { + this.isCaptureTheRestVariable = true; } this.wildcard = true; } diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/PathResourceLookupFunction.java b/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/PathResourceLookupFunction.java index 6fdce491daf..cea16c4c075 100644 --- a/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/PathResourceLookupFunction.java +++ b/spring-webflux/src/main/java/org/springframework/web/reactive/function/server/PathResourceLookupFunction.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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,6 +59,7 @@ class PathResourceLookupFunction implements Function %s", this.pattern, this.location); + return this.pattern + " -> " + this.location; } + } diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/handler/AbstractUrlHandlerMapping.java b/spring-webflux/src/main/java/org/springframework/web/reactive/handler/AbstractUrlHandlerMapping.java index dc23c2c04f6..6eeec5f335a 100644 --- a/spring-webflux/src/main/java/org/springframework/web/reactive/handler/AbstractUrlHandlerMapping.java +++ b/spring-webflux/src/main/java/org/springframework/web/reactive/handler/AbstractUrlHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -112,9 +112,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping { * @see org.springframework.web.util.pattern.PathPattern */ @Nullable - protected Object lookupHandler(PathContainer lookupPath, ServerWebExchange exchange) - throws Exception { - + protected Object lookupHandler(PathContainer lookupPath, ServerWebExchange exchange) throws Exception { return this.handlerMap.entrySet().stream() .filter(entry -> entry.getKey().matches(lookupPath)) .sorted((entry1, entry2) -> @@ -167,9 +165,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping { * @throws BeansException if the handler couldn't be registered * @throws IllegalStateException if there is a conflicting handler registered */ - protected void registerHandler(String[] urlPaths, String beanName) - throws BeansException, IllegalStateException { - + protected void registerHandler(String[] urlPaths, String beanName) throws BeansException, IllegalStateException { Assert.notNull(urlPaths, "URL path array must not be null"); for (String urlPath : urlPaths) { registerHandler(urlPath, beanName); @@ -184,9 +180,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping { * @throws BeansException if the handler couldn't be registered * @throws IllegalStateException if there is a conflicting handler registered */ - protected void registerHandler(String urlPath, Object handler) - throws BeansException, IllegalStateException { - + protected void registerHandler(String urlPath, Object handler) throws BeansException, IllegalStateException { Assert.notNull(urlPath, "URL path must not be null"); Assert.notNull(handler, "Handler object must not be null"); Object resolvedHandler = handler; @@ -196,12 +190,10 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping { PathPattern pattern = getPathPatternParser().parse(urlPath); if (this.handlerMap.containsKey(pattern)) { Object existingHandler = this.handlerMap.get(pattern); - if (existingHandler != null) { - if (existingHandler != resolvedHandler) { - throw new IllegalStateException( - "Cannot map " + getHandlerDescription(handler) + " to [" + urlPath + "]: " + - "there is already " + getHandlerDescription(existingHandler) + " mapped."); - } + if (existingHandler != null && existingHandler != resolvedHandler) { + throw new IllegalStateException( + "Cannot map " + getHandlerDescription(handler) + " to [" + urlPath + "]: " + + "there is already " + getHandlerDescription(existingHandler) + " mapped."); } } @@ -220,6 +212,12 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping { } } + private String getHandlerDescription(Object handler) { + return "handler " + (handler instanceof String ? + "'" + handler + "'" : "of type [" + handler.getClass() + "]"); + } + + private static String prependLeadingSlash(String pattern) { if (StringUtils.hasLength(pattern) && !pattern.startsWith("/")) { return "/" + pattern; @@ -229,9 +227,4 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping { } } - private String getHandlerDescription(Object handler) { - return "handler " + (handler instanceof String ? - "'" + handler + "'" : "of type [" + handler.getClass() + "]"); - } - } diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceUrlProvider.java b/spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceUrlProvider.java index e2f635cc4ca..3e5c2add98f 100644 --- a/spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceUrlProvider.java +++ b/spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceUrlProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -83,15 +83,6 @@ public class ResourceUrlProvider implements ApplicationListener views = new ArrayList<>(this.contentNegotiatingResolver.getDefaultViews()); - views.addAll(Arrays.asList(defaultViews)); - this.contentNegotiatingResolver.setDefaultViews(views); - } + if (!ObjectUtils.isEmpty(defaultViews) && + !CollectionUtils.isEmpty(this.contentNegotiatingResolver.getDefaultViews())) { + List views = new ArrayList<>(this.contentNegotiatingResolver.getDefaultViews()); + views.addAll(Arrays.asList(defaultViews)); + this.contentNegotiatingResolver.setDefaultViews(views); } } else { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariableMapMethodArgumentResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariableMapMethodArgumentResolver.java index 1fbd904b5c7..b66a24080de 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariableMapMethodArgumentResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariableMapMethodArgumentResolver.java @@ -54,12 +54,8 @@ public class MatrixVariableMapMethodArgumentResolver implements HandlerMethodArg @Override public boolean supportsParameter(MethodParameter parameter) { MatrixVariable matrixVariable = parameter.getParameterAnnotation(MatrixVariable.class); - if (matrixVariable != null) { - if (Map.class.isAssignableFrom(parameter.getParameterType())) { - return !StringUtils.hasText(matrixVariable.name()); - } - } - return false; + return (matrixVariable != null && Map.class.isAssignableFrom(parameter.getParameterType()) && + !StringUtils.hasText(matrixVariable.name())); } @Override diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandler.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandler.java index 64888e1ced9..135f5aa8ee0 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandler.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandler.java @@ -94,10 +94,8 @@ public class ModelAndViewMethodReturnValueHandler implements HandlerMethodReturn else { View view = mav.getView(); mavContainer.setView(view); - if (view instanceof SmartView) { - if (((SmartView) view).isRedirectView()) { - mavContainer.setRedirectModelScenario(true); - } + if (view instanceof SmartView && ((SmartView) view).isRedirectView()) { + mavContainer.setRedirectModelScenario(true); } } mavContainer.setStatus(mav.getStatus()); @@ -113,10 +111,7 @@ public class ModelAndViewMethodReturnValueHandler implements HandlerMethodReturn * reference; "false" otherwise. */ protected boolean isRedirectViewName(String viewName) { - if (PatternMatchUtils.simpleMatch(this.redirectPatterns, viewName)) { - return true; - } - return viewName.startsWith("redirect:"); + return (PatternMatchUtils.simpleMatch(this.redirectPatterns, viewName) || viewName.startsWith("redirect:")); } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java index dc191ec42b4..478f8d628f6 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -155,11 +155,9 @@ public class RequestResponseBodyMethodProcessor extends AbstractMessageConverter ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(servletRequest); Object arg = readWithMessageConverters(inputMessage, parameter, paramType); - if (arg == null) { - if (checkRequired(parameter)) { - throw new HttpMessageNotReadableException("Required request body is missing: " + - parameter.getExecutable().toGenericString()); - } + if (arg == null && checkRequired(parameter)) { + throw new HttpMessageNotReadableException("Required request body is missing: " + + parameter.getExecutable().toGenericString()); } return arg; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ViewMethodReturnValueHandler.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ViewMethodReturnValueHandler.java index 643cfe5775a..4b2ec7635a9 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ViewMethodReturnValueHandler.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ViewMethodReturnValueHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -50,19 +50,14 @@ public class ViewMethodReturnValueHandler implements HandlerMethodReturnValueHan public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { - if (returnValue == null) { - return; - } - else if (returnValue instanceof View){ + if (returnValue instanceof View){ View view = (View) returnValue; mavContainer.setView(view); - if (view instanceof SmartView) { - if (((SmartView) view).isRedirectView()) { - mavContainer.setRedirectModelScenario(true); - } + if (view instanceof SmartView && ((SmartView) view).isRedirectView()) { + mavContainer.setRedirectModelScenario(true); } } - else { + else if (returnValue != null) { // should not happen throw new UnsupportedOperationException("Unexpected return type: " + returnType.getParameterType().getName() + " in method: " + returnType.getMethod()); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/InputTag.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/InputTag.java index f2de07a0b1b..1266fe7f5ae 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/InputTag.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/InputTag.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2018 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. @@ -380,12 +380,7 @@ public class InputTag extends AbstractHtmlInputElementTag { */ @Override protected boolean isValidDynamicAttribute(String localName, Object value) { - if ("type".equals(localName)) { - if ("checkbox".equals(value) || "radio".equals(value)) { - return false; - } - } - return true; + return !("type".equals(localName) && ("checkbox".equals(value) || "radio".equals(value))); } /** diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/SockJsClient.java b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/SockJsClient.java index 35e4cb8a925..3459fd550a9 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/SockJsClient.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/SockJsClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -205,8 +205,9 @@ public class SockJsClient implements WebSocketClient, Lifecycle { this.running = true; for (Transport transport : this.transports) { if (transport instanceof Lifecycle) { - if (!((Lifecycle) transport).isRunning()) { - ((Lifecycle) transport).start(); + Lifecycle lifecycle = (Lifecycle) transport; + if (!lifecycle.isRunning()) { + lifecycle.start(); } } } @@ -219,8 +220,9 @@ public class SockJsClient implements WebSocketClient, Lifecycle { this.running = false; for (Transport transport : this.transports) { if (transport instanceof Lifecycle) { - if (((Lifecycle) transport).isRunning()) { - ((Lifecycle) transport).stop(); + Lifecycle lifecycle = (Lifecycle) transport; + if (lifecycle.isRunning()) { + lifecycle.stop(); } } } diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java index a11328741ca..a61f4c36ff2 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java @@ -17,6 +17,7 @@ package org.springframework.web.socket.sockjs.transport; import java.io.IOException; +import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -288,12 +289,11 @@ public class TransportHandlingSockJsService extends AbstractSockJsService implem } } else { - if (session.getPrincipal() != null) { - if (!session.getPrincipal().equals(request.getPrincipal())) { - logger.debug("The user for the session does not match the user for the request."); - response.setStatusCode(HttpStatus.NOT_FOUND); - return; - } + Principal principal = session.getPrincipal(); + if (principal != null && !principal.equals(request.getPrincipal())) { + logger.debug("The user for the session does not match the user for the request."); + response.setStatusCode(HttpStatus.NOT_FOUND); + return; } if (!transportHandler.checkSessionType(session)) { logger.debug("Session type does not match the transport type for the request."); @@ -305,17 +305,11 @@ public class TransportHandlingSockJsService extends AbstractSockJsService implem if (transportType.sendsNoCacheInstruction()) { addNoCacheHeaders(response); } - - if (transportType.supportsCors()) { - if (!checkOrigin(request, response)) { - return; - } + if (transportType.supportsCors() && !checkOrigin(request, response)) { + return; } - transportHandler.handleRequest(request, response, handler, session); - - chain.applyAfterHandshake(request, response, null); } catch (SockJsException ex) { diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractHttpSockJsSession.java b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractHttpSockJsSession.java index 7c19710cb2e..1dd65d5709d 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractHttpSockJsSession.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractHttpSockJsSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2018 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. @@ -332,15 +332,13 @@ public abstract class AbstractHttpSockJsSession extends AbstractSockJsSession { this.readyToSend = false; this.response = null; updateLastActiveTime(); - if (control != null && !control.isCompleted()) { - if (control.isStarted()) { - try { - control.complete(); - } - catch (Throwable ex) { - // Could be part of normal workflow (e.g. browser tab closed) - logger.debug("Failed to complete request: " + ex.getMessage()); - } + if (control != null && !control.isCompleted() && control.isStarted()) { + try { + control.complete(); + } + catch (Throwable ex) { + // Could be part of normal workflow (e.g. browser tab closed) + logger.debug("Failed to complete request: " + ex.getMessage()); } } }