From e3d0ef6015f14ceb7baf380ca0598904d75731d5 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 27 Mar 2018 00:38:32 +0200 Subject: [PATCH] Use Map.forEach instead of manual Map.Entry iteration wherever possible Issue: SPR-16646 --- .../beans/PropertyEditorRegistrySupport.java | 6 +-- .../factory/config/CustomScopeConfigurer.java | 8 ++- .../beans/factory/config/YamlProcessor.java | 9 ++-- .../support/BeanDefinitionValueResolver.java | 11 ++--- ...onfigurationClassBeanDefinitionReader.java | 7 +-- .../org/springframework/core/Constants.java | 14 +++--- .../core/SimpleAliasRegistry.java | 7 ++- .../core/annotation/AnnotationUtils.java | 11 ++--- .../io/support/SpringFactoriesLoader.java | 6 ++- .../util/LinkedMultiValueMap.java | 3 +- .../org/springframework/util/MimeType.java | 5 +- .../core/metadata/CallMetaDataContext.java | 10 ++-- .../core/metadata/TableMetaDataContext.java | 20 +++++--- .../jdbc/core/simple/AbstractJdbcCall.java | 12 ++--- ...CustomSQLExceptionTranslatorRegistrar.java | 10 ++-- .../converter/SimpleMessageConverter.java | 9 ++-- .../messaging/simp/SimpAttributes.java | 10 ++-- .../messaging/simp/SimpMessagingTemplate.java | 7 +-- .../broker/DefaultSubscriptionRegistry.java | 38 ++++++-------- .../broker/SimpleBrokerMessageHandler.java | 13 +++-- .../simp/broker/SubscriptionRegistry.java | 10 ++-- .../org/springframework/http/HttpHeaders.java | 20 ++------ .../HttpComponentsClientHttpRequest.java | 13 ++--- .../http/client/Netty4ClientHttpRequest.java | 6 +-- .../OkHttp3ClientHttpRequestFactory.java | 11 ++--- .../SimpleBufferingClientHttpRequest.java | 11 ++--- .../server/ServletServerHttpResponse.java | 10 ++-- .../DefaultServerHttpRequestBuilder.java | 12 +---- .../reactive/ReactorServerHttpResponse.java | 12 ++--- .../reactive/ServletServerHttpResponse.java | 11 ++--- .../reactive/UndertowServerHttpResponse.java | 8 +-- .../ContentNegotiationManagerFactoryBean.java | 11 ++--- ...MappingMediaTypeFileExtensionResolver.java | 24 ++++----- .../web/bind/WebDataBinder.java | 8 ++- .../bind/support/WebRequestDataBinder.java | 16 +++--- .../web/client/RestTemplate.java | 12 ++--- ...RequestParamMapMethodArgumentResolver.java | 16 +++--- .../web/util/HierarchicalUriComponents.java | 49 +++++++++---------- .../web/util/UrlPathHelper.java | 7 +-- .../web/reactive/function/BodyExtractors.java | 9 +--- .../web/reactive/function/BodyInserters.java | 41 ++++------------ .../handler/AbstractHandlerMethodMapping.java | 7 ++- .../ExceptionHandlerExceptionResolver.java | 3 +- .../resource/ResourceHttpRequestHandler.java | 7 ++- .../web/socket/WebSocketExtension.java | 9 +--- ...ebSocketToJettyExtensionConfigAdapter.java | 9 ++-- .../GlassFishRequestUpgradeStrategy.java | 8 +-- .../WebLogicRequestUpgradeStrategy.java | 6 +-- .../sockjs/client/JettyXhrTransport.java | 10 ++-- .../sockjs/client/UndertowXhrTransport.java | 9 ++-- 50 files changed, 233 insertions(+), 368 deletions(-) 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 34d9f71e826..4f2528d6019 100644 --- a/spring-beans/src/main/java/org/springframework/beans/PropertyEditorRegistrySupport.java +++ b/spring-beans/src/main/java/org/springframework/beans/PropertyEditorRegistrySupport.java @@ -466,9 +466,7 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry { this.customEditors.forEach(target::registerCustomEditor); } if (this.customEditorsForPath != null) { - for (Map.Entry entry : this.customEditorsForPath.entrySet()) { - String editorPath = entry.getKey(); - CustomEditorHolder editorHolder = entry.getValue(); + this.customEditorsForPath.forEach((editorPath, editorHolder) -> { if (nestedProperty != null) { int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(editorPath); if (pos != -1) { @@ -484,7 +482,7 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry { target.registerCustomEditor( editorHolder.getRegisteredType(), editorPath, editorHolder.getPropertyEditor()); } - } + }); } } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/config/CustomScopeConfigurer.java b/spring-beans/src/main/java/org/springframework/beans/factory/config/CustomScopeConfigurer.java index 59e9111e63c..fb20d3d9698 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/config/CustomScopeConfigurer.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/config/CustomScopeConfigurer.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. @@ -97,9 +97,7 @@ public class CustomScopeConfigurer implements BeanFactoryPostProcessor, BeanClas @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (this.scopes != null) { - for (Map.Entry entry : this.scopes.entrySet()) { - String scopeKey = entry.getKey(); - Object value = entry.getValue(); + this.scopes.forEach((scopeKey, value) -> { if (value instanceof Scope) { beanFactory.registerScope(scopeKey, (Scope) value); } @@ -118,7 +116,7 @@ public class CustomScopeConfigurer implements BeanFactoryPostProcessor, BeanClas scopeKey + "] is not an instance of required type [" + Scope.class.getName() + "] or a corresponding Class or String value indicating a Scope implementation"); } - } + }); } } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/config/YamlProcessor.java b/spring-beans/src/main/java/org/springframework/beans/factory/config/YamlProcessor.java index d7fe0ef2beb..2a75fa50cde 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/config/YamlProcessor.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/config/YamlProcessor.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. @@ -25,7 +25,6 @@ import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Properties; import java.util.Set; @@ -272,8 +271,7 @@ public abstract class YamlProcessor { } private void buildFlattenedMap(Map result, Map source, @Nullable String path) { - for (Entry entry : source.entrySet()) { - String key = entry.getKey(); + source.forEach((key, value) -> { if (StringUtils.hasText(path)) { if (key.startsWith("[")) { key = path + key; @@ -282,7 +280,6 @@ public abstract class YamlProcessor { key = path + '.' + key; } } - Object value = entry.getValue(); if (value instanceof String) { result.put(key, value); } @@ -305,7 +302,7 @@ public abstract class YamlProcessor { else { result.put(key, (value != null ? value : "")); } - } + }); } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java index 5d0c0e5e132..11e860b84a5 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.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. @@ -421,12 +421,11 @@ class BeanDefinitionValueResolver { */ private Map resolveManagedMap(Object argName, Map mm) { Map resolved = new LinkedHashMap<>(mm.size()); - for (Map.Entry entry : mm.entrySet()) { - Object resolvedKey = resolveValueIfNecessary(argName, entry.getKey()); - Object resolvedValue = resolveValueIfNecessary( - new KeyedArgName(argName, entry.getKey()), entry.getValue()); + mm.forEach((key, value) -> { + Object resolvedKey = resolveValueIfNecessary(argName, key); + Object resolvedValue = resolveValueIfNecessary(new KeyedArgName(argName, key), value); resolved.put(resolvedKey, resolvedValue); - } + }); return resolved; } diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java index 00103a4472a..57a5ffa146e 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java @@ -315,10 +315,7 @@ class ConfigurationClassBeanDefinitionReader { Map, BeanDefinitionReader> readerInstanceCache = new HashMap<>(); - for (Map.Entry> entry : importedResources.entrySet()) { - String resource = entry.getKey(); - Class readerClass = entry.getValue(); - + importedResources.forEach((resource, readerClass) -> { // Default reader selection necessary? if (BeanDefinitionReader.class == readerClass) { if (StringUtils.endsWithIgnoreCase(resource, ".groovy")) { @@ -352,7 +349,7 @@ class ConfigurationClassBeanDefinitionReader { // TODO SPR-6310: qualify relative path locations as done in AbstractContextLoader.modifyLocations reader.loadBeanDefinitions(resource); - } + }); } private void loadBeanDefinitionsFromRegistrars(Map registrars) { diff --git a/spring-core/src/main/java/org/springframework/core/Constants.java b/spring-core/src/main/java/org/springframework/core/Constants.java index a3a70f2e7ef..b81790ee4b2 100644 --- a/spring-core/src/main/java/org/springframework/core/Constants.java +++ b/spring-core/src/main/java/org/springframework/core/Constants.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. @@ -215,11 +215,11 @@ public class Constants { public Set getValues(@Nullable String namePrefix) { String prefixToUse = (namePrefix != null ? namePrefix.trim().toUpperCase(Locale.ENGLISH) : ""); Set values = new HashSet<>(); - for (String code : this.fieldCache.keySet()) { + this.fieldCache.forEach((code, value) -> { if (code.startsWith(prefixToUse)) { - values.add(this.fieldCache.get(code)); + values.add(value); } - } + }); return values; } @@ -247,11 +247,11 @@ public class Constants { public Set getValuesForSuffix(@Nullable String nameSuffix) { String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : ""); Set values = new HashSet<>(); - for (String code : this.fieldCache.keySet()) { + this.fieldCache.forEach((code, value) -> { if (code.endsWith(suffixToUse)) { - values.add(this.fieldCache.get(code)); + values.add(value); } - } + }); return values; } diff --git a/spring-core/src/main/java/org/springframework/core/SimpleAliasRegistry.java b/spring-core/src/main/java/org/springframework/core/SimpleAliasRegistry.java index 0e676c43eb5..35fdd3d6173 100644 --- a/spring-core/src/main/java/org/springframework/core/SimpleAliasRegistry.java +++ b/spring-core/src/main/java/org/springframework/core/SimpleAliasRegistry.java @@ -141,8 +141,7 @@ public class SimpleAliasRegistry implements AliasRegistry { Assert.notNull(valueResolver, "StringValueResolver must not be null"); synchronized (this.aliasMap) { Map aliasCopy = new HashMap<>(this.aliasMap); - for (String alias : aliasCopy.keySet()) { - String registeredName = aliasCopy.get(alias); + aliasCopy.forEach((alias, registeredName) -> { String resolvedAlias = valueResolver.resolveStringValue(alias); String resolvedName = valueResolver.resolveStringValue(registeredName); if (resolvedAlias == null || resolvedName == null || resolvedAlias.equals(resolvedName)) { @@ -154,7 +153,7 @@ public class SimpleAliasRegistry implements AliasRegistry { if (existingName.equals(resolvedName)) { // Pointing to existing alias - just remove placeholder this.aliasMap.remove(alias); - break; + return; } throw new IllegalStateException( "Cannot register resolved alias '" + resolvedAlias + "' (original: '" + alias + @@ -168,7 +167,7 @@ public class SimpleAliasRegistry implements AliasRegistry { else if (!registeredName.equals(resolvedName)) { this.aliasMap.put(alias, resolvedName); } - } + }); } } diff --git a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java index 59c6cf5327e..2c296bbd5f1 100644 --- a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java +++ b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java @@ -1246,21 +1246,18 @@ public abstract class AnnotationUtils { if (!attributes.validated) { // Validate @AliasFor configuration Map> aliasMap = getAttributeAliasMap(annotationType); - for (String attributeName : aliasMap.keySet()) { + aliasMap.forEach((attributeName, aliasedAttributeNames) -> { if (valuesAlreadyReplaced.contains(attributeName)) { - continue; + return; } Object value = attributes.get(attributeName); boolean valuePresent = (value != null && !(value instanceof DefaultValueHolder)); - - for (String aliasedAttributeName : aliasMap.get(attributeName)) { + for (String aliasedAttributeName : aliasedAttributeNames) { if (valuesAlreadyReplaced.contains(aliasedAttributeName)) { continue; } - Object aliasedValue = attributes.get(aliasedAttributeName); boolean aliasPresent = (aliasedValue != null && !(aliasedValue instanceof DefaultValueHolder)); - // Something to validate or replace with an alias? if (valuePresent || aliasPresent) { if (valuePresent && aliasPresent) { @@ -1290,7 +1287,7 @@ public abstract class AnnotationUtils { } } } - } + }); attributes.validated = true; } diff --git a/spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java b/spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java index 9ce5724e0f1..197e37a7703 100644 --- a/spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java +++ b/spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.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. @@ -121,8 +121,10 @@ public abstract class SpringFactoriesLoader { private static Map> loadSpringFactories(@Nullable ClassLoader classLoader) { MultiValueMap result = cache.get(classLoader); - if (result != null) + if (result != null) { return result; + } + try { Enumeration urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) : diff --git a/spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java b/spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java index 5c20bf35f5b..b510e64e313 100644 --- a/spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java +++ b/spring-core/src/main/java/org/springframework/util/LinkedMultiValueMap.java @@ -196,8 +196,7 @@ public class LinkedMultiValueMap implements MultiValueMap, Serializa */ public LinkedMultiValueMap deepCopy() { LinkedMultiValueMap copy = new LinkedMultiValueMap<>(this.targetMap.size()); - this.targetMap.forEach((k, v) -> copy.put(k, new LinkedList<>(v))); - + this.targetMap.forEach((key, value) -> copy.put(key, new LinkedList<>(value))); return copy; } diff --git a/spring-core/src/main/java/org/springframework/util/MimeType.java b/spring-core/src/main/java/org/springframework/util/MimeType.java index bc2d996ab82..7fb5e0cc894 100644 --- a/spring-core/src/main/java/org/springframework/util/MimeType.java +++ b/spring-core/src/main/java/org/springframework/util/MimeType.java @@ -409,7 +409,8 @@ public class MimeType implements Comparable, Serializable { return false; } - for (String key : this.parameters.keySet()) { + for (Map.Entry entry : this.parameters.entrySet()) { + String key = entry.getKey(); if (!other.parameters.containsKey(key)) { return false; } @@ -418,7 +419,7 @@ public class MimeType implements Comparable, Serializable { return false; } } - else if (!ObjectUtils.nullSafeEquals(this.parameters.get(key), other.parameters.get(key))) { + else if (!ObjectUtils.nullSafeEquals(entry.getValue(), other.parameters.get(key))) { return false; } } 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 bcf39c99264..1d6a5561f40 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 @@ -563,14 +563,14 @@ public class CallMetaDataContext { } Map matchedParameters = new HashMap<>(inParameters.size()); - for (String parameterName : inParameters.keySet()) { + inParameters.forEach((parameterName, parameterValue) -> { String parameterNameToMatch = provider.parameterNameToUse(parameterName); String callParameterName = callParameterNames.get(lowerCase(parameterNameToMatch)); if (callParameterName == null) { if (logger.isDebugEnabled()) { - Object value = inParameters.get(parameterName); + Object value = parameterValue; if (value instanceof SqlParameterValue) { - value = ((SqlParameterValue)value).getValue(); + value = ((SqlParameterValue) value).getValue(); } if (value != null) { logger.debug("Unable to locate the corresponding IN or IN-OUT parameter for \"" + @@ -579,9 +579,9 @@ public class CallMetaDataContext { } } else { - matchedParameters.put(callParameterName, inParameters.get(parameterName)); + matchedParameters.put(callParameterName, parameterValue); } - } + }); if (matchedParameters.size() < callParameterNames.size()) { for (String parameterName : callParameterNames.keySet()) { diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/TableMetaDataContext.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/TableMetaDataContext.java index 10823a73b19..1a26ff5d86c 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/TableMetaDataContext.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/TableMetaDataContext.java @@ -244,13 +244,21 @@ public class TableMetaDataContext { * @param inParameters the parameter names and values */ public List matchInParameterValuesWithInsertColumns(Map inParameters) { - List values = new ArrayList<>(); - Map source = new LinkedHashMap<>(inParameters.size()); - for (String key : inParameters.keySet()) { - source.put(key.toLowerCase(), inParameters.get(key)); - } + List values = new ArrayList<>(inParameters.size()); for (String column : this.tableColumns) { - values.add(source.get(column.toLowerCase())); + Object value = inParameters.get(column); + if (value == null) { + value = inParameters.get(column.toLowerCase()); + if (value == null) { + for (Map.Entry entry : inParameters.entrySet()) { + if (column.equalsIgnoreCase(entry.getKey())) { + value = entry.getValue(); + // TODO: break; + } + } + } + } + values.add(value); } return values; } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcCall.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcCall.java index 406cf1e526b..4e2df89afc9 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcCall.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcCall.java @@ -314,11 +314,9 @@ public abstract class AbstractJdbcCall { this.callMetaDataContext.initializeMetaData(dataSource); // Iterate over the declared RowMappers and register the corresponding SqlParameter - for (Map.Entry> entry : this.declaredRowMappers.entrySet()) { - SqlParameter resultSetParameter = - this.callMetaDataContext.createReturnResultSetParameter(entry.getKey(), entry.getValue()); - this.declaredParameters.add(resultSetParameter); - } + this.declaredRowMappers.forEach((key, value) -> { + this.declaredParameters.add(this.callMetaDataContext.createReturnResultSetParameter(key, value)); + }); this.callMetaDataContext.processParameters(this.declaredParameters); this.callString = this.callMetaDataContext.createCallString(); @@ -326,8 +324,8 @@ public abstract class AbstractJdbcCall { logger.debug("Compiled stored procedure. Call string is [" + this.callString + "]"); } - this.callableStatementFactory = - new CallableStatementCreatorFactory(this.callString, this.callMetaDataContext.getCallParameters()); + this.callableStatementFactory = new CallableStatementCreatorFactory( + this.callString, this.callMetaDataContext.getCallParameters()); onCompileInternal(); } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/CustomSQLExceptionTranslatorRegistrar.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/CustomSQLExceptionTranslatorRegistrar.java index 02ebbfc1adb..e90fb1bc84e 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/support/CustomSQLExceptionTranslatorRegistrar.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/CustomSQLExceptionTranslatorRegistrar.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. @@ -22,8 +22,7 @@ import java.util.Map; import org.springframework.beans.factory.InitializingBean; /** - * Registry for registering custom {@link org.springframework.jdbc.support.SQLExceptionTranslator} - * instances for specific databases. + * Registry for custom {@link SQLExceptionTranslator} instances for specific databases. * * @author Thomas Risberg * @since 3.1.1 @@ -50,9 +49,8 @@ public class CustomSQLExceptionTranslatorRegistrar implements InitializingBean { @Override public void afterPropertiesSet() { - for (String dbName : this.translators.keySet()) { - CustomSQLExceptionTranslatorRegistry.getInstance().registerTranslator(dbName, this.translators.get(dbName)); - } + this.translators.forEach((dbName, translator) -> + CustomSQLExceptionTranslatorRegistry.getInstance().registerTranslator(dbName, translator)); } } diff --git a/spring-jms/src/main/java/org/springframework/jms/support/converter/SimpleMessageConverter.java b/spring-jms/src/main/java/org/springframework/jms/support/converter/SimpleMessageConverter.java index 18dabab78ba..fae059aba3e 100644 --- a/spring-jms/src/main/java/org/springframework/jms/support/converter/SimpleMessageConverter.java +++ b/spring-jms/src/main/java/org/springframework/jms/support/converter/SimpleMessageConverter.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. @@ -147,11 +147,12 @@ public class SimpleMessageConverter implements MessageConverter { protected MapMessage createMessageForMap(Map map, Session session) throws JMSException { MapMessage message = session.createMapMessage(); for (Map.Entry entry : map.entrySet()) { - if (!(entry.getKey() instanceof String)) { + Object key = entry.getKey(); + if (!(key instanceof String)) { throw new MessageConversionException("Cannot convert non-String key of type [" + - ObjectUtils.nullSafeClassName(entry.getKey()) + "] to JMS MapMessage entry"); + ObjectUtils.nullSafeClassName(key) + "] to JMS MapMessage entry"); } - message.setObject((String) entry.getKey(), entry.getValue()); + message.setObject((String) key, entry.getValue()); } return message; } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/SimpAttributes.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/SimpAttributes.java index 29bc4d1175d..e59ab597f4d 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/SimpAttributes.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/SimpAttributes.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 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. @@ -168,16 +168,16 @@ public class SimpAttributes { } private void executeDestructionCallbacks() { - for (Map.Entry entry : this.attributes.entrySet()) { - if (entry.getKey().startsWith(DESTRUCTION_CALLBACK_NAME_PREFIX)) { + this.attributes.forEach((key, value) -> { + if (key.startsWith(DESTRUCTION_CALLBACK_NAME_PREFIX)) { try { - ((Runnable) entry.getValue()).run(); + ((Runnable) value).run(); } catch (Throwable ex) { logger.error("Uncaught error in session attribute destruction callback", ex); } } - } + }); } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessagingTemplate.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessagingTemplate.java index 7d7ac067784..ee06f157e11 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessagingTemplate.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessagingTemplate.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. @@ -263,10 +263,7 @@ public class SimpMessagingTemplate extends AbstractMessageSendingTemplate headerEntry : headers.entrySet()) { - Object value = headerEntry.getValue(); - headerAccessor.setNativeHeader(headerEntry.getKey(), (value != null ? value.toString() : null)); - } + headers.forEach((key, value) -> headerAccessor.setNativeHeader(key, (value != null ? value.toString() : null))); return headerAccessor.getMessageHeaders(); } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/DefaultSubscriptionRegistry.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/DefaultSubscriptionRegistry.java index 18c9a9169e6..b926fae2d5a 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/DefaultSubscriptionRegistry.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/DefaultSubscriptionRegistry.java @@ -270,8 +270,8 @@ public class DefaultSubscriptionRegistry extends AbstractSubscriptionRegistry { for (SessionSubscriptionInfo info : subscriptionRegistry.getAllSubscriptions()) { for (String destinationPattern : info.getDestinations()) { if (getPathMatcher().match(destinationPattern, destination)) { - for (Subscription subscription : info.getSubscriptions(destinationPattern)) { - result.add(info.sessionId, subscription.getId()); + for (Subscription sub : info.getSubscriptions(destinationPattern)) { + result.add(info.sessionId, sub.getId()); } } } @@ -287,27 +287,23 @@ public class DefaultSubscriptionRegistry extends AbstractSubscriptionRegistry { public void updateAfterNewSubscription(String destination, String sessionId, String subsId) { synchronized (this.updateCache) { - for (Map.Entry> entry : this.updateCache.entrySet()) { - String cachedDestination = entry.getKey(); + this.updateCache.forEach((cachedDestination, subscriptions) -> { if (getPathMatcher().match(destination, cachedDestination)) { - LinkedMultiValueMap subs = entry.getValue(); // Subscription id's may also be populated via getSubscriptions() - List subsForSession = subs.get(sessionId); + List subsForSession = subscriptions.get(sessionId); if (subsForSession == null || !subsForSession.contains(subsId)) { - subs.add(sessionId, subsId); - this.accessCache.put(cachedDestination, subs.deepCopy()); + subscriptions.add(sessionId, subsId); + this.accessCache.put(cachedDestination, subscriptions.deepCopy()); } } - } + }); } } public void updateAfterRemovedSubscription(String sessionId, String subsId) { synchronized (this.updateCache) { Set destinationsToRemove = new HashSet<>(); - for (Map.Entry> entry : this.updateCache.entrySet()) { - String destination = entry.getKey(); - LinkedMultiValueMap sessionMap = entry.getValue(); + this.updateCache.forEach((destination, sessionMap) -> { List subscriptions = sessionMap.get(sessionId); if (subscriptions != null) { subscriptions.remove(subsId); @@ -321,7 +317,7 @@ public class DefaultSubscriptionRegistry extends AbstractSubscriptionRegistry { this.accessCache.put(destination, sessionMap.deepCopy()); } } - } + }); for (String destination : destinationsToRemove) { this.updateCache.remove(destination); this.accessCache.remove(destination); @@ -332,9 +328,7 @@ public class DefaultSubscriptionRegistry extends AbstractSubscriptionRegistry { public void updateAfterRemovedSession(SessionSubscriptionInfo info) { synchronized (this.updateCache) { Set destinationsToRemove = new HashSet<>(); - for (Map.Entry> entry : this.updateCache.entrySet()) { - String destination = entry.getKey(); - LinkedMultiValueMap sessionMap = entry.getValue(); + this.updateCache.forEach((destination, sessionMap) -> { if (sessionMap.remove(info.getSessionId()) != null) { if (sessionMap.isEmpty()) { destinationsToRemove.add(destination); @@ -343,7 +337,7 @@ public class DefaultSubscriptionRegistry extends AbstractSubscriptionRegistry { this.accessCache.put(destination, sessionMap.deepCopy()); } } - } + }); for (String destination : destinationsToRemove) { this.updateCache.remove(destination); this.accessCache.remove(destination); @@ -433,13 +427,9 @@ public class DefaultSubscriptionRegistry extends AbstractSubscriptionRegistry { public Subscription getSubscription(String subscriptionId) { for (Map.Entry> destinationEntry : this.destinationLookup.entrySet()) { - - Set subs = destinationEntry.getValue(); - if (subs != null) { - for (Subscription sub : subs) { - if (sub.getId().equalsIgnoreCase(subscriptionId)) { - return sub; - } + for (Subscription sub : destinationEntry.getValue()) { + if (sub.getId().equalsIgnoreCase(subscriptionId)) { + return sub; } } } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandler.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandler.java index 21c2067d162..c2b884ffd54 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandler.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandler.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. @@ -19,7 +19,6 @@ package org.springframework.messaging.simp.broker; import java.security.Principal; import java.util.Arrays; import java.util.Collection; -import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; @@ -352,11 +351,11 @@ public class SimpleBrokerMessageHandler extends AbstractBrokerMessageHandler { logger.debug("Broadcasting to " + subscriptions.size() + " sessions."); } long now = System.currentTimeMillis(); - for (Map.Entry> subscriptionEntry : subscriptions.entrySet()) { - for (String subscriptionId : subscriptionEntry.getValue()) { + subscriptions.forEach((sessionId, subscriptionIds) -> { + for (String subscriptionId : subscriptionIds) { SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE); initHeaders(headerAccessor); - headerAccessor.setSessionId(subscriptionEntry.getKey()); + headerAccessor.setSessionId(sessionId); headerAccessor.setSubscriptionId(subscriptionId); headerAccessor.copyHeadersIfAbsent(message.getHeaders()); Object payload = message.getPayload(); @@ -370,13 +369,13 @@ public class SimpleBrokerMessageHandler extends AbstractBrokerMessageHandler { } } finally { - SessionInfo info = this.sessions.get(subscriptionEntry.getKey()); + SessionInfo info = this.sessions.get(sessionId); if (info != null) { info.setLastWriteTime(now); } } } - } + }); } @Override diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SubscriptionRegistry.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SubscriptionRegistry.java index ac9dc15e543..c16b914026e 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SubscriptionRegistry.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SubscriptionRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 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. @@ -45,11 +45,11 @@ public interface SubscriptionRegistry { void unregisterAllSubscriptions(String sessionId); /** - * Find all subscriptions that should receive the given message. The map - * returned is safe to iterate and will never be modified. + * Find all subscriptions that should receive the given message. + * The map returned is safe to iterate and will never be modified. * @param message the message - * @return a {@code MultiValueMap} with sessionId-subscriptionId pairs, - * possibly empty. + * @return a {@code MultiValueMap} with sessionId-subscriptionId pairs + * (possibly empty) */ MultiValueMap findSubscriptions(Message message); diff --git a/spring-web/src/main/java/org/springframework/http/HttpHeaders.java b/spring-web/src/main/java/org/springframework/http/HttpHeaders.java index adfe99afe23..961662aad25 100644 --- a/spring-web/src/main/java/org/springframework/http/HttpHeaders.java +++ b/spring-web/src/main/java/org/springframework/http/HttpHeaders.java @@ -416,12 +416,8 @@ public class HttpHeaders implements MultiValueMap, Serializable private HttpHeaders(Map> headers, boolean readOnly) { Assert.notNull(headers, "'headers' must not be null"); if (readOnly) { - Map> map = - new LinkedCaseInsensitiveMap<>(headers.size(), Locale.ENGLISH); - for (Entry> entry : headers.entrySet()) { - List values = Collections.unmodifiableList(entry.getValue()); - map.put(entry.getKey(), values); - } + Map> map = new LinkedCaseInsensitiveMap<>(headers.size(), Locale.ENGLISH); + headers.forEach((key, valueList) -> map.put(key, Collections.unmodifiableList(valueList))); this.headers = Collections.unmodifiableMap(map); } else { @@ -1438,9 +1434,7 @@ public class HttpHeaders implements MultiValueMap, Serializable @Override public void addAll(MultiValueMap values) { - for (Entry> entry : values.entrySet()) { - addAll(entry.getKey(), entry.getValue()); - } + values.forEach(this::addAll); } /** @@ -1460,17 +1454,13 @@ public class HttpHeaders implements MultiValueMap, Serializable @Override public void setAll(Map values) { - for (Entry entry : values.entrySet()) { - set(entry.getKey(), entry.getValue()); - } + values.forEach(this::set); } @Override public Map toSingleValueMap() { LinkedHashMap singleValueMap = new LinkedHashMap<>(this.headers.size()); - for (Entry> entry : this.headers.entrySet()) { - singleValueMap.put(entry.getKey(), entry.getValue().get(0)); - } + this.headers.forEach((key, valueList) -> singleValueMap.put(key, valueList.get(0))); return singleValueMap; } diff --git a/spring-web/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequest.java b/spring-web/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequest.java index a605a67683b..324925bff33 100644 --- a/spring-web/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequest.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. @@ -18,8 +18,6 @@ package org.springframework.http.client; import java.io.IOException; import java.net.URI; -import java.util.List; -import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; @@ -97,19 +95,18 @@ final class HttpComponentsClientHttpRequest extends AbstractBufferingClientHttpR * @param headers the headers to add */ static void addHeaders(HttpUriRequest httpRequest, HttpHeaders headers) { - for (Map.Entry> entry : headers.entrySet()) { - String headerName = entry.getKey(); + headers.forEach((headerName, headerValues) -> { if (HttpHeaders.COOKIE.equalsIgnoreCase(headerName)) { // RFC 6265 - String headerValue = StringUtils.collectionToDelimitedString(entry.getValue(), "; "); + String headerValue = StringUtils.collectionToDelimitedString(headerValues, "; "); httpRequest.addHeader(headerName, headerValue); } else if (!HTTP.CONTENT_LEN.equalsIgnoreCase(headerName) && !HTTP.TRANSFER_ENCODING.equalsIgnoreCase(headerName)) { - for (String headerValue : entry.getValue()) { + for (String headerValue : headerValues) { httpRequest.addHeader(headerName, headerValue); } } - } + }); } } diff --git a/spring-web/src/main/java/org/springframework/http/client/Netty4ClientHttpRequest.java b/spring-web/src/main/java/org/springframework/http/client/Netty4ClientHttpRequest.java index 5d9820c2fbf..9a64e6cc0c3 100644 --- a/spring-web/src/main/java/org/springframework/http/client/Netty4ClientHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/client/Netty4ClientHttpRequest.java @@ -19,8 +19,6 @@ package org.springframework.http.client; import java.io.IOException; import java.io.OutputStream; import java.net.URI; -import java.util.List; -import java.util.Map; import java.util.concurrent.ExecutionException; import io.netty.bootstrap.Bootstrap; @@ -142,9 +140,7 @@ class Netty4ClientHttpRequest extends AbstractAsyncClientHttpRequest implements nettyRequest.headers().set(HttpHeaders.HOST, this.uri.getHost() + ":" + getPort(uri)); nettyRequest.headers().set(HttpHeaders.CONNECTION, "close"); - for (Map.Entry> entry : headers.entrySet()) { - nettyRequest.headers().add(entry.getKey(), entry.getValue()); - } + headers.forEach((headerName, headerValues) -> nettyRequest.headers().add(headerName, headerValues)); if (!nettyRequest.headers().contains(HttpHeaders.CONTENT_LENGTH) && this.body.buffer().readableBytes() > 0) { nettyRequest.headers().set(HttpHeaders.CONTENT_LENGTH, this.body.buffer().readableBytes()); } diff --git a/spring-web/src/main/java/org/springframework/http/client/OkHttp3ClientHttpRequestFactory.java b/spring-web/src/main/java/org/springframework/http/client/OkHttp3ClientHttpRequestFactory.java index e160d739308..59c4f7e0591 100644 --- a/spring-web/src/main/java/org/springframework/http/client/OkHttp3ClientHttpRequestFactory.java +++ b/spring-web/src/main/java/org/springframework/http/client/OkHttp3ClientHttpRequestFactory.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. @@ -19,8 +19,6 @@ package org.springframework.http.client; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; -import java.util.List; -import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; @@ -137,12 +135,11 @@ public class OkHttp3ClientHttpRequestFactory RequestBody.create(contentType, content) : null); Request.Builder builder = new Request.Builder().url(uri.toURL()).method(method.name(), body); - for (Map.Entry> entry : headers.entrySet()) { - String headerName = entry.getKey(); - for (String headerValue : entry.getValue()) { + headers.forEach((headerName, headerValues) -> { + for (String headerValue : headerValues) { builder.addHeader(headerName, headerValue); } - } + }); return builder.build(); } diff --git a/spring-web/src/main/java/org/springframework/http/client/SimpleBufferingClientHttpRequest.java b/spring-web/src/main/java/org/springframework/http/client/SimpleBufferingClientHttpRequest.java index d422e498ddc..aade690476a 100644 --- a/spring-web/src/main/java/org/springframework/http/client/SimpleBufferingClientHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/client/SimpleBufferingClientHttpRequest.java @@ -20,8 +20,6 @@ import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; -import java.util.List; -import java.util.Map; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -93,19 +91,18 @@ final class SimpleBufferingClientHttpRequest extends AbstractBufferingClientHttp * @param headers the headers to add */ static void addHeaders(HttpURLConnection connection, HttpHeaders headers) { - for (Map.Entry> entry : headers.entrySet()) { - String headerName = entry.getKey(); + headers.forEach((headerName, headerValues) -> { if (HttpHeaders.COOKIE.equalsIgnoreCase(headerName)) { // RFC 6265 - String headerValue = StringUtils.collectionToDelimitedString(entry.getValue(), "; "); + String headerValue = StringUtils.collectionToDelimitedString(headerValues, "; "); connection.setRequestProperty(headerName, headerValue); } else { - for (String headerValue : entry.getValue()) { + for (String headerValue : headerValues) { String actualHeaderValue = headerValue != null ? headerValue : ""; connection.addRequestProperty(headerName, actualHeaderValue); } } - } + }); } } diff --git a/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpResponse.java b/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpResponse.java index 2fd1b5734a8..a88da3fb2b6 100644 --- a/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpResponse.java +++ b/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpResponse.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. @@ -21,7 +21,6 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpHeaders; @@ -99,12 +98,11 @@ public class ServletServerHttpResponse implements ServerHttpResponse { private void writeHeaders() { if (!this.headersWritten) { - for (Map.Entry> entry : this.headers.entrySet()) { - String headerName = entry.getKey(); - for (String headerValue : entry.getValue()) { + getHeaders().forEach((headerName, headerValues) -> { + for (String headerValue : headerValues) { this.servletResponse.addHeader(headerName, headerValue); } - } + }); // HttpServletResponse exposes some headers as properties: we should include those if not already present if (this.servletResponse.getContentType() == null && this.headers.getContentType() != null) { this.servletResponse.setContentType(this.headers.getContentType().toString()); diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/DefaultServerHttpRequestBuilder.java b/spring-web/src/main/java/org/springframework/http/server/reactive/DefaultServerHttpRequestBuilder.java index bb2884398a1..f357909a270 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/DefaultServerHttpRequestBuilder.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/DefaultServerHttpRequestBuilder.java @@ -20,8 +20,6 @@ import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedList; -import java.util.List; -import java.util.Map; import java.util.function.Consumer; import reactor.core.publisher.Flux; @@ -80,14 +78,8 @@ class DefaultServerHttpRequestBuilder implements ServerHttpRequest.Builder { this.originalRequest = original; } - private static void copyMultiValueMap(MultiValueMap source, - MultiValueMap destination) { - - for (Map.Entry> entry : source.entrySet()) { - K key = entry.getKey(); - List values = new LinkedList<>(entry.getValue()); - destination.put(key, values); - } + private static void copyMultiValueMap(MultiValueMap source, MultiValueMap target) { + source.forEach((key, value) -> target.put(key, new LinkedList<>(value))); } diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpResponse.java b/spring-web/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpResponse.java index b0e071c2ed8..7eb2465a180 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpResponse.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpResponse.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. @@ -17,8 +17,6 @@ package org.springframework.http.server.reactive; import java.io.File; -import java.util.List; -import java.util.Map; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpResponseStatus; @@ -85,11 +83,11 @@ class ReactorServerHttpResponse extends AbstractServerHttpResponse implements Ze @Override protected void applyHeaders() { - for (Map.Entry> entry : getHeaders().entrySet()) { - for (String value : entry.getValue()) { - this.response.responseHeaders().add(entry.getKey(), value); + getHeaders().forEach((headerName, headerValues) -> { + for (String value : headerValues) { + this.response.responseHeaders().add(headerName, value); } - } + }); } @Override diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/ServletServerHttpResponse.java b/spring-web/src/main/java/org/springframework/http/server/reactive/ServletServerHttpResponse.java index 37e12071dd0..143667a2dbc 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/ServletServerHttpResponse.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/ServletServerHttpResponse.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. @@ -19,8 +19,6 @@ package org.springframework.http.server.reactive; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; -import java.util.List; -import java.util.Map; import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; @@ -99,12 +97,11 @@ class ServletServerHttpResponse extends AbstractListenerServerHttpResponse { @Override protected void applyHeaders() { - for (Map.Entry> entry : getHeaders().entrySet()) { - String headerName = entry.getKey(); - for (String headerValue : entry.getValue()) { + getHeaders().forEach((headerName, headerValues) -> { + for (String headerValue : headerValues) { this.response.addHeader(headerName, headerValue); } - } + }); MediaType contentType = getHeaders().getContentType(); if (this.response.getContentType() == null && contentType != null) { this.response.setContentType(contentType.toString()); diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpResponse.java b/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpResponse.java index d6c93f896c9..7d93e21374a 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpResponse.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpResponse.java @@ -21,8 +21,6 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.StandardOpenOption; -import java.util.List; -import java.util.Map; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.Cookie; @@ -82,10 +80,8 @@ class UndertowServerHttpResponse extends AbstractListenerServerHttpResponse impl @Override protected void applyHeaders() { - for (Map.Entry> entry : getHeaders().entrySet()) { - HttpString headerName = HttpString.tryFromString(entry.getKey()); - this.exchange.getResponseHeaders().addAll(headerName, entry.getValue()); - } + getHeaders().forEach((headerName, headerValues) -> + this.exchange.getResponseHeaders().addAll(HttpString.tryFromString(headerName), headerValues)); } @Override diff --git a/spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBean.java b/spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBean.java index f1320608026..a68c94713ac 100644 --- a/spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBean.java +++ b/spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBean.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. @@ -21,7 +21,6 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.Map.Entry; import java.util.Properties; import javax.servlet.ServletContext; @@ -160,11 +159,11 @@ public class ContentNegotiationManagerFactoryBean */ public void setMediaTypes(Properties mediaTypes) { if (!CollectionUtils.isEmpty(mediaTypes)) { - for (Entry entry : mediaTypes.entrySet()) { - String extension = ((String)entry.getKey()).toLowerCase(Locale.ENGLISH); - MediaType mediaType = MediaType.valueOf((String) entry.getValue()); + mediaTypes.forEach((key, value) -> { + String extension = ((String) key).toLowerCase(Locale.ENGLISH); + MediaType mediaType = MediaType.valueOf((String) value); this.mediaTypes.put(extension, mediaType); - } + }); } } diff --git a/spring-web/src/main/java/org/springframework/web/accept/MappingMediaTypeFileExtensionResolver.java b/spring-web/src/main/java/org/springframework/web/accept/MappingMediaTypeFileExtensionResolver.java index 30795bdd677..7bf28fd4309 100644 --- a/spring-web/src/main/java/org/springframework/web/accept/MappingMediaTypeFileExtensionResolver.java +++ b/spring-web/src/main/java/org/springframework/web/accept/MappingMediaTypeFileExtensionResolver.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. @@ -22,7 +22,6 @@ import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -43,11 +42,9 @@ import org.springframework.util.MultiValueMap; */ public class MappingMediaTypeFileExtensionResolver implements MediaTypeFileExtensionResolver { - private final ConcurrentMap mediaTypes = - new ConcurrentHashMap<>(64); + private final ConcurrentMap mediaTypes = new ConcurrentHashMap<>(64); - private final MultiValueMap fileExtensions = - new LinkedMultiValueMap<>(); + private final MultiValueMap fileExtensions = new LinkedMultiValueMap<>(); private final List allFileExtensions = new LinkedList<>(); @@ -57,13 +54,12 @@ public class MappingMediaTypeFileExtensionResolver implements MediaTypeFileExten */ public MappingMediaTypeFileExtensionResolver(@Nullable Map mediaTypes) { if (mediaTypes != null) { - for (Entry entries : mediaTypes.entrySet()) { - String extension = entries.getKey().toLowerCase(Locale.ENGLISH); - MediaType mediaType = entries.getValue(); - this.mediaTypes.put(extension, mediaType); - this.fileExtensions.add(mediaType, extension); - this.allFileExtensions.add(extension); - } + mediaTypes.forEach((extension, mediaType) -> { + String lowerCaseExtension = extension.toLowerCase(Locale.ENGLISH); + this.mediaTypes.put(lowerCaseExtension, mediaType); + this.fileExtensions.add(mediaType, lowerCaseExtension); + this.allFileExtensions.add(lowerCaseExtension); + }); } } @@ -91,7 +87,7 @@ public class MappingMediaTypeFileExtensionResolver implements MediaTypeFileExten @Override public List resolveFileExtensions(MediaType mediaType) { List fileExtensions = this.fileExtensions.get(mediaType); - return (fileExtensions != null) ? fileExtensions : Collections.emptyList(); + return (fileExtensions != null ? fileExtensions : Collections.emptyList()); } @Override diff --git a/spring-web/src/main/java/org/springframework/web/bind/WebDataBinder.java b/spring-web/src/main/java/org/springframework/web/bind/WebDataBinder.java index 2a627dbd854..923f9427395 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/WebDataBinder.java +++ b/spring-web/src/main/java/org/springframework/web/bind/WebDataBinder.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. @@ -315,9 +315,7 @@ public class WebDataBinder extends DataBinder { * @see #setBindEmptyMultipartFiles */ protected void bindMultipart(Map> multipartFiles, MutablePropertyValues mpvs) { - for (Map.Entry> entry : multipartFiles.entrySet()) { - String key = entry.getKey(); - List values = entry.getValue(); + multipartFiles.forEach((key, values) -> { if (values.size() == 1) { MultipartFile value = values.get(0); if (isBindEmptyMultipartFiles() || !value.isEmpty()) { @@ -327,7 +325,7 @@ public class WebDataBinder extends DataBinder { else { mpvs.add(key, values); } - } + }); } } diff --git a/spring-web/src/main/java/org/springframework/web/bind/support/WebRequestDataBinder.java b/spring-web/src/main/java/org/springframework/web/bind/support/WebRequestDataBinder.java index b0c40c40e79..d466731ad53 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/support/WebRequestDataBinder.java +++ b/spring-web/src/main/java/org/springframework/web/bind/support/WebRequestDataBinder.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. @@ -16,8 +16,6 @@ package org.springframework.web.bind.support; -import java.util.List; -import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Part; @@ -141,17 +139,17 @@ public class WebRequestDataBinder extends WebDataBinder { for (Part part : request.getParts()) { map.add(part.getName(), part); } - for (Map.Entry> entry: map.entrySet()) { - if (entry.getValue().size() == 1) { - Part part = entry.getValue().get(0); + map.forEach((key, values) -> { + if (values.size() == 1) { + Part part = values.get(0); if (isBindEmptyMultipartFiles() || part.getSize() > 0) { - mpvs.add(entry.getKey(), part); + mpvs.add(key, part); } } else { - mpvs.add(entry.getKey(), entry.getValue()); + mpvs.add(key, values); } - } + }); } catch (Exception ex) { throw new MultipartException("Failed to get request parts", ex); diff --git a/spring-web/src/main/java/org/springframework/web/client/RestTemplate.java b/spring-web/src/main/java/org/springframework/web/client/RestTemplate.java index a9bc98c2963..18b41589a6f 100644 --- a/spring-web/src/main/java/org/springframework/web/client/RestTemplate.java +++ b/spring-web/src/main/java/org/springframework/web/client/RestTemplate.java @@ -912,9 +912,7 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat HttpHeaders httpHeaders = httpRequest.getHeaders(); HttpHeaders requestHeaders = this.requestEntity.getHeaders(); if (!requestHeaders.isEmpty()) { - for (Map.Entry> entry : requestHeaders.entrySet()) { - httpHeaders.put(entry.getKey(), new LinkedList<>(entry.getValue())); - } + requestHeaders.forEach((key, values) -> httpHeaders.put(key, new LinkedList<>(values))); } if (httpHeaders.getContentLength() < 0) { httpHeaders.setContentLength(0L); @@ -933,9 +931,7 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat (GenericHttpMessageConverter) messageConverter; if (genericConverter.canWrite(requestBodyType, requestBodyClass, requestContentType)) { if (!requestHeaders.isEmpty()) { - for (Map.Entry> entry : requestHeaders.entrySet()) { - httpHeaders.put(entry.getKey(), new LinkedList<>(entry.getValue())); - } + requestHeaders.forEach((key, values) -> httpHeaders.put(key, new LinkedList<>(values))); } if (logger.isDebugEnabled()) { if (requestContentType != null) { @@ -953,9 +949,7 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat } else if (messageConverter.canWrite(requestBodyClass, requestContentType)) { if (!requestHeaders.isEmpty()) { - for (Map.Entry> entry : requestHeaders.entrySet()) { - httpHeaders.put(entry.getKey(), new LinkedList<>(entry.getValue())); - } + requestHeaders.forEach((key, values) -> httpHeaders.put(key, new LinkedList<>(values))); } if (logger.isDebugEnabled()) { if (requestContentType != null) { 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 7c4d9e09ee1..8e9c482c01d 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 @@ -64,20 +64,20 @@ public class RequestParamMapMethodArgumentResolver implements HandlerMethodArgum Map parameterMap = webRequest.getParameterMap(); if (MultiValueMap.class.isAssignableFrom(paramType)) { MultiValueMap result = new LinkedMultiValueMap<>(parameterMap.size()); - for (Map.Entry entry : parameterMap.entrySet()) { - for (String value : entry.getValue()) { - result.add(entry.getKey(), value); + parameterMap.forEach((key, values) -> { + for (String value : values) { + result.add(key, value); } - } + }); return result; } else { Map result = new LinkedHashMap<>(parameterMap.size()); - for (Map.Entry entry : parameterMap.entrySet()) { - if (entry.getValue().length > 0) { - result.put(entry.getKey(), entry.getValue()[0]); + parameterMap.forEach((key, values) -> { + if (values.length > 0) { + result.put(key, values[0]); } - } + }); return result; } } diff --git a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java index e8614657c8b..a0f4160cefd 100644 --- a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java +++ b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java @@ -26,7 +26,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; -import java.util.Map; import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; @@ -151,9 +150,7 @@ final class HierarchicalUriComponents extends UriComponents { public String getQuery() { if (!this.queryParams.isEmpty()) { StringBuilder queryBuilder = new StringBuilder(); - for (Map.Entry> entry : this.queryParams.entrySet()) { - String name = entry.getKey(); - List values = entry.getValue(); + this.queryParams.forEach((name, values) -> { if (CollectionUtils.isEmpty(values)) { if (queryBuilder.length() != 0) { queryBuilder.append('&'); @@ -171,7 +168,7 @@ final class HierarchicalUriComponents extends UriComponents { } } } - } + }); return queryBuilder.toString(); } else { @@ -216,14 +213,14 @@ final class HierarchicalUriComponents extends UriComponents { private MultiValueMap encodeQueryParams(Charset charset) { int size = this.queryParams.size(); MultiValueMap result = new LinkedMultiValueMap<>(size); - for (Map.Entry> entry : this.queryParams.entrySet()) { - String name = encodeUriComponent(entry.getKey(), charset, Type.QUERY_PARAM); - List values = new ArrayList<>(entry.getValue().size()); - for (String value : entry.getValue()) { - values.add(encodeUriComponent(value, charset, Type.QUERY_PARAM)); - } - result.put(name, values); - } + this.queryParams.forEach((key, values) -> { + String name = encodeUriComponent(key, charset, Type.QUERY_PARAM); + List encodedValues = new ArrayList<>(values.size()); + for (String value : values) { + encodedValues.add(encodeUriComponent(value, charset, Type.QUERY_PARAM)); + } + result.put(name, encodedValues); + }); return result; } @@ -298,12 +295,12 @@ final class HierarchicalUriComponents extends UriComponents { verifyUriComponent(this.userInfo, Type.USER_INFO); verifyUriComponent(this.host, getHostType()); this.path.verify(); - for (Map.Entry> entry : queryParams.entrySet()) { - verifyUriComponent(entry.getKey(), Type.QUERY_PARAM); - for (String value : entry.getValue()) { + this.queryParams.forEach((key, values) -> { + verifyUriComponent(key, Type.QUERY_PARAM); + for (String value : values) { verifyUriComponent(value, Type.QUERY_PARAM); } - } + }); verifyUriComponent(getFragment(), Type.FRAGMENT); } @@ -360,15 +357,15 @@ final class HierarchicalUriComponents extends UriComponents { private MultiValueMap expandQueryParams(UriTemplateVariables variables) { int size = this.queryParams.size(); MultiValueMap result = new LinkedMultiValueMap<>(size); - variables = new QueryUriTemplateVariables(variables); - for (Map.Entry> entry : this.queryParams.entrySet()) { - String name = expandUriComponent(entry.getKey(), variables); - List values = new ArrayList<>(entry.getValue().size()); - for (String value : entry.getValue()) { - values.add(expandUriComponent(value, variables)); - } - result.put(name, values); - } + UriTemplateVariables queryVariables = new QueryUriTemplateVariables(variables); + this.queryParams.forEach((key, values) -> { + String name = expandUriComponent(key, queryVariables); + List expandedValues = new ArrayList<>(values.size()); + for (String value : values) { + expandedValues.add(expandUriComponent(value, queryVariables)); + } + result.put(name, expandedValues); + }); return result; } diff --git a/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java b/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java index ecb455e3d15..feefad65408 100644 --- a/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java +++ b/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.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. @@ -20,7 +20,6 @@ import java.net.URLDecoder; import java.nio.charset.UnsupportedCharsetException; import java.util.LinkedHashMap; import java.util.Map; -import java.util.Map.Entry; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; @@ -544,9 +543,7 @@ public class UrlPathHelper { } else { Map decodedVars = new LinkedHashMap<>(vars.size()); - for (Entry entry : vars.entrySet()) { - decodedVars.put(entry.getKey(), decodeInternal(request, entry.getValue())); - } + vars.forEach((key, value) -> decodedVars.put(key, decodeInternal(request, value))); return decodedVars; } } diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyExtractors.java b/spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyExtractors.java index 1d9dafde53f..2fad402232b 100644 --- a/spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyExtractors.java +++ b/spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyExtractors.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. @@ -36,7 +36,6 @@ import org.springframework.http.codec.HttpMessageReader; import org.springframework.http.codec.multipart.Part; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; -import org.springframework.util.Assert; import org.springframework.util.MultiValueMap; /** @@ -65,7 +64,6 @@ public abstract class BodyExtractors { * @return a {@code BodyExtractor} that reads a mono */ public static BodyExtractor, ReactiveHttpInputMessage> toMono(Class elementClass) { - Assert.notNull(elementClass, "'elementClass' must not be null"); return toMono(ResolvableType.forClass(elementClass)); } @@ -87,12 +85,10 @@ public abstract class BodyExtractors { public static BodyExtractor, ReactiveHttpInputMessage> toMono( ParameterizedTypeReference typeReference) { - Assert.notNull(typeReference, "'typeReference' must not be null"); return toMono(ResolvableType.forType(typeReference.getType())); } static BodyExtractor, ReactiveHttpInputMessage> toMono(ResolvableType elementType) { - Assert.notNull(elementType, "'elementType' must not be null"); return (inputMessage, context) -> readWithMessageReaders(inputMessage, context, elementType, (HttpMessageReader reader) -> { @@ -117,7 +113,6 @@ public abstract class BodyExtractors { * @return a {@code BodyExtractor} that reads a flux */ public static BodyExtractor, ReactiveHttpInputMessage> toFlux(Class elementClass) { - Assert.notNull(elementClass, "'elementClass' must not be null"); return toFlux(ResolvableType.forClass(elementClass)); } @@ -139,13 +134,11 @@ public abstract class BodyExtractors { public static BodyExtractor, ReactiveHttpInputMessage> toFlux( ParameterizedTypeReference typeReference) { - Assert.notNull(typeReference, "'typeReference' must not be null"); return toFlux(ResolvableType.forType(typeReference.getType())); } @SuppressWarnings("unchecked") static BodyExtractor, ReactiveHttpInputMessage> toFlux(ResolvableType elementType) { - Assert.notNull(elementType, "'elementType' must not be null"); return (inputMessage, context) -> readWithMessageReaders(inputMessage, context, elementType, (HttpMessageReader reader) -> { diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyInserters.java b/spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyInserters.java index f1a0cfbdebd..5c043d0a298 100644 --- a/spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyInserters.java +++ b/spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyInserters.java @@ -17,7 +17,6 @@ package org.springframework.web.reactive.function; import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; @@ -87,7 +86,6 @@ public abstract class BodyInserters { * @return a {@code BodyInserter} that writes a single object */ public static BodyInserter fromObject(T body) { - Assert.notNull(body, "'body' must not be null"); return bodyInserterFor(Mono.just(body), ResolvableType.forInstance(body)); } @@ -106,8 +104,6 @@ public abstract class BodyInserters { public static > BodyInserter fromPublisher( P publisher, Class elementClass) { - Assert.notNull(publisher, "'publisher' must not be null"); - Assert.notNull(elementClass, "'elementClass' must not be null"); return bodyInserterFor(publisher, ResolvableType.forClass(elementClass)); } @@ -126,8 +122,6 @@ public abstract class BodyInserters { public static > BodyInserter fromPublisher( P publisher, ParameterizedTypeReference typeReference) { - Assert.notNull(publisher, "'publisher' must not be null"); - Assert.notNull(typeReference, "'typeReference' must not be null"); return bodyInserterFor(publisher, ResolvableType.forType(typeReference.getType())); } @@ -140,7 +134,6 @@ public abstract class BodyInserters { * @return a {@code BodyInserter} that writes a {@code Publisher} */ public static BodyInserter fromResource(T resource) { - Assert.notNull(resource, "'resource' must not be null"); return (outputMessage, context) -> { Mono inputStream = Mono.just(resource); HttpMessageWriter messageWriter = resourceHttpMessageWriter(context); @@ -180,7 +173,6 @@ public abstract class BodyInserters { public static >> BodyInserter fromServerSentEvents( S eventsPublisher) { - Assert.notNull(eventsPublisher, "'eventsPublisher' must not be null"); return (serverResponse, context) -> { HttpMessageWriter> messageWriter = findMessageWriter(context, SERVER_SIDE_EVENT_TYPE, MediaType.TEXT_EVENT_STREAM); @@ -208,7 +200,6 @@ public abstract class BodyInserters { * @return the inserter that allows adding more form data */ public static FormInserter fromFormData(MultiValueMap formData) { - Assert.notNull(formData, "'formData' must not be null"); return new DefaultFormInserter().with(formData); } @@ -389,7 +380,7 @@ public abstract class BodyInserters { * @param value the value to be added * @return this inserter for adding more parts */ - FormInserter with(String key, @Nullable T value); + FormInserter with(String key, T value); /** * Adds the specified values to the form. @@ -435,11 +426,6 @@ public abstract class BodyInserters { private final MultiValueMap data = new LinkedMultiValueMap<>(); - - public DefaultFormInserter() { - } - - @Override public FormInserter with(String key, @Nullable String value) { this.data.add(key, value); @@ -467,14 +453,8 @@ public abstract class BodyInserters { private final MultipartBodyBuilder builder = new MultipartBodyBuilder(); - - public DefaultMultipartInserter() { - } - - @Override - public MultipartInserter with(String key, @Nullable Object value) { - Assert.notNull(value, "'value' must not be null"); + public MultipartInserter with(String key, Object value) { this.builder.part(key, value); return this; } @@ -486,26 +466,25 @@ public abstract class BodyInserters { @SuppressWarnings("unchecked") private MultipartInserter withInternal(MultiValueMap values) { - Assert.notNull(values, "'values' must not be null"); - for (Map.Entry> entry : values.entrySet()) { - for (Object value : entry.getValue()) { - this.builder.part(entry.getKey(), value); + values.forEach((key, valueList) -> { + for (Object value : valueList) { + this.builder.part(key, value); } - } + }); return this; } @Override - public > MultipartInserter withPublisher(String name, - P publisher, Class elementClass) { + public > MultipartInserter withPublisher( + String name, P publisher, Class elementClass) { this.builder.asyncPart(name, publisher, elementClass); return this; } @Override - public > MultipartInserter withPublisher(String name, - P publisher, ParameterizedTypeReference typeReference) { + public > MultipartInserter withPublisher( + String name, P publisher, ParameterizedTypeReference typeReference) { this.builder.asyncPart(name, publisher, typeReference); return this; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java index 8247c9f0331..8c71b363463 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java @@ -245,11 +245,10 @@ public abstract class AbstractHandlerMethodMapping extends AbstractHandlerMap if (logger.isDebugEnabled()) { logger.debug(methods.size() + " request handler methods found on " + userType + ": " + methods); } - for (Map.Entry entry : methods.entrySet()) { - Method invocableMethod = AopUtils.selectInvocableMethod(entry.getKey(), userType); - T mapping = entry.getValue(); + methods.forEach((method, mapping) -> { + Method invocableMethod = AopUtils.selectInvocableMethod(method, userType); registerHandlerMethod(handler, invocableMethod, mapping); - } + }); } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java index e70540a1318..b7da900e024 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java @@ -23,7 +23,6 @@ import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -470,7 +469,7 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce } } - for (Entry entry : this.exceptionHandlerAdviceCache.entrySet()) { + for (Map.Entry entry : this.exceptionHandlerAdviceCache.entrySet()) { ControllerAdviceBean advice = entry.getKey(); if (advice.isApplicableToBeanType(handlerType)) { ExceptionHandlerMethodResolver resolver = entry.getValue(); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java index 01de47e9058..ac5457119ca 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java @@ -700,10 +700,9 @@ public class ResourceHttpRequestHandler extends WebContentGenerator } if (resource instanceof HttpResource) { HttpHeaders resourceHeaders = ((HttpResource) resource).getResponseHeaders(); - for (Map.Entry> entry : resourceHeaders.entrySet()) { - String headerName = entry.getKey(); + resourceHeaders.forEach((headerName, headerValues) -> { boolean first = true; - for (String headerValue : entry.getValue()) { + for (String headerValue : headerValues) { if (first) { response.setHeader(headerName, headerValue); } @@ -712,7 +711,7 @@ public class ResourceHttpRequestHandler extends WebContentGenerator } first = false; } - } + }); } response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes"); } diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/WebSocketExtension.java b/spring-websocket/src/main/java/org/springframework/web/socket/WebSocketExtension.java index be885c34602..4a80e48a909 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/WebSocketExtension.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/WebSocketExtension.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. @@ -119,12 +119,7 @@ public class WebSocketExtension { public String toString() { StringBuilder str = new StringBuilder(); str.append(this.name); - for (Map.Entry entry : this.parameters.entrySet()) { - str.append(';'); - str.append(entry.getKey()); - str.append('='); - str.append(entry.getValue()); - } + this.parameters.forEach((key, value) -> str.append(';').append(key).append('=').append(value)); return str.toString(); } diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/adapter/jetty/WebSocketToJettyExtensionConfigAdapter.java b/spring-websocket/src/main/java/org/springframework/web/socket/adapter/jetty/WebSocketToJettyExtensionConfigAdapter.java index 45fab4637b8..4a8c2de0e1f 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/adapter/jetty/WebSocketToJettyExtensionConfigAdapter.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/adapter/jetty/WebSocketToJettyExtensionConfigAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 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. @@ -16,8 +16,6 @@ package org.springframework.web.socket.adapter.jetty; -import java.util.Map; - import org.eclipse.jetty.websocket.api.extensions.ExtensionConfig; import org.springframework.web.socket.WebSocketExtension; @@ -30,8 +28,7 @@ public class WebSocketToJettyExtensionConfigAdapter extends ExtensionConfig { public WebSocketToJettyExtensionConfigAdapter(WebSocketExtension extension) { super(extension.getName()); - for (Map.Entry p : extension.getParameters().entrySet()) { - super.setParameter(p.getKey(), p.getValue()); - } + extension.getParameters().forEach(super::setParameter); } + } diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/server/standard/GlassFishRequestUpgradeStrategy.java b/spring-websocket/src/main/java/org/springframework/web/socket/server/standard/GlassFishRequestUpgradeStrategy.java index dc7c60181d4..d1fb09584e5 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/server/standard/GlassFishRequestUpgradeStrategy.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/server/standard/GlassFishRequestUpgradeStrategy.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. @@ -18,8 +18,6 @@ package org.springframework.web.socket.server.standard; import java.io.IOException; import java.lang.reflect.Constructor; -import java.util.List; -import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -67,9 +65,7 @@ public class GlassFishRequestUpgradeStrategy extends AbstractTyrusRequestUpgrade handler.preInit(upgradeInfo, servletWriter, request.getUserPrincipal() != null); response.setStatus(upgradeResponse.getStatus()); - for (Map.Entry> entry : upgradeResponse.getHeaders().entrySet()) { - response.addHeader(entry.getKey(), Utils.getHeaderFromList(entry.getValue())); - } + upgradeResponse.getHeaders().forEach((key, value) -> response.addHeader(key, Utils.getHeaderFromList(value))); response.flushBuffer(); } diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/server/standard/WebLogicRequestUpgradeStrategy.java b/spring-websocket/src/main/java/org/springframework/web/socket/server/standard/WebLogicRequestUpgradeStrategy.java index 16bda831e2a..d513e37facb 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/server/standard/WebLogicRequestUpgradeStrategy.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/server/standard/WebLogicRequestUpgradeStrategy.java @@ -19,8 +19,6 @@ package org.springframework.web.socket.server.standard; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; -import java.util.List; -import java.util.Map; import javax.servlet.AsyncContext; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -63,9 +61,7 @@ public class WebLogicRequestUpgradeStrategy extends AbstractTyrusRequestUpgradeS UpgradeInfo upgradeInfo, TyrusUpgradeResponse upgradeResponse) throws IOException, ServletException { response.setStatus(upgradeResponse.getStatus()); - for (Map.Entry> entry : upgradeResponse.getHeaders().entrySet()) { - response.addHeader(entry.getKey(), Utils.getHeaderFromList(entry.getValue())); - } + upgradeResponse.getHeaders().forEach((key, value) -> response.addHeader(key, Utils.getHeaderFromList(value))); AsyncContext asyncContext = request.startAsync(); asyncContext.setTimeout(-1L); diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/JettyXhrTransport.java b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/JettyXhrTransport.java index 06a2660538a..f9bf6c4071a 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/JettyXhrTransport.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/JettyXhrTransport.java @@ -20,8 +20,6 @@ import java.io.ByteArrayOutputStream; import java.net.URI; import java.nio.ByteBuffer; import java.util.Enumeration; -import java.util.List; -import java.util.Map; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; @@ -161,11 +159,11 @@ public class JettyXhrTransport extends AbstractXhrTransport implements Lifecycle private static void addHttpHeaders(Request request, HttpHeaders headers) { - for (Map.Entry> entry : headers.entrySet()) { - for (String value : entry.getValue()) { - request.header(entry.getKey(), value); + headers.forEach((key, values) -> { + for (String value : values) { + request.header(key, value); } - } + }); } private static HttpHeaders toHttpHeaders(HttpFields httpFields) { diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/UndertowXhrTransport.java b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/UndertowXhrTransport.java index c2611c7e76f..50f9783e164 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/UndertowXhrTransport.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/UndertowXhrTransport.java @@ -21,7 +21,6 @@ import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.util.List; -import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; @@ -171,11 +170,11 @@ public class UndertowXhrTransport extends AbstractXhrTransport { private static void addHttpHeaders(ClientRequest request, HttpHeaders headers) { HeaderMap headerMap = request.getRequestHeaders(); - for (Map.Entry> entry : headers.entrySet()) { - for (String value : entry.getValue()) { - headerMap.add(HttpString.tryFromString(entry.getKey()), value); + headers.forEach((key, values) -> { + for (String value : values) { + headerMap.add(HttpString.tryFromString(key), value); } - } + }); } private ClientCallback createReceiveCallback(final TransportRequest transportRequest,