Apply "instanceof pattern matching" in spring-jms

This commit is contained in:
Sam Brannen 2023-01-16 19:12:58 +01:00
parent 3a585f8c29
commit 8be542016b
25 changed files with 180 additions and 178 deletions

View File

@ -71,8 +71,8 @@ public abstract class JmsException extends NestedRuntimeException {
@Nullable
public String getErrorCode() {
Throwable cause = getCause();
if (cause instanceof JMSException) {
return ((JMSException) cause).getErrorCode();
if (cause instanceof JMSException jmsException) {
return jmsException.getErrorCode();
}
return null;
}
@ -87,8 +87,8 @@ public abstract class JmsException extends NestedRuntimeException {
public String getMessage() {
String message = super.getMessage();
Throwable cause = getCause();
if (cause instanceof JMSException) {
Exception linkedEx = ((JMSException) cause).getLinkedException();
if (cause instanceof JMSException jmsException) {
Exception linkedEx = jmsException.getLinkedException();
if (linkedEx != null) {
String linkedMessage = linkedEx.getMessage();
String causeMessage = cause.getMessage();

View File

@ -162,8 +162,8 @@ public class JmsListenerAnnotationBeanPostProcessor
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
if (beanFactory instanceof ConfigurableBeanFactory) {
this.embeddedValueResolver = new EmbeddedValueResolver((ConfigurableBeanFactory) beanFactory);
if (beanFactory instanceof ConfigurableBeanFactory cbf) {
this.embeddedValueResolver = new EmbeddedValueResolver(cbf);
}
this.registrar.setBeanFactory(beanFactory);
}
@ -174,10 +174,9 @@ public class JmsListenerAnnotationBeanPostProcessor
// Remove resolved singleton classes from cache
this.nonAnnotatedClasses.clear();
if (this.beanFactory instanceof ListableBeanFactory) {
if (this.beanFactory instanceof ListableBeanFactory lbf) {
// Apply JmsListenerConfigurer beans from the BeanFactory, if any
Map<String, JmsListenerConfigurer> beans =
((ListableBeanFactory) this.beanFactory).getBeansOfType(JmsListenerConfigurer.class);
Map<String, JmsListenerConfigurer> beans = lbf.getBeansOfType(JmsListenerConfigurer.class);
List<JmsListenerConfigurer> configurers = new ArrayList<>(beans.values());
AnnotationAwareOrderComparator.sort(configurers);
for (JmsListenerConfigurer configurer : configurers) {

View File

@ -134,8 +134,8 @@ public abstract class AbstractJmsListenerEndpoint implements JmsListenerEndpoint
@Override
public void setupListenerContainer(MessageListenerContainer listenerContainer) {
if (listenerContainer instanceof AbstractMessageListenerContainer) {
setupJmsListenerContainer((AbstractMessageListenerContainer) listenerContainer);
if (listenerContainer instanceof AbstractMessageListenerContainer abstractContainer) {
setupJmsListenerContainer(abstractContainer);
}
else {
new JcaEndpointConfigurer().configureEndpoint(listenerContainer);
@ -194,8 +194,8 @@ public abstract class AbstractJmsListenerEndpoint implements JmsListenerEndpoint
private class JcaEndpointConfigurer {
public void configureEndpoint(Object listenerContainer) {
if (listenerContainer instanceof JmsMessageEndpointManager) {
setupJcaMessageContainer((JmsMessageEndpointManager) listenerContainer);
if (listenerContainer instanceof JmsMessageEndpointManager endpointManager) {
setupJcaMessageContainer(endpointManager);
}
else {
throw new IllegalArgumentException("Could not configure endpoint with the specified container '" +

View File

@ -124,8 +124,8 @@ public class JmsListenerEndpointRegistrar implements BeanFactoryAware, Initializ
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
if (beanFactory instanceof ConfigurableBeanFactory) {
this.mutex = ((ConfigurableBeanFactory) beanFactory).getSingletonMutex();
if (beanFactory instanceof ConfigurableBeanFactory cbf) {
this.mutex = cbf.getSingletonMutex();
}
}

View File

@ -170,9 +170,9 @@ public class JmsListenerEndpointRegistry implements DisposableBean, SmartLifecyc
MessageListenerContainer listenerContainer = factory.createListenerContainer(endpoint);
if (listenerContainer instanceof InitializingBean) {
if (listenerContainer instanceof InitializingBean initializingBean) {
try {
((InitializingBean) listenerContainer).afterPropertiesSet();
initializingBean.afterPropertiesSet();
}
catch (Exception ex) {
throw new BeanInitializationException("Failed to initialize message listener container", ex);
@ -246,9 +246,9 @@ public class JmsListenerEndpointRegistry implements DisposableBean, SmartLifecyc
@Override
public void destroy() {
for (MessageListenerContainer listenerContainer : getListenerContainers()) {
if (listenerContainer instanceof DisposableBean) {
if (listenerContainer instanceof DisposableBean disposableBean) {
try {
((DisposableBean) listenerContainer).destroy();
disposableBean.destroy();
}
catch (Throwable ex) {
logger.warn("Failed to destroy message listener container", ex);

View File

@ -136,8 +136,8 @@ public class MethodJmsListenerEndpoint extends AbstractJmsListenerEndpoint imple
*/
@Override
public void setBeanFactory(@Nullable BeanFactory beanFactory) {
if (this.embeddedValueResolver == null && beanFactory instanceof ConfigurableBeanFactory) {
this.embeddedValueResolver = new EmbeddedValueResolver((ConfigurableBeanFactory) beanFactory);
if (this.embeddedValueResolver == null && beanFactory instanceof ConfigurableBeanFactory cbf) {
this.embeddedValueResolver = new EmbeddedValueResolver(cbf);
}
}

View File

@ -52,18 +52,18 @@ class CachedMessageConsumer implements MessageConsumer, QueueReceiver, TopicSubs
@Override
@Nullable
public Queue getQueue() throws JMSException {
return (this.target instanceof QueueReceiver ? ((QueueReceiver) this.target).getQueue() : null);
return (this.target instanceof QueueReceiver receiver ? receiver.getQueue() : null);
}
@Override
@Nullable
public Topic getTopic() throws JMSException {
return (this.target instanceof TopicSubscriber ? ((TopicSubscriber) this.target).getTopic() : null);
return (this.target instanceof TopicSubscriber subscriber ? subscriber.getTopic() : null);
}
@Override
public boolean getNoLocal() throws JMSException {
return (this.target instanceof TopicSubscriber && ((TopicSubscriber) this.target).getNoLocal());
return (this.target instanceof TopicSubscriber subscriber && subscriber.getNoLocal());
}
@Override

View File

@ -255,7 +255,7 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
if (session != null) {
if (logger.isTraceEnabled()) {
logger.trace("Found cached JMS Session for mode " + mode + ": " +
(session instanceof SessionProxy ? ((SessionProxy) session).getTargetSession() : session));
(session instanceof SessionProxy sessionProxy ? sessionProxy.getTargetSession() : session));
}
}
else {
@ -455,15 +455,15 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
}
}
else {
if (dest instanceof Topic) {
if (dest instanceof Topic topic) {
if (noLocal == null) {
consumer = (durable ?
this.target.createSharedDurableConsumer((Topic) dest, subscription, selector) :
this.target.createSharedConsumer((Topic) dest, subscription, selector));
this.target.createSharedDurableConsumer(topic, subscription, selector) :
this.target.createSharedConsumer(topic, subscription, selector));
}
else {
consumer = (durable ?
this.target.createDurableSubscriber((Topic) dest, subscription, selector, noLocal) :
this.target.createDurableSubscriber(topic, subscription, selector, noLocal) :
this.target.createConsumer(dest, selector, noLocal));
}
}
@ -559,11 +559,11 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
}
@Override
public boolean equals(@Nullable Object other) {
public boolean equals(@Nullable Object obj) {
// Effectively checking object equality as well as toString equality.
// On WebSphere MQ, Destination objects do not implement equals...
return (this == other || (other instanceof DestinationCacheKey &&
destinationEquals((DestinationCacheKey) other)));
return (this == obj || (obj instanceof DestinationCacheKey otherKey &&
destinationEquals(otherKey)));
}
@Override

View File

@ -68,7 +68,7 @@ public abstract class ConnectionFactoryUtils {
if (con == null) {
return;
}
if (started && cf instanceof SmartConnectionFactory && ((SmartConnectionFactory) cf).shouldStop(con)) {
if (started && cf instanceof SmartConnectionFactory smartFactory && smartFactory.shouldStop(con)) {
try {
con.stop();
}
@ -94,8 +94,8 @@ public abstract class ConnectionFactoryUtils {
*/
public static Session getTargetSession(Session session) {
Session sessionToUse = session;
while (sessionToUse instanceof SessionProxy) {
sessionToUse = ((SessionProxy) sessionToUse).getTargetSession();
while (sessionToUse instanceof SessionProxy sessionProxy) {
sessionToUse = sessionProxy.getTargetSession();
}
return sessionToUse;
}

View File

@ -120,60 +120,60 @@ public class DelegatingConnectionFactory
@Override
public QueueConnection createQueueConnection() throws JMSException {
ConnectionFactory target = obtainTargetConnectionFactory();
if (target instanceof QueueConnectionFactory) {
return ((QueueConnectionFactory) target).createQueueConnection();
if (target instanceof QueueConnectionFactory queueFactory) {
return queueFactory.createQueueConnection();
}
else {
Connection con = target.createConnection();
if (!(con instanceof QueueConnection)) {
if (!(con instanceof QueueConnection queueConnection)) {
throw new jakarta.jms.IllegalStateException("'targetConnectionFactory' is not a QueueConnectionFactory");
}
return (QueueConnection) con;
return queueConnection;
}
}
@Override
public QueueConnection createQueueConnection(String username, String password) throws JMSException {
ConnectionFactory target = obtainTargetConnectionFactory();
if (target instanceof QueueConnectionFactory) {
return ((QueueConnectionFactory) target).createQueueConnection(username, password);
if (target instanceof QueueConnectionFactory queueFactory) {
return queueFactory.createQueueConnection(username, password);
}
else {
Connection con = target.createConnection(username, password);
if (!(con instanceof QueueConnection)) {
if (!(con instanceof QueueConnection queueConnection)) {
throw new jakarta.jms.IllegalStateException("'targetConnectionFactory' is not a QueueConnectionFactory");
}
return (QueueConnection) con;
return queueConnection;
}
}
@Override
public TopicConnection createTopicConnection() throws JMSException {
ConnectionFactory target = obtainTargetConnectionFactory();
if (target instanceof TopicConnectionFactory) {
return ((TopicConnectionFactory) target).createTopicConnection();
if (target instanceof TopicConnectionFactory topicFactory) {
return topicFactory.createTopicConnection();
}
else {
Connection con = target.createConnection();
if (!(con instanceof TopicConnection)) {
if (!(con instanceof TopicConnection topicConnection)) {
throw new jakarta.jms.IllegalStateException("'targetConnectionFactory' is not a TopicConnectionFactory");
}
return (TopicConnection) con;
return topicConnection;
}
}
@Override
public TopicConnection createTopicConnection(String username, String password) throws JMSException {
ConnectionFactory target = obtainTargetConnectionFactory();
if (target instanceof TopicConnectionFactory) {
return ((TopicConnectionFactory) target).createTopicConnection(username, password);
if (target instanceof TopicConnectionFactory topicFactory) {
return topicFactory.createTopicConnection(username, password);
}
else {
Connection con = target.createConnection(username, password);
if (!(con instanceof TopicConnection)) {
if (!(con instanceof TopicConnection topicConnection)) {
throw new jakarta.jms.IllegalStateException("'targetConnectionFactory' is not a TopicConnectionFactory");
}
return (TopicConnection) con;
return topicConnection;
}
}

View File

@ -130,11 +130,11 @@ public class JmsTransactionManager extends AbstractPlatformTransactionManager
* Set the JMS ConnectionFactory that this instance should manage transactions for.
*/
public void setConnectionFactory(@Nullable ConnectionFactory cf) {
if (cf instanceof TransactionAwareConnectionFactoryProxy) {
if (cf instanceof TransactionAwareConnectionFactoryProxy txAwareCFP) {
// If we got a TransactionAwareConnectionFactoryProxy, we need to perform transactions
// for its underlying target ConnectionFactory, else JMS access code won't see
// properly exposed transactions (i.e. transactions for the target ConnectionFactory).
this.connectionFactory = ((TransactionAwareConnectionFactoryProxy) cf).getTargetConnectionFactory();
this.connectionFactory = txAwareCFP.getTargetConnectionFactory();
}
else {
this.connectionFactory = cf;

View File

@ -255,11 +255,11 @@ public class SingleConnectionFactory implements ConnectionFactory, QueueConnecti
this.pubSubMode = Boolean.FALSE;
con = createConnection();
}
if (!(con instanceof QueueConnection)) {
if (!(con instanceof QueueConnection queueConnection)) {
throw new jakarta.jms.IllegalStateException(
"This SingleConnectionFactory does not hold a QueueConnection but rather: " + con);
}
return ((QueueConnection) con);
return queueConnection;
}
@Override
@ -275,11 +275,11 @@ public class SingleConnectionFactory implements ConnectionFactory, QueueConnecti
this.pubSubMode = Boolean.TRUE;
con = createConnection();
}
if (!(con instanceof TopicConnection)) {
if (!(con instanceof TopicConnection topicConnection)) {
throw new jakarta.jms.IllegalStateException(
"This SingleConnectionFactory does not hold a TopicConnection but rather: " + con);
}
return ((TopicConnection) con);
return topicConnection;
}
@Override
@ -399,11 +399,11 @@ public class SingleConnectionFactory implements ConnectionFactory, QueueConnecti
*/
protected Connection doCreateConnection() throws JMSException {
ConnectionFactory cf = getTargetConnectionFactory();
if (Boolean.FALSE.equals(this.pubSubMode) && cf instanceof QueueConnectionFactory) {
return ((QueueConnectionFactory) cf).createQueueConnection();
if (Boolean.FALSE.equals(this.pubSubMode) && cf instanceof QueueConnectionFactory queueFactory) {
return queueFactory.createQueueConnection();
}
else if (Boolean.TRUE.equals(this.pubSubMode) && cf instanceof TopicConnectionFactory) {
return ((TopicConnectionFactory) cf).createTopicConnection();
else if (Boolean.TRUE.equals(this.pubSubMode) && cf instanceof TopicConnectionFactory topicFactory) {
return topicFactory.createTopicConnection();
}
else {
return obtainTargetConnectionFactory().createConnection();
@ -472,11 +472,11 @@ public class SingleConnectionFactory implements ConnectionFactory, QueueConnecti
boolean transacted = (mode == Session.SESSION_TRANSACTED);
int ackMode = (transacted ? Session.AUTO_ACKNOWLEDGE : mode);
// Now actually call the appropriate JMS factory method...
if (Boolean.FALSE.equals(this.pubSubMode) && con instanceof QueueConnection) {
return ((QueueConnection) con).createQueueSession(transacted, ackMode);
if (Boolean.FALSE.equals(this.pubSubMode) && con instanceof QueueConnection queueConnection) {
return queueConnection.createQueueSession(transacted, ackMode);
}
else if (Boolean.TRUE.equals(this.pubSubMode) && con instanceof TopicConnection) {
return ((TopicConnection) con).createTopicSession(transacted, ackMode);
else if (Boolean.TRUE.equals(this.pubSubMode) && con instanceof TopicConnection topicConnection) {
return topicConnection.createTopicSession(transacted, ackMode);
}
else {
return con.createSession(transacted, ackMode);
@ -554,8 +554,8 @@ public class SingleConnectionFactory implements ConnectionFactory, QueueConnecti
return false;
}
InvocationHandler otherHandler = Proxy.getInvocationHandler(other);
return (otherHandler instanceof SharedConnectionInvocationHandler &&
factory() == ((SharedConnectionInvocationHandler) otherHandler).factory());
return (otherHandler instanceof SharedConnectionInvocationHandler sharedHandler &&
factory() == sharedHandler.factory());
case "hashCode":
// Use hashCode of containing SingleConnectionFactory.
return System.identityHashCode(factory());

View File

@ -163,40 +163,40 @@ public class TransactionAwareConnectionFactoryProxy
@Override
public QueueConnection createQueueConnection() throws JMSException {
ConnectionFactory target = getTargetConnectionFactory();
if (!(target instanceof QueueConnectionFactory)) {
if (!(target instanceof QueueConnectionFactory queueFactory)) {
throw new jakarta.jms.IllegalStateException("'targetConnectionFactory' is no QueueConnectionFactory");
}
QueueConnection targetConnection = ((QueueConnectionFactory) target).createQueueConnection();
QueueConnection targetConnection = queueFactory.createQueueConnection();
return (QueueConnection) getTransactionAwareConnectionProxy(targetConnection);
}
@Override
public QueueConnection createQueueConnection(String username, String password) throws JMSException {
ConnectionFactory target = getTargetConnectionFactory();
if (!(target instanceof QueueConnectionFactory)) {
if (!(target instanceof QueueConnectionFactory queueFactory)) {
throw new jakarta.jms.IllegalStateException("'targetConnectionFactory' is no QueueConnectionFactory");
}
QueueConnection targetConnection = ((QueueConnectionFactory) target).createQueueConnection(username, password);
QueueConnection targetConnection = queueFactory.createQueueConnection(username, password);
return (QueueConnection) getTransactionAwareConnectionProxy(targetConnection);
}
@Override
public TopicConnection createTopicConnection() throws JMSException {
ConnectionFactory target = getTargetConnectionFactory();
if (!(target instanceof TopicConnectionFactory)) {
if (!(target instanceof TopicConnectionFactory topicFactory)) {
throw new jakarta.jms.IllegalStateException("'targetConnectionFactory' is no TopicConnectionFactory");
}
TopicConnection targetConnection = ((TopicConnectionFactory) target).createTopicConnection();
TopicConnection targetConnection = topicFactory.createTopicConnection();
return (TopicConnection) getTransactionAwareConnectionProxy(targetConnection);
}
@Override
public TopicConnection createTopicConnection(String username, String password) throws JMSException {
ConnectionFactory target = getTargetConnectionFactory();
if (!(target instanceof TopicConnectionFactory)) {
if (!(target instanceof TopicConnectionFactory topicFactory)) {
throw new jakarta.jms.IllegalStateException("'targetConnectionFactory' is no TopicConnectionFactory");
}
TopicConnection targetConnection = ((TopicConnectionFactory) target).createTopicConnection(username, password);
TopicConnection targetConnection = topicFactory.createTopicConnection(username, password);
return (TopicConnection) getTransactionAwareConnectionProxy(targetConnection);
}

View File

@ -283,14 +283,14 @@ public class UserCredentialsConnectionFactoryAdapter
@Nullable String username, @Nullable String password) throws JMSException {
ConnectionFactory target = obtainTargetConnectionFactory();
if (!(target instanceof TopicConnectionFactory queueFactory)) {
if (!(target instanceof TopicConnectionFactory topicFactory)) {
throw new jakarta.jms.IllegalStateException("'targetConnectionFactory' is not a TopicConnectionFactory");
}
if (StringUtils.hasLength(username)) {
return queueFactory.createTopicConnection(username, password);
return topicFactory.createTopicConnection(username, password);
}
else {
return queueFactory.createTopicConnection();
return topicFactory.createTopicConnection();
}
}

View File

@ -173,7 +173,7 @@ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations
*/
@Nullable
public Destination getDefaultDestination() {
return (this.defaultDestination instanceof Destination ? (Destination) this.defaultDestination : null);
return (this.defaultDestination instanceof Destination dest ? dest : null);
}
@Nullable
@ -207,7 +207,7 @@ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations
*/
@Nullable
public String getDefaultDestinationName() {
return (this.defaultDestination instanceof String ? (String) this.defaultDestination : null);
return (this.defaultDestination instanceof String name ? name : null);
}
private String getRequiredDefaultDestinationName() throws IllegalStateException {

View File

@ -210,7 +210,7 @@ public abstract class AbstractMessageListenerContainer extends AbstractJmsListen
*/
@Nullable
public Destination getDestination() {
return (this.destination instanceof Destination ? (Destination) this.destination : null);
return (this.destination instanceof Destination _destination ? _destination : null);
}
/**
@ -236,7 +236,7 @@ public abstract class AbstractMessageListenerContainer extends AbstractJmsListen
*/
@Nullable
public String getDestinationName() {
return (this.destination instanceof String ? (String) this.destination : null);
return (this.destination instanceof String name ? name : null);
}
/**
@ -326,8 +326,8 @@ public abstract class AbstractMessageListenerContainer extends AbstractJmsListen
* @see SubscriptionNameProvider
*/
protected String getDefaultSubscriptionName(Object messageListener) {
if (messageListener instanceof SubscriptionNameProvider) {
return ((SubscriptionNameProvider) messageListener).getSubscriptionName();
if (messageListener instanceof SubscriptionNameProvider subscriptionNameProvider) {
return subscriptionNameProvider.getSubscriptionName();
}
else {
return messageListener.getClass().getName();
@ -692,11 +692,11 @@ public abstract class AbstractMessageListenerContainer extends AbstractJmsListen
protected void invokeListener(Session session, Message message) throws JMSException {
Object listener = getMessageListener();
if (listener instanceof SessionAwareMessageListener) {
doInvokeListener((SessionAwareMessageListener) listener, session, message);
if (listener instanceof SessionAwareMessageListener sessionAwareMessageListener) {
doInvokeListener(sessionAwareMessageListener, session, message);
}
else if (listener instanceof MessageListener) {
doInvokeListener((MessageListener) listener, message);
else if (listener instanceof MessageListener msgListener) {
doInvokeListener(msgListener, message);
}
else if (listener != null) {
throw new IllegalArgumentException(
@ -853,15 +853,15 @@ public abstract class AbstractMessageListenerContainer extends AbstractJmsListen
* @throws jakarta.jms.JMSException if thrown by JMS API methods
*/
protected MessageConsumer createConsumer(Session session, Destination destination) throws JMSException {
if (isPubSubDomain() && destination instanceof Topic) {
if (isPubSubDomain() && destination instanceof Topic topic) {
if (isSubscriptionShared()) {
return (isSubscriptionDurable() ?
session.createSharedDurableConsumer((Topic) destination, getSubscriptionName(), getMessageSelector()) :
session.createSharedConsumer((Topic) destination, getSubscriptionName(), getMessageSelector()));
session.createSharedDurableConsumer(topic, getSubscriptionName(), getMessageSelector()) :
session.createSharedConsumer(topic, getSubscriptionName(), getMessageSelector()));
}
else if (isSubscriptionDurable()) {
return session.createDurableSubscriber(
(Topic) destination, getSubscriptionName(), getMessageSelector(), isPubSubNoLocal());
topic, getSubscriptionName(), getMessageSelector(), isPubSubNoLocal());
}
else {
// Only pass in the NoLocal flag in case of a Topic (pub-sub mode):
@ -888,8 +888,8 @@ public abstract class AbstractMessageListenerContainer extends AbstractJmsListen
// Internal exception - has been handled before.
return;
}
if (ex instanceof JMSException) {
invokeExceptionListener((JMSException) ex);
if (ex instanceof JMSException jmsException) {
invokeExceptionListener(jmsException);
}
if (isActive()) {
// Regular case: failed while active.

View File

@ -188,9 +188,8 @@ public abstract class AbstractPollingMessageListenerContainer extends AbstractMe
public void initialize() {
// Set sessionTransacted=true in case of a non-JTA transaction manager.
if (!this.sessionTransactedCalled &&
this.transactionManager instanceof ResourceTransactionManager &&
!TransactionSynchronizationUtils.sameResourceFactory(
(ResourceTransactionManager) this.transactionManager, obtainConnectionFactory())) {
this.transactionManager instanceof ResourceTransactionManager rtm &&
!TransactionSynchronizationUtils.sameResourceFactory(rtm, obtainConnectionFactory())) {
super.setSessionTransacted(true);
}
@ -340,8 +339,8 @@ public abstract class AbstractPollingMessageListenerContainer extends AbstractMe
handleListenerException(ex);
// Rethrow JMSException to indicate an infrastructure problem
// that may have to trigger recovery...
if (ex instanceof JMSException) {
throw (JMSException) ex;
if (ex instanceof JMSException jmsException) {
throw jmsException;
}
}
finally {

View File

@ -568,8 +568,8 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe
if (this.taskExecutor == null) {
this.taskExecutor = createDefaultTaskExecutor();
}
else if (this.taskExecutor instanceof SchedulingTaskExecutor &&
((SchedulingTaskExecutor) this.taskExecutor).prefersShortLivedTasks() &&
else if (this.taskExecutor instanceof SchedulingTaskExecutor ste &&
ste.prefersShortLivedTasks() &&
this.maxMessagesPerTask == Integer.MIN_VALUE) {
// TaskExecutor indicated a preference for short-lived tasks. According to
// setMaxMessagesPerTask javadoc, we'll use 10 message per task in this case
@ -861,8 +861,8 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe
super.establishSharedConnection();
}
catch (Exception ex) {
if (ex instanceof JMSException) {
invokeExceptionListener((JMSException) ex);
if (ex instanceof JMSException jmsException) {
invokeExceptionListener(jmsException);
}
logger.debug("Could not establish shared JMS Connection - " +
"leaving it up to asynchronous invokers to establish a Connection as soon as possible", ex);
@ -913,8 +913,8 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe
* @see #recoverAfterListenerSetupFailure()
*/
protected void handleListenerSetupFailure(Throwable ex, boolean alreadyRecovered) {
if (ex instanceof JMSException) {
invokeExceptionListener((JMSException) ex);
if (ex instanceof JMSException jmsException) {
invokeExceptionListener(jmsException);
}
if (ex instanceof SharedConnectionNotInitializedException) {
if (!alreadyRecovered) {
@ -930,7 +930,8 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe
StringBuilder msg = new StringBuilder();
msg.append("Setup of JMS message listener invoker failed for destination '");
msg.append(getDestinationDescription()).append("' - trying to recover. Cause: ");
msg.append(ex instanceof JMSException ? JmsUtils.buildExceptionMessage((JMSException) ex) : ex.getMessage());
msg.append(ex instanceof JMSException jmsException ? JmsUtils.buildExceptionMessage(jmsException) :
ex.getMessage());
if (logger.isDebugEnabled()) {
logger.warn(msg, ex);
}
@ -990,14 +991,15 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe
break;
}
catch (Exception ex) {
if (ex instanceof JMSException) {
invokeExceptionListener((JMSException) ex);
if (ex instanceof JMSException jmsException) {
invokeExceptionListener(jmsException);
}
StringBuilder msg = new StringBuilder();
msg.append("Could not refresh JMS Connection for destination '");
msg.append(getDestinationDescription()).append("' - retrying using ");
msg.append(execution).append(". Cause: ");
msg.append(ex instanceof JMSException ? JmsUtils.buildExceptionMessage((JMSException) ex) : ex.getMessage());
msg.append(ex instanceof JMSException jmsException ? JmsUtils.buildExceptionMessage(jmsException) :
ex.getMessage());
if (logger.isDebugEnabled()) {
logger.error(msg, ex);
}
@ -1026,8 +1028,8 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe
String destName = getDestinationName();
if (destName != null) {
DestinationResolver destResolver = getDestinationResolver();
if (destResolver instanceof CachingDestinationResolver) {
((CachingDestinationResolver) destResolver).removeFromCache(destName);
if (destResolver instanceof CachingDestinationResolver cachingResolver) {
cachingResolver.removeFromCache(destName);
}
}
}

View File

@ -180,8 +180,8 @@ public class JmsMessageEndpointManager extends GenericMessageEndpointManager
@Override
public void setupMessageListener(Object messageListener) {
if (messageListener instanceof MessageListener) {
setMessageListener((MessageListener) messageListener);
if (messageListener instanceof MessageListener msgListener) {
setMessageListener(msgListener);
}
else {
throw new IllegalArgumentException("Unsupported message listener '" +
@ -203,8 +203,8 @@ public class JmsMessageEndpointManager extends GenericMessageEndpointManager
@Override
@Nullable
public DestinationResolver getDestinationResolver() {
if (this.activationSpecFactory instanceof StandardJmsActivationSpecFactory) {
return ((StandardJmsActivationSpecFactory) this.activationSpecFactory).getDestinationResolver();
if (this.activationSpecFactory instanceof StandardJmsActivationSpecFactory standardFactory) {
return standardFactory.getDestinationResolver();
}
return null;
}

View File

@ -269,41 +269,41 @@ public abstract class JmsUtils {
public static JmsException convertJmsAccessException(JMSException ex) {
Assert.notNull(ex, "JMSException must not be null");
if (ex instanceof jakarta.jms.IllegalStateException) {
return new org.springframework.jms.IllegalStateException((jakarta.jms.IllegalStateException) ex);
if (ex instanceof jakarta.jms.IllegalStateException jakartaISE) {
return new org.springframework.jms.IllegalStateException(jakartaISE);
}
if (ex instanceof jakarta.jms.InvalidClientIDException) {
return new InvalidClientIDException((jakarta.jms.InvalidClientIDException) ex);
if (ex instanceof jakarta.jms.InvalidClientIDException jakartaICIDE) {
return new InvalidClientIDException(jakartaICIDE);
}
if (ex instanceof jakarta.jms.InvalidDestinationException) {
return new InvalidDestinationException((jakarta.jms.InvalidDestinationException) ex);
if (ex instanceof jakarta.jms.InvalidDestinationException jakartaIDE) {
return new InvalidDestinationException(jakartaIDE);
}
if (ex instanceof jakarta.jms.InvalidSelectorException) {
return new InvalidSelectorException((jakarta.jms.InvalidSelectorException) ex);
if (ex instanceof jakarta.jms.InvalidSelectorException jakartaISE) {
return new InvalidSelectorException(jakartaISE);
}
if (ex instanceof jakarta.jms.JMSSecurityException) {
return new JmsSecurityException((jakarta.jms.JMSSecurityException) ex);
if (ex instanceof jakarta.jms.JMSSecurityException jakartaJMSSE) {
return new JmsSecurityException(jakartaJMSSE);
}
if (ex instanceof jakarta.jms.MessageEOFException) {
return new MessageEOFException((jakarta.jms.MessageEOFException) ex);
if (ex instanceof jakarta.jms.MessageEOFException jakartaMEOFE) {
return new MessageEOFException(jakartaMEOFE);
}
if (ex instanceof jakarta.jms.MessageFormatException) {
return new MessageFormatException((jakarta.jms.MessageFormatException) ex);
if (ex instanceof jakarta.jms.MessageFormatException jakartaMFE) {
return new MessageFormatException(jakartaMFE);
}
if (ex instanceof jakarta.jms.MessageNotReadableException) {
return new MessageNotReadableException((jakarta.jms.MessageNotReadableException) ex);
if (ex instanceof jakarta.jms.MessageNotReadableException jakartaMNRE) {
return new MessageNotReadableException(jakartaMNRE);
}
if (ex instanceof jakarta.jms.MessageNotWriteableException) {
return new MessageNotWriteableException((jakarta.jms.MessageNotWriteableException) ex);
if (ex instanceof jakarta.jms.MessageNotWriteableException jakartaMNWE) {
return new MessageNotWriteableException(jakartaMNWE);
}
if (ex instanceof jakarta.jms.ResourceAllocationException) {
return new ResourceAllocationException((jakarta.jms.ResourceAllocationException) ex);
if (ex instanceof jakarta.jms.ResourceAllocationException jakartaRAE) {
return new ResourceAllocationException(jakartaRAE);
}
if (ex instanceof jakarta.jms.TransactionInProgressException) {
return new TransactionInProgressException((jakarta.jms.TransactionInProgressException) ex);
if (ex instanceof jakarta.jms.TransactionInProgressException jakartaTIPE) {
return new TransactionInProgressException(jakartaTIPE);
}
if (ex instanceof jakarta.jms.TransactionRolledBackException) {
return new TransactionRolledBackException((jakarta.jms.TransactionRolledBackException) ex);
if (ex instanceof jakarta.jms.TransactionRolledBackException jakartaTRBE) {
return new TransactionRolledBackException(jakartaTRBE);
}
// fallback

View File

@ -65,9 +65,9 @@ public class SimpleJmsHeaderMapper extends AbstractHeaderMapper<Message> impleme
if (jmsCorrelationId instanceof Number) {
jmsCorrelationId = jmsCorrelationId.toString();
}
if (jmsCorrelationId instanceof String) {
if (jmsCorrelationId instanceof String correlationId) {
try {
jmsMessage.setJMSCorrelationID((String) jmsCorrelationId);
jmsMessage.setJMSCorrelationID(correlationId);
}
catch (Exception ex) {
logger.debug("Failed to set JMSCorrelationID - skipping", ex);

View File

@ -348,11 +348,11 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B
* Convenience method to dispatch to converters for individual message types.
*/
private Object convertToObject(Message message, JavaType targetJavaType) throws JMSException, IOException {
if (message instanceof TextMessage) {
return convertFromTextMessage((TextMessage) message, targetJavaType);
if (message instanceof TextMessage textMessage) {
return convertFromTextMessage(textMessage, targetJavaType);
}
else if (message instanceof BytesMessage) {
return convertFromBytesMessage((BytesMessage) message, targetJavaType);
else if (message instanceof BytesMessage bytesMessage) {
return convertFromBytesMessage(bytesMessage, targetJavaType);
}
else {
return convertFromMessage(message, targetJavaType);
@ -474,11 +474,11 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B
}
return extractViewClass(annotation, conversionHint);
}
else if (conversionHint instanceof JsonView) {
return extractViewClass((JsonView) conversionHint, conversionHint);
else if (conversionHint instanceof JsonView jsonView) {
return extractViewClass(jsonView, conversionHint);
}
else if (conversionHint instanceof Class) {
return (Class<?>) conversionHint;
else if (conversionHint instanceof Class<?> clazz) {
return clazz;
}
else {
return null;

View File

@ -81,7 +81,7 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
*/
public MarshallingMessageConverter(Marshaller marshaller) {
Assert.notNull(marshaller, "Marshaller must not be null");
if (!(marshaller instanceof Unmarshaller)) {
if (!(marshaller instanceof Unmarshaller _unmarshaller)) {
throw new IllegalArgumentException(
"Marshaller [" + marshaller + "] does not implement the Unmarshaller " +
"interface. Please set an Unmarshaller explicitly by using the " +
@ -89,7 +89,7 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
}
else {
this.marshaller = marshaller;
this.unmarshaller = (Unmarshaller) marshaller;
this.unmarshaller = _unmarshaller;
}
}

View File

@ -42,6 +42,7 @@ import org.springframework.util.ObjectUtils;
* a Serializable object to a {@link jakarta.jms.ObjectMessage} (or vice versa).
*
* @author Juergen Hoeller
* @author Sam Brannen
* @since 1.1
* @see org.springframework.jms.core.JmsTemplate#convertAndSend
* @see org.springframework.jms.core.JmsTemplate#receiveAndConvert
@ -59,20 +60,20 @@ public class SimpleMessageConverter implements MessageConverter {
*/
@Override
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
if (object instanceof Message) {
return (Message) object;
if (object instanceof Message message) {
return message;
}
else if (object instanceof String) {
return createMessageForString((String) object, session);
else if (object instanceof String text) {
return createMessageForString(text, session);
}
else if (object instanceof byte[]) {
return createMessageForByteArray((byte[]) object, session);
else if (object instanceof byte[] bytes) {
return createMessageForByteArray(bytes, session);
}
else if (object instanceof Map) {
return createMessageForMap((Map<? ,?>) object, session);
else if (object instanceof Map<?, ?> map) {
return createMessageForMap(map, session);
}
else if (object instanceof Serializable) {
return createMessageForSerializable(((Serializable) object), session);
else if (object instanceof Serializable serializable) {
return createMessageForSerializable(serializable, session);
}
else {
throw new MessageConversionException("Cannot convert object of type [" +
@ -93,17 +94,17 @@ public class SimpleMessageConverter implements MessageConverter {
*/
@Override
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
if (message instanceof TextMessage) {
return extractStringFromMessage((TextMessage) message);
if (message instanceof TextMessage textMessage) {
return extractStringFromMessage(textMessage);
}
else if (message instanceof BytesMessage) {
return extractByteArrayFromMessage((BytesMessage) message);
else if (message instanceof BytesMessage bytesMessage) {
return extractByteArrayFromMessage(bytesMessage);
}
else if (message instanceof MapMessage) {
return extractMapFromMessage((MapMessage) message);
else if (message instanceof MapMessage mapMessage) {
return extractMapFromMessage(mapMessage);
}
else if (message instanceof ObjectMessage) {
return extractSerializableFromMessage((ObjectMessage) message);
else if (message instanceof ObjectMessage objectMessage) {
return extractSerializableFromMessage(objectMessage);
}
else {
return message;
@ -149,11 +150,11 @@ public class SimpleMessageConverter implements MessageConverter {
MapMessage message = session.createMapMessage();
for (Map.Entry<?, ?> entry : map.entrySet()) {
Object key = entry.getKey();
if (!(key instanceof String)) {
if (!(key instanceof String str)) {
throw new MessageConversionException("Cannot convert non-String key of type [" +
ObjectUtils.nullSafeClassName(key) + "] to JMS MapMessage entry");
}
message.setObject((String) key, entry.getValue());
message.setObject(str, entry.getValue());
}
return message;
}

View File

@ -31,6 +31,7 @@ import org.springframework.util.Assert;
* @author Arjen Poutsma
* @author Mark Fisher
* @author Rossen Stoyanchev
* @author Sam Brannen
* @since 4.0
* @param <T> the message payload type
* @see GenericMessage
@ -153,14 +154,14 @@ public final class MessageBuilder<T> {
return this.providedMessage;
}
MessageHeaders headersToUse = this.headerAccessor.toMessageHeaders();
if (this.payload instanceof Throwable) {
if (this.providedMessage != null && this.providedMessage instanceof ErrorMessage) {
Message<?> message = ((ErrorMessage) this.providedMessage).getOriginalMessage();
if (this.payload instanceof Throwable throwable) {
if (this.providedMessage != null && this.providedMessage instanceof ErrorMessage errorMessage) {
Message<?> message = errorMessage.getOriginalMessage();
if (message != null) {
return (Message<T>) new ErrorMessage((Throwable) this.payload, headersToUse, message);
return (Message<T>) new ErrorMessage(throwable, headersToUse, message);
}
}
return (Message<T>) new ErrorMessage((Throwable) this.payload, headersToUse);
return (Message<T>) new ErrorMessage(throwable, headersToUse);
}
else {
return new GenericMessage<>(this.payload, headersToUse);
@ -203,8 +204,8 @@ public final class MessageBuilder<T> {
public static <T> Message<T> createMessage(@Nullable T payload, MessageHeaders messageHeaders) {
Assert.notNull(payload, "Payload must not be null");
Assert.notNull(messageHeaders, "MessageHeaders must not be null");
if (payload instanceof Throwable) {
return (Message<T>) new ErrorMessage((Throwable) payload, messageHeaders);
if (payload instanceof Throwable throwable) {
return (Message<T>) new ErrorMessage(throwable, messageHeaders);
}
else {
return new GenericMessage<>(payload, messageHeaders);