diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/AsyncRabbitTemplate.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/AsyncRabbitTemplate.java index 56dcfe9b4a..f670255238 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/AsyncRabbitTemplate.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/AsyncRabbitTemplate.java @@ -581,8 +581,8 @@ public void onMessage(Message message, Channel channel) { MessageConverter messageConverter = this.template.getMessageConverter(); RabbitConverterFuture rabbitFuture = (RabbitConverterFuture) future; Object converted = rabbitFuture.getReturnType() != null - && messageConverter instanceof SmartMessageConverter - ? ((SmartMessageConverter) messageConverter).fromMessage(message, + && messageConverter instanceof SmartMessageConverter smart + ? smart.fromMessage(message, rabbitFuture.getReturnType()) : messageConverter.fromMessage(message); rabbitFuture.complete(converted); diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/annotation/RabbitListenerAnnotationBeanPostProcessor.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/annotation/RabbitListenerAnnotationBeanPostProcessor.java index 0ba855e6e3..0f41248539 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/annotation/RabbitListenerAnnotationBeanPostProcessor.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/annotation/RabbitListenerAnnotationBeanPostProcessor.java @@ -229,9 +229,9 @@ public void setMessageHandlerMethodFactory(MessageHandlerMethodFactory messageHa @Override public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; - if (beanFactory instanceof ConfigurableListableBeanFactory) { - this.resolver = ((ConfigurableListableBeanFactory) beanFactory).getBeanExpressionResolver(); - this.expressionContext = new BeanExpressionContext((ConfigurableListableBeanFactory) beanFactory, null); + if (beanFactory instanceof ConfigurableListableBeanFactory clbf) { + this.resolver = clbf.getBeanExpressionResolver(); + this.expressionContext = new BeanExpressionContext(clbf, null); } } @@ -265,9 +265,9 @@ MessageHandlerMethodFactory getMessageHandlerMethodFactory() { public void afterSingletonsInstantiated() { this.registrar.setBeanFactory(this.beanFactory); - if (this.beanFactory instanceof ListableBeanFactory) { + if (this.beanFactory instanceof ListableBeanFactory lbf) { Map instances = - ((ListableBeanFactory) this.beanFactory).getBeansOfType(RabbitListenerConfigurer.class); + lbf.getBeansOfType(RabbitListenerConfigurer.class); for (RabbitListenerConfigurer configurer : instances.values()) { configurer.configureRabbitListeners(this.registrar); } @@ -445,8 +445,8 @@ protected Collection processListener(MethodRabbitListenerEndpoint en String group = rabbitListener.group(); if (StringUtils.hasText(group)) { Object resolvedGroup = resolveExpression(group); - if (resolvedGroup instanceof String) { - endpoint.setGroup((String) resolvedGroup); + if (resolvedGroup instanceof String str) { + endpoint.setGroup(str); } } String autoStartup = rabbitListener.autoStartup(); @@ -483,8 +483,8 @@ protected Collection processListener(MethodRabbitListenerEndpoint en private void resolveErrorHandler(MethodRabbitListenerEndpoint endpoint, RabbitListener rabbitListener) { Object errorHandler = resolveExpression(rabbitListener.errorHandler()); - if (errorHandler instanceof RabbitListenerErrorHandler) { - endpoint.setErrorHandler((RabbitListenerErrorHandler) errorHandler); + if (errorHandler instanceof RabbitListenerErrorHandler rleh) { + endpoint.setErrorHandler(rleh); } else { String errorHandlerBeanName = resolveExpressionAsString(rabbitListener.errorHandler(), "errorHandler"); @@ -499,11 +499,11 @@ private void resolveAckMode(MethodRabbitListenerEndpoint endpoint, RabbitListene String ackModeAttr = rabbitListener.ackMode(); if (StringUtils.hasText(ackModeAttr)) { Object ackMode = resolveExpression(ackModeAttr); - if (ackMode instanceof String) { - endpoint.setAckMode(AcknowledgeMode.valueOf((String) ackMode)); + if (ackMode instanceof String str) { + endpoint.setAckMode(AcknowledgeMode.valueOf(str)); } - else if (ackMode instanceof AcknowledgeMode) { - endpoint.setAckMode((AcknowledgeMode) ackMode); + else if (ackMode instanceof AcknowledgeMode mode) { + endpoint.setAckMode(mode); } else { Assert.isNull(ackMode, "ackMode must resolve to a String or AcknowledgeMode"); @@ -513,8 +513,8 @@ else if (ackMode instanceof AcknowledgeMode) { private void resolveAdmin(MethodRabbitListenerEndpoint endpoint, RabbitListener rabbitListener, Object adminTarget) { Object resolved = resolveExpression(rabbitListener.admin()); - if (resolved instanceof AmqpAdmin) { - endpoint.setAdmin((AmqpAdmin) resolved); + if (resolved instanceof AmqpAdmin admin) { + endpoint.setAdmin(admin); } else { String rabbitAdmin = resolveExpressionAsString(rabbitListener.admin(), "admin"); @@ -538,8 +538,8 @@ private RabbitListenerContainerFactory resolveContainerFactory(RabbitListener RabbitListenerContainerFactory factory = null; Object resolved = resolveExpression(rabbitListener.containerFactory()); - if (resolved instanceof RabbitListenerContainerFactory) { - return (RabbitListenerContainerFactory) resolved; + if (resolved instanceof RabbitListenerContainerFactory rlcf) { + return rlcf; } String containerFactoryBeanName = resolveExpressionAsString(rabbitListener.containerFactory(), "containerFactory"); @@ -561,8 +561,8 @@ private void resolveExecutor(MethodRabbitListenerEndpoint endpoint, RabbitListen Object execTarget, String beanName) { Object resolved = resolveExpression(rabbitListener.executor()); - if (resolved instanceof TaskExecutor) { - endpoint.setTaskExecutor((TaskExecutor) resolved); + if (resolved instanceof TaskExecutor tex) { + endpoint.setTaskExecutor(tex); } else { String execBeanName = resolveExpressionAsString(rabbitListener.executor(), "executor"); @@ -583,8 +583,8 @@ private void resolvePostProcessor(MethodRabbitListenerEndpoint endpoint, RabbitL Object target, String beanName) { Object resolved = resolveExpression(rabbitListener.replyPostProcessor()); - if (resolved instanceof ReplyPostProcessor) { - endpoint.setReplyPostProcessor((ReplyPostProcessor) resolved); + if (resolved instanceof ReplyPostProcessor rpp) { + endpoint.setReplyPostProcessor(rpp); } else { String ppBeanName = resolveExpressionAsString(rabbitListener.replyPostProcessor(), "replyPostProcessor"); @@ -605,8 +605,8 @@ private void resolveMessageConverter(MethodRabbitListenerEndpoint endpoint, Rabb Object target, String beanName) { Object resolved = resolveExpression(rabbitListener.messageConverter()); - if (resolved instanceof MessageConverter) { - endpoint.setMessageConverter((MessageConverter) resolved); + if (resolved instanceof MessageConverter converter) { + endpoint.setMessageConverter(converter); } else { String mcBeanName = resolveExpressionAsString(rabbitListener.messageConverter(), "messageConverter"); @@ -704,20 +704,20 @@ private void resolveAsStringOrQueue(Object resolvedValue, List names, @N String what) { Object resolvedValueToUse = resolvedValue; - if (resolvedValue instanceof String[]) { - resolvedValueToUse = Arrays.asList((String[]) resolvedValue); + if (resolvedValue instanceof String[] strings) { + resolvedValueToUse = Arrays.asList(strings); } - if (queues != null && resolvedValueToUse instanceof Queue) { + if (queues != null && resolvedValueToUse instanceof Queue q) { if (!names.isEmpty()) { // revert to the previous behavior of just using the name when there is mixture of String and Queue - names.add(((Queue) resolvedValueToUse).getName()); + names.add(q.getName()); } else { - queues.add((Queue) resolvedValueToUse); + queues.add(q); } } - else if (resolvedValueToUse instanceof String) { - names.add((String) resolvedValueToUse); + else if (resolvedValueToUse instanceof String str) { + names.add(str); } else if (resolvedValueToUse instanceof Iterable) { for (Object object : (Iterable) resolvedValueToUse) { @@ -858,8 +858,8 @@ private Map resolveArguments(Argument[] arguments) { Object type = resolveExpression(arg.type()); Class typeClass; String typeName; - if (type instanceof Class) { - typeClass = (Class) type; + if (type instanceof Class clazz) { + typeClass = clazz; typeName = typeClass.getName(); } else { @@ -924,12 +924,11 @@ private boolean resolveExpressionAsBoolean(String value) { private boolean resolveExpressionAsBoolean(String value, boolean defaultValue) { Object resolved = resolveExpression(value); - if (resolved instanceof Boolean) { - return (Boolean) resolved; + if (resolved instanceof Boolean bool) { + return bool; } - else if (resolved instanceof String) { - final String s = (String) resolved; - return StringUtils.hasText(s) ? Boolean.parseBoolean(s) : defaultValue; + else if (resolved instanceof String str) { + return StringUtils.hasText(str) ? Boolean.parseBoolean(str) : defaultValue; } else { return defaultValue; @@ -938,8 +937,8 @@ else if (resolved instanceof String) { protected String resolveExpressionAsString(String value, String attribute) { Object resolved = resolveExpression(value); - if (resolved instanceof String) { - return (String) resolved; + if (resolved instanceof String str) { + return str; } else { throw new IllegalStateException("The [" + attribute + "] must resolve to a String. " @@ -952,8 +951,8 @@ private String resolveExpressionAsStringOrInteger(String value, String attribute return null; } Object resolved = resolveExpression(value); - if (resolved instanceof String) { - return (String) resolved; + if (resolved instanceof String str) { + return str; } else if (resolved instanceof Integer) { return resolved.toString(); @@ -977,8 +976,8 @@ private Object resolveExpression(String value) { * @see ConfigurableBeanFactory#resolveEmbeddedValue */ private String resolve(String value) { - if (this.beanFactory != null && this.beanFactory instanceof ConfigurableBeanFactory) { - return ((ConfigurableBeanFactory) this.beanFactory).resolveEmbeddedValue(value); + if (this.beanFactory != null && this.beanFactory instanceof ConfigurableBeanFactory cbf) { + return cbf.resolveEmbeddedValue(value); } return value; } @@ -1086,8 +1085,8 @@ public Object resolveArgument(MethodParameter parameter, Message message) thr } private boolean isOptional(Message message, Type type) { - return (Optional.class.equals(type) || (type instanceof ParameterizedType - && Optional.class.equals(((ParameterizedType) type).getRawType()))) + return (Optional.class.equals(type) || (type instanceof ParameterizedType pType + && Optional.class.equals(pType.getRawType()))) && message.getPayload().equals(Optional.empty()); } diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/config/StatefulRetryOperationsInterceptorFactoryBean.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/config/StatefulRetryOperationsInterceptorFactoryBean.java index 2a89750059..3aa40f94ef 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/config/StatefulRetryOperationsInterceptorFactoryBean.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/config/StatefulRetryOperationsInterceptorFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2022 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,11 +104,11 @@ private MethodInvocationRecoverer createRecoverer() { if (messageRecoverer == null) { logger.warn("Message(s) dropped on recovery: " + arg, cause); } - else if (arg instanceof Message) { - messageRecoverer.recover((Message) arg, cause); + else if (arg instanceof Message msg) { + messageRecoverer.recover(msg, cause); } - else if (arg instanceof List && messageRecoverer instanceof MessageBatchRecoverer) { - ((MessageBatchRecoverer) messageRecoverer).recover((List) arg, cause); + else if (arg instanceof List && messageRecoverer instanceof MessageBatchRecoverer recoverer) { + recoverer.recover((List) arg, cause); } // This is actually a normal outcome. It means the recovery was successful, but we don't want to consume // any more messages until the acks and commits are sent for this (problematic) message... @@ -137,8 +137,8 @@ private MethodArgumentsKeyGenerator createKeyGenerator() { private Message argToMessage(Object[] args) { Object arg = args[1]; Message message = null; - if (arg instanceof Message) { - message = (Message) arg; + if (arg instanceof Message msg) { + message = msg; } else if (arg instanceof List) { message = ((List) arg).get(0); diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/AbstractConnectionFactory.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/AbstractConnectionFactory.java index f17411c9dc..3bc3bf9510 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/AbstractConnectionFactory.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/AbstractConnectionFactory.java @@ -550,8 +550,8 @@ protected final Connection createBareConnection() { com.rabbitmq.client.Connection rabbitConnection = connect(connectionName); Connection connection = new SimpleConnection(rabbitConnection, this.closeTimeout); - if (rabbitConnection instanceof AutorecoveringConnection) { - ((AutorecoveringConnection) rabbitConnection).addRecoveryListener(new RecoveryListener() { + if (rabbitConnection instanceof AutorecoveringConnection auto) { + auto.addRecoveryListener(new RecoveryListener() { @Override public void handleRecoveryStarted(Recoverable recoverable) { @@ -573,8 +573,8 @@ public void handleRecovery(Recoverable recoverable) { if (this.logger.isInfoEnabled()) { this.logger.info("Created new connection: " + connectionName + "/" + connection); } - if (this.recoveryListener != null && rabbitConnection instanceof AutorecoveringConnection) { - ((AutorecoveringConnection) rabbitConnection).addRecoveryListener(this.recoveryListener); + if (this.recoveryListener != null && rabbitConnection instanceof AutorecoveringConnection auto) { + auto.addRecoveryListener(this.recoveryListener); } if (this.applicationEventPublisher != null) { @@ -717,8 +717,7 @@ private static class DefaultChannelCloseLogger implements ConditionalExceptionLo @Override public void log(Log logger, String message, Throwable t) { - if (t instanceof ShutdownSignalException) { - ShutdownSignalException cause = (ShutdownSignalException) t; + if (t instanceof ShutdownSignalException cause) { if (RabbitUtils.isPassiveDeclarationChannelClose(cause)) { if (logger.isDebugEnabled()) { logger.debug(message + ": " + cause.getMessage()); diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/CachingConnectionFactory.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/CachingConnectionFactory.java index 6ac59839a2..1397d1d472 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/CachingConnectionFactory.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/CachingConnectionFactory.java @@ -1291,8 +1291,8 @@ private void physicalClose(Object proxy) throws IOException, TimeoutException { } else { this.target.close(); - if (this.target instanceof AutorecoveringChannel) { - ClosingRecoveryListener.removeChannel((AutorecoveringChannel) this.target); + if (this.target instanceof AutorecoveringChannel auto) { + ClosingRecoveryListener.removeChannel(auto); } } } diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/ClosingRecoveryListener.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/ClosingRecoveryListener.java index 1f66d5605c..e9a828b7fc 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/ClosingRecoveryListener.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/ClosingRecoveryListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2018-2019 the original author or authors. + * Copyright 2018-2022 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,14 +79,13 @@ public void handleRecoveryStarted(Recoverable recoverable) { */ public static void addRecoveryListenerIfNecessary(Channel channel) { AutorecoveringChannel autorecoveringChannel = null; - if (channel instanceof ChannelProxy) { - if (((ChannelProxy) channel).getTargetChannel() instanceof AutorecoveringChannel) { - autorecoveringChannel = (AutorecoveringChannel) ((ChannelProxy) channel) - .getTargetChannel(); + if (channel instanceof ChannelProxy proxy) { + if (proxy.getTargetChannel() instanceof AutorecoveringChannel auto) { + autorecoveringChannel = auto; } } - else if (channel instanceof AutorecoveringChannel) { - autorecoveringChannel = (AutorecoveringChannel) channel; + else if (channel instanceof AutorecoveringChannel auto) { + autorecoveringChannel = auto; } if (autorecoveringChannel != null && hasListener.putIfAbsent(autorecoveringChannel, Boolean.TRUE) == null) { diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/LocalizedQueueConnectionFactory.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/LocalizedQueueConnectionFactory.java index 83885e82cc..aa25c7a5ff 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/LocalizedQueueConnectionFactory.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/LocalizedQueueConnectionFactory.java @@ -339,9 +339,9 @@ protected ConnectionFactory createConnectionFactory(String address, String node) public void resetConnection() { Exception lastException = null; for (ConnectionFactory connectionFactory : this.nodeFactories.values()) { - if (connectionFactory instanceof DisposableBean) { + if (connectionFactory instanceof DisposableBean disposable) { try { - ((DisposableBean) connectionFactory).destroy(); + disposable.destroy(); } catch (Exception e) { lastException = e; diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/PublisherCallbackChannelImpl.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/PublisherCallbackChannelImpl.java index d1c695d9e8..70ba93125c 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/PublisherCallbackChannelImpl.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/PublisherCallbackChannelImpl.java @@ -179,8 +179,8 @@ public Connection getConnection() { @Override public void close(int closeCode, String closeMessage) throws IOException, TimeoutException { this.delegate.close(closeCode, closeMessage); - if (this.delegate instanceof AutorecoveringChannel) { - ClosingRecoveryListener.removeChannel((AutorecoveringChannel) this.delegate); + if (this.delegate instanceof AutorecoveringChannel auto) { + ClosingRecoveryListener.removeChannel(auto); } } diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/RabbitUtils.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/RabbitUtils.java index d52e769ca8..1b42b8c80a 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/RabbitUtils.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/RabbitUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2022 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. @@ -156,8 +156,8 @@ public static void rollbackIfNecessary(Channel channel) { } public static void closeMessageConsumer(Channel channel, Collection consumerTags, boolean transactional) { - if (!channel.isOpen() && !(channel instanceof ChannelProxy - && ((ChannelProxy) channel).getTargetChannel() instanceof AutorecoveringChannel) + if (!channel.isOpen() && !(channel instanceof ChannelProxy proxy + && proxy.getTargetChannel() instanceof AutorecoveringChannel) && !(channel instanceof AutorecoveringChannel)) { return; } @@ -251,9 +251,9 @@ public static void clearPhysicalCloseRequired() { */ public static boolean isNormalShutdown(ShutdownSignalException sig) { Method shutdownReason = sig.getReason(); - return shutdownReason instanceof AMQP.Connection.Close - && AMQP.REPLY_SUCCESS == ((AMQP.Connection.Close) shutdownReason).getReplyCode() - && "OK".equals(((AMQP.Connection.Close) shutdownReason).getReplyText()); + return shutdownReason instanceof AMQP.Connection.Close closeReason + && AMQP.REPLY_SUCCESS == closeReason.getReplyCode() + && "OK".equals(closeReason.getReplyText()); } /** @@ -265,9 +265,9 @@ public static boolean isNormalShutdown(ShutdownSignalException sig) { public static boolean isNormalChannelClose(ShutdownSignalException sig) { Method shutdownReason = sig.getReason(); return isNormalShutdown(sig) || - (shutdownReason instanceof AMQP.Channel.Close - && AMQP.REPLY_SUCCESS == ((AMQP.Channel.Close) shutdownReason).getReplyCode() - && "OK".equals(((AMQP.Channel.Close) shutdownReason).getReplyText())); + (shutdownReason instanceof AMQP.Channel.Close closeReason + && AMQP.REPLY_SUCCESS == closeReason.getReplyCode() + && "OK".equals(closeReason.getReplyText())); } /** @@ -278,11 +278,11 @@ public static boolean isNormalChannelClose(ShutdownSignalException sig) { */ public static boolean isPassiveDeclarationChannelClose(ShutdownSignalException sig) { Method shutdownReason = sig.getReason(); - return shutdownReason instanceof AMQP.Channel.Close // NOSONAR boolean complexity - && AMQP.NOT_FOUND == ((AMQP.Channel.Close) shutdownReason).getReplyCode() - && ((((AMQP.Channel.Close) shutdownReason).getClassId() == EXCHANGE_CLASS_ID_40 - || ((AMQP.Channel.Close) shutdownReason).getClassId() == QUEUE_CLASS_ID_50) - && ((AMQP.Channel.Close) shutdownReason).getMethodId() == DECLARE_METHOD_ID_10); + return shutdownReason instanceof AMQP.Channel.Close closeReason // NOSONAR boolean complexity + && AMQP.NOT_FOUND == closeReason.getReplyCode() + && ((closeReason.getClassId() == EXCHANGE_CLASS_ID_40 + || closeReason.getClassId() == QUEUE_CLASS_ID_50) + && closeReason.getMethodId() == DECLARE_METHOD_ID_10); } /** @@ -294,11 +294,11 @@ public static boolean isPassiveDeclarationChannelClose(ShutdownSignalException s */ public static boolean isExclusiveUseChannelClose(ShutdownSignalException sig) { Method shutdownReason = sig.getReason(); - return shutdownReason instanceof AMQP.Channel.Close // NOSONAR boolean complexity - && AMQP.ACCESS_REFUSED == ((AMQP.Channel.Close) shutdownReason).getReplyCode() - && ((AMQP.Channel.Close) shutdownReason).getClassId() == BASIC_CLASS_ID_60 - && ((AMQP.Channel.Close) shutdownReason).getMethodId() == CONSUME_METHOD_ID_20 - && ((AMQP.Channel.Close) shutdownReason).getReplyText().contains("exclusive"); + return shutdownReason instanceof AMQP.Channel.Close closeReason // NOSONAR boolean complexity + && AMQP.ACCESS_REFUSED == closeReason.getReplyCode() + && closeReason.getClassId() == BASIC_CLASS_ID_60 + && closeReason.getMethodId() == CONSUME_METHOD_ID_20 + && closeReason.getReplyText().contains("exclusive"); } /** @@ -324,10 +324,10 @@ public static boolean isMismatchedQueueArgs(Exception e) { } else { Method shutdownReason = sig.getReason(); - return shutdownReason instanceof AMQP.Channel.Close - && AMQP.PRECONDITION_FAILED == ((AMQP.Channel.Close) shutdownReason).getReplyCode() - && ((AMQP.Channel.Close) shutdownReason).getClassId() == QUEUE_CLASS_ID_50 - && ((AMQP.Channel.Close) shutdownReason).getMethodId() == DECLARE_METHOD_ID_10; + return shutdownReason instanceof AMQP.Channel.Close closeReason + && AMQP.PRECONDITION_FAILED == closeReason.getReplyCode() + && closeReason.getClassId() == QUEUE_CLASS_ID_50 + && closeReason.getMethodId() == DECLARE_METHOD_ID_10; } } @@ -354,10 +354,10 @@ public static boolean isExchangeDeclarationFailure(Exception e) { } else { Method shutdownReason = sig.getReason(); - return shutdownReason instanceof AMQP.Connection.Close - && AMQP.COMMAND_INVALID == ((AMQP.Connection.Close) shutdownReason).getReplyCode() - && ((AMQP.Connection.Close) shutdownReason).getClassId() == EXCHANGE_CLASS_ID_40 - && ((AMQP.Connection.Close) shutdownReason).getMethodId() == DECLARE_METHOD_ID_10; + return shutdownReason instanceof AMQP.Connection.Close closeReason + && AMQP.COMMAND_INVALID == closeReason.getReplyCode() + && closeReason.getClassId() == EXCHANGE_CLASS_ID_40 + && closeReason.getMethodId() == DECLARE_METHOD_ID_10; } } diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/SimpleConnection.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/SimpleConnection.java index c59aadc2a1..4c14f1d02f 100755 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/SimpleConnection.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/SimpleConnection.java @@ -109,8 +109,8 @@ public boolean isOpen() { @Override public int getLocalPort() { - if (this.delegate instanceof NetworkConnection) { - return ((NetworkConnection) this.delegate).getLocalPort(); + if (this.delegate instanceof NetworkConnection networkConn) { + return networkConn.getLocalPort(); } return 0; } @@ -127,8 +127,8 @@ public boolean removeBlockedListener(BlockedListener listener) { @Override public InetAddress getLocalAddress() { - if (this.delegate instanceof NetworkConnection) { - return ((NetworkConnection) this.delegate).getLocalAddress(); + if (this.delegate instanceof NetworkConnection networkConn) { + return networkConn.getLocalAddress(); } return null; } diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/ThreadChannelConnectionFactory.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/ThreadChannelConnectionFactory.java index 0eb4593401..6433b324d1 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/ThreadChannelConnectionFactory.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/ThreadChannelConnectionFactory.java @@ -179,8 +179,8 @@ public Object prepareSwitchContext() { @Nullable Object prepareSwitchContext(UUID uuid) { Object pubContext = null; - if (getPublisherConnectionFactory() instanceof ThreadChannelConnectionFactory) { - pubContext = ((ThreadChannelConnectionFactory) getPublisherConnectionFactory()).prepareSwitchContext(uuid); // NOSONAR + if (getPublisherConnectionFactory() instanceof ThreadChannelConnectionFactory tccf) { + pubContext = tccf.prepareSwitchContext(uuid); } Context context = ((ConnectionWrapper) createConnection()).prepareSwitchContext(); if (context.getNonTx() == null && context.getTx() == null) { @@ -214,8 +214,8 @@ public void switchContext(@Nullable Object toSwitch) { boolean doSwitch(Object toSwitch) { boolean switched = false; - if (getPublisherConnectionFactory() instanceof ThreadChannelConnectionFactory) { - switched = ((ThreadChannelConnectionFactory) getPublisherConnectionFactory()).doSwitch(toSwitch); // NOSONAR + if (getPublisherConnectionFactory() instanceof ThreadChannelConnectionFactory tccf) { + switched = tccf.doSwitch(toSwitch); // NOSONAR } Context context = this.contextSwitches.remove(toSwitch); this.switchesInProgress.remove(toSwitch); diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitAdmin.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitAdmin.java index 9a2be6b7eb..6644c447e4 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitAdmin.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitAdmin.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2022 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. @@ -264,8 +264,7 @@ private void removeExchangeBindings(final String exchangeName) { Iterator> iterator = this.manualDeclarables.entrySet().iterator(); while (iterator.hasNext()) { Entry next = iterator.next(); - if (next.getValue() instanceof Binding) { - Binding binding = (Binding) next.getValue(); + if (next.getValue() instanceof Binding binding) { if ((!binding.isDestinationQueue() && binding.getDestination().equals(exchangeName)) || binding.getExchange().equals(exchangeName)) { iterator.remove(); @@ -363,8 +362,7 @@ private void removeQueueBindings(final String queueName) { Iterator> iterator = this.manualDeclarables.entrySet().iterator(); while (iterator.hasNext()) { Entry next = iterator.next(); - if (next.getValue() instanceof Binding) { - Binding binding = (Binding) next.getValue(); + if (next.getValue() instanceof Binding binding) { if (binding.isDestinationQueue() && binding.getDestination().equals(queueName)) { iterator.remove(); } @@ -472,8 +470,8 @@ public QueueInformation getQueueInfo(String queueName) { e); } try { - if (channel instanceof ChannelProxy) { - ((ChannelProxy) channel).getTargetChannel().close(); + if (channel instanceof ChannelProxy proxy) { + proxy.getTargetChannel().close(); } } catch (@SuppressWarnings(UNUSED) TimeoutException e1) { @@ -592,8 +590,8 @@ public void afterPropertiesSet() { backOffPolicy.setMaxInterval(DECLARE_MAX_RETRY_INTERVAL); this.retryTemplate.setBackOffPolicy(backOffPolicy); } - if (this.connectionFactory instanceof CachingConnectionFactory && - ((CachingConnectionFactory) this.connectionFactory).getCacheMode() == CacheMode.CONNECTION) { + if (this.connectionFactory instanceof CachingConnectionFactory ccf && + ccf.getCacheMode() == CacheMode.CONNECTION) { this.logger.warn("RabbitAdmin auto declaration is not supported with CacheMode.CONNECTION"); return; } @@ -698,11 +696,11 @@ public void initialize() { synchronized (this.manualDeclarables) { this.logger.debug("Redeclaring manually declared Declarables"); for (Declarable dec : this.manualDeclarables.values()) { - if (dec instanceof Queue) { - declareQueue((Queue) dec); + if (dec instanceof Queue queue) { + declareQueue(queue); } - else if (dec instanceof Exchange) { - declareExchange((Exchange) dec); + else if (dec instanceof Exchange exch) { + declareExchange(exch); } else { declareBinding((Binding) dec); @@ -731,14 +729,14 @@ private void processDeclarables(Collection contextExchanges, Collectio .values(); declarables.forEach(d -> { d.getDeclarables().forEach(declarable -> { - if (declarable instanceof Exchange) { - contextExchanges.add((Exchange) declarable); + if (declarable instanceof Exchange exch) { + contextExchanges.add(exch); } - else if (declarable instanceof Queue) { - contextQueues.add((Queue) declarable); + else if (declarable instanceof Queue queue) { + contextQueues.add(queue); } - else if (declarable instanceof Binding) { - contextBindings.add((Binding) declarable); + else if (declarable instanceof Binding binding) { + contextBindings.add(binding); } }); }); @@ -847,8 +845,8 @@ private void closeChannelAfterIllegalArg(final Channel channel, Queue queue) { this.logger.error("Exception while declaring queue: '" + queue.getName() + "'"); } try { - if (channel instanceof ChannelProxy) { - ((ChannelProxy) channel).getTargetChannel().close(); + if (channel instanceof ChannelProxy proxy) { + proxy.getTargetChannel().close(); } } catch (IOException | TimeoutException e1) { diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitMessagingTemplate.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitMessagingTemplate.java index 0f64eac1a2..304200fea7 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitMessagingTemplate.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitMessagingTemplate.java @@ -213,8 +213,8 @@ public T convertSendAndReceive(String exchange, String routingKey, Object re protected void doSend(String destination, Message message) { try { Object correlation = message.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM_CORRELATION); - if (correlation instanceof CorrelationData) { - this.rabbitTemplate.send(destination, createMessage(message), (CorrelationData) correlation); + if (correlation instanceof CorrelationData corrData) { + this.rabbitTemplate.send(destination, createMessage(message), corrData); } else { this.rabbitTemplate.send(destination, createMessage(message)); @@ -228,8 +228,8 @@ protected void doSend(String destination, Message message) { protected void doSend(String exchange, String routingKey, Message message) { try { Object correlation = message.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM_CORRELATION); - if (correlation instanceof CorrelationData) { - this.rabbitTemplate.send(exchange, routingKey, createMessage(message), (CorrelationData) correlation); + if (correlation instanceof CorrelationData corrData) { + this.rabbitTemplate.send(exchange, routingKey, createMessage(message), corrData); } else { this.rabbitTemplate.send(exchange, routingKey, createMessage(message)); @@ -324,8 +324,8 @@ protected Message convertAmqpMessage(@Nullable org.springframework.amqp.core. @SuppressWarnings("ThrowableResultOfMethodCallIgnored") protected MessagingException convertAmqpException(RuntimeException ex) { - if (ex instanceof MessagingException) { - return (MessagingException) ex; + if (ex instanceof MessagingException mex) { + return mex; } if (ex instanceof org.springframework.amqp.support.converter.MessageConversionException) { return new MessageConversionException(ex.getMessage(), ex); diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitTemplate.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitTemplate.java index 639d74163a..7b4efd9e80 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitTemplate.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitTemplate.java @@ -1098,9 +1098,7 @@ && isMandatoryFor(message), } private ConnectionFactory obtainTargetConnectionFactory(Expression expression, @Nullable Object rootObject) { - if (expression != null && getConnectionFactory() instanceof AbstractRoutingConnectionFactory) { - AbstractRoutingConnectionFactory routingConnectionFactory = - (AbstractRoutingConnectionFactory) getConnectionFactory(); + if (expression != null && getConnectionFactory() instanceof AbstractRoutingConnectionFactory routingCF) { Object lookupKey; if (rootObject != null) { lookupKey = expression.getValue(this.evaluationContext, rootObject); @@ -1109,11 +1107,11 @@ private ConnectionFactory obtainTargetConnectionFactory(Expression expression, @ lookupKey = expression.getValue(this.evaluationContext); } if (lookupKey != null) { - ConnectionFactory connectionFactory = routingConnectionFactory.getTargetConnectionFactory(lookupKey); + ConnectionFactory connectionFactory = routingCF.getTargetConnectionFactory(lookupKey); if (connectionFactory != null) { return connectionFactory; } - else if (!routingConnectionFactory.isLenientFallback()) { + else if (!routingCF.isLenientFallback()) { throw new IllegalStateException("Cannot determine target ConnectionFactory for lookup key [" + lookupKey + "]"); } @@ -1843,8 +1841,8 @@ protected Message convertSendAndReceiveRaw(final String exchange, final String r } protected Message convertMessageIfNecessary(final Object object) { - if (object instanceof Message) { - return (Message) object; + if (object instanceof Message msg) { + return msg; } return getRequiredMessageConverter().toMessage(object, new MessageProperties()); } @@ -2316,8 +2314,8 @@ public T invoke(OperationsCallback action, @Nullable com.rabbitmq.client. private ConfirmListener addConfirmListener(@Nullable com.rabbitmq.client.ConfirmCallback acks, @Nullable com.rabbitmq.client.ConfirmCallback nacks, Channel channel) { ConfirmListener listener = null; - if (acks != null && nacks != null && channel instanceof ChannelProxy - && ((ChannelProxy) channel).isConfirmSelected()) { + if (acks != null && nacks != null && channel instanceof ChannelProxy proxy + && proxy.isConfirmSelected()) { listener = channel.addConfirmListener(acks, nacks); } return listener; @@ -2474,14 +2472,13 @@ protected void sendToRabbit(Channel channel, String exchange, String routingKey, } private void setupConfirm(Channel channel, Message message, @Nullable CorrelationData correlationDataArg) { - final boolean publisherConfirms = channel instanceof ChannelProxy - && ((ChannelProxy) channel).isPublisherConfirms(); + final boolean publisherConfirms = channel instanceof ChannelProxy proxy + && proxy.isPublisherConfirms(); if ((publisherConfirms || this.confirmCallback != null) - && channel instanceof PublisherCallbackChannel) { + && channel instanceof PublisherCallbackChannel publisherCallbackChannel) { long nextPublishSeqNo = channel.getNextPublishSeqNo(); if (nextPublishSeqNo > 0) { - PublisherCallbackChannel publisherCallbackChannel = (PublisherCallbackChannel) channel; CorrelationData correlationData = this.correlationDataPostProcessor != null ? this.correlationDataPostProcessor.postProcess(message, correlationDataArg) : correlationDataArg; @@ -2497,7 +2494,7 @@ private void setupConfirm(Channel channel, Message message, @Nullable Correlatio logger.debug("Factory does not have confirms enabled"); } } - else if (channel instanceof ChannelProxy && ((ChannelProxy) channel).isConfirmSelected()) { + else if (channel instanceof ChannelProxy proxy && proxy.isConfirmSelected()) { long nextPublishSeqNo = channel.getNextPublishSeqNo(); message.getMessageProperties().setPublishSequenceNumber(nextPublishSeqNo); } @@ -2596,9 +2593,8 @@ private Address getReplyToAddress(Message request) throws AmqpException { * @since 2.0 */ public void addListener(Channel channel) { - if (channel instanceof PublisherCallbackChannel) { - PublisherCallbackChannel publisherCallbackChannel = (PublisherCallbackChannel) channel; - Channel key = channel instanceof ChannelProxy ? ((ChannelProxy) channel).getTargetChannel() : channel; + if (channel instanceof PublisherCallbackChannel publisherCallbackChannel) { + Channel key = channel instanceof ChannelProxy proxy ? proxy.getTargetChannel() : channel; if (this.publisherConfirmChannels.putIfAbsent(key, this) == null) { publisherCallbackChannel.addListener(this); if (logger.isDebugEnabled()) { @@ -2760,8 +2756,8 @@ public void handleDelivery(String consumerTag, Envelope envelope, BasicPropertie }; channel.basicConsume(queueName, consumer); if (!latch.await(timeoutMillis, TimeUnit.MILLISECONDS)) { - if (channel instanceof ChannelProxy) { - ((ChannelProxy) channel).getTargetChannel().close(); + if (channel instanceof ChannelProxy proxy) { + proxy.getTargetChannel().close(); } future.completeExceptionally( new ConsumeOkNotReceivedException("Blocking receive, consumer failed to consume within " diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/AbstractMessageListenerContainer.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/AbstractMessageListenerContainer.java index 1ddd3a738e..28e621136a 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/AbstractMessageListenerContainer.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/AbstractMessageListenerContainer.java @@ -627,8 +627,8 @@ public final void setApplicationContext(ApplicationContext applicationContext) { @Override public ConnectionFactory getConnectionFactory() { ConnectionFactory connectionFactory = super.getConnectionFactory(); - if (connectionFactory instanceof RoutingConnectionFactory) { - ConnectionFactory targetConnectionFactory = ((RoutingConnectionFactory) connectionFactory) + if (connectionFactory instanceof RoutingConnectionFactory rcf) { + ConnectionFactory targetConnectionFactory = rcf .getTargetConnectionFactory(getRoutingLookupKey()); // NOSONAR never null if (targetConnectionFactory != null) { return targetConnectionFactory; @@ -696,9 +696,7 @@ private String queuesAsListString() { */ @Nullable protected RoutingConnectionFactory getRoutingConnectionFactory() { - return super.getConnectionFactory() instanceof RoutingConnectionFactory - ? (RoutingConnectionFactory) super.getConnectionFactory() - : null; + return super.getConnectionFactory() instanceof RoutingConnectionFactory rcf ? rcf : null; } /** @@ -1565,20 +1563,20 @@ protected void executeListenerAndHandleException(Channel channel, Object data) { try { doExecuteListener(channel, data); if (sample != null) { - this.micrometerHolder.success(sample, data instanceof Message - ? ((Message) data).getMessageProperties().getConsumerQueue() + this.micrometerHolder.success(sample, data instanceof Message message + ? message.getMessageProperties().getConsumerQueue() : queuesAsListString()); } } catch (RuntimeException ex) { if (sample != null) { - this.micrometerHolder.failure(sample, data instanceof Message - ? ((Message) data).getMessageProperties().getConsumerQueue() + this.micrometerHolder.failure(sample, data instanceof Message message + ? message.getMessageProperties().getConsumerQueue() : queuesAsListString(), ex.getClass().getSimpleName()); } Message message; - if (data instanceof Message) { - message = (Message) data; + if (data instanceof Message msg) { + message = msg; } else { message = ((List) data).get(0); @@ -1604,8 +1602,7 @@ private void checkStatefulRetry(RuntimeException ex, Message message) { } private void doExecuteListener(Channel channel, Object data) { - if (data instanceof Message) { - Message message = (Message) data; + if (data instanceof Message message) { if (this.afterReceivePostProcessors != null) { for (MessagePostProcessor processor : this.afterReceivePostProcessors) { message = processor.postProcessMessage(message); @@ -1639,10 +1636,10 @@ protected void invokeListener(Channel channel, Object data) { */ protected void actualInvokeListener(Channel channel, Object data) { Object listener = getMessageListener(); - if (listener instanceof ChannelAwareMessageListener) { - doInvokeListener((ChannelAwareMessageListener) listener, channel, data); + if (listener instanceof ChannelAwareMessageListener chaml) { + doInvokeListener(chaml, channel, data); } - else if (listener instanceof MessageListener) { + else if (listener instanceof MessageListener msgListener) { boolean bindChannel = isExposeListenerChannel() && isChannelLocallyTransacted(); if (bindChannel) { RabbitResourceHolder resourceHolder = new RabbitResourceHolder(channel, false); @@ -1651,7 +1648,7 @@ else if (listener instanceof MessageListener) { resourceHolder); } try { - doInvokeListener((MessageListener) listener, data); + doInvokeListener(msgListener, data); } finally { if (bindChannel) { @@ -2149,8 +2146,7 @@ private static class DefaultExclusiveConsumerLogger implements ConditionalExcept @Override public void log(Log logger, String message, Throwable t) { - if (t instanceof ShutdownSignalException) { - ShutdownSignalException cause = (ShutdownSignalException) t; + if (t instanceof ShutdownSignalException cause) { if (RabbitUtils.isExclusiveUseChannelClose(cause)) { if (logger.isWarnEnabled()) { logger.warn(message + ": " + cause.toString()); diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/AbstractRabbitListenerEndpoint.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/AbstractRabbitListenerEndpoint.java index 8cac1fc019..a4031e88dc 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/AbstractRabbitListenerEndpoint.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/AbstractRabbitListenerEndpoint.java @@ -99,9 +99,9 @@ public abstract class AbstractRabbitListenerEndpoint implements RabbitListenerEn @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; - if (beanFactory instanceof ConfigurableListableBeanFactory) { - this.resolver = ((ConfigurableListableBeanFactory) beanFactory).getBeanExpressionResolver(); - this.expressionContext = new BeanExpressionContext((ConfigurableListableBeanFactory) beanFactory, null); + if (beanFactory instanceof ConfigurableListableBeanFactory clbf) { + this.resolver = clbf.getBeanExpressionResolver(); + this.expressionContext = new BeanExpressionContext(clbf, null); } this.beanResolver = new BeanFactoryResolver(beanFactory); } @@ -301,6 +301,7 @@ public boolean isBatchListener() { return this.batchListener == null ? false : this.batchListener; } + @Override /** * True if this endpoint is for a batch listener. * @return {@link Boolean#TRUE} if batch. @@ -389,9 +390,7 @@ public void setConverterWinsContentType(boolean converterWinsContentType) { public void setupListenerContainer(MessageListenerContainer listenerContainer) { Collection qNames = getQueueNames(); boolean queueNamesEmpty = qNames.isEmpty(); - if (listenerContainer instanceof AbstractMessageListenerContainer) { - AbstractMessageListenerContainer container = (AbstractMessageListenerContainer) listenerContainer; - + if (listenerContainer instanceof AbstractMessageListenerContainer container) { boolean queuesEmpty = getQueues().isEmpty(); if (!queuesEmpty && !queueNamesEmpty) { throw new IllegalStateException("Queues or queue names must be provided but not both for " + this); diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/BlockingQueueConsumer.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/BlockingQueueConsumer.java index e1359b3b39..cf7eacdcf1 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/BlockingQueueConsumer.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/BlockingQueueConsumer.java @@ -739,8 +739,8 @@ private void attemptPassiveDeclarations() { } catch (IllegalArgumentException e) { try { - if (this.channel instanceof ChannelProxy) { - ((ChannelProxy) this.channel).getTargetChannel().close(); + if (this.channel instanceof ChannelProxy proxy) { + proxy.getTargetChannel().close(); } } catch (TimeoutException e1) { diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/ConditionalRejectingErrorHandler.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/ConditionalRejectingErrorHandler.java index d58d9918ed..4ddb6c1a5c 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/ConditionalRejectingErrorHandler.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/ConditionalRejectingErrorHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 the original author or authors. + * Copyright 2014-2022 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. @@ -131,8 +131,8 @@ protected FatalExceptionStrategy getExceptionStrategy() { public void handleError(Throwable t) { log(t); if (!this.causeChainContainsARADRE(t) && this.exceptionStrategy.isFatal(t)) { - if (this.discardFatalsWithXDeath && t instanceof ListenerExecutionFailedException) { - Message failed = ((ListenerExecutionFailedException) t).getFailedMessage(); + if (this.discardFatalsWithXDeath && t instanceof ListenerExecutionFailedException lefe) { + Message failed = lefe.getFailedMessage(); if (failed != null) { List> xDeath = failed.getMessageProperties().getXDeathHeader(); if (xDeath != null && xDeath.size() > 0) { @@ -205,8 +205,8 @@ public boolean isFatal(Throwable t) { && !(cause instanceof MethodArgumentResolutionException)) { cause = cause.getCause(); } - if (t instanceof ListenerExecutionFailedException && isCauseFatal(cause)) { - logFatalException((ListenerExecutionFailedException) t, cause); + if (t instanceof ListenerExecutionFailedException lefe && isCauseFatal(cause)) { + logFatalException(lefe, cause); return true; } return false; diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/DirectMessageListenerContainer.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/DirectMessageListenerContainer.java index 27d26326b3..cabbe13dc6 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/DirectMessageListenerContainer.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/DirectMessageListenerContainer.java @@ -963,8 +963,8 @@ final class SimpleConsumer extends DefaultConsumer { this.queue = queue; this.index = index; this.ackRequired = !getAcknowledgeMode().isAutoAck() && !getAcknowledgeMode().isManual(); - if (channel instanceof ChannelProxy) { - this.targetChannel = ((ChannelProxy) channel).getTargetChannel(); + if (channel instanceof ChannelProxy proxy) { + this.targetChannel = proxy.getTargetChannel(); } else { this.targetChannel = null; @@ -1050,9 +1050,9 @@ public void handleDelivery(String consumerTag, Envelope envelope, try { executeListenerInTransaction(data, deliveryTag); } - catch (WrappedTransactionException e) { - if (e.getCause() instanceof Error) { - throw (Error) e.getCause(); + catch (WrappedTransactionException ex) { + if (ex.getCause() instanceof Error error) { + throw error; } } catch (Exception e) { diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/RabbitListenerEndpointRegistrar.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/RabbitListenerEndpointRegistrar.java index 998c28957b..99e20ff77b 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/RabbitListenerEndpointRegistrar.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/RabbitListenerEndpointRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2022 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. @@ -188,8 +188,8 @@ protected void registerAllEndpoints() { Assert.state(this.endpointRegistry != null, "No registry available"); synchronized (this.endpointDescriptors) { for (AmqpListenerEndpointDescriptor descriptor : this.endpointDescriptors) { - if (descriptor.endpoint instanceof MultiMethodRabbitListenerEndpoint && this.validator != null) { - ((MultiMethodRabbitListenerEndpoint) descriptor.endpoint).setValidator(this.validator); + if (descriptor.endpoint instanceof MultiMethodRabbitListenerEndpoint multi && this.validator != null) { + multi.setValidator(this.validator); } this.endpointRegistry.registerListenerContainer(// NOSONAR never null descriptor.endpoint, resolveContainerFactory(descriptor)); diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/RabbitListenerEndpointRegistry.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/RabbitListenerEndpointRegistry.java index 5b20169ffa..7765c3acc9 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/RabbitListenerEndpointRegistry.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/RabbitListenerEndpointRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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,8 @@ public class RabbitListenerEndpointRegistry implements DisposableBean, SmartLife @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - if (applicationContext instanceof ConfigurableApplicationContext) { - this.applicationContext = (ConfigurableApplicationContext) applicationContext; + if (applicationContext instanceof ConfigurableApplicationContext configurable) { + this.applicationContext = configurable; } } @@ -209,9 +209,9 @@ public MessageListenerContainer unregisterListenerContainer(String id) { @Override public void destroy() { for (MessageListenerContainer listenerContainer : getListenerContainers()) { - if (listenerContainer instanceof DisposableBean) { + if (listenerContainer instanceof DisposableBean disposable) { try { - ((DisposableBean) listenerContainer).destroy(); + disposable.destroy(); } catch (Exception ex) { this.logger.warn("Failed to destroy listener container [" + listenerContainer + "]", ex); diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/SimpleMessageListenerContainer.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/SimpleMessageListenerContainer.java index 4bfef6db04..023a7a5031 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/SimpleMessageListenerContainer.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/SimpleMessageListenerContainer.java @@ -566,8 +566,8 @@ protected void doStart() { private void checkListenerContainerAware() { Object messageListener = getMessageListener(); - if (messageListener instanceof ListenerContainerAware) { - Collection expectedQueueNames = ((ListenerContainerAware) messageListener).expectedQueueNames(); + if (messageListener instanceof ListenerContainerAware containerAware) { + Collection expectedQueueNames = containerAware.expectedQueueNames(); if (expectedQueueNames != null) { String[] queueNames = getQueueNames(); Assert.state(expectedQueueNames.size() == queueNames.length, diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/adapter/AbstractAdaptableMessageListener.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/adapter/AbstractAdaptableMessageListener.java index 2e0bd8181e..96b21afb41 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/adapter/AbstractAdaptableMessageListener.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/adapter/AbstractAdaptableMessageListener.java @@ -374,12 +374,12 @@ protected void handleResult(InvocationResult resultArg, Message request, Channel */ protected void handleResult(InvocationResult resultArg, Message request, Channel channel, Object source) { if (channel != null) { - if (resultArg.getReturnValue() instanceof CompletableFuture) { + if (resultArg.getReturnValue() instanceof CompletableFuture completable) { if (!this.isManualAck) { this.logger.warn("Container AcknowledgeMode must be MANUAL for a Future return type; " + "otherwise the container will ack the message immediately"); } - ((CompletableFuture) resultArg.getReturnValue()).whenComplete((r, t) -> { + completable.whenComplete((r, t) -> { if (t == null) { asyncSuccess(resultArg, request, channel, source, r); basicAck(request, channel); @@ -498,11 +498,13 @@ protected Message buildMessage(Channel channel, Object result, Type genericType) return convert(result, genericType, converter); } else { - if (!(result instanceof Message)) { + if (result instanceof Message msg) { + return msg; + } + else { throw new MessageConversionException("No MessageConverter specified - cannot handle message [" + result + "]"); } - return (Message) result; } } @@ -593,8 +595,8 @@ private Address evaluateReplyTo(Message request, Object source, Object result, E Object value = expression.getValue(this.evalContext, new ReplyExpressionRoot(request, source, result)); Assert.state(value instanceof String || value instanceof Address, "response expression must evaluate to a String or Address"); - if (value instanceof String) { - replyTo = new Address((String) value); + if (value instanceof String sValue) { + replyTo = new Address(sValue); } else { replyTo = (Address) value; diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/adapter/MessageListenerAdapter.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/adapter/MessageListenerAdapter.java index d4ef95993a..c9c90a1871 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/adapter/MessageListenerAdapter.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/adapter/MessageListenerAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2022 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. @@ -269,12 +269,12 @@ public void onMessage(Message message, Channel channel) throws Exception { // NO // In that case, the adapter will simply act as a pass-through. Object delegateListener = getDelegate(); if (!delegateListener.equals(this)) { - if (delegateListener instanceof ChannelAwareMessageListener) { - ((ChannelAwareMessageListener) delegateListener).onMessage(message, channel); + if (delegateListener instanceof ChannelAwareMessageListener chaml) { + chaml.onMessage(message, channel); return; } - else if (delegateListener instanceof MessageListener) { - ((MessageListener) delegateListener).onMessage(message); + else if (delegateListener instanceof MessageListener messageListener) { + messageListener.onMessage(message); return; } } @@ -367,8 +367,8 @@ protected Object invokeListenerMethod(String methodName, Object[] arguments, Mes } catch (InvocationTargetException ex) { Throwable targetEx = ex.getTargetException(); - if (targetEx instanceof IOException) { - throw new AmqpIOException((IOException) targetEx); // NOSONAR lost stack trace + if (targetEx instanceof IOException iox) { + throw new AmqpIOException(iox); // NOSONAR lost stack trace } else { throw new ListenerExecutionFailedException("Listener method '" // NOSONAR lost stack trace diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/adapter/MessagingMessageListenerAdapter.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/adapter/MessagingMessageListenerAdapter.java index f7acd82e2c..27fa54ead0 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/adapter/MessagingMessageListenerAdapter.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/adapter/MessagingMessageListenerAdapter.java @@ -300,11 +300,13 @@ protected org.springframework.amqp.core.Message buildMessage(Channel channel, Ob } } else { - if (!(result instanceof org.springframework.amqp.core.Message)) { + if (result instanceof org.springframework.amqp.core.Message msg) { + return msg; + } + else { throw new MessageConversionException("No MessageConverter specified - cannot handle message [" + result + "]"); } - return (org.springframework.amqp.core.Message) result; } } @@ -417,10 +419,8 @@ private Type determineInferredType() { // NOSONAR - complexity } protected Type checkOptional(Type genericParameterType) { - if (genericParameterType instanceof ParameterizedType - && ((ParameterizedType) genericParameterType).getRawType().equals(Optional.class)) { - - return ((ParameterizedType) genericParameterType).getActualTypeArguments()[0]; + if (genericParameterType instanceof ParameterizedType pType && pType.getRawType().equals(Optional.class)) { + return pType.getActualTypeArguments()[0]; } return genericParameterType; } @@ -436,8 +436,7 @@ private boolean isEligibleParameter(MethodParameter methodParameter) { || parameterType.equals(org.springframework.amqp.core.Message.class)) { return false; } - if (parameterType instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) parameterType; + if (parameterType instanceof ParameterizedType parameterizedType) { if (parameterizedType.getRawType().equals(Message.class)) { return !(parameterizedType.getActualTypeArguments()[0] instanceof WildcardType); } @@ -447,8 +446,7 @@ private boolean isEligibleParameter(MethodParameter methodParameter) { private Type extractGenericParameterTypFromMethodParameter(MethodParameter methodParameter) { Type genericParameterType = methodParameter.getGenericParameterType(); - if (genericParameterType instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) genericParameterType; + if (genericParameterType instanceof ParameterizedType parameterizedType) { if (parameterizedType.getRawType().equals(Message.class)) { genericParameterType = ((ParameterizedType) genericParameterType).getActualTypeArguments()[0]; } @@ -459,8 +457,8 @@ else if (this.isBatch this.isCollection = true; Type paramType = parameterizedType.getActualTypeArguments()[0]; - boolean messageHasGeneric = paramType instanceof ParameterizedType - && ((ParameterizedType) paramType).getRawType().equals(Message.class); + boolean messageHasGeneric = paramType instanceof ParameterizedType pType + && pType.getRawType().equals(Message.class); this.isMessageList = paramType.equals(Message.class) || messageHasGeneric; this.isAmqpMessageList = paramType.equals(org.springframework.amqp.core.Message.class); if (messageHasGeneric) { diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/support/ContainerUtils.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/support/ContainerUtils.java index cf88726675..06d83ebc02 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/support/ContainerUtils.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/support/ContainerUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2018-2019 the original author or authors. + * Copyright 2018-2022 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. @@ -75,8 +75,8 @@ else if (t instanceof ImmediateRequeueAmqpException) { * @since 2.2 */ public static boolean isRejectManual(Throwable ex) { - return ex instanceof AmqpRejectAndDontRequeueException - && ((AmqpRejectAndDontRequeueException) ex).isRejectManual(); + return ex instanceof AmqpRejectAndDontRequeueException aradrex + && aradrex.isRejectManual(); } } diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/logback/AmqpAppender.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/logback/AmqpAppender.java index be35f98c0b..ba5a6e25f9 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/logback/AmqpAppender.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/logback/AmqpAppender.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 the original author or authors. + * Copyright 2014-2022 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. @@ -952,10 +952,10 @@ private void sendOneEncoderPatternMessage(RabbitTemplate rabbitTemplate, String private void doSend(RabbitTemplate rabbitTemplate, final Event event, ILoggingEvent logEvent, String name, MessageProperties amqpProps, String routingKey) { byte[] msgBody; - if (AmqpAppender.this.abbreviator != null && logEvent instanceof LoggingEvent) { - ((LoggingEvent) logEvent).setLoggerName(AmqpAppender.this.abbreviator.abbreviate(name)); + if (AmqpAppender.this.abbreviator != null && logEvent instanceof LoggingEvent logEv) { + logEv.setLoggerName(AmqpAppender.this.abbreviator.abbreviate(name)); msgBody = encodeMessage(logEvent); - ((LoggingEvent) logEvent).setLoggerName(name); + logEv.setLoggerName(name); } else { msgBody = encodeMessage(logEvent); diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/support/DefaultMessagePropertiesConverter.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/support/DefaultMessagePropertiesConverter.java index 4fb2d0c73f..72053d2846 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/support/DefaultMessagePropertiesConverter.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/support/DefaultMessagePropertiesConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -92,8 +92,8 @@ public MessageProperties toMessageProperties(final BasicProperties source, final String key = entry.getKey(); if (MessageProperties.X_DELAY.equals(key)) { Object value = entry.getValue(); - if (value instanceof Integer) { - target.setReceivedDelay((Integer) value); + if (value instanceof Integer integ) { + target.setReceivedDelay(integ); } } else { @@ -192,8 +192,7 @@ private Object convertHeaderValueIfNecessary(@Nullable Object valueArg) { if (!valid && value != null) { value = value.toString(); } - else if (value instanceof Object[]) { - Object[] array = (Object[]) value; + else if (value instanceof Object[] array) { Object[] writableArray = new Object[array.length]; for (int i = 0; i < writableArray.length; i++) { writableArray[i] = convertHeaderValueIfNecessary(array[i]); @@ -216,8 +215,8 @@ else if (value instanceof Map) { } value = writableMap; } - else if (value instanceof Class) { - value = ((Class) value).getName(); + else if (value instanceof Class clazz) { + value = clazz.getName(); } return value; } @@ -254,8 +253,8 @@ private Object convertLongString(LongString longString, String charset) { */ private Object convertLongStringIfNecessary(Object valueArg, String charset) { Object value = valueArg; - if (value instanceof LongString) { - value = convertLongString((LongString) value, charset); + if (value instanceof LongString longStr) { + value = convertLongString(longStr, charset); } else if (value instanceof List) { List convertedList = new ArrayList(((List) value).size()); diff --git a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/support/RabbitExceptionTranslator.java b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/support/RabbitExceptionTranslator.java index 19e339bb83..d553473dc0 100644 --- a/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/support/RabbitExceptionTranslator.java +++ b/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/support/RabbitExceptionTranslator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2022 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. @@ -54,11 +54,11 @@ public static RuntimeException convertRabbitAccessException(Throwable ex) { if (ex instanceof AmqpException) { return (AmqpException) ex; } - if (ex instanceof ShutdownSignalException) { - return new AmqpConnectException((ShutdownSignalException) ex); + if (ex instanceof ShutdownSignalException sigEx) { + return new AmqpConnectException(sigEx); } - if (ex instanceof ConnectException) { - return new AmqpConnectException((ConnectException) ex); + if (ex instanceof ConnectException connEx) { + return new AmqpConnectException(connEx); } if (ex instanceof PossibleAuthenticationFailureException) { return new AmqpAuthenticationException(ex); @@ -66,8 +66,8 @@ public static RuntimeException convertRabbitAccessException(Throwable ex) { if (ex instanceof UnsupportedEncodingException) { return new AmqpUnsupportedEncodingException(ex); } - if (ex instanceof IOException) { - return new AmqpIOException((IOException) ex); + if (ex instanceof IOException ioEx) { + return new AmqpIOException(ioEx); } if (ex instanceof TimeoutException) { return new AmqpTimeoutException(ex);