Apply 'instanceof pattern matching' in spring-web

Closes gh-29530
This commit is contained in:
divcon 2022-11-21 00:36:07 +09:00 committed by Sam Brannen
parent 64c6a97130
commit 99ae209c25
50 changed files with 216 additions and 227 deletions

View File

@ -202,8 +202,8 @@ public class HttpComponentsClientHttpRequestFactory implements ClientHttpRequest
if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
// Use request configuration given by the user, when available
RequestConfig config = null;
if (httpRequest instanceof Configurable) {
config = ((Configurable) httpRequest).getConfig();
if (httpRequest instanceof Configurable configurable) {
config = configurable.getConfig();
}
if (config == null) {
config = createRequestConfig(client);
@ -328,8 +328,8 @@ public class HttpComponentsClientHttpRequestFactory implements ClientHttpRequest
@Override
public void destroy() throws Exception {
HttpClient httpClient = getHttpClient();
if (httpClient instanceof Closeable) {
((Closeable) httpClient).close();
if (httpClient instanceof Closeable closeable) {
closeable.close();
}
}

View File

@ -159,9 +159,8 @@ public class HttpComponentsClientHttpConnector implements ClientHttpConnector, C
@Override
public void failed(Exception ex) {
Throwable t = ex;
if (t instanceof HttpStreamResetException) {
HttpStreamResetException httpStreamResetException = (HttpStreamResetException) ex;
t = httpStreamResetException.getCause();
if (t instanceof HttpStreamResetException hsre) {
t = hsre.getCause();
}
this.sink.error(t);
}

View File

@ -131,16 +131,16 @@ public class JettyResourceFactory implements InitializingBean, DisposableBean {
}
if (this.byteBufferPool == null) {
this.byteBufferPool = new MappedByteBufferPool(2048,
this.executor instanceof ThreadPool.SizedThreadPool
? ((ThreadPool.SizedThreadPool) this.executor).getMaxThreads() / 2
this.executor instanceof ThreadPool.SizedThreadPool sizedThreadPool
? sizedThreadPool.getMaxThreads() / 2
: ProcessorUtils.availableProcessors() * 2);
}
if (this.scheduler == null) {
this.scheduler = new ScheduledExecutorScheduler(name + "-scheduler", false);
}
if (this.executor instanceof LifeCycle) {
((LifeCycle)this.executor).start();
if (this.executor instanceof LifeCycle lifeCycle) {
lifeCycle.start();
}
this.scheduler.start();
}
@ -148,8 +148,8 @@ public class JettyResourceFactory implements InitializingBean, DisposableBean {
@Override
public void destroy() throws Exception {
try {
if (this.executor instanceof LifeCycle) {
((LifeCycle)this.executor).stop();
if (this.executor instanceof LifeCycle lifeCycle) {
lifeCycle.stop();
}
}
catch (Throwable ex) {

View File

@ -67,10 +67,10 @@ public class DecoderHttpMessageReader<T> implements HttpMessageReader<T> {
}
private static void initLogger(Decoder<?> decoder) {
if (decoder instanceof AbstractDecoder &&
if (decoder instanceof AbstractDecoder<?> abstractDecoder &&
decoder.getClass().getName().startsWith("org.springframework.core.codec")) {
Log logger = HttpLogging.forLog(((AbstractDecoder<?>) decoder).getLogger());
((AbstractDecoder<?>) decoder).setLogger(logger);
Log logger = HttpLogging.forLog(abstractDecoder.getLogger());
abstractDecoder.setLogger(logger);
}
}
@ -163,9 +163,8 @@ public class DecoderHttpMessageReader<T> implements HttpMessageReader<T> {
protected Map<String, Object> getReadHints(ResolvableType actualType,
ResolvableType elementType, ServerHttpRequest request, ServerHttpResponse response) {
if (this.decoder instanceof HttpMessageDecoder) {
HttpMessageDecoder<?> decoder = (HttpMessageDecoder<?>) this.decoder;
return decoder.getDecodeHints(actualType, elementType, request, response);
if (this.decoder instanceof HttpMessageDecoder<?> httpMethodDecoder) {
return httpMethodDecoder.getDecodeHints(actualType, elementType, request, response);
}
return Hints.none();
}

View File

@ -79,10 +79,10 @@ public class EncoderHttpMessageWriter<T> implements HttpMessageWriter<T> {
}
private static void initLogger(Encoder<?> encoder) {
if (encoder instanceof AbstractEncoder &&
if (encoder instanceof AbstractEncoder<?> abstractEncoder &&
encoder.getClass().getName().startsWith("org.springframework.core.codec")) {
Log logger = HttpLogging.forLog(((AbstractEncoder<?>) encoder).getLogger());
((AbstractEncoder<?>) encoder).setLogger(logger);
Log logger = HttpLogging.forLog(abstractEncoder.getLogger());
abstractEncoder.setLogger(logger);
}
}
@ -224,9 +224,8 @@ public class EncoderHttpMessageWriter<T> implements HttpMessageWriter<T> {
protected Map<String, Object> getWriteHints(ResolvableType streamType, ResolvableType elementType,
@Nullable MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response) {
if (this.encoder instanceof HttpMessageEncoder) {
HttpMessageEncoder<?> encoder = (HttpMessageEncoder<?>) this.encoder;
return encoder.getEncodeHints(streamType, elementType, mediaType, request, response);
if (this.encoder instanceof HttpMessageEncoder<?> httpMessageEncoder) {
return httpMessageEncoder.getEncodeHints(streamType, elementType, mediaType, request, response);
}
return Hints.none();
}

View File

@ -179,7 +179,7 @@ public class ResourceHttpMessageWriter implements HttpMessageWriter<Resource> {
private static Optional<Mono<Void>> zeroCopy(Resource resource, @Nullable ResourceRegion region,
ReactiveHttpOutputMessage message, Map<String, Object> hints) {
if (message instanceof ZeroCopyHttpOutputMessage && resource.isFile()) {
if (message instanceof ZeroCopyHttpOutputMessage zeroCopyHttpOutputMessage && resource.isFile()) {
try {
File file = resource.getFile();
long pos = region != null ? region.getPosition() : 0;
@ -188,7 +188,7 @@ public class ResourceHttpMessageWriter implements HttpMessageWriter<Resource> {
String formatted = region != null ? "region " + pos + "-" + (count) + " of " : "";
logger.debug(Hints.getLogPrefix(hints) + "Zero-copy " + formatted + "[" + resource + "]");
}
return Optional.of(((ZeroCopyHttpOutputMessage) message).writeWith(file, pos, count));
return Optional.of(zeroCopyHttpOutputMessage.writeWith(file, pos, count));
}
catch (IOException ex) {
// should not happen

View File

@ -121,8 +121,8 @@ public class ServerSentEventHttpMessageWriter implements HttpMessageWriter<Objec
return Flux.from(input).map(element -> {
ServerSentEvent<?> sse = (element instanceof ServerSentEvent ?
(ServerSentEvent<?>) element : ServerSentEvent.builder().data(element).build());
ServerSentEvent<?> sse = (element instanceof ServerSentEvent<?> serverSentEvent ?
serverSentEvent : ServerSentEvent.builder().data(element).build());
StringBuilder sb = new StringBuilder();
String id = sse.id();
@ -150,9 +150,9 @@ public class ServerSentEventHttpMessageWriter implements HttpMessageWriter<Objec
if (data == null) {
result = Flux.just(encodeText(sb + "\n", mediaType, factory));
}
else if (data instanceof String) {
data = StringUtils.replace((String) data, "\n", "\ndata:");
result = Flux.just(encodeText(sb + (String) data + "\n\n", mediaType, factory));
else if (data instanceof String dataString) {
dataString = StringUtils.replace(dataString, "\n", "\ndata:");
result = Flux.just(encodeText(sb + dataString + "\n\n", mediaType, factory));
}
else {
result = encodeEvent(sb, data, dataType, mediaType, factory, hints);
@ -203,9 +203,8 @@ public class ServerSentEventHttpMessageWriter implements HttpMessageWriter<Objec
private Map<String, Object> getEncodeHints(ResolvableType actualType, ResolvableType elementType,
@Nullable MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response) {
if (this.encoder instanceof HttpMessageEncoder) {
HttpMessageEncoder<?> encoder = (HttpMessageEncoder<?>) this.encoder;
return encoder.getEncodeHints(actualType, elementType, mediaType, request, response);
if (this.encoder instanceof HttpMessageEncoder<?> httpMessageEncoder) {
return httpMessageEncoder.getEncodeHints(actualType, elementType, mediaType, request, response);
}
return Hints.none();
}

View File

@ -264,12 +264,12 @@ public abstract class AbstractJackson2Decoder extends Jackson2CodecSupport imple
}
private CodecException processException(IOException ex) {
if (ex instanceof InvalidDefinitionException) {
JavaType type = ((InvalidDefinitionException) ex).getType();
if (ex instanceof InvalidDefinitionException ide) {
JavaType type = ide.getType();
return new CodecException("Type definition error: " + type, ex);
}
if (ex instanceof JsonProcessingException) {
String originalMessage = ((JsonProcessingException) ex).getOriginalMessage();
if (ex instanceof JsonProcessingException jpe) {
String originalMessage = jpe.getOriginalMessage();
return new DecodingException("JSON decoding error: " + originalMessage, ex);
}
return new DecodingException("I/O error while parsing input stream", ex);

View File

@ -255,7 +255,7 @@ public abstract class Jackson2CodecSupport {
@Nullable
protected MethodParameter getParameter(ResolvableType type) {
return (type.getSource() instanceof MethodParameter ? (MethodParameter) type.getSource() : null);
return (type.getSource() instanceof MethodParameter methodParameter ? methodParameter : null);
}
@Nullable

View File

@ -129,7 +129,7 @@ public class MultipartHttpMessageReader extends LoggingCodecSupport
}
private List<Part> toList(Collection<Part> collection) {
return collection instanceof List ? (List<Part>) collection : new ArrayList<>(collection);
return collection instanceof List<Part> partList ? partList : new ArrayList<>(collection);
}
}

View File

@ -81,7 +81,7 @@ public class PartHttpMessageWriter extends MultipartWriterSupport implements Htt
String name = part.name();
if (!headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
headers.setContentDispositionFormData(name,
(part instanceof FilePart ? ((FilePart) part).filename() : null));
(part instanceof FilePart filePart ? filePart.filename() : null));
}
return Flux.concat(

View File

@ -196,20 +196,18 @@ abstract class BaseCodecConfigurer implements CodecConfigurer {
private void addCodec(Object codec, boolean applyDefaultConfig) {
if (codec instanceof Decoder) {
codec = new DecoderHttpMessageReader<>((Decoder<?>) codec);
if (codec instanceof Decoder<?> decoder) {
codec = new DecoderHttpMessageReader<>(decoder);
}
else if (codec instanceof Encoder) {
codec = new EncoderHttpMessageWriter<>((Encoder<?>) codec);
else if (codec instanceof Encoder<?> encoder) {
codec = new EncoderHttpMessageWriter<>(encoder);
}
if (codec instanceof HttpMessageReader) {
HttpMessageReader<?> reader = (HttpMessageReader<?>) codec;
if (codec instanceof HttpMessageReader<?> reader) {
boolean canReadToObject = reader.canRead(ResolvableType.forClass(Object.class), null);
(canReadToObject ? this.objectReaders : this.typedReaders).put(reader, applyDefaultConfig);
}
else if (codec instanceof HttpMessageWriter) {
HttpMessageWriter<?> writer = (HttpMessageWriter<?>) codec;
else if (codec instanceof HttpMessageWriter<?> writer) {
boolean canWriteObject = writer.canWrite(ResolvableType.forClass(Object.class), null);
(canWriteObject ? this.objectWriters : this.typedWriters).put(writer, applyDefaultConfig);
}

View File

@ -424,13 +424,12 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
* if configured by the application, to the given codec , including any
* codec it contains.
*/
@SuppressWarnings("rawtypes")
private void initCodec(@Nullable Object codec) {
if (codec instanceof DecoderHttpMessageReader) {
codec = ((DecoderHttpMessageReader) codec).getDecoder();
if (codec instanceof DecoderHttpMessageReader<?> decoderHttpMessageReader) {
codec = decoderHttpMessageReader.getDecoder();
}
else if (codec instanceof EncoderHttpMessageWriter) {
codec = ((EncoderHttpMessageWriter<?>) codec).getEncoder();
else if (codec instanceof EncoderHttpMessageWriter<?> encoderHttpMessageWriter) {
codec = encoderHttpMessageWriter.getEncoder();
}
if (codec == null) {
@ -439,72 +438,72 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
Integer size = this.maxInMemorySize;
if (size != null) {
if (codec instanceof AbstractDataBufferDecoder) {
((AbstractDataBufferDecoder<?>) codec).setMaxInMemorySize(size);
if (codec instanceof AbstractDataBufferDecoder<?> abstractDataBufferDecoder) {
abstractDataBufferDecoder.setMaxInMemorySize(size);
}
if (protobufPresent) {
if (codec instanceof ProtobufDecoder) {
((ProtobufDecoder) codec).setMaxMessageSize(size);
if (codec instanceof ProtobufDecoder protobufDecoderCodec) {
protobufDecoderCodec.setMaxMessageSize(size);
}
}
if (kotlinSerializationCborPresent) {
if (codec instanceof KotlinSerializationCborDecoder) {
((KotlinSerializationCborDecoder) codec).setMaxInMemorySize(size);
if (codec instanceof KotlinSerializationCborDecoder kotlinSerializationCborDecoderCodec) {
kotlinSerializationCborDecoderCodec.setMaxInMemorySize(size);
}
}
if (kotlinSerializationJsonPresent) {
if (codec instanceof KotlinSerializationJsonDecoder) {
((KotlinSerializationJsonDecoder) codec).setMaxInMemorySize(size);
if (codec instanceof KotlinSerializationJsonDecoder kotlinSerializationJsonDecoderCodec) {
kotlinSerializationJsonDecoderCodec.setMaxInMemorySize(size);
}
}
if (kotlinSerializationProtobufPresent) {
if (codec instanceof KotlinSerializationProtobufDecoder) {
((KotlinSerializationProtobufDecoder) codec).setMaxInMemorySize(size);
if (codec instanceof KotlinSerializationProtobufDecoder kotlinSerializationProtobufDecoderCodec) {
kotlinSerializationProtobufDecoderCodec.setMaxInMemorySize(size);
}
}
if (jackson2Present) {
if (codec instanceof AbstractJackson2Decoder) {
((AbstractJackson2Decoder) codec).setMaxInMemorySize(size);
if (codec instanceof AbstractJackson2Decoder abstractJackson2Decoder) {
abstractJackson2Decoder.setMaxInMemorySize(size);
}
}
if (jaxb2Present) {
if (codec instanceof Jaxb2XmlDecoder) {
((Jaxb2XmlDecoder) codec).setMaxInMemorySize(size);
if (codec instanceof Jaxb2XmlDecoder jaxb2XmlDecoder) {
jaxb2XmlDecoder.setMaxInMemorySize(size);
}
}
if (codec instanceof FormHttpMessageReader) {
((FormHttpMessageReader) codec).setMaxInMemorySize(size);
if (codec instanceof FormHttpMessageReader formHttpMessageReader) {
formHttpMessageReader.setMaxInMemorySize(size);
}
if (codec instanceof ServerSentEventHttpMessageReader) {
((ServerSentEventHttpMessageReader) codec).setMaxInMemorySize(size);
if (codec instanceof ServerSentEventHttpMessageReader serverSentEventHttpMessageReader) {
serverSentEventHttpMessageReader.setMaxInMemorySize(size);
}
if (codec instanceof DefaultPartHttpMessageReader) {
((DefaultPartHttpMessageReader) codec).setMaxInMemorySize(size);
if (codec instanceof DefaultPartHttpMessageReader defaultPartHttpMessageReader) {
defaultPartHttpMessageReader.setMaxInMemorySize(size);
}
if (codec instanceof PartEventHttpMessageReader) {
((PartEventHttpMessageReader) codec).setMaxInMemorySize(size);
if (codec instanceof PartEventHttpMessageReader partEventHttpMessageReader) {
partEventHttpMessageReader.setMaxInMemorySize(size);
}
}
Boolean enable = this.enableLoggingRequestDetails;
if (enable != null) {
if (codec instanceof FormHttpMessageReader) {
((FormHttpMessageReader) codec).setEnableLoggingRequestDetails(enable);
if (codec instanceof FormHttpMessageReader formHttpMessageReader) {
formHttpMessageReader.setEnableLoggingRequestDetails(enable);
}
if (codec instanceof MultipartHttpMessageReader) {
((MultipartHttpMessageReader) codec).setEnableLoggingRequestDetails(enable);
if (codec instanceof MultipartHttpMessageReader multipartHttpMessageReader) {
multipartHttpMessageReader.setEnableLoggingRequestDetails(enable);
}
if (codec instanceof DefaultPartHttpMessageReader) {
((DefaultPartHttpMessageReader) codec).setEnableLoggingRequestDetails(enable);
if (codec instanceof DefaultPartHttpMessageReader defaultPartHttpMessageReader) {
defaultPartHttpMessageReader.setEnableLoggingRequestDetails(enable);
}
if (codec instanceof PartEventHttpMessageReader) {
((PartEventHttpMessageReader) codec).setEnableLoggingRequestDetails(enable);
if (codec instanceof PartEventHttpMessageReader partEventHttpMessageReader) {
partEventHttpMessageReader.setEnableLoggingRequestDetails(enable);
}
if (codec instanceof FormHttpMessageWriter) {
((FormHttpMessageWriter) codec).setEnableLoggingRequestDetails(enable);
if (codec instanceof FormHttpMessageWriter formHttpMessageWriter) {
formHttpMessageWriter.setEnableLoggingRequestDetails(enable);
}
if (codec instanceof MultipartHttpMessageWriter) {
((MultipartHttpMessageWriter) codec).setEnableLoggingRequestDetails(enable);
if (codec instanceof MultipartHttpMessageWriter multipartHttpMessageWriter) {
multipartHttpMessageWriter.setEnableLoggingRequestDetails(enable);
}
}
@ -513,17 +512,17 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
}
// Recurse for nested codecs
if (codec instanceof MultipartHttpMessageReader) {
initCodec(((MultipartHttpMessageReader) codec).getPartReader());
if (codec instanceof MultipartHttpMessageReader multipartHttpMessageReader) {
initCodec(multipartHttpMessageReader.getPartReader());
}
else if (codec instanceof MultipartHttpMessageWriter) {
initCodec(((MultipartHttpMessageWriter) codec).getFormWriter());
else if (codec instanceof MultipartHttpMessageWriter multipartHttpMessageWriter) {
initCodec(multipartHttpMessageWriter.getFormWriter());
}
else if (codec instanceof ServerSentEventHttpMessageReader) {
initCodec(((ServerSentEventHttpMessageReader) codec).getDecoder());
else if (codec instanceof ServerSentEventHttpMessageReader serverSentEventHttpMessageReader) {
initCodec(serverSentEventHttpMessageReader.getDecoder());
}
else if (codec instanceof ServerSentEventHttpMessageWriter) {
initCodec(((ServerSentEventHttpMessageWriter) codec).getEncoder());
else if (codec instanceof ServerSentEventHttpMessageWriter serverSentEventHttpMessageWriter) {
initCodec(serverSentEventHttpMessageWriter.getEncoder());
}
}

View File

@ -819,20 +819,20 @@ public class Jackson2ObjectMapperBuilder {
@SuppressWarnings("deprecation") // on Jackson 2.13: configure(MapperFeature, boolean)
private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) {
if (feature instanceof JsonParser.Feature) {
objectMapper.configure((JsonParser.Feature) feature, enabled);
if (feature instanceof JsonParser.Feature jsonParserFeature) {
objectMapper.configure(jsonParserFeature, enabled);
}
else if (feature instanceof JsonGenerator.Feature) {
objectMapper.configure((JsonGenerator.Feature) feature, enabled);
else if (feature instanceof JsonGenerator.Feature jsonGeneratorFeature) {
objectMapper.configure(jsonGeneratorFeature, enabled);
}
else if (feature instanceof SerializationFeature) {
objectMapper.configure((SerializationFeature) feature, enabled);
else if (feature instanceof SerializationFeature serializationFeature) {
objectMapper.configure(serializationFeature, enabled);
}
else if (feature instanceof DeserializationFeature) {
objectMapper.configure((DeserializationFeature) feature, enabled);
else if (feature instanceof DeserializationFeature deserializationFeature) {
objectMapper.configure(deserializationFeature, enabled);
}
else if (feature instanceof MapperFeature) {
objectMapper.configure((MapperFeature) feature, enabled);
else if (feature instanceof MapperFeature mapperFeature) {
objectMapper.configure(mapperFeature, enabled);
}
else {
throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName());

View File

@ -69,8 +69,8 @@ public class MarshallingHttpMessageConverter extends AbstractXmlHttpMessageConve
public MarshallingHttpMessageConverter(Marshaller marshaller) {
Assert.notNull(marshaller, "Marshaller must not be null");
this.marshaller = marshaller;
if (marshaller instanceof Unmarshaller) {
this.unmarshaller = (Unmarshaller) marshaller;
if (marshaller instanceof Unmarshaller um) {
this.unmarshaller = um;
}
}

View File

@ -335,8 +335,8 @@ public class ChannelSendOperator<T> extends Mono<Void> implements Scannable {
private void releaseCachedItem() {
synchronized (this) {
Object item = this.item;
if (item instanceof DataBuffer) {
DataBufferUtils.release((DataBuffer) item);
if (item instanceof DataBuffer dataBuffer) {
DataBufferUtils.release(dataBuffer);
}
this.item = null;
}

View File

@ -100,8 +100,8 @@ final class DefaultSslInfo implements SslInfo {
List<X509Certificate> result = new ArrayList<>(certificates.length);
for (Certificate certificate : certificates) {
if (certificate instanceof X509Certificate) {
result.add((X509Certificate) certificate);
if (certificate instanceof X509Certificate x509Certificate) {
result.add(x509Certificate);
}
}
return (!result.isEmpty() ? result.toArray(new X509Certificate[0]) : null);

View File

@ -105,7 +105,7 @@ class JettyHeadersAdapter implements MultiValueMap<String, String> {
@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
@ -134,9 +134,9 @@ class JettyHeadersAdapter implements MultiValueMap<String, String> {
@Nullable
@Override
public List<String> remove(Object key) {
if (key instanceof String) {
if (key instanceof String headerName) {
List<String> oldValues = get(key);
this.headers.remove((String) key);
this.headers.remove(headerName);
return oldValues;
}
return null;

View File

@ -196,8 +196,8 @@ class ReactorNetty2ServerHttpRequest extends AbstractServerHttpRequest {
@Override
@Nullable
protected String initId() {
if (this.request instanceof Connection) {
return ((Connection) this.request).channel().id().asShortText() +
if (this.request instanceof Connection connection) {
return connection.channel().id().asShortText() +
"-" + logPrefixIndex.incrementAndGet();
}
return null;
@ -212,8 +212,8 @@ class ReactorNetty2ServerHttpRequest extends AbstractServerHttpRequest {
if (id != null) {
return id;
}
if (this.request instanceof Connection) {
return ((Connection) this.request).channel().id().asShortText() +
if (this.request instanceof Connection connection) {
return connection.channel().id().asShortText() +
"-" + logPrefixIndex.incrementAndGet();
}
return getId();

View File

@ -193,8 +193,8 @@ class ReactorServerHttpRequest extends AbstractServerHttpRequest {
@Override
@Nullable
protected String initId() {
if (this.request instanceof Connection) {
return ((Connection) this.request).channel().id().asShortText() +
if (this.request instanceof Connection connection) {
return connection.channel().id().asShortText() +
"-" + logPrefixIndex.incrementAndGet();
}
return null;
@ -209,8 +209,8 @@ class ReactorServerHttpRequest extends AbstractServerHttpRequest {
if (id != null) {
return id;
}
if (this.request instanceof Connection) {
return ((Connection) this.request).channel().id().asShortText() +
if (this.request instanceof Connection connection) {
return connection.channel().id().asShortText() +
"-" + logPrefixIndex.incrementAndGet();
}
return getId();

View File

@ -123,11 +123,11 @@ public class ServerHttpRequestDecorator implements ServerHttpRequest {
* @since 5.3.3
*/
public static <T> T getNativeRequest(ServerHttpRequest request) {
if (request instanceof AbstractServerHttpRequest) {
return ((AbstractServerHttpRequest) request).getNativeRequest();
if (request instanceof AbstractServerHttpRequest abstractServerHttpRequest) {
return abstractServerHttpRequest.getNativeRequest();
}
else if (request instanceof ServerHttpRequestDecorator) {
return getNativeRequest(((ServerHttpRequestDecorator) request).getDelegate());
else if (request instanceof ServerHttpRequestDecorator serverHttpRequestDecorator) {
return getNativeRequest(serverHttpRequestDecorator.getDelegate());
}
else {
throw new IllegalArgumentException(

View File

@ -131,11 +131,11 @@ public class ServerHttpResponseDecorator implements ServerHttpResponse {
* @since 5.3.3
*/
public static <T> T getNativeResponse(ServerHttpResponse response) {
if (response instanceof AbstractServerHttpResponse) {
return ((AbstractServerHttpResponse) response).getNativeResponse();
if (response instanceof AbstractServerHttpResponse abstractServerHttpResponse) {
return abstractServerHttpResponse.getNativeResponse();
}
else if (response instanceof ServerHttpResponseDecorator) {
return getNativeResponse(((ServerHttpResponseDecorator) response).getDelegate());
else if (response instanceof ServerHttpResponseDecorator serverHttpResponseDecorator) {
return getNativeResponse(serverHttpResponseDecorator.getDelegate());
}
else {
throw new IllegalArgumentException(

View File

@ -74,8 +74,8 @@ public class ContentNegotiationManager implements ContentNegotiationStrategy, Me
Assert.notEmpty(strategies, "At least one ContentNegotiationStrategy is expected");
this.strategies.addAll(strategies);
for (ContentNegotiationStrategy strategy : this.strategies) {
if (strategy instanceof MediaTypeFileExtensionResolver) {
this.resolvers.add((MediaTypeFileExtensionResolver) strategy);
if (strategy instanceof MediaTypeFileExtensionResolver mediaTypeFileExtensionResolver) {
this.resolvers.add(mediaTypeFileExtensionResolver);
}
}
}
@ -180,8 +180,8 @@ public class ContentNegotiationManager implements ContentNegotiationStrategy, Me
public Map<String, MediaType> getMediaTypeMappings() {
Map<String, MediaType> result = null;
for (MediaTypeFileExtensionResolver resolver : this.resolvers) {
if (resolver instanceof MappingMediaTypeFileExtensionResolver) {
Map<String, MediaType> map = ((MappingMediaTypeFileExtensionResolver) resolver).getMediaTypes();
if (resolver instanceof MappingMediaTypeFileExtensionResolver mappingMediaTypeFileExtensionResolver) {
Map<String, MediaType> map = mappingMediaTypeFileExtensionResolver.getMediaTypes();
if (CollectionUtils.isEmpty(map)) {
continue;
}

View File

@ -122,7 +122,7 @@ public class WebExchangeDataBinder extends WebDataBinder {
protected static void addBindValue(Map<String, Object> params, String key, List<?> values) {
if (!CollectionUtils.isEmpty(values)) {
values = values.stream()
.map(value -> value instanceof FormFieldPart ? ((FormFieldPart) value).value() : value)
.map(value -> value instanceof FormFieldPart formFieldPart ? formFieldPart.value() : value)
.toList();
params.put(key, values.size() == 1 ? values.get(0) : values);
}

View File

@ -94,9 +94,7 @@ public class HttpMessageConverterExtractor<T> implements ResponseExtractor<T> {
try {
for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
if (messageConverter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<?> genericMessageConverter =
(GenericHttpMessageConverter<?>) messageConverter;
if (messageConverter instanceof GenericHttpMessageConverter genericMessageConverter) {
if (genericMessageConverter.canRead(this.responseType, null, contentType)) {
if (logger.isDebugEnabled()) {
ResolvableType resolvableType = ResolvableType.forType(this.responseType);

View File

@ -321,8 +321,8 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
* @since 4.3
*/
public void setDefaultUriVariables(Map<String, ?> uriVars) {
if (this.uriTemplateHandler instanceof DefaultUriBuilderFactory) {
((DefaultUriBuilderFactory) this.uriTemplateHandler).setDefaultUriVariables(uriVars);
if (this.uriTemplateHandler instanceof DefaultUriBuilderFactory defaultUriVariables) {
defaultUriVariables.setDefaultUriVariables(uriVars);
}
else {
throw new IllegalArgumentException(
@ -723,8 +723,7 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
}
private URI resolveUrl(RequestEntity<?> entity) {
if (entity instanceof RequestEntity.UriTemplateRequestEntity) {
RequestEntity.UriTemplateRequestEntity<?> ext = (RequestEntity.UriTemplateRequestEntity<?>) entity;
if (entity instanceof RequestEntity.UriTemplateRequestEntity<?> ext) {
if (ext.getVars() != null) {
return this.uriTemplateHandler.expand(ext.getUriTemplate(), ext.getVars());
}
@ -1003,19 +1002,18 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
}
private boolean canReadResponse(Type responseType, HttpMessageConverter<?> converter) {
Class<?> responseClass = (responseType instanceof Class ? (Class<?>) responseType : null);
Class<?> responseClass = (responseType instanceof Class<?> type ? type : null);
if (responseClass != null) {
return converter.canRead(responseClass, null);
}
else if (converter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter;
else if (converter instanceof GenericHttpMessageConverter<?> genericConverter) {
return genericConverter.canRead(responseType, null, null);
}
return false;
}
private Stream<MediaType> getSupportedMediaTypes(Type type, HttpMessageConverter<?> converter) {
Type rawType = (type instanceof ParameterizedType ? ((ParameterizedType) type).getRawType() : type);
Type rawType = (type instanceof ParameterizedType parameterizedType ? parameterizedType.getRawType() : type);
Class<?> clazz = (rawType instanceof Class ? (Class<?>) rawType : null);
return (clazz != null ? converter.getSupportedMediaTypes(clazz) : converter.getSupportedMediaTypes())
.stream()
@ -1042,8 +1040,8 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
public HttpEntityRequestCallback(@Nullable Object requestBody, @Nullable Type responseType) {
super(responseType);
if (requestBody instanceof HttpEntity) {
this.requestEntity = (HttpEntity<?>) requestBody;
if (requestBody instanceof HttpEntity<?> httpEntity) {
this.requestEntity = httpEntity;
}
else if (requestBody != null) {
this.requestEntity = new HttpEntity<>(requestBody);
@ -1070,8 +1068,8 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
}
else {
Class<?> requestBodyClass = requestBody.getClass();
Type requestBodyType = (this.requestEntity instanceof RequestEntity ?
((RequestEntity<?>)this.requestEntity).getType() : requestBodyClass);
Type requestBodyType = (this.requestEntity instanceof RequestEntity<?> re ?
re.getType() : requestBodyClass);
HttpHeaders httpHeaders = httpRequest.getHeaders();
HttpHeaders requestHeaders = this.requestEntity.getHeaders();
MediaType requestContentType = requestHeaders.getContentType();

View File

@ -65,9 +65,9 @@ public class ContextCleanupListener implements ServletContextListener {
String attrName = attrNames.nextElement();
if (attrName.startsWith("org.springframework.")) {
Object attrValue = servletContext.getAttribute(attrName);
if (attrValue instanceof DisposableBean) {
if (attrValue instanceof DisposableBean disposableBean) {
try {
((DisposableBean) attrValue).destroy();
disposableBean.destroy();
}
catch (Throwable ex) {
if (logger.isWarnEnabled()) {

View File

@ -51,11 +51,10 @@ public class RequestContextListener implements ServletRequestListener {
@Override
public void requestInitialized(ServletRequestEvent requestEvent) {
if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
if (!(requestEvent.getServletRequest() instanceof HttpServletRequest request)) {
throw new IllegalArgumentException(
"Request is not an HttpServletRequest: " + requestEvent.getServletRequest());
}
HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();
ServletRequestAttributes attributes = new ServletRequestAttributes(request);
request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);
LocaleContextHolder.setLocale(request.getLocale());

View File

@ -209,8 +209,8 @@ public abstract class AbstractRefreshableWebApplicationContext extends AbstractR
@Override
protected void initPropertySources() {
ConfigurableEnvironment env = getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, this.servletConfig);
if (env instanceof ConfigurableWebEnvironment configurableWebEnv) {
configurableWebEnv.initPropertySources(this.servletContext, this.servletConfig);
}
}

View File

@ -208,8 +208,8 @@ public class GenericWebApplicationContext extends GenericApplicationContext
@Override
protected void initPropertySources() {
ConfigurableEnvironment env = getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, null);
if (env instanceof ConfigurableWebEnvironment configurableWebEnv) {
configurableWebEnv.initPropertySources(this.servletContext, null);
}
}

View File

@ -104,11 +104,11 @@ public class ServletContextAwareProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (getServletContext() != null && bean instanceof ServletContextAware) {
((ServletContextAware) bean).setServletContext(getServletContext());
if (getServletContext() != null && bean instanceof ServletContextAware servletContextAware) {
servletContextAware.setServletContext(getServletContext());
}
if (getServletConfig() != null && bean instanceof ServletConfigAware) {
((ServletConfigAware) bean).setServletConfig(getServletConfig());
if (getServletConfig() != null && bean instanceof ServletConfigAware servletConfigAware) {
servletConfigAware.setServletConfig(getServletConfig());
}
return bean;
}

View File

@ -114,19 +114,19 @@ public abstract class WebApplicationContextUtils {
if (attr == null) {
return null;
}
if (attr instanceof RuntimeException) {
throw (RuntimeException) attr;
if (attr instanceof RuntimeException re) {
throw re;
}
if (attr instanceof Error) {
throw (Error) attr;
if (attr instanceof Error error) {
throw error;
}
if (attr instanceof Exception) {
throw new IllegalStateException((Exception) attr);
if (attr instanceof Exception ex) {
throw new IllegalStateException(ex);
}
if (!(attr instanceof WebApplicationContext)) {
if (!(attr instanceof WebApplicationContext wac)) {
throw new IllegalStateException("Context attribute is not of type WebApplicationContext: " + attr);
}
return (WebApplicationContext) attr;
return wac;
}
/**
@ -311,10 +311,10 @@ public abstract class WebApplicationContextUtils {
*/
private static ServletRequestAttributes currentRequestAttributes() {
RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes();
if (!(requestAttr instanceof ServletRequestAttributes)) {
if (!(requestAttr instanceof ServletRequestAttributes servletRequestAttributes)) {
throw new IllegalStateException("Current request is not a servlet request");
}
return (ServletRequestAttributes) requestAttr;
return servletRequestAttributes;
}

View File

@ -76,8 +76,8 @@ public abstract class WebApplicationObjectSupport extends ApplicationObjectSuppo
@Override
protected void initApplicationContext(ApplicationContext context) {
super.initApplicationContext(context);
if (this.servletContext == null && context instanceof WebApplicationContext) {
this.servletContext = ((WebApplicationContext) context).getServletContext();
if (this.servletContext == null && context instanceof WebApplicationContext wac) {
this.servletContext = wac.getServletContext();
if (this.servletContext != null) {
initServletContext(this.servletContext);
}
@ -108,8 +108,8 @@ public abstract class WebApplicationObjectSupport extends ApplicationObjectSuppo
@Nullable
protected final WebApplicationContext getWebApplicationContext() throws IllegalStateException {
ApplicationContext ctx = getApplicationContext();
if (ctx instanceof WebApplicationContext) {
return (WebApplicationContext) getApplicationContext();
if (ctx instanceof WebApplicationContext wac) {
return wac;
}
else if (isContextRequired()) {
throw new IllegalStateException("WebApplicationObjectSupport instance [" + this +

View File

@ -110,8 +110,8 @@ public class DelegatingNavigationHandlerProxy extends NavigationHandler {
@Override
public void handleNavigation(FacesContext facesContext, String fromAction, String outcome) {
NavigationHandler handler = getDelegate(facesContext);
if (handler instanceof DecoratingNavigationHandler) {
((DecoratingNavigationHandler) handler).handleNavigation(
if (handler instanceof DecoratingNavigationHandler decoratingNavigationHandler) {
decoratingNavigationHandler.handleNavigation(
facesContext, fromAction, outcome, this.originalNavigationHandler);
}
else {

View File

@ -55,16 +55,16 @@ public abstract class FacesContextUtils {
if (attr == null) {
return null;
}
if (attr instanceof RuntimeException) {
throw (RuntimeException) attr;
if (attr instanceof RuntimeException re) {
throw re;
}
if (attr instanceof Error) {
throw (Error) attr;
if (attr instanceof Error error) {
throw error;
}
if (!(attr instanceof WebApplicationContext)) {
if (!(attr instanceof WebApplicationContext wac)) {
throw new IllegalStateException("Root context attribute is not of type WebApplicationContext: " + attr);
}
return (WebApplicationContext) attr;
return wac;
}
/**

View File

@ -160,8 +160,8 @@ public class ControllerAdviceBean implements Ordered {
if (this.order == null) {
String beanName = null;
Object resolvedBean = null;
if (this.beanFactory != null && this.beanOrName instanceof String) {
beanName = (String) this.beanOrName;
if (this.beanFactory != null && this.beanOrName instanceof String stringBeanName) {
beanName = stringBeanName;
String targetBeanName = ScopedProxyUtils.getTargetBeanName(beanName);
boolean isScopedProxy = this.beanFactory.containsBean(targetBeanName);
// Avoid eager @ControllerAdvice bean resolution for scoped proxies,

View File

@ -65,8 +65,8 @@ public class MapMethodProcessor implements HandlerMethodArgumentResolver, Handle
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
if (returnValue instanceof Map){
mavContainer.addAllAttributes((Map) returnValue);
if (returnValue instanceof Map returnValueMap) {
mavContainer.addAllAttributes(returnValueMap);
}
else if (returnValue != null) {
// should not happen

View File

@ -406,9 +406,9 @@ public class ModelAttributeMethodProcessor implements HandlerMethodArgumentResol
Object[] validationHints = ValidationAnnotationUtils.determineValidationHints(ann);
if (validationHints != null) {
for (Validator validator : binder.getValidators()) {
if (validator instanceof SmartValidator) {
if (validator instanceof SmartValidator smartValidator) {
try {
((SmartValidator) validator).validateValue(targetType, fieldName, value,
smartValidator.validateValue(targetType, fieldName, value,
binder.getBindingResult(), validationHints);
}
catch (IllegalArgumentException ex) {

View File

@ -65,8 +65,8 @@ public class ModelMethodProcessor implements HandlerMethodArgumentResolver, Hand
if (returnValue == null) {
return;
}
else if (returnValue instanceof Model) {
mavContainer.addAllAttributes(((Model) returnValue).asMap());
else if (returnValue instanceof Model model) {
mavContainer.addAllAttributes(model.asMap());
}
else {
// should not happen

View File

@ -234,8 +234,8 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod
Assert.state(name != null, "Unresolvable parameter name");
parameter = parameter.nestedIfOptional();
if (value instanceof Optional) {
value = ((Optional<?>) value).orElse(null);
if (value instanceof Optional<?> optionalValue) {
value = optionalValue.orElse(null);
}
if (value == null) {
@ -245,8 +245,8 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod
}
builder.queryParam(name);
}
else if (value instanceof Collection) {
for (Object element : (Collection<?>) value) {
else if (value instanceof Collection<?> collectionValue) {
for (Object element : collectionValue) {
element = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), element);
builder.queryParam(name, element);
}
@ -263,8 +263,8 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod
if (value == null) {
return null;
}
else if (value instanceof String) {
return (String) value;
else if (value instanceof String stringValue) {
return stringValue;
}
else if (cs != null) {
return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR);

View File

@ -94,8 +94,8 @@ public class HandlerMethodReturnValueHandlerComposite implements HandlerMethodRe
private boolean isAsyncReturnValue(@Nullable Object value, MethodParameter returnType) {
for (HandlerMethodReturnValueHandler handler : this.returnValueHandlers) {
if (handler instanceof AsyncHandlerMethodReturnValueHandler &&
((AsyncHandlerMethodReturnValueHandler) handler).isAsyncReturnValue(value, returnType)) {
if (handler instanceof AsyncHandlerMethodReturnValueHandler asyncHandlerMethodReturnValueHandler &&
asyncHandlerMethodReturnValueHandler.isAsyncReturnValue(value, returnType)) {
return true;
}
}

View File

@ -215,14 +215,14 @@ public class InvocableHandlerMethod extends HandlerMethod {
catch (InvocationTargetException ex) {
// Unwrap for HandlerExceptionResolvers ...
Throwable targetException = ex.getTargetException();
if (targetException instanceof RuntimeException) {
throw (RuntimeException) targetException;
if (targetException instanceof RuntimeException re) {
throw re;
}
else if (targetException instanceof Error) {
throw (Error) targetException;
else if (targetException instanceof Error error) {
throw error;
}
else if (targetException instanceof Exception) {
throw (Exception) targetException;
else if (targetException instanceof Exception exception) {
throw exception;
}
else {
throw new IllegalStateException(formatInvokeError("Invocation failure", args), targetException);

View File

@ -106,7 +106,7 @@ public class ModelAndViewContainer {
*/
@Nullable
public String getViewName() {
return (this.view instanceof String ? (String) this.view : null);
return (this.view instanceof String stringView ? stringView : null);
}
/**

View File

@ -89,8 +89,8 @@ class MultipartFileResource extends AbstractResource {
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof MultipartFileResource &&
((MultipartFileResource) other).multipartFile.equals(this.multipartFile)));
return (this == other || (other instanceof MultipartFileResource multipartFileResource &&
multipartFileResource.multipartFile.equals(this.multipartFile)));
}
@Override

View File

@ -114,8 +114,8 @@ public class StandardServletMultipartResolver implements MultipartResolver {
@Override
public void cleanupMultipart(MultipartHttpServletRequest request) {
if (!(request instanceof AbstractMultipartHttpServletRequest) ||
((AbstractMultipartHttpServletRequest) request).isResolved()) {
if (!(request instanceof AbstractMultipartHttpServletRequest abstractMultipartHttpServletRequest) ||
abstractMultipartHttpServletRequest.isResolved()) {
// To be on the safe side: explicitly delete the parts,
// but only actual file parts (for Resin compatibility)
try {

View File

@ -247,8 +247,9 @@ public final class WebHttpHandlerBuilder {
List<WebFilter> filtersToUse = this.filters.stream()
.peek(filter -> {
if (filter instanceof ForwardedHeaderTransformer && this.forwardedHeaderTransformer == null) {
this.forwardedHeaderTransformer = (ForwardedHeaderTransformer) filter;
if (filter instanceof ForwardedHeaderTransformer forwardedHeaderTransformerFilter
&& this.forwardedHeaderTransformer == null) {
this.forwardedHeaderTransformer = forwardedHeaderTransformerFilter;
}
})
.filter(filter -> !(filter instanceof ForwardedHeaderTransformer))

View File

@ -95,8 +95,8 @@ public class ResponseStatusExceptionHandler implements WebExceptionHandler {
int code = (statusCode != null ? statusCode.value() : determineRawStatusCode(ex));
if (code != -1) {
if (response.setStatusCode(statusCode)) {
if (ex instanceof ResponseStatusException) {
((ResponseStatusException) ex).getHeaders().forEach((name, values) ->
if (ex instanceof ResponseStatusException responseStatusException) {
responseStatusException.getHeaders().forEach((name, values) ->
values.forEach(value -> response.getHeaders().add(name, value)));
}
result = true;

View File

@ -159,8 +159,8 @@ public abstract class ServletRequestPathUtils {
*/
public static String getCachedPathValue(ServletRequest request) {
Object path = getCachedPath(request);
if (path instanceof PathContainer) {
String value = ((PathContainer) path).value();
if (path instanceof PathContainer pathContainer) {
String value = pathContainer.value();
path = UrlPathHelper.defaultInstance.removeSemicolonContent(value);
}
return (String) path;

View File

@ -726,8 +726,8 @@ public class UriComponentsBuilder implements UriBuilder, Cloneable {
@Nullable
private String getQueryParamValue(@Nullable Object value) {
if (value != null) {
return (value instanceof Optional ?
((Optional<?>) value).map(Object::toString).orElse(null) :
return (value instanceof Optional<?> optionalValue ?
optionalValue.map(Object::toString).orElse(null) :
value.toString());
}
return null;
@ -741,8 +741,8 @@ public class UriComponentsBuilder implements UriBuilder, Cloneable {
@Override
public UriComponentsBuilder queryParamIfPresent(String name, Optional<?> value) {
value.ifPresent(o -> {
if (o instanceof Collection) {
queryParam(name, (Collection<?>) o);
if (o instanceof Collection<?> elements) {
queryParam(name, elements);
}
else {
queryParam(name, o);

View File

@ -66,8 +66,8 @@ class CaptureTheRestPathElement extends PathElement {
MultiValueMap<String,String> parametersCollector = null;
for (int i = pathIndex; i < matchingContext.pathLength; i++) {
Element element = matchingContext.pathElements.get(i);
if (element instanceof PathSegment) {
MultiValueMap<String, String> parameters = ((PathSegment) element).parameters();
if (element instanceof PathSegment pathSegment) {
MultiValueMap<String, String> parameters = pathSegment.parameters();
if (!parameters.isEmpty()) {
if (parametersCollector == null) {
parametersCollector = new LinkedMultiValueMap<>();
@ -86,8 +86,8 @@ class CaptureTheRestPathElement extends PathElement {
StringBuilder sb = new StringBuilder();
for (int i = fromSegment, max = pathElements.size(); i < max; i++) {
Element element = pathElements.get(i);
if (element instanceof PathSegment) {
sb.append(((PathSegment)element).valueToMatch());
if (element instanceof PathSegment pathSegment) {
sb.append(pathSegment.valueToMatch());
}
else {
sb.append(element.value());