Fix RabbitAmqpUtils.toAmqpMessage() util for to prop

The `messageProperties.getReplyTo()` might be null, so set it into `amqpMessage::to`
only if it is not null

* Add convenient `JavaUtils.acceptOrElseIfNotNull()` for two alternative values
This commit is contained in:
Artem Bilan
2025-03-10 11:17:07 -04:00
parent b6b61c4cfe
commit 6b2ad0dc73
2 changed files with 24 additions and 6 deletions

View File

@@ -136,4 +136,24 @@ public final class JavaUtils {
return this;
}
/**
* Invoke {@link Consumer#accept(Object)} with the value or alternative if one of them is not null.
* @param value the value.
* @param alternative the other value if the {@code value} argument is null.
* @param consumer the consumer.
* @param <T> the value type.
* @return this.
* @since 4.0
*/
public <T> JavaUtils acceptOrElseIfNotNull(@Nullable T value, @Nullable T alternative, Consumer<T> consumer) {
if (value != null) {
consumer.accept(value);
}
else if (alternative != null) {
consumer.accept(alternative);
}
return this;
}
}

View File

@@ -19,7 +19,6 @@ package org.springframework.amqp.rabbitmq.client;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import com.rabbitmq.client.amqp.Consumer;
@@ -88,11 +87,7 @@ public final class RabbitAmqpUtils {
.contentEncoding(messageProperties.getContentEncoding())
.contentType(messageProperties.getContentType())
.messageId(messageProperties.getMessageId())
.correlationId(
Objects.requireNonNullElse(
messageProperties.getCorrelationId(), messageProperties.getMessageId()))
.priority(messageProperties.getPriority().byteValue())
.to(messageProperties.getReplyTo());
.priority(messageProperties.getPriority().byteValue());
Map<String, @Nullable Object> headers = messageProperties.getHeaders();
if (!headers.isEmpty()) {
@@ -100,8 +95,11 @@ public final class RabbitAmqpUtils {
}
JavaUtils.INSTANCE
.acceptOrElseIfNotNull(messageProperties.getCorrelationId(),
messageProperties.getMessageId(), amqpMessage::correlationId)
.acceptIfNotNull(messageProperties.getUserId(),
(userId) -> amqpMessage.userId(userId.getBytes(StandardCharsets.UTF_8)))
.acceptIfNotNull(messageProperties.getReplyTo(), amqpMessage::to)
.acceptIfNotNull(messageProperties.getTimestamp(),
(timestamp) -> amqpMessage.creationTime(timestamp.getTime()))
.acceptIfNotNull(messageProperties.getExpiration(),