Apply Java pattern matching

This commit is contained in:
Tran Ngoc Nhan
2024-09-04 23:20:44 +07:00
committed by GitHub
parent 8f8e1d1294
commit d7058bbac6
26 changed files with 107 additions and 113 deletions

View File

@@ -447,12 +447,10 @@ public class MessageProperties implements Serializable {
*/
public Long getDelayLong() {
Object delay = this.headers.get(X_DELAY);
if (delay instanceof Long) {
return (Long) delay;
}
else {
return null;
if (delay instanceof Long delayLong) {
return delayLong;
}
return null;
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2019 the original author or authors.
* Copyright 2014-2024 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.
@@ -87,12 +87,10 @@ public class AmqpMessageHeaderAccessor extends NativeMessageHeaderAccessor {
@Override
public MimeType getContentType() {
Object value = getHeader(AmqpHeaders.CONTENT_TYPE);
if (value instanceof String) {
return MimeType.valueOf((String) value);
}
else {
return super.getContentType();
if (value instanceof String contentType) {
return MimeType.valueOf(contentType);
}
return super.getContentType();
}
public String getCorrelationId() {

View File

@@ -66,8 +66,8 @@ public class SimpleAmqpHeaderMapper extends AbstractHeaderMapper<MessageProperti
amqpMessageProperties::setContentLength)
.acceptIfHasText(extractContentTypeAsString(headers), amqpMessageProperties::setContentType);
Object correlationId = headers.get(AmqpHeaders.CORRELATION_ID);
if (correlationId instanceof String) {
amqpMessageProperties.setCorrelationId((String) correlationId);
if (correlationId instanceof String string) {
amqpMessageProperties.setCorrelationId(string);
}
javaUtils
.acceptIfNotNull(getHeaderIfAvailable(headers, AmqpHeaders.DELAY, Long.class),
@@ -195,8 +195,8 @@ public class SimpleAmqpHeaderMapper extends AbstractHeaderMapper<MessageProperti
if (contentType instanceof MimeType) {
contentTypeStringValue = contentType.toString();
}
else if (contentType instanceof String) {
contentTypeStringValue = (String) contentType;
else if (contentType instanceof String string) {
contentTypeStringValue = string;
}
else {
if (logger.isWarnEnabled()) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2022 the original author or authors.
* Copyright 2018-2024 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.
@@ -246,8 +246,8 @@ public abstract class AbstractJackson2MessageConverter extends AbstractMessageCo
if (this.typeMapperSet) {
throw new IllegalStateException("When providing your own type mapper, you should set the precedence on it");
}
if (this.javaTypeMapper instanceof DefaultJackson2JavaTypeMapper) {
((DefaultJackson2JavaTypeMapper) this.javaTypeMapper).setTypePrecedence(typePrecedence);
if (this.javaTypeMapper instanceof DefaultJackson2JavaTypeMapper defaultJackson2JavaTypeMapper) {
defaultJackson2JavaTypeMapper.setTypePrecedence(typePrecedence);
}
else {
throw new IllegalStateException("Type precedence is available with the DefaultJackson2JavaTypeMapper");
@@ -384,10 +384,10 @@ public abstract class AbstractJackson2MessageConverter extends AbstractMessageCo
content = tryConverType(message, encoding, inferredType);
}
if (content == null) {
if (conversionHint instanceof ParameterizedTypeReference) {
if (conversionHint instanceof ParameterizedTypeReference<?> parameterizedTypeReference) {
content = convertBytesToObject(message.getBody(), encoding,
this.objectMapper.getTypeFactory().constructType(
((ParameterizedTypeReference<?>) conversionHint).getType()));
parameterizedTypeReference.getType()));
}
else if (getClassMapper() == null) {
JavaType targetJavaType = getJavaTypeMapper()

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2022 the original author or authors.
* Copyright 2016-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,9 +51,9 @@ public class RemoteInvocationAwareMessageConverterAdapter implements MessageConv
@Override
public Object fromMessage(Message message) throws MessageConversionException {
Object result = this.delegate.fromMessage(message);
if (result instanceof RemoteInvocationResult) {
if (result instanceof RemoteInvocationResult remoteInvocationResult) {
try {
result = ((RemoteInvocationResult) result).recreate();
result = remoteInvocationResult.recreate();
if (result == null) {
throw new MessageConversionException("RemoteInvocationResult returned null");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2021 the original author or authors.
* Copyright 2021-2024 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.
@@ -143,8 +143,8 @@ public class RemoteInvocationResult implements Serializable {
public Object recreate() throws Throwable {
if (this.exception != null) {
Throwable exToThrow = this.exception;
if (this.exception instanceof InvocationTargetException) {
exToThrow = ((InvocationTargetException) this.exception).getTargetException();
if (this.exception instanceof InvocationTargetException invocationTargetException) {
exToThrow = invocationTargetException.getTargetException();
}
RemoteInvocationUtils.fillInClientStackTraceIfPossible(exToThrow);
throw exToThrow;

View File

@@ -187,9 +187,9 @@ public class SerializerMessageConverter extends AllowedListDeserializingMessageC
throws MessageConversionException {
byte[] bytes;
if (object instanceof String) {
if (object instanceof String string) {
try {
bytes = ((String) object).getBytes(this.defaultCharset);
bytes = string.getBytes(this.defaultCharset);
}
catch (UnsupportedEncodingException e) {
throw new MessageConversionException("failed to convert Message content", e);
@@ -197,8 +197,8 @@ public class SerializerMessageConverter extends AllowedListDeserializingMessageC
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);
messageProperties.setContentEncoding(this.defaultCharset);
}
else if (object instanceof byte[]) {
bytes = (byte[]) object;
else if (object instanceof byte[] objectBytes) {
bytes = objectBytes;
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_BYTES);
}
else {

View File

@@ -112,13 +112,13 @@ public class SimpleMessageConverter extends AllowedListDeserializingMessageConve
throws MessageConversionException {
byte[] bytes = null;
if (object instanceof byte[]) {
bytes = (byte[]) object;
if (object instanceof byte[] objectBytes) {
bytes = objectBytes;
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_BYTES);
}
else if (object instanceof String) {
else if (object instanceof String string) {
try {
bytes = ((String) object).getBytes(this.defaultCharset);
bytes = string.getBytes(this.defaultCharset);
}
catch (UnsupportedEncodingException e) {
throw new MessageConversionException("failed to convert to Message content", e);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2020 the original author or authors.
* Copyright 2014-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -83,7 +83,7 @@ public abstract class AbstractDecompressingPostProcessor implements MessagePostP
public Message postProcessMessage(Message message) throws AmqpException {
Object autoDecompress = message.getMessageProperties().getHeaders()
.get(MessageProperties.SPRING_AUTO_DECOMPRESS);
if (this.alwaysDecompress || (autoDecompress instanceof Boolean && ((Boolean) autoDecompress))) {
if (this.alwaysDecompress || (autoDecompress instanceof Boolean isAutoDecompress && isAutoDecompress)) {
ByteArrayInputStream zipped = new ByteArrayInputStream(message.getBody());
try {
InputStream unzipper = getDecompressorStream(zipped);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2023 the original author or authors.
* Copyright 2016-2024 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.
@@ -74,7 +74,7 @@ public class AllowedListDeserializingMessageConverterTests {
@Override
public boolean equals(Object other) {
return (other instanceof TestBean && this.text.equals(((TestBean) other).text));
return (other instanceof TestBean testBean && this.text.equals(testBean.text));
}
@Override

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2021-2023 the original author or authors.
* Copyright 2021-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -104,8 +104,8 @@ public class StreamRabbitListenerContainerFactory
@Override
public StreamListenerContainer createListenerContainer(RabbitListenerEndpoint endpoint) {
if (endpoint instanceof MethodRabbitListenerEndpoint && this.nativeListener) {
((MethodRabbitListenerEndpoint) endpoint).setAdapterProvider(
if (endpoint instanceof MethodRabbitListenerEndpoint methodRabbitListenerEndpoint && this.nativeListener) {
methodRabbitListenerEndpoint.setAdapterProvider(
(boolean batch, Object bean, Method method, boolean returnExceptions,
RabbitListenerErrorHandler errorHandler, @Nullable BatchingStrategy batchingStrategy) -> {

View File

@@ -338,11 +338,11 @@ public class StreamListenerContainer extends ObservableListenerContainer {
}
else {
Message message2 = this.streamConverter.toMessage(message, new StreamMessageProperties(context));
if (this.messageListener instanceof ChannelAwareMessageListener) {
if (this.messageListener instanceof ChannelAwareMessageListener channelAwareMessageListener) {
try {
observation.observe(() -> {
try {
((ChannelAwareMessageListener) this.messageListener).onMessage(message2, null);
channelAwareMessageListener.onMessage(message2, null);
if (finalSample != null) {
micrometerHolder.success(finalSample, this.streamName);
}
@@ -375,8 +375,8 @@ public class StreamListenerContainer extends ObservableListenerContainer {
private void adviseIfNeeded(MessageListener messageListener) {
this.messageListener = messageListener;
if (messageListener instanceof StreamMessageListener) {
this.streamListener = (StreamMessageListener) messageListener;
if (messageListener instanceof StreamMessageListener streamMessageListener) {
this.streamListener = streamMessageListener;
}
if (this.adviceChain != null && this.adviceChain.length > 0) {
ProxyFactory factory = new ProxyFactory(messageListener);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2021 the original author or authors.
* Copyright 2021-2024 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.
@@ -115,35 +115,35 @@ public class DefaultStreamMessageConverter implements StreamMessageConverter {
}
private void mapProp(String key, Object val, ApplicationPropertiesBuilder builder) { // NOSONAR - complexity
if (val instanceof String) {
builder.entry(key, (String) val);
if (val instanceof String string) {
builder.entry(key, string);
}
else if (val instanceof Long) {
builder.entry(key, (Long) val);
else if (val instanceof Long longValue) {
builder.entry(key, longValue);
}
else if (val instanceof Integer) {
builder.entry(key, (Integer) val);
else if (val instanceof Integer intValue) {
builder.entry(key, intValue);
}
else if (val instanceof Short) {
builder.entry(key, (Short) val);
else if (val instanceof Short shortValue) {
builder.entry(key, shortValue);
}
else if (val instanceof Byte) {
builder.entry(key, (Byte) val);
else if (val instanceof Byte byteValue) {
builder.entry(key, byteValue);
}
else if (val instanceof Double) {
builder.entry(key, (Double) val);
else if (val instanceof Double doubleValue) {
builder.entry(key, doubleValue);
}
else if (val instanceof Float) {
builder.entry(key, (Float) val);
else if (val instanceof Float floatValue) {
builder.entry(key, floatValue);
}
else if (val instanceof Character) {
builder.entry(key, (Character) val);
else if (val instanceof Character character) {
builder.entry(key, character);
}
else if (val instanceof UUID) {
builder.entry(key, (UUID) val);
else if (val instanceof UUID uuid) {
builder.entry(key, uuid);
}
else if (val instanceof byte[]) {
builder.entry(key, (byte[]) val);
else if (val instanceof byte[] bytes) {
builder.entry(key, bytes);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2023 the original author or authors.
* Copyright 2017-2024 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.
@@ -143,9 +143,8 @@ public class TestRabbitTemplate extends RabbitTemplate
Channel channel = mock(Channel.class);
final AtomicReference<Message> reply = new AtomicReference<>();
Object listener = listenersForRoute.next();
if (listener instanceof AbstractAdaptableMessageListener) {
if (listener instanceof AbstractAdaptableMessageListener adapter) {
try {
AbstractAdaptableMessageListener adapter = (AbstractAdaptableMessageListener) listener;
willAnswer(i -> {
Envelope envelope = new Envelope(1, false, "", REPLY_QUEUE);
reply.set(MessageBuilder.withBody(i.getArgument(4)) // NOSONAR magic #
@@ -170,16 +169,16 @@ public class TestRabbitTemplate extends RabbitTemplate
}
private void invoke(Object listener, Message message, Channel channel) {
if (listener instanceof ChannelAwareMessageListener) {
if (listener instanceof ChannelAwareMessageListener channelAwareMessageListener) {
try {
((ChannelAwareMessageListener) listener).onMessage(message, channel);
channelAwareMessageListener.onMessage(message, channel);
}
catch (Exception e) {
throw RabbitExceptionTranslator.convertRabbitAccessException(e);
}
}
else if (listener instanceof MessageListener) {
((MessageListener) listener).onMessage(message);
else if (listener instanceof MessageListener messageListener) {
messageListener.onMessage(message);
}
else {
// Not really necessary since the container doesn't allow it, but no hurt

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2021-2023 the original author or authors.
* Copyright 2021-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -140,8 +140,7 @@ public abstract class BaseRabbitListenerContainerFactory<C extends MessageListen
endpoint.setupListenerContainer(instance);
}
Object iml = instance.getMessageListener();
if (iml instanceof AbstractAdaptableMessageListener) {
AbstractAdaptableMessageListener messageListener = (AbstractAdaptableMessageListener) iml;
if (iml instanceof AbstractAdaptableMessageListener messageListener) {
JavaUtils.INSTANCE // NOSONAR
.acceptIfNotNull(this.beforeSendReplyPostProcessors,
messageListener::setBeforeSendReplyPostProcessors)

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2024 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.
@@ -74,11 +74,11 @@ public class StatelessRetryOperationsInterceptorFactoryBean extends AbstractRetr
if (messageRecoverer == null) {
this.logger.warn("Message(s) dropped on recovery: " + arg, cause);
}
else if (arg instanceof Message) {
messageRecoverer.recover((Message) arg, cause);
else if (arg instanceof Message message) {
messageRecoverer.recover(message, cause);
}
else if (arg instanceof List && messageRecoverer instanceof MessageBatchRecoverer) {
((MessageBatchRecoverer) messageRecoverer).recover((List<Message>) arg, cause);
else if (arg instanceof List && messageRecoverer instanceof MessageBatchRecoverer messageBatchRecoverer) {
messageBatchRecoverer.recover((List<Message>) arg, cause);
}
return null;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2020-2023 the original author or authors.
* Copyright 2020-2024 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.
@@ -343,8 +343,8 @@ public class PooledChannelConnectionFactory extends AbstractConnectionFactory
@Override
public void destroyObject(PooledObject<Channel> p) throws Exception {
Channel channel = p.getObject();
if (channel instanceof ChannelProxy) {
channel = ((ChannelProxy) channel).getTargetChannel();
if (channel instanceof ChannelProxy channelProxy) {
channel = channelProxy.getTargetChannel();
}
ConnectionWrapper.this.physicalClose(channel);

View File

@@ -314,8 +314,8 @@ public abstract class RabbitUtils {
Throwable cause = e;
ShutdownSignalException sig = null;
while (cause != null && sig == null) {
if (cause instanceof ShutdownSignalException) {
sig = (ShutdownSignalException) cause;
if (cause instanceof ShutdownSignalException shutdownSignalException) {
sig = shutdownSignalException;
}
cause = cause.getCause();
}
@@ -344,8 +344,8 @@ public abstract class RabbitUtils {
Throwable cause = e;
ShutdownSignalException sig = null;
while (cause != null && sig == null) {
if (cause instanceof ShutdownSignalException) {
sig = (ShutdownSignalException) cause;
if (cause instanceof ShutdownSignalException shutdownSignalException) {
sig = shutdownSignalException;
}
cause = cause.getCause();
}

View File

@@ -86,10 +86,10 @@ public class DirectReplyToMessageListenerContainer extends DirectMessageListener
@Override
public void setMessageListener(MessageListener messageListener) {
if (messageListener instanceof ChannelAwareMessageListener) {
if (messageListener instanceof ChannelAwareMessageListener channelAwareMessageListener) {
super.setMessageListener((ChannelAwareMessageListener) (message, channel) -> {
try {
((ChannelAwareMessageListener) messageListener).onMessage(message, channel);
channelAwareMessageListener.onMessage(message, channel);
}
finally {
this.inUseConsumerChannels.remove(channel);

View File

@@ -203,9 +203,9 @@ public class DefaultMessagePropertiesConverter implements MessagePropertiesConve
}
value = writableArray;
}
else if (value instanceof List<?>) {
List<Object> writableList = new ArrayList<>(((List<?>) value).size());
for (Object listValue : (List<?>) value) {
else if (value instanceof List<?> values) {
List<Object> writableList = new ArrayList<>(values.size());
for (Object listValue : values) {
writableList.add(convertHeaderValueIfNecessary(listValue));
}
value = writableList;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,8 +51,8 @@ public final class RabbitExceptionTranslator {
public static RuntimeException convertRabbitAccessException(Throwable ex) {
Assert.notNull(ex, "Exception must not be null");
if (ex instanceof AmqpException) {
return (AmqpException) ex;
if (ex instanceof AmqpException amqpException) {
return amqpException;
}
if (ex instanceof ShutdownSignalException sigEx) {
return new AmqpConnectException(sigEx);
@@ -75,8 +75,8 @@ public final class RabbitExceptionTranslator {
if (ex instanceof ConsumerCancelledException) {
return new org.springframework.amqp.rabbit.support.ConsumerCancelledException(ex);
}
if (ex instanceof org.springframework.amqp.rabbit.support.ConsumerCancelledException) {
return (org.springframework.amqp.rabbit.support.ConsumerCancelledException) ex;
if (ex instanceof org.springframework.amqp.rabbit.support.ConsumerCancelledException consumerCancelledException) {
return consumerCancelledException;
}
// fallback
return new UncategorizedAmqpException(ex);

View File

@@ -1806,12 +1806,12 @@ public class EnableRabbitIntegrationTests extends NeedsManagementTests {
@Override
public void validate(Object target, Errors errors) {
if (target instanceof ValidatedClass) {
if (((ValidatedClass) target).getBar() > 10) {
if (target instanceof ValidatedClass validatedClass) {
if (validatedClass.getBar() > 10) {
errors.reject("bar too large");
}
else {
((ValidatedClass) target).setValidated(true);
validatedClass.setValidated(true);
}
}
}
@@ -2095,8 +2095,8 @@ public class EnableRabbitIntegrationTests extends NeedsManagementTests {
@RabbitHandler(isDefault = true)
public String defaultHandler(@Payload Object payload) {
if (payload instanceof Foo) {
return "FOO: " + ((Foo) payload).field + " handled by default handler";
if (payload instanceof Foo foo) {
return "FOO: " + foo.field + " handled by default handler";
}
return payload.toString() + " handled by default handler";
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2024 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.
@@ -77,8 +77,8 @@ public class RabbitListenerContainerFactoryIntegrationTests {
SimpleMessageListenerContainer messageListenerContainer =
containerFactory.createListenerContainer(endpoint);
Object listener = messageListenerContainer.getMessageListener();
if (listener instanceof ChannelAwareMessageListener) {
((ChannelAwareMessageListener) listener).onMessage(message, mock(Channel.class));
if (listener instanceof ChannelAwareMessageListener awareMessageListener) {
awareMessageListener.onMessage(message, mock(Channel.class));
}
else {
((MessageListener) listener).onMessage(message);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2024 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.
@@ -77,8 +77,8 @@ public class BlockingQueueConsumerIntegrationTests {
CountDownLatch latch = new CountDownLatch(2);
List<ConsumeOkEvent> events = new ArrayList<>();
blockingQueueConsumer.setApplicationEventPublisher(e -> {
if (e instanceof ConsumeOkEvent) {
events.add((ConsumeOkEvent) e);
if (e instanceof ConsumeOkEvent consumeOkEvent) {
events.add(consumeOkEvent);
latch.countDown();
}
});

View File

@@ -257,8 +257,8 @@ public class MessageListenerContainerErrorHandlerIntegrationTests {
// Verify that the exception strategy has access to the message
final AtomicReference<Message> failed = new AtomicReference<Message>();
ConditionalRejectingErrorHandler eh = new ConditionalRejectingErrorHandler(t -> {
if (t instanceof ListenerExecutionFailedException) {
failed.set(((ListenerExecutionFailedException) t).getFailedMessage());
if (t instanceof ListenerExecutionFailedException exception) {
failed.set(exception.getFailedMessage());
}
return t instanceof ListenerExecutionFailedException
&& t.getCause() instanceof MessageConversionException;

View File

@@ -220,8 +220,8 @@ public class SimpleMessageListenerContainerIntegration2Tests {
@Override
public void publishEvent(ApplicationEvent event) {
if (event instanceof AsyncConsumerStartedEvent) {
newConsumer.set(((AsyncConsumerStartedEvent) event).getConsumer());
if (event instanceof AsyncConsumerStartedEvent asyncConsumerStartedEvent) {
newConsumer.set(asyncConsumerStartedEvent.getConsumer());
latch2.countDown();
}
}