diff --git a/spring-web/src/main/java/org/springframework/http/ContentDisposition.java b/spring-web/src/main/java/org/springframework/http/ContentDisposition.java index 1d5254e336..63149ae9e0 100644 --- a/spring-web/src/main/java/org/springframework/http/ContentDisposition.java +++ b/spring-web/src/main/java/org/springframework/http/ContentDisposition.java @@ -212,10 +212,9 @@ public final class ContentDisposition { if (this == other) { return true; } - if (!(other instanceof ContentDisposition)) { + if (!(other instanceof ContentDisposition otherCd)) { return false; } - ContentDisposition otherCd = (ContentDisposition) other; return (ObjectUtils.nullSafeEquals(this.type, otherCd.type) && ObjectUtils.nullSafeEquals(this.name, otherCd.name) && ObjectUtils.nullSafeEquals(this.filename, otherCd.filename) && diff --git a/spring-web/src/main/java/org/springframework/http/HttpCookie.java b/spring-web/src/main/java/org/springframework/http/HttpCookie.java index e09070c9bf..c09cdc947f 100644 --- a/spring-web/src/main/java/org/springframework/http/HttpCookie.java +++ b/spring-web/src/main/java/org/springframework/http/HttpCookie.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2021 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. @@ -66,10 +66,9 @@ public class HttpCookie { if (this == other) { return true; } - if (!(other instanceof HttpCookie)) { + if (!(other instanceof HttpCookie otherCookie)) { return false; } - HttpCookie otherCookie = (HttpCookie) other; return (this.name.equalsIgnoreCase(otherCookie.getName())); } diff --git a/spring-web/src/main/java/org/springframework/http/HttpRange.java b/spring-web/src/main/java/org/springframework/http/HttpRange.java index ae591cd335..25159745e5 100644 --- a/spring-web/src/main/java/org/springframework/http/HttpRange.java +++ b/spring-web/src/main/java/org/springframework/http/HttpRange.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -272,10 +272,9 @@ public abstract class HttpRange { if (this == other) { return true; } - if (!(other instanceof ByteRange)) { + if (!(other instanceof ByteRange otherRange)) { return false; } - ByteRange otherRange = (ByteRange) other; return (this.firstPos == otherRange.firstPos && ObjectUtils.nullSafeEquals(this.lastPos, otherRange.lastPos)); } @@ -335,10 +334,9 @@ public abstract class HttpRange { if (this == other) { return true; } - if (!(other instanceof SuffixByteRange)) { + if (!(other instanceof SuffixByteRange otherRange)) { return false; } - SuffixByteRange otherRange = (SuffixByteRange) other; return (this.suffixLength == otherRange.suffixLength); } diff --git a/spring-web/src/main/java/org/springframework/http/MediaType.java b/spring-web/src/main/java/org/springframework/http/MediaType.java index ec57d77a5a..dfd68464b4 100644 --- a/spring-web/src/main/java/org/springframework/http/MediaType.java +++ b/spring-web/src/main/java/org/springframework/http/MediaType.java @@ -691,8 +691,8 @@ public class MediaType extends MimeType implements Serializable { * @since 5.0 */ public static MediaType asMediaType(MimeType mimeType) { - if (mimeType instanceof MediaType) { - return (MediaType) mimeType; + if (mimeType instanceof MediaType mediaType) { + return mediaType; } return new MediaType(mimeType.getType(), mimeType.getSubtype(), mimeType.getParameters()); } @@ -817,7 +817,7 @@ public class MediaType extends MimeType implements Serializable { /** * Comparator used by {@link #sortBySpecificity(List)}. */ - public static final Comparator SPECIFICITY_COMPARATOR = new SpecificityComparator() { + public static final Comparator SPECIFICITY_COMPARATOR = new SpecificityComparator<>() { @Override protected int compareParameters(MediaType mediaType1, MediaType mediaType2) { diff --git a/spring-web/src/main/java/org/springframework/http/ResponseCookie.java b/spring-web/src/main/java/org/springframework/http/ResponseCookie.java index bada6e5598..cd0a19f0b5 100644 --- a/spring-web/src/main/java/org/springframework/http/ResponseCookie.java +++ b/spring-web/src/main/java/org/springframework/http/ResponseCookie.java @@ -134,10 +134,9 @@ public final class ResponseCookie extends HttpCookie { if (this == other) { return true; } - if (!(other instanceof ResponseCookie)) { + if (!(other instanceof ResponseCookie otherCookie)) { return false; } - ResponseCookie otherCookie = (ResponseCookie) other; return (getName().equalsIgnoreCase(otherCookie.getName()) && ObjectUtils.nullSafeEquals(this.path, otherCookie.getPath()) && ObjectUtils.nullSafeEquals(this.domain, otherCookie.getDomain())); 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 e1b328df0f..5803e19f92 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-2018 the original author or authors. + * Copyright 2002-2021 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. @@ -79,8 +79,7 @@ final class HttpComponentsClientHttpRequest extends AbstractBufferingClientHttpR protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException { addHeaders(this.httpRequest, headers); - if (this.httpRequest instanceof HttpEntityEnclosingRequest) { - HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) this.httpRequest; + if (this.httpRequest instanceof HttpEntityEnclosingRequest entityEnclosingRequest) { HttpEntity requestEntity = new ByteArrayEntity(bufferedOutput); entityEnclosingRequest.setEntity(requestEntity); } diff --git a/spring-web/src/main/java/org/springframework/http/client/HttpComponentsStreamingClientHttpRequest.java b/spring-web/src/main/java/org/springframework/http/client/HttpComponentsStreamingClientHttpRequest.java index 7b145e2a30..ed0cc19fa7 100644 --- a/spring-web/src/main/java/org/springframework/http/client/HttpComponentsStreamingClientHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/client/HttpComponentsStreamingClientHttpRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2021 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. @@ -90,8 +90,7 @@ final class HttpComponentsStreamingClientHttpRequest extends AbstractClientHttpR protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException { HttpComponentsClientHttpRequest.addHeaders(this.httpRequest, headers); - if (this.httpRequest instanceof HttpEntityEnclosingRequest && this.body != null) { - HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) this.httpRequest; + if (this.httpRequest instanceof HttpEntityEnclosingRequest entityEnclosingRequest && this.body != null) { HttpEntity requestEntity = new StreamingHttpEntity(getHeaders(), this.body); entityEnclosingRequest.setEntity(requestEntity); } diff --git a/spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java b/spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java index 8b75f7e31a..57198a5e69 100644 --- a/spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -41,9 +41,9 @@ class InterceptingClientHttpRequest extends AbstractBufferingClientHttpRequest { private final List interceptors; - private HttpMethod method; + private final HttpMethod method; - private URI uri; + private final URI uri; protected InterceptingClientHttpRequest(ClientHttpRequestFactory requestFactory, @@ -98,8 +98,7 @@ class InterceptingClientHttpRequest extends AbstractBufferingClientHttpRequest { ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), method); request.getHeaders().forEach((key, value) -> delegate.getHeaders().addAll(key, value)); if (body.length > 0) { - if (delegate instanceof StreamingHttpOutputMessage) { - StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) delegate; + if (delegate instanceof StreamingHttpOutputMessage streamingOutputMessage) { streamingOutputMessage.setBody(outputStream -> StreamUtils.copy(body, outputStream)); } else { diff --git a/spring-web/src/main/java/org/springframework/http/client/MultipartBodyBuilder.java b/spring-web/src/main/java/org/springframework/http/client/MultipartBodyBuilder.java index 9d76f72f15..c80e3c56e2 100644 --- a/spring-web/src/main/java/org/springframework/http/client/MultipartBodyBuilder.java +++ b/spring-web/src/main/java/org/springframework/http/client/MultipartBodyBuilder.java @@ -83,6 +83,7 @@ import org.springframework.util.MultiValueMap; * * @author Arjen Poutsma * @author Rossen Stoyanchev + * @author Sam Brannen * @since 5.0.2 * @see RFC 7578 */ @@ -127,8 +128,7 @@ public final class MultipartBodyBuilder { Assert.hasLength(name, "'name' must not be empty"); Assert.notNull(part, "'part' must not be null"); - if (part instanceof Part) { - Part partObject = (Part) part; + if (part instanceof Part partObject) { PartBuilder builder = asyncPart(name, partObject.content(), DataBuffer.class); if (!partObject.headers().isEmpty()) { builder.headers(headers -> { @@ -144,8 +144,8 @@ public final class MultipartBodyBuilder { return builder; } - if (part instanceof PublisherEntity) { - PublisherPartBuilder builder = new PublisherPartBuilder<>(name, (PublisherEntity) part); + if (part instanceof PublisherEntity publisherEntity) { + PublisherPartBuilder builder = new PublisherPartBuilder<>(name, publisherEntity); if (contentType != null) { builder.contentType(contentType); } @@ -155,20 +155,20 @@ public final class MultipartBodyBuilder { Object partBody; HttpHeaders partHeaders = null; - if (part instanceof HttpEntity) { - partBody = ((HttpEntity) part).getBody(); + if (part instanceof HttpEntity httpEntity) { + partBody = httpEntity.getBody(); partHeaders = new HttpHeaders(); - partHeaders.putAll(((HttpEntity) part).getHeaders()); + partHeaders.putAll(httpEntity.getHeaders()); } else { partBody = part; } if (partBody instanceof Publisher) { - throw new IllegalArgumentException( - "Use asyncPart(String, Publisher, Class)" + - " or asyncPart(String, Publisher, ParameterizedTypeReference) or" + - " or MultipartBodyBuilder.PublisherEntity"); + throw new IllegalArgumentException(""" + Use asyncPart(String, Publisher, Class) \ + or asyncPart(String, Publisher, ParameterizedTypeReference) \ + or MultipartBodyBuilder.PublisherEntity"""); } DefaultPartBuilder builder = new DefaultPartBuilder(name, partHeaders, partBody); diff --git a/spring-web/src/main/java/org/springframework/http/client/reactive/HttpComponentsHeadersAdapter.java b/spring-web/src/main/java/org/springframework/http/client/reactive/HttpComponentsHeadersAdapter.java index f24d77cb86..9b914c1a4e 100644 --- a/spring-web/src/main/java/org/springframework/http/client/reactive/HttpComponentsHeadersAdapter.java +++ b/spring-web/src/main/java/org/springframework/http/client/reactive/HttpComponentsHeadersAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -102,7 +102,7 @@ class HttpComponentsHeadersAdapter implements MultiValueMap { @Override public boolean containsKey(Object key) { - return (key instanceof String && this.response.containsHeader((String) key)); + return (key instanceof String headerName && this.response.containsHeader(headerName)); } @Override @@ -136,9 +136,9 @@ class HttpComponentsHeadersAdapter implements MultiValueMap { @Nullable @Override public List remove(Object key) { - if (key instanceof String) { + if (key instanceof String headerName) { List oldValues = get(key); - this.response.removeHeaders((String) key); + this.response.removeHeaders(headerName); return oldValues; } return null; @@ -174,7 +174,7 @@ class HttpComponentsHeadersAdapter implements MultiValueMap { @Override public Set>> entrySet() { - return new AbstractSet>>() { + return new AbstractSet<>() { @Override public Iterator>> iterator() { return new EntryIterator(); @@ -196,7 +196,7 @@ class HttpComponentsHeadersAdapter implements MultiValueMap { private class EntryIterator implements Iterator>> { - private Iterator
iterator = response.headerIterator(); + private final Iterator
iterator = response.headerIterator(); @Override public boolean hasNext() { diff --git a/spring-web/src/main/java/org/springframework/http/client/reactive/JettyHeadersAdapter.java b/spring-web/src/main/java/org/springframework/http/client/reactive/JettyHeadersAdapter.java index 6d42dc7620..b1c01aa882 100644 --- a/spring-web/src/main/java/org/springframework/http/client/reactive/JettyHeadersAdapter.java +++ b/spring-web/src/main/java/org/springframework/http/client/reactive/JettyHeadersAdapter.java @@ -40,6 +40,7 @@ import org.springframework.util.MultiValueMap; * * @author Rossen Stoyanchev * @author Juergen Hoeller + * @author Sam Brannen * @since 5.3 */ class JettyHeadersAdapter implements MultiValueMap { @@ -59,10 +60,10 @@ class JettyHeadersAdapter implements MultiValueMap { @Override public void add(String key, @Nullable String value) { - if (!(this.headers instanceof HttpFields.Mutable)) { + if (!(this.headers instanceof HttpFields.Mutable mutableHttpFields)) { throw new IllegalStateException("Immutable headers"); } - ((HttpFields.Mutable) this.headers).add(key, value); + mutableHttpFields.add(key, value); } @Override @@ -77,10 +78,10 @@ class JettyHeadersAdapter implements MultiValueMap { @Override public void set(String key, @Nullable String value) { - if (!(this.headers instanceof HttpFields.Mutable)) { + if (!(this.headers instanceof HttpFields.Mutable mutableHttpFields)) { throw new IllegalStateException("Immutable headers"); } - ((HttpFields.Mutable) this.headers).put(key, value); + mutableHttpFields.put(key, value); } @Override @@ -112,13 +113,13 @@ class JettyHeadersAdapter implements MultiValueMap { @Override public boolean containsKey(Object key) { - return (key instanceof String && this.headers.contains((String) key)); + return (key instanceof String headerName && this.headers.contains(headerName)); } @Override public boolean containsValue(Object value) { - return (value instanceof String && - this.headers.stream().anyMatch(field -> field.contains((String) value))); + return (value instanceof String searchString && + this.headers.stream().anyMatch(field -> field.contains(searchString))); } @Nullable @@ -133,23 +134,23 @@ class JettyHeadersAdapter implements MultiValueMap { @Nullable @Override public List put(String key, List value) { - if (!(this.headers instanceof HttpFields.Mutable)) { + if (!(this.headers instanceof HttpFields.Mutable mutableHttpFields)) { throw new IllegalStateException("Immutable headers"); } List oldValues = get(key); - ((HttpFields.Mutable) this.headers).put(key, value); + mutableHttpFields.put(key, value); return oldValues; } @Nullable @Override public List remove(Object key) { - if (!(this.headers instanceof HttpFields.Mutable)) { + if (!(this.headers instanceof HttpFields.Mutable mutableHttpFields)) { throw new IllegalStateException("Immutable headers"); } - if (key instanceof String) { + if (key instanceof String name) { List oldValues = get(key); - ((HttpFields.Mutable) this.headers).remove((String) key); + mutableHttpFields.remove(name); return oldValues; } return null; @@ -162,10 +163,10 @@ class JettyHeadersAdapter implements MultiValueMap { @Override public void clear() { - if (!(this.headers instanceof HttpFields.Mutable)) { + if (!(this.headers instanceof HttpFields.Mutable mutableHttpFields)) { throw new IllegalStateException("Immutable headers"); } - ((HttpFields.Mutable) this.headers).clear(); + mutableHttpFields.clear(); } @Override @@ -181,7 +182,7 @@ class JettyHeadersAdapter implements MultiValueMap { @Override public Set>> entrySet() { - return new AbstractSet>>() { + return new AbstractSet<>() { @Override public Iterator>> iterator() { return new EntryIterator(); @@ -237,11 +238,11 @@ class JettyHeadersAdapter implements MultiValueMap { @Override public List setValue(List value) { - if (!(headers instanceof HttpFields.Mutable)) { + if (!(headers instanceof HttpFields.Mutable mutableHttpFields)) { throw new IllegalStateException("Immutable headers"); } List previousValues = headers.getValuesList(this.key); - ((HttpFields.Mutable) headers).put(this.key, value); + mutableHttpFields.put(this.key, value); return previousValues; } } @@ -285,7 +286,7 @@ class JettyHeadersAdapter implements MultiValueMap { @Override public void remove() { - if (!(headers instanceof HttpFields.Mutable)) { + if (!(headers instanceof HttpFields.Mutable mutableHttpFields)) { throw new IllegalStateException("Immutable headers"); } if (this.currentName == null) { @@ -294,7 +295,7 @@ class JettyHeadersAdapter implements MultiValueMap { if (!headers.contains(this.currentName)) { throw new IllegalStateException("Header not present: " + this.currentName); } - ((HttpFields.Mutable) headers).remove(this.currentName); + mutableHttpFields.remove(this.currentName); } } diff --git a/spring-web/src/main/java/org/springframework/http/client/reactive/NettyHeadersAdapter.java b/spring-web/src/main/java/org/springframework/http/client/reactive/NettyHeadersAdapter.java index 382203b34b..b35fa91ed9 100644 --- a/spring-web/src/main/java/org/springframework/http/client/reactive/NettyHeadersAdapter.java +++ b/spring-web/src/main/java/org/springframework/http/client/reactive/NettyHeadersAdapter.java @@ -36,6 +36,7 @@ import org.springframework.util.MultiValueMap; *

There is a duplicate of this class in the server package! * * @author Rossen Stoyanchev + * @author Sam Brannen * @since 5.3 */ class NettyHeadersAdapter implements MultiValueMap { @@ -107,7 +108,7 @@ class NettyHeadersAdapter implements MultiValueMap { @Override public boolean containsKey(Object key) { - return (key instanceof String && this.headers.contains((String) key)); + return (key instanceof String headerName && this.headers.contains(headerName)); } @Override @@ -137,9 +138,9 @@ class NettyHeadersAdapter implements MultiValueMap { @Nullable @Override public List remove(Object key) { - if (key instanceof String) { - List previousValues = this.headers.getAll((String) key); - this.headers.remove((String) key); + if (key instanceof String headerName) { + List previousValues = this.headers.getAll(headerName); + this.headers.remove(headerName); return previousValues; } return null; @@ -168,7 +169,7 @@ class NettyHeadersAdapter implements MultiValueMap { @Override public Set>> entrySet() { - return new AbstractSet>>() { + return new AbstractSet<>() { @Override public Iterator>> iterator() { return new EntryIterator(); @@ -190,7 +191,7 @@ class NettyHeadersAdapter implements MultiValueMap { private class EntryIterator implements Iterator>> { - private Iterator names = headers.names().iterator(); + private final Iterator names = headers.names().iterator(); @Override public boolean hasNext() { diff --git a/spring-web/src/main/java/org/springframework/http/client/reactive/ReactorClientHttpResponse.java b/spring-web/src/main/java/org/springframework/http/client/reactive/ReactorClientHttpResponse.java index 26903c4481..5139d9e3ae 100644 --- a/spring-web/src/main/java/org/springframework/http/client/reactive/ReactorClientHttpResponse.java +++ b/spring-web/src/main/java/org/springframework/http/client/reactive/ReactorClientHttpResponse.java @@ -105,8 +105,8 @@ class ReactorClientHttpResponse implements ClientHttpResponse { if (reactorNettyRequestChannelOperationsIdPresent) { id = ChannelOperationsIdHelper.getId(this.response); } - if (id == null && this.response instanceof Connection) { - id = ((Connection) this.response).channel().id().asShortText(); + if (id == null && this.response instanceof Connection connection) { + id = connection.channel().id().asShortText(); } return (id != null ? id : ObjectUtils.getIdentityHexString(this)); } @@ -163,8 +163,7 @@ class ReactorClientHttpResponse implements ClientHttpResponse { @Nullable private static String getSameSite(Cookie cookie) { - if (cookie instanceof DefaultCookie) { - DefaultCookie defaultCookie = (DefaultCookie) cookie; + if (cookie instanceof DefaultCookie defaultCookie) { if (defaultCookie.sameSite() != null) { return defaultCookie.sameSite().name(); } @@ -206,10 +205,8 @@ class ReactorClientHttpResponse implements ClientHttpResponse { @Nullable public static String getId(HttpClientResponse response) { - if (response instanceof reactor.netty.ChannelOperationsId) { - return (logger.isDebugEnabled() ? - ((reactor.netty.ChannelOperationsId) response).asLongText() : - ((reactor.netty.ChannelOperationsId) response).asShortText()); + if (response instanceof reactor.netty.ChannelOperationsId id) { + return (logger.isDebugEnabled() ? id.asLongText() : id.asShortText()); } return null; } diff --git a/spring-web/src/main/java/org/springframework/http/codec/json/AbstractJackson2Encoder.java b/spring-web/src/main/java/org/springframework/http/codec/json/AbstractJackson2Encoder.java index 89644fecff..0eeaf5832e 100644 --- a/spring-web/src/main/java/org/springframework/http/codec/json/AbstractJackson2Encoder.java +++ b/spring-web/src/main/java/org/springframework/http/codec/json/AbstractJackson2Encoder.java @@ -202,11 +202,10 @@ public abstract class AbstractJackson2Encoder extends Jackson2CodecSupport imple } Class jsonView = null; FilterProvider filters = null; - if (value instanceof MappingJacksonValue) { - MappingJacksonValue container = (MappingJacksonValue) value; - value = container.getValue(); - jsonView = container.getSerializationView(); - filters = container.getFilters(); + if (value instanceof MappingJacksonValue mappingJacksonValue) { + value = mappingJacksonValue.getValue(); + jsonView = mappingJacksonValue.getSerializationView(); + filters = mappingJacksonValue.getFilters(); } ObjectWriter writer = createObjectWriter(mapper, valueType, mimeType, jsonView, hints); if (filters != null) { diff --git a/spring-web/src/main/java/org/springframework/http/converter/AbstractGenericHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/AbstractGenericHttpMessageConverter.java index 3b34625e5a..ce3eadc42b 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/AbstractGenericHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/AbstractGenericHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 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. @@ -68,7 +68,7 @@ public abstract class AbstractGenericHttpMessageConverter extends AbstractHtt @Override public boolean canRead(Type type, @Nullable Class contextClass, @Nullable MediaType mediaType) { - return (type instanceof Class ? canRead((Class) type, mediaType) : canRead(mediaType)); + return (type instanceof Class clazz ? canRead(clazz, mediaType) : canRead(mediaType)); } @Override @@ -87,8 +87,7 @@ public abstract class AbstractGenericHttpMessageConverter extends AbstractHtt final HttpHeaders headers = outputMessage.getHeaders(); addDefaultHeaders(headers, t, contentType); - if (outputMessage instanceof StreamingHttpOutputMessage) { - StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage; + if (outputMessage instanceof StreamingHttpOutputMessage streamingOutputMessage) { streamingOutputMessage.setBody(outputStream -> writeInternal(t, type, new HttpOutputMessage() { @Override public OutputStream getBody() { diff --git a/spring-web/src/main/java/org/springframework/http/converter/AbstractHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/AbstractHttpMessageConverter.java index cf0674e06a..644be4f36e 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/AbstractHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/AbstractHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -210,8 +210,7 @@ public abstract class AbstractHttpMessageConverter implements HttpMessageConv final HttpHeaders headers = outputMessage.getHeaders(); addDefaultHeaders(headers, t, contentType); - if (outputMessage instanceof StreamingHttpOutputMessage) { - StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage; + if (outputMessage instanceof StreamingHttpOutputMessage streamingOutputMessage) { streamingOutputMessage.setBody(outputStream -> writeInternal(t, new HttpOutputMessage() { @Override public OutputStream getBody() { diff --git a/spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java index cdfa5781c9..c1cf744b80 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -221,8 +221,7 @@ public class BufferedImageHttpMessageConverter implements HttpMessageConverter writeInternal(image, selectedContentType, outputStream)); } else { diff --git a/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java index c113194183..680da1ae2a 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -274,8 +274,7 @@ public class FormHttpMessageConverter implements HttpMessageConverter candidate : this.partConverters) { - if (candidate instanceof AbstractHttpMessageConverter) { - AbstractHttpMessageConverter converter = (AbstractHttpMessageConverter) candidate; + if (candidate instanceof AbstractHttpMessageConverter converter) { // Only override default charset if the converter operates with a charset to begin with... if (converter.getDefaultCharset() != null) { converter.setDefaultCharset(this.charset); @@ -400,8 +399,7 @@ public class FormHttpMessageConverter implements HttpMessageConverter StreamUtils.copy(bytes, outputStream)); } else { @@ -486,8 +484,7 @@ public class FormHttpMessageConverter implements HttpMessageConverter { writeParts(outputStream, parts, boundary); writeEnd(outputStream, boundary); @@ -562,7 +559,7 @@ public class FormHttpMessageConverter implements HttpMessageConverter getHttpEntity(Object part) { - return (part instanceof HttpEntity ? (HttpEntity) part : new HttpEntity<>(part)); + return (part instanceof HttpEntity httpEntity ? httpEntity : new HttpEntity<>(part)); } /** @@ -575,8 +572,7 @@ public class FormHttpMessageConverter implements HttpMessageConverter { @@ -55,8 +56,8 @@ public class ResourceRegionHttpMessageConverter extends AbstractGenericHttpMessa @SuppressWarnings("unchecked") protected MediaType getDefaultContentType(Object object) { Resource resource = null; - if (object instanceof ResourceRegion) { - resource = ((ResourceRegion) object).getResource(); + if (object instanceof ResourceRegion resourceRegion) { + resource = resourceRegion.getResource(); } else { Collection regions = (Collection) object; @@ -98,15 +99,12 @@ public class ResourceRegionHttpMessageConverter extends AbstractGenericHttpMessa @Override public boolean canWrite(@Nullable Type type, @Nullable Class clazz, @Nullable MediaType mediaType) { - if (!(type instanceof ParameterizedType)) { - return (type instanceof Class && ResourceRegion.class.isAssignableFrom((Class) type)); + if (!(type instanceof ParameterizedType parameterizedType)) { + return (type instanceof Class c && ResourceRegion.class.isAssignableFrom(c)); } - - ParameterizedType parameterizedType = (ParameterizedType) type; - if (!(parameterizedType.getRawType() instanceof Class)) { + if (!(parameterizedType.getRawType() instanceof Class rawType)) { return false; } - Class rawType = (Class) parameterizedType.getRawType(); if (!(Collection.class.isAssignableFrom(rawType))) { return false; } @@ -114,11 +112,9 @@ public class ResourceRegionHttpMessageConverter extends AbstractGenericHttpMessa return false; } Type typeArgument = parameterizedType.getActualTypeArguments()[0]; - if (!(typeArgument instanceof Class)) { + if (!(typeArgument instanceof Class typeArgumentClass)) { return false; } - - Class typeArgumentClass = (Class) typeArgument; return ResourceRegion.class.isAssignableFrom(typeArgumentClass); } @@ -127,8 +123,8 @@ public class ResourceRegionHttpMessageConverter extends AbstractGenericHttpMessa protected void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { - if (object instanceof ResourceRegion) { - writeResourceRegion((ResourceRegion) object, outputMessage); + if (object instanceof ResourceRegion resourceRegion) { + writeResourceRegion(resourceRegion, outputMessage); } else { Collection regions = (Collection) object; @@ -136,7 +132,7 @@ public class ResourceRegionHttpMessageConverter extends AbstractGenericHttpMessa writeResourceRegion(regions.iterator().next(), outputMessage); } else { - writeResourceRegionCollection((Collection) object, outputMessage); + writeResourceRegionCollection(regions, outputMessage); } } } diff --git a/spring-web/src/main/java/org/springframework/http/converter/json/AbstractJackson2HttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/json/AbstractJackson2HttpMessageConverter.java index 19b22fef2c..3a547e62c5 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/json/AbstractJackson2HttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/json/AbstractJackson2HttpMessageConverter.java @@ -74,6 +74,7 @@ import org.springframework.util.TypeUtils; * @author Rossen Stoyanchev * @author Juergen Hoeller * @author Sebastien Deleuze + * @author Sam Brannen * @since 4.1 * @see MappingJackson2HttpMessageConverter */ @@ -107,7 +108,7 @@ public abstract class AbstractJackson2HttpMessageConverter extends AbstractGener private Boolean prettyPrint; @Nullable - private PrettyPrinter ssePrettyPrinter; + private final PrettyPrinter ssePrettyPrinter; protected AbstractJackson2HttpMessageConverter(ObjectMapper objectMapper) { @@ -361,8 +362,8 @@ public abstract class AbstractJackson2HttpMessageConverter extends AbstractGener "UTF-16".equals(charset.name()) || "UTF-32".equals(charset.name()); try { - if (inputMessage instanceof MappingJacksonInputMessage) { - Class deserializationView = ((MappingJacksonInputMessage) inputMessage).getDeserializationView(); + if (inputMessage instanceof MappingJacksonInputMessage mappingJacksonInputMessage) { + Class deserializationView = mappingJacksonInputMessage.getDeserializationView(); if (deserializationView != null) { ObjectReader objectReader = objectMapper.readerWithView(deserializationView).forType(javaType); if (isUnicode) { @@ -414,8 +415,8 @@ public abstract class AbstractJackson2HttpMessageConverter extends AbstractGener MediaType contentType = outputMessage.getHeaders().getContentType(); JsonEncoding encoding = getJsonEncoding(contentType); - Class clazz = (object instanceof MappingJacksonValue ? - ((MappingJacksonValue) object).getValue().getClass() : object.getClass()); + Class clazz = (object instanceof MappingJacksonValue mappingJacksonValue ? + mappingJacksonValue.getValue().getClass() : object.getClass()); ObjectMapper objectMapper = selectObjectMapper(clazz, contentType); Assert.state(objectMapper != null, "No ObjectMapper for " + clazz.getName()); @@ -428,11 +429,10 @@ public abstract class AbstractJackson2HttpMessageConverter extends AbstractGener FilterProvider filters = null; JavaType javaType = null; - if (object instanceof MappingJacksonValue) { - MappingJacksonValue container = (MappingJacksonValue) object; - value = container.getValue(); - serializationView = container.getSerializationView(); - filters = container.getFilters(); + if (object instanceof MappingJacksonValue mappingJacksonValue) { + value = mappingJacksonValue.getValue(); + serializationView = mappingJacksonValue.getSerializationView(); + filters = mappingJacksonValue.getFilters(); } if (type != null && TypeUtils.isAssignable(type, value.getClass())) { javaType = getJavaType(type, null); @@ -510,16 +510,16 @@ public abstract class AbstractJackson2HttpMessageConverter extends AbstractGener @Override @Nullable protected MediaType getDefaultContentType(Object object) throws IOException { - if (object instanceof MappingJacksonValue) { - object = ((MappingJacksonValue) object).getValue(); + if (object instanceof MappingJacksonValue mappingJacksonValue) { + object = mappingJacksonValue.getValue(); } return super.getDefaultContentType(object); } @Override protected Long getContentLength(Object object, @Nullable MediaType contentType) throws IOException { - if (object instanceof MappingJacksonValue) { - object = ((MappingJacksonValue) object).getValue(); + if (object instanceof MappingJacksonValue mappingJacksonValue) { + object = mappingJacksonValue.getValue(); } return super.getContentLength(object, contentType); } diff --git a/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverter.java index c2e3bfdc10..e1acb3a833 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 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 @@ import org.springframework.util.xml.StaxUtils; * * @author Arjen Poutsma * @author Rossen Stoyanchev + * @author Sam Brannen * @since 3.2 * @param the converted object type */ @@ -86,14 +87,12 @@ public class Jaxb2CollectionHttpMessageConverter */ @Override public boolean canRead(Type type, @Nullable Class contextClass, @Nullable MediaType mediaType) { - if (!(type instanceof ParameterizedType)) { + if (!(type instanceof ParameterizedType parameterizedType)) { return false; } - ParameterizedType parameterizedType = (ParameterizedType) type; - if (!(parameterizedType.getRawType() instanceof Class)) { + if (!(parameterizedType.getRawType() instanceof Class rawType)) { return false; } - Class rawType = (Class) parameterizedType.getRawType(); if (!(Collection.class.isAssignableFrom(rawType))) { return false; } @@ -101,10 +100,9 @@ public class Jaxb2CollectionHttpMessageConverter return false; } Type typeArgument = parameterizedType.getActualTypeArguments()[0]; - if (!(typeArgument instanceof Class)) { + if (!(typeArgument instanceof Class typeArgumentClass)) { return false; } - Class typeArgumentClass = (Class) typeArgument; return (typeArgumentClass.isAnnotationPresent(XmlRootElement.class) || typeArgumentClass.isAnnotationPresent(XmlType.class)) && canRead(mediaType); } diff --git a/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverter.java index c41fb18b85..a1acfda553 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverter.java @@ -151,8 +151,7 @@ public class Jaxb2RootElementHttpMessageConverter extends AbstractJaxb2HttpMessa @SuppressWarnings("deprecation") protected Source processSource(Source source) { - if (source instanceof StreamSource) { - StreamSource streamSource = (StreamSource) source; + if (source instanceof StreamSource streamSource) { InputSource inputSource = new InputSource(streamSource.getInputStream()); try { XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); diff --git a/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpAsyncRequestControl.java b/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpAsyncRequestControl.java index 0a0d1b4fa3..7833b92bbb 100644 --- a/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpAsyncRequestControl.java +++ b/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpAsyncRequestControl.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ public class ServletServerHttpAsyncRequestControl implements ServerHttpAsyncRequ @Nullable private AsyncContext asyncContext; - private AtomicBoolean asyncCompleted = new AtomicBoolean(); + private final AtomicBoolean asyncCompleted = new AtomicBoolean(); /** diff --git a/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpRequest.java b/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpRequest.java index f7b3e9e99f..7bac4b70a9 100644 --- a/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpRequest.java @@ -216,11 +216,10 @@ public class ServletServerHttpRequest implements ServerHttpRequest { @Override public ServerHttpAsyncRequestControl getAsyncRequestControl(ServerHttpResponse response) { if (this.asyncRequestControl == null) { - if (!(response instanceof ServletServerHttpResponse)) { + if (!(response instanceof ServletServerHttpResponse servletServerResponse)) { throw new IllegalArgumentException( "Response must be a ServletServerHttpResponse: " + response.getClass()); } - ServletServerHttpResponse servletServerResponse = (ServletServerHttpResponse) response; this.asyncRequestControl = new ServletServerHttpAsyncRequestControl(this, servletServerResponse); } return this.asyncRequestControl; 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 d4398d7609..956808e57a 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 @@ -45,7 +45,7 @@ class DefaultServerHttpRequestBuilder implements ServerHttpRequest.Builder { private URI uri; - private HttpHeaders headers; + private final HttpHeaders headers; private String httpMethodValue; @@ -61,7 +61,7 @@ class DefaultServerHttpRequestBuilder implements ServerHttpRequest.Builder { @Nullable private InetSocketAddress remoteAddress; - private Flux body; + private final Flux body; private final ServerHttpRequest originalRequest; @@ -182,7 +182,7 @@ class DefaultServerHttpRequestBuilder implements ServerHttpRequest.Builder { private final SslInfo sslInfo; @Nullable - private InetSocketAddress remoteAddress; + private final InetSocketAddress remoteAddress; private final Flux body; diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/JettyHttpHandlerAdapter.java b/spring-web/src/main/java/org/springframework/http/server/reactive/JettyHttpHandlerAdapter.java index 8c1615e6d2..2862ce8e7a 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/JettyHttpHandlerAdapter.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/JettyHttpHandlerAdapter.java @@ -89,11 +89,10 @@ public class JettyHttpHandlerAdapter extends ServletHttpHandlerAdapter { } private static Request getRequest(HttpServletRequest request) { - if (request instanceof Request) { - return (Request) request; + if (request instanceof Request jettyRequest) { + return jettyRequest; } - else if (request instanceof HttpServletRequestWrapper) { - HttpServletRequestWrapper wrapper = (HttpServletRequestWrapper) request; + else if (request instanceof HttpServletRequestWrapper wrapper) { HttpServletRequest wrappedRequest = (HttpServletRequest) wrapper.getRequest(); return getRequest(wrappedRequest); } @@ -121,11 +120,10 @@ public class JettyHttpHandlerAdapter extends ServletHttpHandlerAdapter { } private static Response getResponse(HttpServletResponse response) { - if (response instanceof Response) { - return (Response) response; + if (response instanceof Response jettyResponse) { + return jettyResponse; } - else if (response instanceof HttpServletResponseWrapper) { - HttpServletResponseWrapper wrapper = (HttpServletResponseWrapper) response; + else if (response instanceof HttpServletResponseWrapper wrapper) { HttpServletResponse wrappedResponse = (HttpServletResponse) wrapper.getResponse(); return getResponse(wrappedResponse); } diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/NettyHeadersAdapter.java b/spring-web/src/main/java/org/springframework/http/server/reactive/NettyHeadersAdapter.java index 08ae3207f9..fdbdcacf51 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/NettyHeadersAdapter.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/NettyHeadersAdapter.java @@ -107,7 +107,7 @@ class NettyHeadersAdapter implements MultiValueMap { @Override public boolean containsKey(Object key) { - return (key instanceof String && this.headers.contains((String) key)); + return (key instanceof String headerName && this.headers.contains(headerName)); } @Override @@ -137,9 +137,9 @@ class NettyHeadersAdapter implements MultiValueMap { @Nullable @Override public List remove(Object key) { - if (key instanceof String) { - List previousValues = this.headers.getAll((String) key); - this.headers.remove((String) key); + if (key instanceof String headerName) { + List previousValues = this.headers.getAll(headerName); + this.headers.remove(headerName); return previousValues; } return null; @@ -168,7 +168,7 @@ class NettyHeadersAdapter implements MultiValueMap { @Override public Set>> entrySet() { - return new AbstractSet>>() { + return new AbstractSet<>() { @Override public Iterator>> iterator() { return new EntryIterator(); @@ -190,7 +190,7 @@ class NettyHeadersAdapter implements MultiValueMap { private class EntryIterator implements Iterator>> { - private Iterator names = headers.names().iterator(); + private final Iterator names = headers.names().iterator(); @Override public boolean hasNext() { diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/TomcatHeadersAdapter.java b/spring-web/src/main/java/org/springframework/http/server/reactive/TomcatHeadersAdapter.java index 6bde8a98a3..baaf0788c4 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/TomcatHeadersAdapter.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/TomcatHeadersAdapter.java @@ -38,6 +38,7 @@ import org.springframework.util.MultiValueMap; * {@code MultiValueMap} implementation for wrapping Tomcat HTTP headers. * * @author Brian Clozel + * @author Sam Brannen * @since 5.1.1 */ class TomcatHeadersAdapter implements MultiValueMap { @@ -105,19 +106,19 @@ class TomcatHeadersAdapter implements MultiValueMap { @Override public boolean containsKey(Object key) { - if (key instanceof String) { - return (this.headers.findHeader((String) key, 0) != -1); + if (key instanceof String headerName) { + return (this.headers.findHeader(headerName, 0) != -1); } return false; } @Override public boolean containsValue(Object value) { - if (value instanceof String) { - MessageBytes needle = MessageBytes.newInstance(); - needle.setString((String) value); + if (value instanceof String text) { + MessageBytes messageBytes = MessageBytes.newInstance(); + messageBytes.setString(text); for (int i = 0; i < this.headers.size(); i++) { - if (this.headers.getValue(i).equals(needle)) { + if (this.headers.getValue(i).equals(messageBytes)) { return true; } } @@ -146,9 +147,9 @@ class TomcatHeadersAdapter implements MultiValueMap { @Override @Nullable public List remove(Object key) { - if (key instanceof String) { + if (key instanceof String headerName) { List previousValues = get(key); - this.headers.removeHeader((String) key); + this.headers.removeHeader(headerName); return previousValues; } return null; @@ -176,7 +177,7 @@ class TomcatHeadersAdapter implements MultiValueMap { @Override public Set>> entrySet() { - return new AbstractSet>>() { + return new AbstractSet<>() { @Override public Iterator>> iterator() { return new EntryIterator(); @@ -198,7 +199,7 @@ class TomcatHeadersAdapter implements MultiValueMap { private class EntryIterator implements Iterator>> { - private Enumeration names = headers.names(); + private final Enumeration names = headers.names(); @Override public boolean hasNext() { diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/TomcatHttpHandlerAdapter.java b/spring-web/src/main/java/org/springframework/http/server/reactive/TomcatHttpHandlerAdapter.java index f9a8e7277c..b34723afa0 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/TomcatHttpHandlerAdapter.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/TomcatHttpHandlerAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -52,6 +52,7 @@ import org.springframework.util.ReflectionUtils; * * @author Violeta Georgieva * @author Brian Clozel + * @author Sam Brannen * @since 5.0 * @see org.springframework.web.server.adapter.AbstractReactiveWebInitializer */ @@ -115,11 +116,10 @@ public class TomcatHttpHandlerAdapter extends ServletHttpHandlerAdapter { } private static RequestFacade getRequestFacade(HttpServletRequest request) { - if (request instanceof RequestFacade) { - return (RequestFacade) request; + if (request instanceof RequestFacade facade) { + return facade; } - else if (request instanceof HttpServletRequestWrapper) { - HttpServletRequestWrapper wrapper = (HttpServletRequestWrapper) request; + else if (request instanceof HttpServletRequestWrapper wrapper) { HttpServletRequest wrappedRequest = (HttpServletRequest) wrapper.getRequest(); return getRequestFacade(wrappedRequest); } @@ -132,7 +132,7 @@ public class TomcatHttpHandlerAdapter extends ServletHttpHandlerAdapter { @Override protected DataBuffer readFromInputStream() throws IOException { ServletInputStream inputStream = ((ServletRequest) getNativeRequest()).getInputStream(); - if (!(inputStream instanceof CoyoteInputStream)) { + if (!(inputStream instanceof CoyoteInputStream coyoteInputStream)) { // It's possible InputStream can be wrapped, preventing use of CoyoteInputStream return super.readFromInputStream(); } @@ -141,7 +141,7 @@ public class TomcatHttpHandlerAdapter extends ServletHttpHandlerAdapter { DataBuffer dataBuffer = this.factory.allocateBuffer(capacity); try { ByteBuffer byteBuffer = dataBuffer.asByteBuffer(0, capacity); - int read = ((CoyoteInputStream) inputStream).read(byteBuffer); + int read = coyoteInputStream.read(byteBuffer); logBytesRead(read); if (read > 0) { dataBuffer.writePosition(read); @@ -192,11 +192,10 @@ public class TomcatHttpHandlerAdapter extends ServletHttpHandlerAdapter { } private static ResponseFacade getResponseFacade(HttpServletResponse response) { - if (response instanceof ResponseFacade) { - return (ResponseFacade) response; + if (response instanceof ResponseFacade facade) { + return facade; } - else if (response instanceof HttpServletResponseWrapper) { - HttpServletResponseWrapper wrapper = (HttpServletResponseWrapper) response; + else if (response instanceof HttpServletResponseWrapper wrapper) { HttpServletResponse wrappedResponse = (HttpServletResponse) wrapper.getResponse(); return getResponseFacade(wrappedResponse); } diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowHeadersAdapter.java b/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowHeadersAdapter.java index fa197aa0c2..9e24903187 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowHeadersAdapter.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowHeadersAdapter.java @@ -17,6 +17,7 @@ package org.springframework.http.server.reactive; import java.util.AbstractSet; +import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -36,6 +37,7 @@ import org.springframework.util.MultiValueMap; * {@code MultiValueMap} implementation for wrapping Undertow HTTP headers. * * @author Brian Clozel + * @author Sam Brannen * @since 5.1.1 */ class UndertowHeadersAdapter implements MultiValueMap { @@ -99,7 +101,7 @@ class UndertowHeadersAdapter implements MultiValueMap { @Override public boolean containsKey(Object key) { - return (key instanceof String && this.headers.contains((String) key)); + return (key instanceof String headerName && this.headers.contains(headerName)); } @Override @@ -113,10 +115,7 @@ class UndertowHeadersAdapter implements MultiValueMap { @Override @Nullable public List get(Object key) { - if (key instanceof String) { - return this.headers.get((String) key); - } - return null; + return (key instanceof String headerName ? this.headers.get(headerName) : null); } @Override @@ -130,8 +129,11 @@ class UndertowHeadersAdapter implements MultiValueMap { @Override @Nullable public List remove(Object key) { - if (key instanceof String) { - this.headers.remove((String) key); + if (key instanceof String headerName) { + Collection removed = this.headers.remove(headerName); + if (removed != null) { + return new ArrayList<>(removed); + } } return null; } @@ -161,7 +163,7 @@ class UndertowHeadersAdapter implements MultiValueMap { @Override public Set>> entrySet() { - return new AbstractSet>>() { + return new AbstractSet<>() { @Override public Iterator>> iterator() { return new EntryIterator(); @@ -183,7 +185,7 @@ class UndertowHeadersAdapter implements MultiValueMap { private class EntryIterator implements Iterator>> { - private Iterator names = headers.getHeaderNames().iterator(); + private final Iterator names = headers.getHeaderNames().iterator(); @Override public boolean hasNext() { diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpRequest.java b/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpRequest.java index 4d87fa5f38..6de7dfb399 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpRequest.java @@ -175,7 +175,7 @@ class UndertowServerHttpRequest extends AbstractServerHttpRequest { @Nullable protected DataBuffer read() throws IOException { PooledByteBuffer pooledByteBuffer = this.byteBufferPool.allocate(); - try { + try (pooledByteBuffer) { ByteBuffer byteBuffer = pooledByteBuffer.getBuffer(); int read = this.channel.read(byteBuffer); @@ -194,9 +194,6 @@ class UndertowServerHttpRequest extends AbstractServerHttpRequest { } return null; } - finally { - pooledByteBuffer.close(); - } } @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 a7c2358dd5..a9fcb4d8dc 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-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -110,7 +110,7 @@ public class ContentNegotiationManagerFactoryBean private boolean favorPathExtension = false; - private Map mediaTypes = new HashMap<>(); + private final Map mediaTypes = new HashMap<>(); private boolean ignoreUnknownPathExtensions = true; diff --git a/spring-web/src/main/java/org/springframework/web/bind/EscapedErrors.java b/spring-web/src/main/java/org/springframework/web/bind/EscapedErrors.java index a2cb47e478..eb1166f9ad 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/EscapedErrors.java +++ b/spring-web/src/main/java/org/springframework/web/bind/EscapedErrors.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2021 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. @@ -204,7 +204,7 @@ public class EscapedErrors implements Errors { @Nullable public Object getFieldValue(String field) { Object value = this.source.getFieldValue(field); - return (value instanceof String ? HtmlUtils.htmlEscape((String) value) : value); + return (value instanceof String text ? HtmlUtils.htmlEscape(text) : value); } @Override @@ -223,11 +223,10 @@ public class EscapedErrors implements Errors { if (defaultMessage != null) { defaultMessage = HtmlUtils.htmlEscape(defaultMessage); } - if (source instanceof FieldError) { - FieldError fieldError = (FieldError) source; + if (source instanceof FieldError fieldError) { Object value = fieldError.getRejectedValue(); - if (value instanceof String) { - value = HtmlUtils.htmlEscape((String) value); + if (value instanceof String text) { + value = HtmlUtils.htmlEscape(text); } return (T) new FieldError( fieldError.getObjectName(), fieldError.getField(), value, fieldError.isBindingFailure(), 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 23e747a17c..7be21a3db4 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 @@ -109,8 +109,7 @@ public class WebRequestDataBinder extends WebDataBinder { */ public void bind(WebRequest request) { MutablePropertyValues mpvs = new MutablePropertyValues(request.getParameterMap()); - if (request instanceof NativeWebRequest) { - NativeWebRequest nativeRequest = (NativeWebRequest) request; + if (request instanceof NativeWebRequest nativeRequest) { MultipartRequest multipartRequest = nativeRequest.getNativeRequest(MultipartRequest.class); if (multipartRequest != null) { bindMultipart(multipartRequest.getMultiFileMap(), mpvs); diff --git a/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java b/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java index 722fb7a170..45a4bb69a9 100644 --- a/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java +++ b/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 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. @@ -277,19 +277,16 @@ public class ContextLoader { if (this.context == null) { this.context = createWebApplicationContext(servletContext); } - if (this.context instanceof ConfigurableWebApplicationContext) { - ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; - if (!cwac.isActive()) { - // The context has not yet been refreshed -> provide services such as - // setting the parent context, setting the application context id, etc - if (cwac.getParent() == null) { - // The context instance was injected without an explicit parent -> - // determine parent for root web application context, if any. - ApplicationContext parent = loadParentContext(servletContext); - cwac.setParent(parent); - } - configureAndRefreshWebApplicationContext(cwac, servletContext); + if (this.context instanceof ConfigurableWebApplicationContext cwac && !cwac.isActive()) { + // The context has not yet been refreshed -> provide services such as + // setting the parent context, setting the application context id, etc + if (cwac.getParent() == null) { + // The context instance was injected without an explicit parent -> + // determine parent for root web application context, if any. + ApplicationContext parent = loadParentContext(servletContext); + cwac.setParent(parent); } + configureAndRefreshWebApplicationContext(cwac, servletContext); } servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); @@ -392,8 +389,8 @@ public class ContextLoader { // is refreshed; do it eagerly here to ensure servlet property sources are in place for // use in any post-processing or initialization that occurs below prior to #refresh ConfigurableEnvironment env = wac.getEnvironment(); - if (env instanceof ConfigurableWebEnvironment) { - ((ConfigurableWebEnvironment) env).initPropertySources(sc, null); + if (env instanceof ConfigurableWebEnvironment cwe) { + cwe.initPropertySources(sc, null); } customizeContext(sc, wac); @@ -512,8 +509,8 @@ public class ContextLoader { public void closeWebApplicationContext(ServletContext servletContext) { servletContext.log("Closing Spring root WebApplicationContext"); try { - if (this.context instanceof ConfigurableWebApplicationContext) { - ((ConfigurableWebApplicationContext) this.context).close(); + if (this.context instanceof ConfigurableWebApplicationContext cwac) { + cwac.close(); } } finally { diff --git a/spring-web/src/main/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequest.java b/spring-web/src/main/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequest.java index 18d29550bf..395166f84e 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequest.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -48,7 +48,7 @@ public class StandardServletAsyncWebRequest extends ServletWebRequest implements private AsyncContext asyncContext; - private AtomicBoolean asyncCompleted = new AtomicBoolean(); + private final AtomicBoolean asyncCompleted = new AtomicBoolean(); private final List timeoutHandlers = new ArrayList<>(); diff --git a/spring-web/src/main/java/org/springframework/web/context/support/RequestHandledEvent.java b/spring-web/src/main/java/org/springframework/web/context/support/RequestHandledEvent.java index 30d32153eb..4ee3ec2367 100644 --- a/spring-web/src/main/java/org/springframework/web/context/support/RequestHandledEvent.java +++ b/spring-web/src/main/java/org/springframework/web/context/support/RequestHandledEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -38,11 +38,11 @@ public class RequestHandledEvent extends ApplicationEvent { /** Session id that applied to the request, if any. */ @Nullable - private String sessionId; + private final String sessionId; /** Usually the UserPrincipal. */ @Nullable - private String userName; + private final String userName; /** Request processing time. */ private final long processingTimeMillis; diff --git a/spring-web/src/main/java/org/springframework/web/context/support/ServletContextResource.java b/spring-web/src/main/java/org/springframework/web/context/support/ServletContextResource.java index 3942fa0dea..bf498cda85 100644 --- a/spring-web/src/main/java/org/springframework/web/context/support/ServletContextResource.java +++ b/spring-web/src/main/java/org/springframework/web/context/support/ServletContextResource.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 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. @@ -241,10 +241,9 @@ public class ServletContextResource extends AbstractFileResolvingResource implem if (this == other) { return true; } - if (!(other instanceof ServletContextResource)) { + if (!(other instanceof ServletContextResource otherRes)) { return false; } - ServletContextResource otherRes = (ServletContextResource) other; return (this.servletContext.equals(otherRes.servletContext) && this.path.equals(otherRes.path)); } diff --git a/spring-web/src/main/java/org/springframework/web/context/support/ServletContextResourcePatternResolver.java b/spring-web/src/main/java/org/springframework/web/context/support/ServletContextResourcePatternResolver.java index c9bd0c447e..e452d222ec 100644 --- a/spring-web/src/main/java/org/springframework/web/context/support/ServletContextResourcePatternResolver.java +++ b/spring-web/src/main/java/org/springframework/web/context/support/ServletContextResourcePatternResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -80,8 +80,7 @@ public class ServletContextResourcePatternResolver extends PathMatchingResourceP protected Set doFindPathMatchingFileResources(Resource rootDirResource, String subPattern) throws IOException { - if (rootDirResource instanceof ServletContextResource) { - ServletContextResource scResource = (ServletContextResource) rootDirResource; + if (rootDirResource instanceof ServletContextResource scResource) { ServletContext sc = scResource.getServletContext(); String fullPattern = scResource.getPath() + subPattern; Set result = new LinkedHashSet<>(8); diff --git a/spring-web/src/main/java/org/springframework/web/filter/DelegatingFilterProxy.java b/spring-web/src/main/java/org/springframework/web/filter/DelegatingFilterProxy.java index dff469446a..8a85966ed3 100644 --- a/spring-web/src/main/java/org/springframework/web/filter/DelegatingFilterProxy.java +++ b/spring-web/src/main/java/org/springframework/web/filter/DelegatingFilterProxy.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2021 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. @@ -300,12 +300,9 @@ public class DelegatingFilterProxy extends GenericFilterBean { protected WebApplicationContext findWebApplicationContext() { if (this.webApplicationContext != null) { // The user has injected a context at construction time -> use it... - if (this.webApplicationContext instanceof ConfigurableApplicationContext) { - ConfigurableApplicationContext cac = (ConfigurableApplicationContext) this.webApplicationContext; - if (!cac.isActive()) { - // The context has not yet been refreshed -> do so before returning it... - cac.refresh(); - } + if (this.webApplicationContext instanceof ConfigurableApplicationContext cac && !cac.isActive()) { + // The context has not yet been refreshed -> do so before returning it... + cac.refresh(); } return this.webApplicationContext; } diff --git a/spring-web/src/main/java/org/springframework/web/filter/FormContentFilter.java b/spring-web/src/main/java/org/springframework/web/filter/FormContentFilter.java index a66a2ba49e..bad214fb5d 100644 --- a/spring-web/src/main/java/org/springframework/web/filter/FormContentFilter.java +++ b/spring-web/src/main/java/org/springframework/web/filter/FormContentFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 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. @@ -126,7 +126,7 @@ public class FormContentFilter extends OncePerRequestFilter { private static class FormContentRequestWrapper extends HttpServletRequestWrapper { - private MultiValueMap formParams; + private final MultiValueMap formParams; public FormContentRequestWrapper(HttpServletRequest request, MultiValueMap params) { super(request); diff --git a/spring-web/src/main/java/org/springframework/web/filter/HttpPutFormContentFilter.java b/spring-web/src/main/java/org/springframework/web/filter/HttpPutFormContentFilter.java index acb0c0fbfe..66745fc0cb 100644 --- a/spring-web/src/main/java/org/springframework/web/filter/HttpPutFormContentFilter.java +++ b/spring-web/src/main/java/org/springframework/web/filter/HttpPutFormContentFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 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. @@ -132,7 +132,7 @@ public class HttpPutFormContentFilter extends OncePerRequestFilter { private static class HttpPutFormContentRequestWrapper extends HttpServletRequestWrapper { - private MultiValueMap formParameters; + private final MultiValueMap formParameters; public HttpPutFormContentRequestWrapper(HttpServletRequest request, MultiValueMap parameters) { super(request); diff --git a/spring-web/src/main/java/org/springframework/web/filter/OncePerRequestFilter.java b/spring-web/src/main/java/org/springframework/web/filter/OncePerRequestFilter.java index 953bda7f86..6f50536382 100644 --- a/spring-web/src/main/java/org/springframework/web/filter/OncePerRequestFilter.java +++ b/spring-web/src/main/java/org/springframework/web/filter/OncePerRequestFilter.java @@ -64,6 +64,7 @@ import org.springframework.web.util.WebUtils; * * @author Juergen Hoeller * @author Rossen Stoyanchev + * @author Sam Brannen * @since 06.12.2003 */ public abstract class OncePerRequestFilter extends GenericFilterBean { @@ -88,22 +89,18 @@ public abstract class OncePerRequestFilter extends GenericFilterBean { public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { - if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { + if (!((request instanceof HttpServletRequest httpRequest) && (response instanceof HttpServletResponse httpResponse))) { throw new ServletException("OncePerRequestFilter just supports HTTP requests"); } - HttpServletRequest httpRequest = (HttpServletRequest) request; - HttpServletResponse httpResponse = (HttpServletResponse) response; String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName(); boolean hasAlreadyFilteredAttribute = request.getAttribute(alreadyFilteredAttributeName) != null; if (skipDispatch(httpRequest) || shouldNotFilter(httpRequest)) { - // Proceed without invoking this filter... filterChain.doFilter(request, response); } else if (hasAlreadyFilteredAttribute) { - if (DispatcherType.ERROR.equals(request.getDispatcherType())) { doFilterNestedErrorDispatch(httpRequest, httpResponse, filterChain); return; diff --git a/spring-web/src/main/java/org/springframework/web/jsf/DecoratingNavigationHandler.java b/spring-web/src/main/java/org/springframework/web/jsf/DecoratingNavigationHandler.java index 98dd6cce8a..f80280f223 100644 --- a/spring-web/src/main/java/org/springframework/web/jsf/DecoratingNavigationHandler.java +++ b/spring-web/src/main/java/org/springframework/web/jsf/DecoratingNavigationHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2021 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. @@ -135,10 +135,9 @@ public abstract class DecoratingNavigationHandler extends NavigationHandler { NavigationHandler decoratedNavigationHandler = getDecoratedNavigationHandler(); - if (decoratedNavigationHandler instanceof DecoratingNavigationHandler) { + if (decoratedNavigationHandler instanceof DecoratingNavigationHandler decHandler) { // DecoratingNavigationHandler specified through constructor argument: // Call it with original NavigationHandler passed in. - DecoratingNavigationHandler decHandler = (DecoratingNavigationHandler) decoratedNavigationHandler; decHandler.handleNavigation(facesContext, fromAction, outcome, originalNavigationHandler); } else if (decoratedNavigationHandler != null) { diff --git a/spring-web/src/main/java/org/springframework/web/jsf/el/WebApplicationContextFacesELResolver.java b/spring-web/src/main/java/org/springframework/web/jsf/el/WebApplicationContextFacesELResolver.java index 86babdf0a4..a991ed8a1c 100644 --- a/spring-web/src/main/java/org/springframework/web/jsf/el/WebApplicationContextFacesELResolver.java +++ b/spring-web/src/main/java/org/springframework/web/jsf/el/WebApplicationContextFacesELResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 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. @@ -70,8 +70,7 @@ public class WebApplicationContextFacesELResolver extends ELResolver { @Nullable public Object getValue(ELContext elContext, @Nullable Object base, Object property) throws ELException { if (base != null) { - if (base instanceof WebApplicationContext) { - WebApplicationContext wac = (WebApplicationContext) base; + if (base instanceof WebApplicationContext wac) { String beanName = property.toString(); if (logger.isTraceEnabled()) { logger.trace("Attempting to resolve property '" + beanName + "' in root WebApplicationContext"); @@ -108,8 +107,7 @@ public class WebApplicationContextFacesELResolver extends ELResolver { @Nullable public Class getType(ELContext elContext, @Nullable Object base, Object property) throws ELException { if (base != null) { - if (base instanceof WebApplicationContext) { - WebApplicationContext wac = (WebApplicationContext) base; + if (base instanceof WebApplicationContext wac) { String beanName = property.toString(); if (logger.isDebugEnabled()) { logger.debug("Attempting to resolve property '" + beanName + "' in root WebApplicationContext"); diff --git a/spring-web/src/main/java/org/springframework/web/method/ControllerAdviceBean.java b/spring-web/src/main/java/org/springframework/web/method/ControllerAdviceBean.java index b8e2436d51..f9b353ac0c 100644 --- a/spring-web/src/main/java/org/springframework/web/method/ControllerAdviceBean.java +++ b/spring-web/src/main/java/org/springframework/web/method/ControllerAdviceBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -176,16 +176,15 @@ public class ControllerAdviceBean implements Ordered { resolvedBean = resolveBean(); } - if (resolvedBean instanceof Ordered) { - this.order = ((Ordered) resolvedBean).getOrder(); + if (resolvedBean instanceof Ordered ordered) { + this.order = ordered.getOrder(); } else { - if (beanName != null && this.beanFactory instanceof ConfigurableBeanFactory) { - ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) this.beanFactory; + if (beanName != null && this.beanFactory instanceof ConfigurableBeanFactory cbf) { try { BeanDefinition bd = cbf.getMergedBeanDefinition(beanName); - if (bd instanceof RootBeanDefinition) { - Method factoryMethod = ((RootBeanDefinition) bd).getResolvedFactoryMethod(); + if (bd instanceof RootBeanDefinition rbd) { + Method factoryMethod = rbd.getResolvedFactoryMethod(); if (factoryMethod != null) { this.order = OrderUtils.getOrder(factoryMethod); } @@ -261,10 +260,9 @@ public class ControllerAdviceBean implements Ordered { if (this == other) { return true; } - if (!(other instanceof ControllerAdviceBean)) { + if (!(other instanceof ControllerAdviceBean otherAdvice)) { return false; } - ControllerAdviceBean otherAdvice = (ControllerAdviceBean) other; return (this.beanOrName.equals(otherAdvice.beanOrName) && this.beanFactory == otherAdvice.beanFactory); } @@ -291,9 +289,9 @@ public class ControllerAdviceBean implements Ordered { */ public static List findAnnotatedBeans(ApplicationContext context) { ListableBeanFactory beanFactory = context; - if (context instanceof ConfigurableApplicationContext) { + if (context instanceof ConfigurableApplicationContext cac) { // Use internal BeanFactory for potential downcast to ConfigurableBeanFactory above - beanFactory = ((ConfigurableApplicationContext) context).getBeanFactory(); + beanFactory = cac.getBeanFactory(); } List adviceBeans = new ArrayList<>(); for (String name : BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, Object.class)) { diff --git a/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java b/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java index 80d6e7999e..541592c336 100644 --- a/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java +++ b/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java @@ -370,9 +370,8 @@ public class HandlerMethod { */ public HandlerMethod createWithResolvedBean() { Object handler = this.bean; - if (this.bean instanceof String) { + if (this.bean instanceof String beanName) { Assert.state(this.beanFactory != null, "Cannot resolve bean name without BeanFactory"); - String beanName = (String) this.bean; handler = this.beanFactory.getBean(beanName); } return new HandlerMethod(this, handler); @@ -428,10 +427,9 @@ public class HandlerMethod { if (this == other) { return true; } - if (!(other instanceof HandlerMethod)) { + if (!(other instanceof HandlerMethod otherMethod)) { return false; } - HandlerMethod otherMethod = (HandlerMethod) other; return (this.bean.equals(otherMethod.bean) && this.method.equals(otherMethod.method)); } 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 9c20b6f3bb..2e2ffaf8fb 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 @@ -36,6 +36,7 @@ import org.springframework.web.util.UriComponentsBuilder; * * @author Rossen Stoyanchev * @author Juergen Hoeller + * @author Sam Brannen * @since 4.0 */ public class CompositeUriComponentsContributor implements UriComponentsContributor { @@ -104,13 +105,13 @@ public class CompositeUriComponentsContributor implements UriComponentsContribut @Override public boolean supportsParameter(MethodParameter parameter) { for (Object contributor : this.contributors) { - if (contributor instanceof UriComponentsContributor) { - if (((UriComponentsContributor) contributor).supportsParameter(parameter)) { + if (contributor instanceof UriComponentsContributor ucc) { + if (ucc.supportsParameter(parameter)) { return true; } } - else if (contributor instanceof HandlerMethodArgumentResolver) { - if (((HandlerMethodArgumentResolver) contributor).supportsParameter(parameter)) { + else if (contributor instanceof HandlerMethodArgumentResolver resolver) { + if (resolver.supportsParameter(parameter)) { return false; } } @@ -123,15 +124,14 @@ public class CompositeUriComponentsContributor implements UriComponentsContribut UriComponentsBuilder builder, Map uriVariables, ConversionService conversionService) { for (Object contributor : this.contributors) { - if (contributor instanceof UriComponentsContributor) { - UriComponentsContributor ucc = (UriComponentsContributor) contributor; + if (contributor instanceof UriComponentsContributor ucc) { if (ucc.supportsParameter(parameter)) { ucc.contributeMethodArgument(parameter, value, builder, uriVariables, conversionService); break; } } - else if (contributor instanceof HandlerMethodArgumentResolver) { - if (((HandlerMethodArgumentResolver) contributor).supportsParameter(parameter)) { + else if (contributor instanceof HandlerMethodArgumentResolver resolver) { + if (resolver.supportsParameter(parameter)) { break; } } diff --git a/spring-web/src/main/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditor.java b/spring-web/src/main/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditor.java index b5439e5589..71068c2960 100644 --- a/spring-web/src/main/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditor.java +++ b/spring-web/src/main/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditor.java @@ -33,8 +33,7 @@ public class ByteArrayMultipartFileEditor extends ByteArrayPropertyEditor { @Override public void setValue(@Nullable Object value) { - if (value instanceof MultipartFile) { - MultipartFile multipartFile = (MultipartFile) value; + if (value instanceof MultipartFile multipartFile) { try { super.setValue(multipartFile.getBytes()); } diff --git a/spring-web/src/main/java/org/springframework/web/multipart/support/StringMultipartFileEditor.java b/spring-web/src/main/java/org/springframework/web/multipart/support/StringMultipartFileEditor.java index 015663c274..32bb903a97 100644 --- a/spring-web/src/main/java/org/springframework/web/multipart/support/StringMultipartFileEditor.java +++ b/spring-web/src/main/java/org/springframework/web/multipart/support/StringMultipartFileEditor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2021 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. @@ -61,8 +61,7 @@ public class StringMultipartFileEditor extends PropertyEditorSupport { @Override public void setValue(Object value) { - if (value instanceof MultipartFile) { - MultipartFile multipartFile = (MultipartFile) value; + if (value instanceof MultipartFile multipartFile) { try { super.setValue(this.charsetName != null ? new String(multipartFile.getBytes(), this.charsetName) : diff --git a/spring-web/src/main/java/org/springframework/web/server/adapter/AbstractReactiveWebInitializer.java b/spring-web/src/main/java/org/springframework/web/server/adapter/AbstractReactiveWebInitializer.java index 93db78699c..6e18bec9bb 100644 --- a/spring-web/src/main/java/org/springframework/web/server/adapter/AbstractReactiveWebInitializer.java +++ b/spring-web/src/main/java/org/springframework/web/server/adapter/AbstractReactiveWebInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 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. @@ -41,6 +41,7 @@ import org.springframework.web.WebApplicationInitializer; * the {@link ServletHttpHandlerAdapter}. * * @author Rossen Stoyanchev + * @author Sam Brannen * @since 5.0.2 */ public abstract class AbstractReactiveWebInitializer implements WebApplicationInitializer { @@ -108,11 +109,8 @@ public abstract class AbstractReactiveWebInitializer implements WebApplicationIn * Refresh the given application context, if necessary. */ protected void refreshApplicationContext(ApplicationContext context) { - if (context instanceof ConfigurableApplicationContext) { - ConfigurableApplicationContext cac = (ConfigurableApplicationContext) context; - if (!cac.isActive()) { - cac.refresh(); - } + if (context instanceof ConfigurableApplicationContext cac && !cac.isActive()) { + cac.refresh(); } } @@ -124,10 +122,8 @@ public abstract class AbstractReactiveWebInitializer implements WebApplicationIn * closed when {@code servletContext} is destroyed */ protected void registerCloseListener(ServletContext servletContext, ApplicationContext applicationContext) { - if (applicationContext instanceof ConfigurableApplicationContext) { - ConfigurableApplicationContext cac = (ConfigurableApplicationContext) applicationContext; - ServletContextDestroyedListener listener = new ServletContextDestroyedListener(cac); - servletContext.addListener(listener); + if (applicationContext instanceof ConfigurableApplicationContext cac) { + servletContext.addListener(new ServletContextDestroyedListener(cac)); } } 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 a037452b60..1d5c5843cc 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 @@ -46,6 +46,7 @@ import org.springframework.util.StringUtils; * @author Juergen Hoeller * @author Rossen Stoyanchev * @author Phillip Webb + * @author Sam Brannen * @since 3.1.3 * @see Hierarchical URIs */ @@ -552,10 +553,9 @@ final class HierarchicalUriComponents extends UriComponents { if (this == other) { return true; } - if (!(other instanceof HierarchicalUriComponents)) { + if (!(other instanceof HierarchicalUriComponents otherComp)) { return false; } - HierarchicalUriComponents otherComp = (HierarchicalUriComponents) other; return (ObjectUtils.nullSafeEquals(getScheme(), otherComp.getScheme()) && ObjectUtils.nullSafeEquals(getUserInfo(), otherComp.getUserInfo()) && ObjectUtils.nullSafeEquals(getHost(), otherComp.getHost()) && @@ -925,8 +925,8 @@ final class HierarchicalUriComponents extends UriComponents { @Override public boolean equals(@Nullable Object other) { - return (this == other || (other instanceof FullPathComponent && - getPath().equals(((FullPathComponent) other).getPath()))); + return (this == other || (other instanceof FullPathComponent fullPathComponent && + getPath().equals(fullPathComponent.getPath()))); } @Override @@ -999,8 +999,8 @@ final class HierarchicalUriComponents extends UriComponents { @Override public boolean equals(@Nullable Object other) { - return (this == other || (other instanceof PathSegmentComponent && - getPathSegments().equals(((PathSegmentComponent) other).getPathSegments()))); + return (this == other || (other instanceof PathSegmentComponent pathSegmentComponent && + getPathSegments().equals(pathSegmentComponent.getPathSegments()))); } @Override diff --git a/spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java index a588cffaf4..f6a231c470 100644 --- a/spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java +++ b/spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 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. @@ -161,10 +161,9 @@ final class OpaqueUriComponents extends UriComponents { if (this == other) { return true; } - if (!(other instanceof OpaqueUriComponents)) { + if (!(other instanceof OpaqueUriComponents otherComp)) { return false; } - OpaqueUriComponents otherComp = (OpaqueUriComponents) other; return (ObjectUtils.nullSafeEquals(getScheme(), otherComp.getScheme()) && ObjectUtils.nullSafeEquals(this.ssp, otherComp.ssp) && ObjectUtils.nullSafeEquals(getFragment(), otherComp.getFragment())); diff --git a/spring-web/src/main/java/org/springframework/web/util/WebUtils.java b/spring-web/src/main/java/org/springframework/web/util/WebUtils.java index 6b2532a2a3..e2f4448749 100644 --- a/spring-web/src/main/java/org/springframework/web/util/WebUtils.java +++ b/spring-web/src/main/java/org/springframework/web/util/WebUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -48,11 +48,12 @@ import org.springframework.util.StringUtils; /** * Miscellaneous utilities for web applications. - * Used by various framework classes. + *

Used by various framework classes. * * @author Rod Johnson * @author Juergen Hoeller * @author Sebastien Deleuze + * @author Sam Brannen */ public abstract class WebUtils { @@ -460,8 +461,8 @@ public abstract class WebUtils { if (requiredType.isInstance(request)) { return (T) request; } - else if (request instanceof ServletRequestWrapper) { - return getNativeRequest(((ServletRequestWrapper) request).getRequest(), requiredType); + else if (request instanceof ServletRequestWrapper wrapper) { + return getNativeRequest(wrapper.getRequest(), requiredType); } } return null; @@ -482,8 +483,8 @@ public abstract class WebUtils { if (requiredType.isInstance(response)) { return (T) response; } - else if (response instanceof ServletResponseWrapper) { - return getNativeResponse(((ServletResponseWrapper) response).getResponse(), requiredType); + else if (response instanceof ServletResponseWrapper wrapper) { + return getNativeResponse(wrapper.getResponse(), requiredType); } } return null; @@ -649,8 +650,7 @@ public abstract class WebUtils { public static String findParameterValue(Map parameters, String name) { // First try to get it as a normal name=value parameter Object value = parameters.get(name); - if (value instanceof String[]) { - String[] values = (String[]) value; + if (value instanceof String[] values) { return (values.length > 0 ? values[0] : null); } else if (value != null) { @@ -801,9 +801,9 @@ public abstract class WebUtils { String scheme; String host; int port; - if (request instanceof ServletServerHttpRequest) { + if (request instanceof ServletServerHttpRequest servletServerHttpRequest) { // Build more efficiently if we can: we only need scheme, host, port for origin comparison - HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); + HttpServletRequest servletRequest = servletServerHttpRequest.getServletRequest(); scheme = servletRequest.getScheme(); host = servletRequest.getServerName(); port = servletRequest.getServerPort(); diff --git a/spring-web/src/main/java/org/springframework/web/util/pattern/PathPattern.java b/spring-web/src/main/java/org/springframework/web/util/pattern/PathPattern.java index ba87fd6b6f..956aafe34a 100644 --- a/spring-web/src/main/java/org/springframework/web/util/pattern/PathPattern.java +++ b/spring-web/src/main/java/org/springframework/web/util/pattern/PathPattern.java @@ -430,10 +430,9 @@ public class PathPattern implements Comparable { @Override public boolean equals(@Nullable Object other) { - if (!(other instanceof PathPattern)) { + if (!(other instanceof PathPattern otherPattern)) { return false; } - PathPattern otherPattern = (PathPattern) other; return (this.patternString.equals(otherPattern.getPatternString()) && getSeparator() == otherPattern.getSeparator() && this.caseSensitive == otherPattern.caseSensitive); @@ -726,10 +725,7 @@ public class PathPattern implements Comparable { */ String pathElementValue(int pathIndex) { Element element = (pathIndex < this.pathLength) ? this.pathElements.get(pathIndex) : null; - if (element instanceof PathContainer.PathSegment) { - return ((PathContainer.PathSegment)element).valueToMatch(); - } - return ""; + return (element instanceof PathContainer.PathSegment pathSegment ? pathSegment.valueToMatch() : ""); } }