Skip to content

Commit 33da2a6

Browse files
ngocnhan-tran1996artembilan
authored andcommitted
Improve conditions in code
* Reduce `else` condition and modernize switch pattern * Check condition after calling lock method * Some additional code clean up
1 parent f330752 commit 33da2a6

16 files changed

+162
-193
lines changed

spring-rabbit-stream/src/main/java/org/springframework/rabbit/stream/producer/RabbitStreamTemplate.java

Lines changed: 41 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2021-2023 the original author or authors.
2+
* Copyright 2021-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -55,6 +55,7 @@
5555
*
5656
* @author Gary Russell
5757
* @author Christian Tzolov
58+
* @author Ngoc Nhan
5859
* @since 2.4
5960
*
6061
*/
@@ -107,29 +108,31 @@ public RabbitStreamTemplate(Environment environment, String streamName) {
107108

108109

109110
private Producer createOrGetProducer() {
110-
this.lock.lock();
111-
try {
112-
if (this.producer == null) {
113-
ProducerBuilder builder = this.environment.producerBuilder();
114-
if (this.superStreamRouting == null) {
115-
builder.stream(this.streamName);
116-
}
117-
else {
118-
builder.superStream(this.streamName)
119-
.routing(this.superStreamRouting);
120-
}
121-
this.producerCustomizer.accept(this.beanName, builder);
122-
this.producer = builder.build();
123-
if (!this.streamConverterSet) {
124-
((DefaultStreamMessageConverter) this.streamConverter).setBuilderSupplier(
125-
() -> this.producer.messageBuilder());
111+
if (this.producer == null) {
112+
this.lock.lock();
113+
try {
114+
if (this.producer == null) {
115+
ProducerBuilder builder = this.environment.producerBuilder();
116+
if (this.superStreamRouting == null) {
117+
builder.stream(this.streamName);
118+
}
119+
else {
120+
builder.superStream(this.streamName)
121+
.routing(this.superStreamRouting);
122+
}
123+
this.producerCustomizer.accept(this.beanName, builder);
124+
this.producer = builder.build();
125+
if (!this.streamConverterSet) {
126+
((DefaultStreamMessageConverter) this.streamConverter).setBuilderSupplier(
127+
() -> this.producer.messageBuilder());
128+
}
126129
}
127130
}
128-
return this.producer;
129-
}
130-
finally {
131-
this.lock.unlock();
131+
finally {
132+
this.lock.unlock();
133+
}
132134
}
135+
return this.producer;
133136
}
134137

135138
@Override
@@ -305,24 +308,13 @@ private ConfirmationHandler handleConfirm(CompletableFuture<Boolean> future, Obs
305308
}
306309
else {
307310
int code = confStatus.getCode();
308-
String errorMessage;
309-
switch (code) {
310-
case Constants.CODE_MESSAGE_ENQUEUEING_FAILED:
311-
errorMessage = "Message Enqueueing Failed";
312-
break;
313-
case Constants.CODE_PRODUCER_CLOSED:
314-
errorMessage = "Producer Closed";
315-
break;
316-
case Constants.CODE_PRODUCER_NOT_AVAILABLE:
317-
errorMessage = "Producer Not Available";
318-
break;
319-
case Constants.CODE_PUBLISH_CONFIRM_TIMEOUT:
320-
errorMessage = "Publish Confirm Timeout";
321-
break;
322-
default:
323-
errorMessage = "Unknown code: " + code;
324-
break;
325-
}
311+
String errorMessage = switch (code) {
312+
case Constants.CODE_MESSAGE_ENQUEUEING_FAILED -> "Message Enqueueing Failed";
313+
case Constants.CODE_PRODUCER_CLOSED -> "Producer Closed";
314+
case Constants.CODE_PRODUCER_NOT_AVAILABLE -> "Producer Not Available";
315+
case Constants.CODE_PUBLISH_CONFIRM_TIMEOUT -> "Publish Confirm Timeout";
316+
default -> "Unknown code: " + code;
317+
};
326318
StreamSendException ex = new StreamSendException(errorMessage, code);
327319
observation.error(ex);
328320
observation.stop();
@@ -339,15 +331,17 @@ private ConfirmationHandler handleConfirm(CompletableFuture<Boolean> future, Obs
339331
*/
340332
@Override
341333
public void close() {
342-
this.lock.lock();
343-
try {
344-
if (this.producer != null) {
345-
this.producer.close();
346-
this.producer = null;
334+
if (this.producer != null) {
335+
this.lock.lock();
336+
try {
337+
if (this.producer != null) {
338+
this.producer.close();
339+
this.producer = null;
340+
}
341+
}
342+
finally {
343+
this.lock.unlock();
347344
}
348-
}
349-
finally {
350-
this.lock.unlock();
351345
}
352346
}
353347

spring-rabbit/src/main/java/org/springframework/amqp/rabbit/annotation/RabbitListenerAnnotationBeanPostProcessor.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@
7676
import org.springframework.context.expression.StandardBeanExpressionResolver;
7777
import org.springframework.core.Ordered;
7878
import org.springframework.core.annotation.AnnotationUtils;
79+
import org.springframework.core.annotation.MergedAnnotation;
7980
import org.springframework.core.annotation.MergedAnnotations;
8081
import org.springframework.core.annotation.MergedAnnotations.SearchStrategy;
8182
import org.springframework.core.convert.ConversionService;
@@ -357,7 +358,7 @@ else if (source instanceof Method method) {
357358
}
358359
return !name.contains("$MockitoMock$");
359360
})
360-
.map(ann -> ann.synthesize())
361+
.map(MergedAnnotation::synthesize)
361362
.collect(Collectors.toList());
362363
}
363364

@@ -893,7 +894,7 @@ private void addToMap(Map<String, Object> map, String key, Object value, Class<?
893894
}
894895
}
895896
else {
896-
if (value instanceof String && !StringUtils.hasText((String) value)) {
897+
if (value instanceof String string && !StringUtils.hasText(string)) {
897898
putEmpty(map, key);
898899
}
899900
else {

spring-rabbit/src/main/java/org/springframework/amqp/rabbit/batch/SimpleBatchingStrategy.java

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -107,13 +107,12 @@ public Date nextRelease() {
107107
if (this.messages.isEmpty() || this.timeout <= 0) {
108108
return null;
109109
}
110-
else if (this.currentSize >= this.bufferLimit) {
110+
if (this.currentSize >= this.bufferLimit) {
111111
// release immediately, we're already over the limit
112112
return new Date();
113113
}
114-
else {
115-
return new Date(System.currentTimeMillis() + this.timeout);
116-
}
114+
115+
return new Date(System.currentTimeMillis() + this.timeout);
117116
}
118117

119118
@Override
@@ -122,9 +121,8 @@ public Collection<MessageBatch> releaseBatches() {
122121
if (batch == null) {
123122
return Collections.emptyList();
124123
}
125-
else {
126-
return Collections.singletonList(batch);
127-
}
124+
125+
return Collections.singletonList(batch);
128126
}
129127

130128
private MessageBatch doReleaseBatch() {

spring-rabbit/src/main/java/org/springframework/amqp/rabbit/config/ListenerContainerFactoryBean.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -575,14 +575,13 @@ private AbstractMessageListenerContainer createContainer() {
575575
.acceptIfNotNull(this.retryDeclarationInterval, container::setRetryDeclarationInterval);
576576
return container;
577577
}
578-
else {
579-
DirectMessageListenerContainer container = new DirectMessageListenerContainer(this.connectionFactory);
580-
JavaUtils.INSTANCE
581-
.acceptIfNotNull(this.consumersPerQueue, container::setConsumersPerQueue)
582-
.acceptIfNotNull(this.taskScheduler, container::setTaskScheduler)
583-
.acceptIfNotNull(this.monitorInterval, container::setMonitorInterval);
584-
return container;
585-
}
578+
579+
DirectMessageListenerContainer container = new DirectMessageListenerContainer(this.connectionFactory);
580+
JavaUtils.INSTANCE
581+
.acceptIfNotNull(this.consumersPerQueue, container::setConsumersPerQueue)
582+
.acceptIfNotNull(this.taskScheduler, container::setTaskScheduler)
583+
.acceptIfNotNull(this.monitorInterval, container::setMonitorInterval);
584+
return container;
586585
}
587586

588587
@Override

spring-rabbit/src/main/java/org/springframework/amqp/rabbit/config/ListenerContainerParser.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,8 @@ public BeanDefinition parse(Element element, ParserContext parserContext) {
101101
}
102102

103103
List<Element> childElements = DomUtils.getChildElementsByTagName(element, LISTENER_ELEMENT);
104-
for (int i = 0; i < childElements.size(); i++) {
105-
parseListener(childElements.get(i), element, parserContext, containerList);
104+
for (Element childElement : childElements) {
105+
parseListener(childElement, element, parserContext, containerList);
106106
}
107107

108108
parserContext.popAndRegisterContainingComponent();
@@ -190,8 +190,8 @@ private void parseListener(Element listenerEle, Element containerEle, ParserCont
190190
else {
191191
String[] names = StringUtils.commaDelimitedListToStringArray(queues);
192192
List<RuntimeBeanReference> values = new ManagedList<>();
193-
for (int i = 0; i < names.length; i++) {
194-
values.add(new RuntimeBeanReference(names[i].trim()));
193+
for (String name : names) {
194+
values.add(new RuntimeBeanReference(name.trim()));
195195
}
196196
containerDef.getPropertyValues().add("queues", values);
197197
}

spring-rabbit/src/main/java/org/springframework/amqp/rabbit/config/StatefulRetryOperationsInterceptorFactoryBean.java

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2022 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -27,12 +27,14 @@
2727
import org.springframework.amqp.rabbit.retry.MessageKeyGenerator;
2828
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
2929
import org.springframework.amqp.rabbit.retry.NewMessageIdentifier;
30+
import org.springframework.lang.Nullable;
3031
import org.springframework.retry.RetryOperations;
3132
import org.springframework.retry.interceptor.MethodArgumentsKeyGenerator;
3233
import org.springframework.retry.interceptor.MethodInvocationRecoverer;
3334
import org.springframework.retry.interceptor.NewMethodArgumentsIdentifier;
3435
import org.springframework.retry.interceptor.StatefulRetryOperationsInterceptor;
3536
import org.springframework.retry.support.RetryTemplate;
37+
import org.springframework.util.Assert;
3638

3739
/**
3840
* Convenient factory bean for creating a stateful retry interceptor for use in a message listener container, giving you
@@ -47,6 +49,7 @@
4749
*
4850
* @author Dave Syer
4951
* @author Gary Russell
52+
* @author Ngoc Nhan
5053
*
5154
* @see RetryOperations#execute(org.springframework.retry.RetryCallback, org.springframework.retry.RecoveryCallback,
5255
* org.springframework.retry.RetryState)
@@ -90,9 +93,8 @@ private NewMethodArgumentsIdentifier createNewItemIdentifier() {
9093
if (StatefulRetryOperationsInterceptorFactoryBean.this.newMessageIdentifier == null) {
9194
return !message.getMessageProperties().isRedelivered();
9295
}
93-
else {
94-
return StatefulRetryOperationsInterceptorFactoryBean.this.newMessageIdentifier.isNew(message);
95-
}
96+
97+
return StatefulRetryOperationsInterceptorFactoryBean.this.newMessageIdentifier.isNew(message);
9698
};
9799
}
98100

@@ -120,40 +122,33 @@ else if (arg instanceof List && messageRecoverer instanceof MessageBatchRecovere
120122
private MethodArgumentsKeyGenerator createKeyGenerator() {
121123
return args -> {
122124
Message message = argToMessage(args);
125+
Assert.notNull(message, "The 'args' must not convert to null");
123126
if (StatefulRetryOperationsInterceptorFactoryBean.this.messageKeyGenerator == null) {
124127
String messageId = message.getMessageProperties().getMessageId();
125128
if (messageId == null && message.getMessageProperties().isRedelivered()) {
126129
message.getMessageProperties().setFinalRetryForMessageWithNoId(true);
127130
}
128131
return messageId;
129132
}
130-
else {
131-
return StatefulRetryOperationsInterceptorFactoryBean.this.messageKeyGenerator.getKey(message);
132-
}
133+
return StatefulRetryOperationsInterceptorFactoryBean.this.messageKeyGenerator.getKey(message);
133134
};
134135
}
135136

136-
@SuppressWarnings("unchecked")
137+
@Nullable
137138
private Message argToMessage(Object[] args) {
138139
Object arg = args[1];
139-
Message message = null;
140140
if (arg instanceof Message msg) {
141-
message = msg;
141+
return msg;
142142
}
143-
else if (arg instanceof List) {
144-
message = ((List<Message>) arg).get(0);
143+
if (arg instanceof List<?> list) {
144+
return (Message) list.get(0);
145145
}
146-
return message;
146+
return null;
147147
}
148148

149149
@Override
150150
public Class<?> getObjectType() {
151151
return StatefulRetryOperationsInterceptor.class;
152152
}
153153

154-
@Override
155-
public boolean isSingleton() {
156-
return true;
157-
}
158-
159154
}

spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/AbstractRoutingConnectionFactory.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ public void setTargetConnectionFactories(Map<Object, ConnectionFactory> targetCo
6969
Assert.noNullElements(targetConnectionFactories.values().toArray(),
7070
"'targetConnectionFactories' cannot have null values.");
7171
this.targetConnectionFactories.putAll(targetConnectionFactories);
72-
targetConnectionFactories.values().stream().forEach(cf -> checkConfirmsAndReturns(cf));
72+
targetConnectionFactories.values().forEach(this::checkConfirmsAndReturns);
7373
}
7474

7575
/**
@@ -293,7 +293,7 @@ public void destroy() {
293293

294294
@Override
295295
public void resetConnection() {
296-
this.targetConnectionFactories.values().forEach(factory -> factory.resetConnection());
296+
this.targetConnectionFactories.values().forEach(ConnectionFactory::resetConnection);
297297
this.defaultTargetConnectionFactory.resetConnection();
298298
}
299299

spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/ConsumerChannelRegistry.java

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -84,11 +84,9 @@ public static void unRegisterConsumerChannel() {
8484
@Nullable
8585
public static Channel getConsumerChannel() {
8686
ChannelHolder channelHolder = consumerChannel.get();
87-
Channel channel = null;
88-
if (channelHolder != null) {
89-
channel = channelHolder.getChannel();
90-
}
91-
return channel;
87+
return channelHolder != null
88+
? channelHolder.getChannel()
89+
: null;
9290
}
9391

9492
/**

spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/PendingConfirm.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2020 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -27,6 +27,7 @@
2727
* expired. It also holds {@link CorrelationData} for
2828
* the client to correlate a confirm with a sent message.
2929
* @author Gary Russell
30+
* @author Ngoc Nhan
3031
* @since 1.0.1
3132
*
3233
*/
@@ -115,7 +116,7 @@ public void setReturned(boolean isReturned) {
115116
* @since 2.2.10
116117
*/
117118
public boolean waitForReturnIfNeeded() throws InterruptedException {
118-
return this.returned ? this.latch.await(RETURN_CALLBACK_TIMEOUT, TimeUnit.SECONDS) : true;
119+
return !this.returned || this.latch.await(RETURN_CALLBACK_TIMEOUT, TimeUnit.SECONDS);
119120
}
120121

121122
/**

0 commit comments

Comments
 (0)