From 1af6bd6b149faa4f8b9e55de32baa8149e72ff08 Mon Sep 17 00:00:00 2001 From: Jacob Li Date: Wed, 1 Mar 2023 20:17:42 -0800 Subject: [PATCH] Upgrade to SpringBoot3.0 --- README.md | 2 +- pom.xml | 55 +- .../AmazonSQSMessagingClientWrapper.java | 94 +- .../sqs/javamessaging/PrefetchManager.java | 6 +- .../javamessaging/ProviderConfiguration.java | 6 +- .../sqs/javamessaging/SQSConnection.java | 81 +- .../javamessaging/SQSConnectionFactory.java | 81 +- .../javamessaging/SQSConnectionMetaData.java | 26 +- .../sqs/javamessaging/SQSMessageConsumer.java | 20 +- .../SQSMessageConsumerPrefetch.java | 58 +- .../sqs/javamessaging/SQSMessageProducer.java | 86 +- .../SQSMessagingClientConstants.java | 5 +- .../javamessaging/SQSQueueDestination.java | 13 +- .../amazon/sqs/javamessaging/SQSSession.java | 125 +- .../SQSSessionCallbackScheduler.java | 50 +- .../acknowledge/AcknowledgeMode.java | 22 +- .../acknowledge/Acknowledger.java | 18 +- .../acknowledge/AutoAcknowledger.java | 4 +- .../acknowledge/BulkSQSOperation.java | 17 +- .../acknowledge/NegativeAcknowledger.java | 16 +- .../acknowledge/RangedAcknowledger.java | 14 +- .../acknowledge/SQSMessageIdentifier.java | 15 +- .../acknowledge/UnorderedAcknowledger.java | 6 +- .../message/SQSBytesMessage.java | 25 +- .../sqs/javamessaging/message/SQSMessage.java | 240 ++-- .../message/SQSObjectMessage.java | 6 +- .../javamessaging/message/SQSTextMessage.java | 5 +- .../util/ExponentialBackoffStrategy.java | 8 +- .../util/SQSMessagingClientThreadFactory.java | 2 +- .../util/SQSMessagingClientUtil.java | 2 +- .../sqs/javamessaging/AcknowledgerCommon.java | 15 +- .../AmazonSQSMessagingClientWrapperTest.java | 408 +++---- .../javamessaging/AutoAcknowledgerTest.java | 44 +- .../javamessaging/BulkSQSOperationTest.java | 51 +- .../ExponentialBackoffStrategyTest.java | 25 +- ...essageListenerConcurrentOperationTest.java | 90 +- .../ModifyWaitTimeSecondsTest.java | 1 - .../NegativeAcknowledgerTest.java | 64 +- .../javamessaging/RangedAcknowledgerTest.java | 27 +- .../SQSConnectionFactoryTest.java | 12 +- .../sqs/javamessaging/SQSConnectionTest.java | 601 ++++------ .../SQSMessageConsumerPrefetchFifoTest.java | 361 +++--- .../SQSMessageConsumerPrefetchTest.java | 1045 ++++++++--------- .../javamessaging/SQSMessageConsumerTest.java | 110 +- .../SQSMessageProducerFifoTest.java | 101 +- .../javamessaging/SQSMessageProducerTest.java | 260 ++-- .../SQSMessagingClientUtilTest.java | 6 +- .../SQSQueueDestinationTest.java | 10 +- .../SQSSessionCallbackSchedulerTest.java | 310 ++--- .../sqs/javamessaging/SQSSessionTest.java | 630 ++++------ .../UnorderedAcknowledgerTest.java | 29 +- .../message/SQSBytesMessageTest.java | 342 ++---- .../javamessaging/message/SQSMessageTest.java | 388 +++--- .../message/SQSObjectMessageTest.java | 62 +- .../message/SQSTextMessageTest.java | 11 +- 55 files changed, 2439 insertions(+), 3672 deletions(-) diff --git a/README.md b/README.md index a033fb3..04cf6dd 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ for communicating with Amazon Simple Queue Service. This project builds on top o com.amazonaws amazon-sqs-java-messaging-lib - 1.1.3 + 1.2.0 jar ``` diff --git a/pom.xml b/pom.xml index e762846..6f8d172 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.amazonaws amazon-sqs-java-messaging-lib - 1.1.3 + 1.2.0 Amazon SQS Java Messaging Library The Amazon SQS Java Messaging Library holds the Java Message Service compatible classes, that are used for communicating with Amazon Simple Queue Service. @@ -29,7 +29,7 @@ - 1.12.360 + 1.12.415 UTF-8 @@ -40,14 +40,14 @@ ${aws-java-sdk.version} - org.apache.geronimo.specs - geronimo-jms_1.1_spec - 1.1.1 + jakarta.jms + jakarta.jms-api + 3.1.0 org.junit.jupiter - junit-jupiter-engine - 5.9.1 + junit-jupiter + 5.9.2 test @@ -59,9 +59,14 @@ org.mockito mockito-core - 1.10.8 + 5.1.1 test + + org.projectlombok + lombok + 1.18.24 + @@ -72,15 +77,22 @@ maven-compiler-plugin 3.10.1 - 1.7 - 1.7 + 1.8 + 1.8 UTF-8 + + + org.projectlombok + lombok + 1.18.24 + + org.apache.maven.plugins maven-failsafe-plugin - 3.0.0-M1 + 3.0.0-M7 @@ -90,6 +102,11 @@ + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M7 + @@ -109,7 +126,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.9.1 + 3.4.1 attach-javadocs @@ -117,11 +134,7 @@ jar - - -Xdoclint:none + none @@ -137,6 +150,14 @@ true + + org.apache.maven.plugins + maven-compiler-plugin + + 16 + 16 + + diff --git a/src/main/java/com/amazon/sqs/javamessaging/AmazonSQSMessagingClientWrapper.java b/src/main/java/com/amazon/sqs/javamessaging/AmazonSQSMessagingClientWrapper.java index 0423c92..0c4cdfa 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/AmazonSQSMessagingClientWrapper.java +++ b/src/main/java/com/amazon/sqs/javamessaging/AmazonSQSMessagingClientWrapper.java @@ -14,12 +14,11 @@ */ package com.amazon.sqs.javamessaging; -import java.util.HashSet; import java.util.Set; -import javax.jms.InvalidDestinationException; -import javax.jms.JMSException; -import javax.jms.JMSSecurityException; +import jakarta.jms.InvalidDestinationException; +import jakarta.jms.JMSException; +import jakarta.jms.JMSSecurityException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -53,20 +52,14 @@ */ public class AmazonSQSMessagingClientWrapper { private static final Log LOG = LogFactory.getLog(AmazonSQSMessagingClientWrapper.class); - - private static final Set SECURITY_EXCEPTION_ERROR_CODES; - static { - /** - * List of exceptions that can classified as security. These exceptions - * are not thrown during connection-set-up rather after the service - * calls of the AmazonSQSClient. - */ - SECURITY_EXCEPTION_ERROR_CODES = new HashSet(); - SECURITY_EXCEPTION_ERROR_CODES.add("MissingClientTokenId"); - SECURITY_EXCEPTION_ERROR_CODES.add("InvalidClientTokenId"); - SECURITY_EXCEPTION_ERROR_CODES.add("MissingAuthenticationToken"); - SECURITY_EXCEPTION_ERROR_CODES.add("AccessDenied"); - } + + /** + * List of exceptions that can classified as security. These exceptions + * are not thrown during connection-set-up rather after the service + * calls of the AmazonSQSClient. + */ + private static final Set SECURITY_EXCEPTION_ERROR_CODES = Set.of( + "MissingClientTokenId", "InvalidClientTokenId", "MissingAuthenticationToken", "AccessDenied"); private final AmazonSQS amazonSQSClient; private final AWSCredentialsProvider credentialsProvider; @@ -112,7 +105,7 @@ public AmazonSQS getAmazonSQSClient() { * @param endpoint * The endpoint (ex: "sqs.us-east-1.amazonaws.com") of the region * specific AWS endpoint this client will communicate with. - * @throws JMSException + * @throws JMSException jmsException */ @Deprecated public void setEndpoint(String endpoint) throws JMSException { @@ -127,12 +120,12 @@ public void setEndpoint(String endpoint) throws JMSException { /** * Sets SQS region and wraps IllegalArgumentException. * Deprecated. Instead of manipulating settings of existing AmazonSQS client, provide correct configuration when creating it through SQSConnectionFactory constructors. - * + * * @param region * The region this client will communicate with. See * {@link Region#getRegion(com.amazonaws.regions.Regions)} for * accessing a given region. - * @throws JMSException + * @throws JMSException jmsException */ @Deprecated public void setRegion(Region region) throws JMSException { @@ -151,7 +144,7 @@ public void setRegion(Region region) throws JMSException { * @param deleteMessageRequest * Container for the necessary parameters to execute the * deleteMessage service method on AmazonSQS. - * @throws JMSException + * @throws JMSException jmsException */ public void deleteMessage(DeleteMessageRequest deleteMessageRequest) throws JMSException { try { @@ -174,7 +167,7 @@ public void deleteMessage(DeleteMessageRequest deleteMessageRequest) throws JMSE * batch version of deleteMessage. Max batch size is 10. * @return The response from the deleteMessageBatch service method, as * returned by AmazonSQS - * @throws JMSException + * @throws JMSException jmsException */ public DeleteMessageBatchResult deleteMessageBatch(DeleteMessageBatchRequest deleteMessageBatchRequest) throws JMSException { try { @@ -194,7 +187,7 @@ public DeleteMessageBatchResult deleteMessageBatch(DeleteMessageBatchRequest del * sendMessage service method on AmazonSQS. * @return The response from the sendMessage service method, as returned by * AmazonSQS - * @throws JMSException + * @throws JMSException jmsException */ public SendMessageResult sendMessage(SendMessageRequest sendMessageRequest) throws JMSException { try { @@ -213,7 +206,7 @@ public SendMessageResult sendMessage(SendMessageRequest sendMessageRequest) thro * @param queueName * the queue to check * @return true if the queue exists, false if it doesn't. - * @throws JMSException + * @throws JMSException jmsException */ public boolean queueExists(String queueName) throws JMSException { try { @@ -237,7 +230,7 @@ public boolean queueExists(String queueName) throws JMSException { * @param queueOwnerAccountId * The AWS accountId of the account that created the queue * @return true if the queue exists, false if it doesn't. - * @throws JMSException + * @throws JMSException jmsException */ public boolean queueExists(String queueName, String queueOwnerAccountId) throws JMSException { try { @@ -256,10 +249,10 @@ public boolean queueExists(String queueName, String queueOwnerAccountId) throws /** * Gets the queueUrl of a queue given a queue name. * - * @param queueName + * @param queueName name of the queue * @return The response from the GetQueueUrl service method, as returned by * AmazonSQS, which will include queue`s URL - * @throws JMSException + * @throws JMSException jmsException */ public GetQueueUrlResult getQueueUrl(String queueName) throws JMSException { return getQueueUrl(new GetQueueUrlRequest(queueName)); @@ -268,11 +261,11 @@ public GetQueueUrlResult getQueueUrl(String queueName) throws JMSException { /** * Gets the queueUrl of a queue given a queue name owned by the provided accountId. * - * @param queueName + * @param queueName name of the queue * @param queueOwnerAccountId The AWS accountId of the account that created the queue * @return The response from the GetQueueUrl service method, as returned by * AmazonSQS, which will include queue`s URL - * @throws JMSException + * @throws JMSException jmsException */ public GetQueueUrlResult getQueueUrl(String queueName, String queueOwnerAccountId) throws JMSException { return getQueueUrl(new GetQueueUrlRequest(queueName).withQueueOwnerAWSAccountId(queueOwnerAccountId)); @@ -286,7 +279,7 @@ public GetQueueUrlResult getQueueUrl(String queueName, String queueOwnerAccountI * getQueueUrl service method on AmazonSQS. * @return The response from the GetQueueUrl service method, as returned by * AmazonSQS, which will include queue`s URL - * @throws JMSException + * @throws JMSException jmsException */ public GetQueueUrlResult getQueueUrl(GetQueueUrlRequest getQueueUrlRequest) throws JMSException { try { @@ -301,11 +294,11 @@ public GetQueueUrlResult getQueueUrl(GetQueueUrlRequest getQueueUrlRequest) thro * Calls createQueue to create the queue with the default queue attributes, * and wraps AmazonClientException * - * @param queueName + * @param queueName name of the queue * @return The response from the createQueue service method, as returned by * AmazonSQS. This call creates a new queue, or returns the URL of * an existing one. - * @throws JMSException + * @throws JMSException jmsException */ public CreateQueueResult createQueue(String queueName) throws JMSException { return createQueue(new CreateQueueRequest(queueName)); @@ -321,7 +314,7 @@ public CreateQueueResult createQueue(String queueName) throws JMSException { * @return The response from the createQueue service method, as returned by * AmazonSQS. This call creates a new queue, or returns the URL of * an existing one. - * @throws JMSException + * @throws JMSException jmsException */ public CreateQueueResult createQueue(CreateQueueRequest createQueueRequest) throws JMSException { try { @@ -343,7 +336,7 @@ public CreateQueueResult createQueue(CreateQueueRequest createQueueRequest) thro * receiveMessage service method on AmazonSQS. * @return The response from the ReceiveMessage service method, as returned * by AmazonSQS. - * @throws JMSException + * @throws JMSException jmsException */ public ReceiveMessageResult receiveMessage(ReceiveMessageRequest receiveMessageRequest) throws JMSException { try { @@ -361,12 +354,12 @@ public ReceiveMessageResult receiveMessage(ReceiveMessageRequest receiveMessageR * @param changeMessageVisibilityRequest * Container for the necessary parameters to execute the * changeMessageVisibility service method on AmazonSQS. - * @throws JMSException + * @throws JMSException jmsException */ public void changeMessageVisibility(ChangeMessageVisibilityRequest changeMessageVisibilityRequest) throws JMSException { try { prepareRequest(changeMessageVisibilityRequest); - amazonSQSClient.changeMessageVisibility(changeMessageVisibilityRequest); + amazonSQSClient.changeMessageVisibility(prepareRequest(changeMessageVisibilityRequest)); } catch (AmazonClientException e) { throw handleException(e, "changeMessageVisibility"); } @@ -382,10 +375,10 @@ public void changeMessageVisibility(ChangeMessageVisibilityRequest changeMessage * changeMessageVisibilityBatch service method on AmazonSQS. * @return The response from the changeMessageVisibilityBatch service * method, as returned by AmazonSQS. - * @throws JMSException + * @throws JMSException jmsException */ - public ChangeMessageVisibilityBatchResult changeMessageVisibilityBatch(ChangeMessageVisibilityBatchRequest changeMessageVisibilityBatchRequest) - throws JMSException { + public ChangeMessageVisibilityBatchResult changeMessageVisibilityBatch( + ChangeMessageVisibilityBatchRequest changeMessageVisibilityBatchRequest) throws JMSException { try { prepareRequest(changeMessageVisibilityBatchRequest); return amazonSQSClient.changeMessageVisibilityBatch(changeMessageVisibilityBatchRequest); @@ -400,8 +393,7 @@ public ChangeMessageVisibilityBatchResult changeMessageVisibilityBatch(ChangeMes */ private String logAndGetAmazonServiceException(AmazonServiceException ase, String action) { String errorMessage = "AmazonServiceException: " + action + ". RequestId: " + ase.getRequestId() + - "\nHTTPStatusCode: " + ase.getStatusCode() + " AmazonErrorCode: " + - ase.getErrorCode(); + "\nHTTPStatusCode: " + ase.getStatusCode() + " AmazonErrorCode: " + ase.getErrorCode(); LOG.error(errorMessage, ase); return errorMessage; } @@ -416,11 +408,9 @@ private String logAndGetAmazonClientException(AmazonClientException ace, String return errorMessage; } - private JMSException handleException(AmazonClientException e, String operationName) throws JMSException { + private JMSException handleException(AmazonClientException e, String operationName) { JMSException jmsException; - if (e instanceof AmazonServiceException) { - AmazonServiceException se = ( AmazonServiceException ) e; - + if (e instanceof AmazonServiceException se) { if (e instanceof QueueDoesNotExistException) { jmsException = new InvalidDestinationException( logAndGetAmazonServiceException(se, operationName), se.getErrorCode()); @@ -431,16 +421,19 @@ private JMSException handleException(AmazonClientException e, String operationNa jmsException = new JMSException( logAndGetAmazonServiceException(se, operationName), se.getErrorCode()); } - } else { jmsException = new JMSException(logAndGetAmazonClientException(e, operationName)); } jmsException.initCause(e); return jmsException; } - - private boolean isJMSSecurityException(AmazonServiceException e) { - return SECURITY_EXCEPTION_ERROR_CODES.contains(e.getErrorCode()) ; + + private static String errorCode(AmazonServiceException e) { + return e.getErrorCode() != null ? e.getErrorCode() : ""; + } + + private static boolean isJMSSecurityException(AmazonServiceException e) { + return SECURITY_EXCEPTION_ERROR_CODES.contains(errorCode(e)); } private T prepareRequest(T request) { @@ -450,5 +443,4 @@ private T prepareRequest(T request) { } return request; } - } diff --git a/src/main/java/com/amazon/sqs/javamessaging/PrefetchManager.java b/src/main/java/com/amazon/sqs/javamessaging/PrefetchManager.java index b0a203a..2251f7d 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/PrefetchManager.java +++ b/src/main/java/com/amazon/sqs/javamessaging/PrefetchManager.java @@ -25,13 +25,13 @@ public interface PrefetchManager { * messageQueue when user calls for receive or message listener onMessage is * called. */ - public void messageDispatched(); + void messageDispatched(); /** * Notify the prefetchThread that the message listener has finished with any * previous message and is ready to accept another. */ - public void messageListenerReady(); + void messageListenerReady(); /** * This is used to determine the state of the consumer, when the message @@ -39,5 +39,5 @@ public interface PrefetchManager { * * @return The message consumer, which owns the prefetchThread */ - public SQSMessageConsumer getMessageConsumer(); + SQSMessageConsumer getMessageConsumer(); } diff --git a/src/main/java/com/amazon/sqs/javamessaging/ProviderConfiguration.java b/src/main/java/com/amazon/sqs/javamessaging/ProviderConfiguration.java index 5f12e24..c5ccfc1 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/ProviderConfiguration.java +++ b/src/main/java/com/amazon/sqs/javamessaging/ProviderConfiguration.java @@ -28,7 +28,11 @@ public int getNumberOfMessagesToPrefetch() { public void setNumberOfMessagesToPrefetch(int numberOfMessagesToPrefetch) { if (numberOfMessagesToPrefetch < SQSMessagingClientConstants.MIN_PREFETCH) { - throw new IllegalArgumentException(String.format("Invalid prefetch size. Provided value '%1$s' cannot be smaller than '%2$s'", numberOfMessagesToPrefetch, SQSMessagingClientConstants.MIN_PREFETCH)); + throw new IllegalArgumentException(String.format( + "Invalid prefetch size. Provided value '%1$s' cannot be smaller than '%2$s'", + numberOfMessagesToPrefetch, + SQSMessagingClientConstants.MIN_PREFETCH + )); } this.numberOfMessagesToPrefetch = numberOfMessagesToPrefetch; } diff --git a/src/main/java/com/amazon/sqs/javamessaging/SQSConnection.java b/src/main/java/com/amazon/sqs/javamessaging/SQSConnection.java index 0f32135..95b1f1e 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/SQSConnection.java +++ b/src/main/java/com/amazon/sqs/javamessaging/SQSConnection.java @@ -18,20 +18,20 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import javax.jms.IllegalStateException; -import javax.jms.Connection; -import javax.jms.ConnectionConsumer; -import javax.jms.ConnectionMetaData; -import javax.jms.Destination; -import javax.jms.ExceptionListener; -import javax.jms.InvalidClientIDException; -import javax.jms.JMSException; -import javax.jms.Queue; -import javax.jms.QueueConnection; -import javax.jms.QueueSession; -import javax.jms.ServerSessionPool; -import javax.jms.Session; -import javax.jms.Topic; +import jakarta.jms.IllegalStateException; +import jakarta.jms.Connection; +import jakarta.jms.ConnectionConsumer; +import jakarta.jms.ConnectionMetaData; +import jakarta.jms.Destination; +import jakarta.jms.ExceptionListener; +import jakarta.jms.InvalidClientIDException; +import jakarta.jms.JMSException; +import jakarta.jms.Queue; +import jakarta.jms.QueueConnection; +import jakarta.jms.QueueSession; +import jakarta.jms.ServerSessionPool; +import jakarta.jms.Session; +import jakarta.jms.Topic; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -106,12 +106,11 @@ public class SQSConnection implements Connection, QueueConnection { */ private volatile boolean actionOnConnectionTaken = false; - private final Set sessions = Collections.newSetFromMap(new ConcurrentHashMap()); + private final Set sessions = Collections.newSetFromMap(new ConcurrentHashMap<>()); SQSConnection(AmazonSQSMessagingClientWrapper amazonSQSClientJMSWrapper, int numberOfMessagesToPrefetch) { amazonSQSClient = amazonSQSClientJMSWrapper; this.numberOfMessagesToPrefetch = numberOfMessagesToPrefetch; - } /** @@ -197,7 +196,7 @@ public Session createSession(boolean transacted, int acknowledgeMode) throws JMS } synchronized (stateLock) { if (closing) { - /** + /* * SQSSession's constructor has already started a SQSSessionCallbackScheduler which should be closed * before leaving sqsSession object. */ @@ -206,7 +205,7 @@ public Session createSession(boolean transacted, int acknowledgeMode) throws JMS } sessions.add(sqsSession); - /** + /* * Any new sessions created on a started connection should be * started on creation */ @@ -214,10 +213,19 @@ public Session createSession(boolean transacted, int acknowledgeMode) throws JMS sqsSession.start(); } } - return sqsSession; } + @Override + public Session createSession(int acknowledgeMode) throws JMSException { + return createSession(false, acknowledgeMode); + } + + @Override + public Session createSession() throws JMSException { + throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + @Override public ExceptionListener getExceptionListener() throws JMSException { checkClosing(); @@ -302,7 +310,7 @@ public void start() throws JMSException { * This means that a client can rely on the fact that none of its message * listeners will be called and that all threads of control waiting for * receive calls to return will not return with a message until the - * connection is restarted. The receive timers for a stopped connection + * connection is restarted. The Receive timers for a stopped connection * continue to advance, so receives may time out while the connection is * stopped. *

@@ -335,7 +343,7 @@ public void stop() throws JMSException { try { for (Session session : sessions) { SQSSession sqsSession = (SQSSession) session; - /** + /* * Session stop call blocks until receives and/or * message listeners in progress have completed. */ @@ -379,7 +387,7 @@ public void close() throws JMSException { return; } - /** + /* * A message listener must not attempt to close its own connection as * this would lead to deadlock. */ @@ -410,7 +418,7 @@ public void close() throws JMSException { } } - }/** Blocks until closing of the connection completes */ + }// Blocks until closing of the connection completes else { synchronized (stateLock) { while (!closed) { @@ -431,7 +439,7 @@ public void close() throws JMSException { * from list of Sessions. */ void removeSession(Session session) throws JMSException { - /** + /* * No need to synchronize on stateLock assuming this can be only called * by session.close(), on which point connection will not be worried * about missing closing this session. @@ -513,8 +521,25 @@ public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String su /** This method is not supported. */ @Override - public ConnectionConsumer createConnectionConsumer(Queue queue, String messageSelector, ServerSessionPool sessionPool, int maxMessages) - throws JMSException { + public ConnectionConsumer createConnectionConsumer( + Queue queue, String messageSelector, ServerSessionPool sessionPool, int maxMessages + ) throws JMSException { + throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + + /** This method is not supported. */ + @Override + public ConnectionConsumer createSharedConnectionConsumer( + Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages + ) throws JMSException { + throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + + /** This method is not supported. */ + @Override + public ConnectionConsumer createSharedDurableConnectionConsumer( + Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages + ) throws JMSException { throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); } @@ -529,8 +554,8 @@ boolean isClosed() { return closed; } - void setClosing(boolean closing) { - this.closing = closing; + void setClosing() { + this.closing = true; } void setRunning(boolean running) { diff --git a/src/main/java/com/amazon/sqs/javamessaging/SQSConnectionFactory.java b/src/main/java/com/amazon/sqs/javamessaging/SQSConnectionFactory.java index 3e01779..044c104 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/SQSConnectionFactory.java +++ b/src/main/java/com/amazon/sqs/javamessaging/SQSConnectionFactory.java @@ -14,10 +14,12 @@ */ package com.amazon.sqs.javamessaging; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.QueueConnection; -import javax.jms.QueueConnectionFactory; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.JMSContext; +import jakarta.jms.JMSException; +import jakarta.jms.JMSRuntimeException; +import jakarta.jms.QueueConnection; +import jakarta.jms.QueueConnectionFactory; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSCredentials; @@ -81,12 +83,7 @@ public SQSConnectionFactory(ProviderConfiguration providerConfiguration, final A throw new IllegalArgumentException("AmazonSQS client cannot be null"); } this.providerConfiguration = providerConfiguration; - this.amazonSQSClientSupplier = new AmazonSQSClientSupplier() { - @Override - public AmazonSQS get() { - return client; - } - }; + this.amazonSQSClientSupplier = () -> client; } /* @@ -101,31 +98,23 @@ public SQSConnectionFactory(ProviderConfiguration providerConfiguration, final A throw new IllegalArgumentException("AmazonSQS client builder cannot be null"); } this.providerConfiguration = providerConfiguration; - this.amazonSQSClientSupplier = new AmazonSQSClientSupplier() { - @Override - public AmazonSQS get() { - return clientBuilder.build(); - } - }; + this.amazonSQSClientSupplier = clientBuilder::build; } private SQSConnectionFactory(final Builder builder) { this.providerConfiguration = builder.providerConfiguration; - this.amazonSQSClientSupplier = new AmazonSQSClientSupplier() { - @Override - public AmazonSQS get() { - AmazonSQSClient amazonSQSClient = new AmazonSQSClient(builder.awsCredentialsProvider, builder.clientConfiguration); - if (builder.region != null) { - amazonSQSClient.setRegion(builder.region); - } - if (builder.endpoint != null) { - amazonSQSClient.setEndpoint(builder.endpoint); - } - if (builder.signerRegionOverride != null) { - amazonSQSClient.setSignerRegionOverride(builder.signerRegionOverride); - } - return amazonSQSClient; + this.amazonSQSClientSupplier = () -> { + AmazonSQSClient amazonSQSClient = new AmazonSQSClient(builder.awsCredentialsProvider, builder.clientConfiguration); + if (builder.region != null) { + amazonSQSClient.setRegion(builder.region); + } + if (builder.endpoint != null) { + amazonSQSClient.setEndpoint(builder.endpoint); } + if (builder.signerRegionOverride != null) { + amazonSQSClient.setSignerRegionOverride(builder.signerRegionOverride); + } + return amazonSQSClient; }; } @@ -163,20 +152,43 @@ private SQSConnection createConnection(AmazonSQS amazonSQS, AWSCredentialsProvid AmazonSQSMessagingClientWrapper amazonSQSClientJMSWrapper = new AmazonSQSMessagingClientWrapper(amazonSQS, awsCredentialsProvider); return new SQSConnection(amazonSQSClientJMSWrapper, providerConfiguration.getNumberOfMessagesToPrefetch()); } + + /** This method is not supported. */ + @Override + public JMSContext createContext() { + throw new JMSRuntimeException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + + /** This method is not supported. */ + @Override + public JMSContext createContext(String userName, String password) { + throw new JMSRuntimeException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + + /** This method is not supported. */ + @Override + public JMSContext createContext(String userName, String password, int sessionMode) { + throw new JMSRuntimeException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + + /** This method is not supported. */ + @Override + public JMSContext createContext(int sessionMode) { + throw new JMSRuntimeException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } @Override public QueueConnection createQueueConnection() throws JMSException { - return (QueueConnection) createConnection(); + return createConnection(); } @Override public QueueConnection createQueueConnection(String userName, String password) throws JMSException { - return (QueueConnection) createConnection(userName, password); + return createConnection(userName, password); } /** * Deprecated. Use one of the constructors of this class instead and provide either AmazonSQS client or AmazonSQSClientBuilder. - * @return */ @Deprecated public static Builder builder() { @@ -185,7 +197,6 @@ public static Builder builder() { /** * Deprecated. Use one of the constructors of SQSConnectionFactory instead. - * @return */ @Deprecated public static class Builder { @@ -194,7 +205,7 @@ public static class Builder { private String signerRegionOverride; private ClientConfiguration clientConfiguration; private AWSCredentialsProvider awsCredentialsProvider = new DefaultAWSCredentialsProviderChain(); - private ProviderConfiguration providerConfiguration; + private final ProviderConfiguration providerConfiguration; public Builder(Region region) { this(); diff --git a/src/main/java/com/amazon/sqs/javamessaging/SQSConnectionMetaData.java b/src/main/java/com/amazon/sqs/javamessaging/SQSConnectionMetaData.java index 40eee1e..ea6a3cb 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/SQSConnectionMetaData.java +++ b/src/main/java/com/amazon/sqs/javamessaging/SQSConnectionMetaData.java @@ -19,26 +19,26 @@ import java.util.Enumeration; import java.util.List; -import javax.jms.ConnectionMetaData; -import javax.jms.JMSException; +import jakarta.jms.ConnectionMetaData; +import jakarta.jms.JMSException; public class SQSConnectionMetaData implements ConnectionMetaData { - private String jmsVersion; - private int jmsMajorVersion; - private int jmsMinorVersion; + private final String jmsVersion; + private final int jmsMajorVersion; + private final int jmsMinorVersion; - private String jmsProviderName; - private String providerVersion; - private int providerMajorVersion; - private int providerMinorVersion; + private final String jmsProviderName; + private final String providerVersion; + private final int providerMajorVersion; + private final int providerMinorVersion; - private List jmsxProperty; + private final List jmsxProperty; SQSConnectionMetaData() { - this.jmsVersion = "1.1"; - this.jmsMajorVersion = 1; + this.jmsVersion = "3.1"; + this.jmsMajorVersion = 3; this.jmsMinorVersion = 1; this.jmsProviderName = "Amazon"; @@ -46,7 +46,7 @@ public class SQSConnectionMetaData implements ConnectionMetaData { this.providerMajorVersion = 1; this.providerMinorVersion = 0; - this.jmsxProperty = new ArrayList(); + this.jmsxProperty = new ArrayList<>(); jmsxProperty.add(SQSMessagingClientConstants.JMSX_DELIVERY_COUNT); jmsxProperty.add(SQSMessagingClientConstants.JMSX_GROUP_ID); jmsxProperty.add(SQSMessagingClientConstants.JMSX_GROUP_SEC); diff --git a/src/main/java/com/amazon/sqs/javamessaging/SQSMessageConsumer.java b/src/main/java/com/amazon/sqs/javamessaging/SQSMessageConsumer.java index ce6e1d8..ab27a4b 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/SQSMessageConsumer.java +++ b/src/main/java/com/amazon/sqs/javamessaging/SQSMessageConsumer.java @@ -21,13 +21,13 @@ import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; -import javax.jms.IllegalStateException; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Queue; -import javax.jms.QueueReceiver; +import jakarta.jms.IllegalStateException; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.Queue; +import jakarta.jms.QueueReceiver; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -67,7 +67,7 @@ public class SQSMessageConsumer implements MessageConsumer, QueueReceiver { private final ExecutorService prefetchExecutor; /** - * Prefetch Runnable. This include keeping internal message buffer filled and call MessageListener if set. + * Prefetch Runnable. This includes keeping internal message buffer filled and call MessageListener if set. */ private final SQSMessageConsumerPrefetch sqsMessageConsumerPrefetch; @@ -107,7 +107,7 @@ public class SQSMessageConsumer implements MessageConsumer, QueueReceiver { */ @Override public Queue getQueue() throws JMSException { - return (Queue) sqsDestination; + return sqsDestination; } /** @@ -227,7 +227,7 @@ void doClose() { try { if (!prefetchExecutor.isShutdown()) { LOG.info("Shutting down " + SQSSession.CONSUMER_PREFETCH_EXECUTER_NAME + " executor"); - /** Shut down executor. */ + // Shut down executor prefetchExecutor.shutdown(); } diff --git a/src/main/java/com/amazon/sqs/javamessaging/SQSMessageConsumerPrefetch.java b/src/main/java/com/amazon/sqs/javamessaging/SQSMessageConsumerPrefetch.java index 5c71787..f29cd3e 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/SQSMessageConsumerPrefetch.java +++ b/src/main/java/com/amazon/sqs/javamessaging/SQSMessageConsumerPrefetch.java @@ -23,9 +23,9 @@ import java.util.Set; import java.util.UUID; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageListener; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.MessageListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -76,7 +76,7 @@ public class SQSMessageConsumerPrefetch implements Runnable, PrefetchManager { private final SQSQueueDestination sqsDestination; /** - * Internal buffer of Messages. The size of queue is MIN_BATCH by default + * Internal buffer of Messages. The size of queue is MIN_BATCH by default, * and it can be changed by user. */ protected final ArrayDeque messageQueue; @@ -134,7 +134,7 @@ public class SQSMessageConsumerPrefetch implements Runnable, PrefetchManager { queueUrl = sqsDestination.getQueueUrl(); this.sqsDestination = sqsDestination; this.sqsSessionRunnable = sqsSessionRunnable; - messageQueue = new ArrayDeque(numberOfMessagesToPrefetch); + messageQueue = new ArrayDeque<>(numberOfMessagesToPrefetch); } MessageListener getMessageListener() { @@ -170,7 +170,7 @@ protected void setMessageListener(MessageListener messageListener) { return; } - List allPrefetchedMessages = new ArrayList(messageQueue); + List allPrefetchedMessages = new ArrayList<>(messageQueue); sqsSessionRunnable.scheduleCallBacks(messageListener, allPrefetchedMessages); messageQueue.clear(); @@ -268,11 +268,11 @@ protected List getMessages(int batchSize, int waitTimeSeconds) throws J * converted to JMS message will be immediately negative acknowledged. */ protected void processReceivedMessages(List messages) { - List nackMessages = new ArrayList(); - List messageManagers = new ArrayList(); + List nackMessages = new ArrayList<>(); + List messageManagers = new ArrayList<>(); for (Message message : messages) { try { - javax.jms.Message jmsMessage = convertToJMSMessage(message); + jakarta.jms.Message jmsMessage = convertToJMSMessage(message); messageManagers.add(new MessageManager(this, jmsMessage)); } catch (JMSException e) { LOG.warn("Caught exception while converting received messages", e); @@ -323,7 +323,7 @@ protected void waitForPrefetch() throws InterruptedException { stateLock.wait(); } catch (InterruptedException e) { LOG.warn("Interrupted while waiting on prefetch", e); - /** For interruption, we do not nack the messages */ + // For interruption, we do not nack the messages throw e; } } @@ -334,12 +334,12 @@ protected void waitForPrefetch() throws InterruptedException { * Convert the return SQS message into JMS message * @param message SQS message to convert * @return Converted JMS message - * @throws JMSException + * @throws JMSException jmsException */ - protected javax.jms.Message convertToJMSMessage(Message message) throws JMSException { + protected jakarta.jms.Message convertToJMSMessage(Message message) throws JMSException { MessageAttributeValue messageTypeAttribute = message.getMessageAttributes().get( SQSMessage.JMS_SQS_MESSAGE_TYPE); - javax.jms.Message jmsMessage = null; + jakarta.jms.Message jmsMessage; if (messageTypeAttribute == null) { jmsMessage = new SQSTextMessage(acknowledger, queueUrl, message); } else { @@ -456,31 +456,15 @@ private void unrequestMessage() { } } - public static class MessageManager { + public record MessageManager(PrefetchManager prefetchManager, jakarta.jms.Message message) { - private final PrefetchManager prefetchManager; - - private final javax.jms.Message message; - - public MessageManager(PrefetchManager prefetchManager, javax.jms.Message message) { - this.prefetchManager = prefetchManager; - this.message = message; - } - - public PrefetchManager getPrefetchManager() { - return prefetchManager; - } - - public javax.jms.Message getMessage() { - return message; - } } - javax.jms.Message receive() throws JMSException { + jakarta.jms.Message receive() throws JMSException { return receive(0); } - javax.jms.Message receive(long timeout) throws JMSException { + jakarta.jms.Message receive(long timeout) throws JMSException { if (cannotDeliver()) { return null; } @@ -533,7 +517,7 @@ protected void notifyStateChange() { } } - javax.jms.Message receiveNoWait() throws JMSException { + jakarta.jms.Message receiveNoWait() throws JMSException { if (cannotDeliver()) { return null; } @@ -588,11 +572,11 @@ void close() { /** * Helper that notifies PrefetchThread that message is dispatched and AutoAcknowledge */ - private javax.jms.Message messageHandler(MessageManager messageManager) throws JMSException { + private jakarta.jms.Message messageHandler(MessageManager messageManager) throws JMSException { if (messageManager == null) { return null; } - javax.jms.Message message = messageManager.getMessage(); + jakarta.jms.Message message = messageManager.message(); // Notify PrefetchThread that message is dispatched this.messageDispatched(); @@ -631,13 +615,13 @@ protected boolean isClosed() { } List purgePrefetchedMessagesWithGroups(Set affectedGroups) throws JMSException { - List purgedMessages = new ArrayList(); + List purgedMessages = new ArrayList<>(); synchronized (stateLock) { //let's walk over the prefetched messages Iterator managerIterator = messageQueue.iterator(); while (managerIterator.hasNext()) { MessageManager messageManager = managerIterator.next(); - SQSMessage prefetchedMessage = (SQSMessage)messageManager.getMessage(); + SQSMessage prefetchedMessage = (SQSMessage)messageManager.message(); SQSMessageIdentifier messageIdentifier = SQSMessageIdentifier.fromSQSMessage(prefetchedMessage); //is the prefetch entry for one of the affected group ids? diff --git a/src/main/java/com/amazon/sqs/javamessaging/SQSMessageProducer.java b/src/main/java/com/amazon/sqs/javamessaging/SQSMessageProducer.java index 8093f04..8a11be7 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/SQSMessageProducer.java +++ b/src/main/java/com/amazon/sqs/javamessaging/SQSMessageProducer.java @@ -20,15 +20,16 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import javax.jms.Destination; -import javax.jms.IllegalStateException; -import javax.jms.InvalidDestinationException; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageFormatException; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.QueueSender; +import jakarta.jms.CompletionListener; +import jakarta.jms.Destination; +import jakarta.jms.IllegalStateException; +import jakarta.jms.InvalidDestinationException; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageFormatException; +import jakarta.jms.MessageProducer; +import jakarta.jms.Queue; +import jakarta.jms.QueueSender; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -56,7 +57,7 @@ public class SQSMessageProducer implements MessageProducer, QueueSender { private static final Log LOG = LogFactory.getLog(SQSMessageProducer.class); - private long MAXIMUM_DELIVERY_DELAY_MILLISECONDS = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES); + private final long MAXIMUM_DELIVERY_DELAY_MILLISECONDS = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES); private int deliveryDelaySeconds = 0; @@ -92,12 +93,11 @@ void sendInternal(SQSQueueDestination queue, Message rawMessage) throws JMSExcep checkClosed(); String sqsMessageBody = null; String messageType = null; - if (!(rawMessage instanceof SQSMessage)) { + if (!(rawMessage instanceof SQSMessage message)) { throw new MessageFormatException( "Unrecognized message type. Messages have to be one of: SQSBytesMessage, SQSObjectMessage, or SQSTextMessage"); } - - SQSMessage message = (SQSMessage)rawMessage; + message.setJMSDestination(queue); if (message instanceof SQSBytesMessage) { sqsMessageBody = Base64.encodeAsString(((SQSBytesMessage) message).getBodyAsBytes()); @@ -113,9 +113,9 @@ void sendInternal(SQSQueueDestination queue, Message rawMessage) throws JMSExcep if (sqsMessageBody == null || sqsMessageBody.isEmpty()) { throw new JMSException("Message body cannot be null or empty"); } - Map messageAttributes = propertyToMessageAttribute((SQSMessage) message); + Map messageAttributes = propertyToMessageAttribute(message); - /** + /* * These will override existing attributes if they exist. Everything that * has prefix JMS_ is reserved for JMS Provider, but if the user sets that * attribute, it will be overwritten. @@ -143,7 +143,7 @@ void sendInternal(SQSQueueDestination queue, Message rawMessage) throws JMSExcep SendMessageResult sendMessageResult = amazonSQSClient.sendMessage(sendMessageRequest); String messageId = sendMessageResult.getMessageId(); LOG.info("Message sent to SQS with SQS-assigned messageId: " + messageId); - /** TODO: Do not support disableMessageID for now. */ + // TODO: Do not support disableMessageID for now. message.setSQSMessageId(messageId); // if the message was sent to FIFO queue, the sequence number will be @@ -196,7 +196,7 @@ public void send(Queue queue, Message message) throws JMSException { */ Map propertyToMessageAttribute(SQSMessage message) throws JMSException { - Map messageAttributes = new HashMap(); + Map messageAttributes = new HashMap<>(); Enumeration propertyNames = message.getPropertyNames(); while (propertyNames.hasMoreElements()) { @@ -248,10 +248,9 @@ private void addReplyToQueueReservedAttributes(Map messageAttrib * the queue destination to send this message to * @param message * the message to send - * @param deliveryMode - * @param priority - * @param timeToLive + * @param deliveryMode delivery mode + * @param priority delivery priority + * @param timeToLive delivery time * @throws InvalidDestinationException * If a client uses this method with a destination other than * SQS queue destination. @@ -366,13 +365,11 @@ public void send(Message message) throws JMSException { * Send does not support deliveryMode, priority, and timeToLive. It will * ignore anything in deliveryMode, priority, and timeToLive. * - * @param message - * the message to send - * @param deliveryMode - * @param priority - * @param timeToLive - * @throws MessageFormatException - * If an invalid message is specified. + * @param message the message to send + * @param deliveryMode delivery mode + * @param priority delivery priority + * @param timeToLive delivery time + * @throws MessageFormatException If an invalid message is specified. * @throws UnsupportedOperationException * If a client uses this method with a MessageProducer that did * not specify a destination at creation time. @@ -443,6 +440,31 @@ public void send(Destination destination, Message message, int deliveryMode, int send(destination, message); } + /** This method is not supported. */ + @Override + public void send(Message message, CompletionListener completionListener) throws JMSException { + throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + + /** This method is not supported. */ + @Override + public void send(Message message, int deliveryMode, int priority, long timeToLive, CompletionListener completionListener) throws JMSException { + throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + + /** This method is not supported. */ + @Override + public void send(Destination destination, Message message, CompletionListener completionListener) throws JMSException { + throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + + /** This method is not supported. */ + @Override + public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive, + CompletionListener completionListener) throws JMSException { + throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + /** This method is not supported. */ @Override public void setDisableMessageID(boolean value) throws JMSException { @@ -525,7 +547,7 @@ public void setDeliveryDelay(long deliveryDelay) { * message is sent before the JMS provider may deliver the message to a consumer. */ public long getDeliveryDelay() { - return deliveryDelaySeconds * 1000; + return deliveryDelaySeconds * 1000L; } void checkClosed() throws IllegalStateException { diff --git a/src/main/java/com/amazon/sqs/javamessaging/SQSMessagingClientConstants.java b/src/main/java/com/amazon/sqs/javamessaging/SQSMessagingClientConstants.java index 099c8b4..21ccdfb 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/SQSMessagingClientConstants.java +++ b/src/main/java/com/amazon/sqs/javamessaging/SQSMessagingClientConstants.java @@ -14,9 +14,8 @@ */ package com.amazon.sqs.javamessaging; -import javax.jms.ConnectionMetaData; -import javax.jms.JMSException; - +import jakarta.jms.ConnectionMetaData; +import jakarta.jms.JMSException; public class SQSMessagingClientConstants { diff --git a/src/main/java/com/amazon/sqs/javamessaging/SQSQueueDestination.java b/src/main/java/com/amazon/sqs/javamessaging/SQSQueueDestination.java index 4a42eb1..6bc8d12 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/SQSQueueDestination.java +++ b/src/main/java/com/amazon/sqs/javamessaging/SQSQueueDestination.java @@ -14,10 +14,10 @@ */ package com.amazon.sqs.javamessaging; -import javax.jms.Destination; -import javax.jms.JMSException; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; -import javax.jms.Queue; +import jakarta.jms.Queue; /** * A SQSQueueDestination object encapsulates a queue name and SQS specific queue @@ -90,10 +90,7 @@ public boolean equals(Object obj) { } else if (!queueName.equals(other.queueName)) return false; if (queueUrl == null) { - if (other.queueUrl != null) - return false; - } else if (!queueUrl.equals(other.queueUrl)) - return false; - return true; + return other.queueUrl == null; + } else return queueUrl.equals(other.queueUrl); } } diff --git a/src/main/java/com/amazon/sqs/javamessaging/SQSSession.java b/src/main/java/com/amazon/sqs/javamessaging/SQSSession.java index fb79167..cd64a10 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/SQSSession.java +++ b/src/main/java/com/amazon/sqs/javamessaging/SQSSession.java @@ -26,28 +26,28 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import javax.jms.BytesMessage; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.ObjectMessage; -import javax.jms.Queue; -import javax.jms.QueueBrowser; -import javax.jms.QueueReceiver; -import javax.jms.QueueSender; -import javax.jms.QueueSession; -import javax.jms.Session; -import javax.jms.StreamMessage; -import javax.jms.TemporaryQueue; -import javax.jms.TemporaryTopic; -import javax.jms.TextMessage; -import javax.jms.Topic; -import javax.jms.TopicSubscriber; -import javax.jms.IllegalStateException; +import jakarta.jms.BytesMessage; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.MapMessage; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.MessageProducer; +import jakarta.jms.ObjectMessage; +import jakarta.jms.Queue; +import jakarta.jms.QueueBrowser; +import jakarta.jms.QueueReceiver; +import jakarta.jms.QueueSender; +import jakarta.jms.QueueSession; +import jakarta.jms.Session; +import jakarta.jms.StreamMessage; +import jakarta.jms.TemporaryQueue; +import jakarta.jms.TemporaryTopic; +import jakarta.jms.TextMessage; +import jakarta.jms.Topic; +import jakarta.jms.TopicSubscriber; +import jakarta.jms.IllegalStateException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -181,8 +181,8 @@ public class SQSSession implements Session, QueueSession { SQSSession(SQSConnection parentSQSConnection, AcknowledgeMode acknowledgeMode) throws JMSException{ this(parentSQSConnection, acknowledgeMode, - Collections.newSetFromMap(new ConcurrentHashMap()), - Collections.newSetFromMap(new ConcurrentHashMap())); + Collections.newSetFromMap(new ConcurrentHashMap<>()), + Collections.newSetFromMap(new ConcurrentHashMap<>())); } SQSSession(SQSConnection parentSQSConnection, AcknowledgeMode acknowledgeMode, @@ -233,7 +233,7 @@ public QueueReceiver createReceiver(Queue queue) throws JMSException { * * @param queue * a queue destination - * @param messageSelector + * @param messageSelector message selector * @return new message receiver * @throws JMSException * If session is closed @@ -380,7 +380,7 @@ public void close() throws JMSException { return; } - /** + /* * A MessageListener must not attempt to close its own Session as * this would lead to deadlock */ @@ -420,7 +420,7 @@ void doClose() throws JMSException { if (executor != null) { LOG.info("Shutting down " + SESSION_EXECUTOR_NAME + " executor"); - /** Shut down executor. */ + // Shut down executor executor.shutdown(); waitForCallbackComplete(); @@ -450,7 +450,7 @@ void doClose() throws JMSException { stateLock.notifyAll(); } } - }/** Blocks until closing of the session completes */ + }// Blocks until closing of the session completes else { synchronized (stateLock) { while (!closed) { @@ -501,13 +501,13 @@ public void recover() throws JMSException { } private Map> getAffectedGroupsPerQueueUrl(List messages) { - Map> queueToGroupsMapping = new HashMap>(); + Map> queueToGroupsMapping = new HashMap<>(); for (SQSMessageIdentifier message : messages) { String groupId = message.getGroupId(); if (groupId != null) { String queueUrl = message.getQueueUrl(); if (!queueToGroupsMapping.containsKey(queueUrl)) { - queueToGroupsMapping.put(queueUrl, new HashSet()); + queueToGroupsMapping.put(queueUrl, new HashSet<>()); } queueToGroupsMapping.get(queueUrl).add(groupId); } @@ -585,9 +585,8 @@ SQSMessageConsumer createSQSMessageConsumer(SQSQueueDestination destination) { * Only queue destinations are supported at this time. * It will ignore any argument in messageSelector. * - * @param destination - * a queue destination - * @param messageSelector + * @param destination a queue destination + * @param messageSelector message selector * @return new message consumer * @throws JMSException * If session is closed or queue destination is not used @@ -622,10 +621,22 @@ public MessageConsumer createConsumer(Destination destination, String messageSel return createConsumer(destination); } + /** This method is not supported. */ + @Override + public MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName) throws JMSException { + throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + + /** This method is not supported. */ + @Override + public MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector) throws JMSException { + throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + /** * This does not create SQS Queue. This method is only to create JMS Queue Object. * Make sure the queue exists corresponding to the queueName. - * @param queueName + * @param queueName name of the queue * @return a queue destination * @throws JMSException * If session is closed or invalid queue is provided @@ -641,7 +652,7 @@ public Queue createQueue(String queueName) throws JMSException { * Object. Make sure the queue exists corresponding to the queueName and * ownerAccountId. * - * @param queueName + * @param queueName name of the queue * @param ownerAccountId * the account id, which originally created the queue on SQS * @return a queue destination @@ -772,6 +783,30 @@ public TopicSubscriber createDurableSubscriber(Topic topic, String name, String throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); } + /** This method is not supported. */ + @Override + public MessageConsumer createDurableConsumer(Topic topic, String name) throws JMSException { + throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + + /** This method is not supported. */ + @Override + public MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal) throws JMSException { + throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + + /** This method is not supported. */ + @Override + public MessageConsumer createSharedDurableConsumer(Topic topic, String name) throws JMSException { + throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + + /** This method is not supported. */ + @Override + public MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector) throws JMSException { + throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); + } + /** This method is not supported. */ @Override public QueueBrowser createBrowser(Queue queue) throws JMSException { @@ -820,22 +855,7 @@ public MapMessage createMapMessage() throws JMSException { throw new JMSException(SQSMessagingClientConstants.UNSUPPORTED_METHOD); } - static class CallbackEntry { - private final MessageListener messageListener; - private final MessageManager messageManager; - - CallbackEntry(MessageListener messageListener, MessageManager messageManager) { - this.messageListener = messageListener; - this.messageManager = messageManager; - } - - public MessageListener getMessageListener() { - return messageListener; - } - - public MessageManager getMessageManager() { - return messageManager; - } + record CallbackEntry(MessageListener messageListener, MessageManager messageManager) { } /** @@ -882,10 +902,9 @@ void stop() throws IllegalStateException { } } - /* + /** * Unit Tests Utility Functions */ - boolean isCallbackActive() { return activeConsumerInCallback != null; } diff --git a/src/main/java/com/amazon/sqs/javamessaging/SQSSessionCallbackScheduler.java b/src/main/java/com/amazon/sqs/javamessaging/SQSSessionCallbackScheduler.java index 3606e44..abc6e62 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/SQSSessionCallbackScheduler.java +++ b/src/main/java/com/amazon/sqs/javamessaging/SQSSessionCallbackScheduler.java @@ -22,9 +22,9 @@ import java.util.Map; import java.util.Set; -import javax.jms.JMSException; -import javax.jms.MessageListener; -import javax.jms.Session; +import jakarta.jms.JMSException; +import jakarta.jms.MessageListener; +import jakarta.jms.Session; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -46,11 +46,11 @@ public class SQSSessionCallbackScheduler implements Runnable { protected ArrayDeque callbackQueue; - private AcknowledgeMode acknowledgeMode; + private final AcknowledgeMode acknowledgeMode; - private SQSSession session; + private final SQSSession session; - private NegativeAcknowledger negativeAcknowledger; + private final NegativeAcknowledger negativeAcknowledger; private final Acknowledger acknowledger; @@ -71,7 +71,7 @@ public class SQSSessionCallbackScheduler implements Runnable { this.acknowledgeMode = acknowledgeMode; this.acknowledger = acknowledger; this.negativeAcknowledger = negativeAcknowledger; - callbackQueue = new ArrayDeque(); + callbackQueue = new ArrayDeque<>(); } /** @@ -80,7 +80,7 @@ public class SQSSessionCallbackScheduler implements Runnable { */ void close() { closed = true; - /** Wake-up the thread in case it was blocked on empty queue */ + // Wake-up the thread in case it was blocked on empty queue synchronized (callbackQueue) { callbackQueue.notify(); } @@ -101,7 +101,7 @@ public void run() { try { callbackQueue.wait(); } catch (InterruptedException e) { - /** + /* * Will be retried on the next loop, and * break if the callback scheduler is closed. */ @@ -113,10 +113,10 @@ public void run() { } } - MessageListener messageListener = callbackEntry.getMessageListener(); - MessageManager messageManager = callbackEntry.getMessageManager(); - SQSMessage message = (SQSMessage) messageManager.getMessage(); - SQSMessageConsumer messageConsumer = messageManager.getPrefetchManager().getMessageConsumer(); + MessageListener messageListener = callbackEntry.messageListener(); + MessageManager messageManager = callbackEntry.messageManager(); + SQSMessage message = (SQSMessage) messageManager.message(); + SQSMessageConsumer messageConsumer = messageManager.prefetchManager().getMessageConsumer(); if (messageConsumer.isClosed()) { nackReceivedMessage(message); continue; @@ -133,11 +133,11 @@ public void run() { } try { - /** + /* * Notifying consumer prefetch thread so that it can * continue to prefetch */ - messageManager.getPrefetchManager().messageDispatched(); + messageManager.prefetchManager().messageDispatched(); int ackMode = acknowledgeMode.getOriginalAcknowledgeMode(); boolean tryNack = true; try { @@ -171,7 +171,7 @@ public void run() { } } - /** + /* * The consumer close is delegated to the session thread * if consumer close is called by its message listener's * onMessage method on its own consumer. @@ -185,7 +185,7 @@ public void run() { // Let the prefetch manager know we're available to // process another message (if there is a still a listener attached). - messageManager.getPrefetchManager().messageListenerReady(); + messageManager.prefetchManager().messageListenerReady(); } } catch (Throwable ex) { LOG.error("Unexpected exception thrown during the run of the scheduled callback", ex); @@ -193,7 +193,7 @@ public void run() { } } finally { if (callbackEntry != null) { - nackReceivedMessage((SQSMessage) callbackEntry.getMessageManager().getMessage()); + nackReceivedMessage((SQSMessage) callbackEntry.messageManager().message()); } nackQueuedMessages(); } @@ -219,9 +219,9 @@ void scheduleCallBacks(MessageListener messageListener, List mes void nackQueuedMessages() { synchronized (callbackQueue) { try { - List nackMessageIdentifiers = new ArrayList(); + List nackMessageIdentifiers = new ArrayList<>(); while (!callbackQueue.isEmpty()) { - SQSMessage nackMessage = (SQSMessage) callbackQueue.pollFirst().getMessageManager().getMessage(); + SQSMessage nackMessage = (SQSMessage) callbackQueue.pollFirst().messageManager().message(); nackMessageIdentifiers.add(SQSMessageIdentifier.fromSQSMessage(nackMessage)); } @@ -237,7 +237,7 @@ void nackQueuedMessages() { private void nackReceivedMessage(SQSMessage message) { try { SQSMessageIdentifier messageIdentifier = SQSMessageIdentifier.fromSQSMessage(message); - List nackMessageIdentifiers = new ArrayList(); + List nackMessageIdentifiers = new ArrayList<>(); nackMessageIdentifiers.add(messageIdentifier); //failing to process a message with a specific group id means we have to nack all the pending messages with the same group id @@ -255,13 +255,13 @@ private void nackReceivedMessage(SQSMessage message) { } List purgeScheduledCallbacksForQueuesAndGroups(Map> queueToGroupsMapping) throws JMSException { - List purgedCallbacks = new ArrayList(); + List purgedCallbacks = new ArrayList<>(); synchronized (callbackQueue) { //let's walk over the callback queue Iterator callbackIterator = callbackQueue.iterator(); while (callbackIterator.hasNext()) { CallbackEntry callbackEntry = callbackIterator.next(); - SQSMessageIdentifier pendingCallbackIdentifier = SQSMessageIdentifier.fromSQSMessage((SQSMessage) callbackEntry.getMessageManager().getMessage()); + SQSMessageIdentifier pendingCallbackIdentifier = SQSMessageIdentifier.fromSQSMessage((SQSMessage) callbackEntry.messageManager().message()); //is the callback entry for one of the affected queues? Set affectedGroupsInQueue = queueToGroupsMapping.get(pendingCallbackIdentifier.getQueueUrl()); @@ -273,8 +273,8 @@ List purgeScheduledCallbacksForQueuesAndGroups(Map new AutoAcknowledger(amazonSQSClient, parentSQSSession); + case ACK_RANGE -> new RangedAcknowledger(amazonSQSClient, parentSQSSession); + case ACK_UNORDERED -> new UnorderedAcknowledger(amazonSQSClient, parentSQSSession); + default -> throw new JMSException(this + " - AcknowledgeMode does not exist"); + }; } } diff --git a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/Acknowledger.java b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/Acknowledger.java index 290d902..bbbe8e8 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/Acknowledger.java +++ b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/Acknowledger.java @@ -16,7 +16,7 @@ import java.util.List; -import javax.jms.JMSException; +import jakarta.jms.JMSException; import com.amazon.sqs.javamessaging.message.SQSMessage; @@ -25,31 +25,27 @@ public interface Acknowledger { /** * Generic Acknowledge method. This method will delete message(s) in SQS Queue. * - * @param message - * message to acknowledge. - * @throws JMSException + * @param message message to acknowledge. */ - public void acknowledge(SQSMessage message) throws JMSException; + void acknowledge(SQSMessage message) throws JMSException; /** * Used when receiving messages. Depending on acknowledge mode this will * help create list of message backlog. * - * @param message - * notify acknowledger message is received - * @throws JMSException + * @param message notify acknowledger message is received */ - public void notifyMessageReceived(SQSMessage message) throws JMSException; + void notifyMessageReceived(SQSMessage message) throws JMSException; /** * Used in negative acknowledge. Gets all delivered but not acknowledged * messages. */ - public List getUnAckMessages(); + List getUnAckMessages(); /** * Deletes all not acknowledged delivered messages. */ - public void forgetUnAckMessages(); + void forgetUnAckMessages(); } diff --git a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/AutoAcknowledger.java b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/AutoAcknowledger.java index 59db0c0..08ea93e 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/AutoAcknowledger.java +++ b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/AutoAcknowledger.java @@ -17,7 +17,7 @@ import java.util.Collections; import java.util.List; -import javax.jms.JMSException; +import jakarta.jms.JMSException; import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; import com.amazon.sqs.javamessaging.SQSSession; @@ -62,7 +62,7 @@ public void notifyMessageReceived(SQSMessage message) throws JMSException { */ @Override public List getUnAckMessages() { - return Collections.emptyList(); + return Collections.emptyList(); } /** AutoAcknowledge doesn't need to do anything in this method. */ diff --git a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/BulkSQSOperation.java b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/BulkSQSOperation.java index 6eb0243..38b474d 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/BulkSQSOperation.java +++ b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/BulkSQSOperation.java @@ -20,7 +20,7 @@ import java.util.Map; import java.util.Map.Entry; -import javax.jms.JMSException; +import jakarta.jms.JMSException; import com.amazon.sqs.javamessaging.SQSMessagingClientConstants; @@ -46,7 +46,7 @@ public void bulkAction(List messageIdentifierList, int ind assert indexOfMessage > 0; assert indexOfMessage <= messageIdentifierList.size(); - Map> receiptHandleWithSameQueueUrl = new HashMap>(); + Map> receiptHandleWithSameQueueUrl = new HashMap<>(); // Add all messages up to and including requested message into Map. // Map contains key as queueUrl and value as list receiptHandles from @@ -55,13 +55,9 @@ public void bulkAction(List messageIdentifierList, int ind for (int i = 0; i < indexOfMessage; i++) { SQSMessageIdentifier messageIdentifier = messageIdentifierList.get(i); String queueUrl = messageIdentifier.getQueueUrl(); - List receiptHandles = receiptHandleWithSameQueueUrl.get(queueUrl); - // if value of queueUrl is null create new list. - if (receiptHandles == null) { - receiptHandles = new ArrayList(); - receiptHandleWithSameQueueUrl.put(queueUrl, receiptHandles); - } - // add receiptHandle to the list. + // if value of queueUrl is null create new list + List receiptHandles = receiptHandleWithSameQueueUrl.computeIfAbsent(queueUrl, k -> new ArrayList<>()); + // add receiptHandle to the list receiptHandles.add(messageIdentifier.getReceiptHandle()); // Once there are 10 messages in messageBatch, apply the batch action if (receiptHandles.size() == SQSMessagingClientConstants.MAX_BATCH) { @@ -83,9 +79,8 @@ public void bulkAction(List messageIdentifierList, int ind * @param queueUrl * queueUrl of the queue, which the receipt handles belong * @param receiptHandles - * the list of handles, which is be used to (negative)acknowledge + * the list of handles, which is being used to (negative)acknowledge * the messages. - * @throws JMSException */ public abstract void action(String queueUrl, List receiptHandles) throws JMSException; diff --git a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/NegativeAcknowledger.java b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/NegativeAcknowledger.java index b49f910..9c0a9a8 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/NegativeAcknowledger.java +++ b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/NegativeAcknowledger.java @@ -18,7 +18,7 @@ import java.util.ArrayList; import java.util.List; -import javax.jms.JMSException; +import jakarta.jms.JMSException; import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; import com.amazon.sqs.javamessaging.SQSMessagingClientConstants; @@ -58,9 +58,9 @@ public NegativeAcknowledger(AmazonSQSMessagingClientWrapper amazonSQSClient) { * If action throws. */ public void bulkAction(ArrayDeque messageQueue, String queueUrl) throws JMSException { - List receiptHandles = new ArrayList(); + List receiptHandles = new ArrayList<>(); while (!messageQueue.isEmpty()) { - receiptHandles.add(((SQSMessage) (messageQueue.pollFirst().getMessage())).getReceiptHandle()); + receiptHandles.add(((SQSMessage) (messageQueue.pollFirst().message())).getReceiptHandle()); // If there is more than 10 stop can call action if (receiptHandles.size() == SQSMessagingClientConstants.MAX_BATCH) { @@ -79,7 +79,7 @@ public void bulkAction(ArrayDeque messageQueue, String queueUrl) * @param queueUrl * The queueUrl of the queue, which the receipt handles belong. * @param receiptHandles - * The list of handles, which is be used to negative acknowledge + * The list of handles, which is being used to negative acknowledge * the messages via using * changeMessageVisibilityBatch. * @throws JMSException @@ -87,17 +87,17 @@ public void bulkAction(ArrayDeque messageQueue, String queueUrl) */ @Override public void action(String queueUrl, List receiptHandles) throws JMSException { - if (receiptHandles == null || receiptHandles.isEmpty()) { return; } - List nackEntries = new ArrayList( + List nackEntries = new ArrayList<>( receiptHandles.size()); int batchId = 0; for (String messageReceiptHandle : receiptHandles) { - ChangeMessageVisibilityBatchRequestEntry changeMessageVisibilityBatchRequestEntry = new ChangeMessageVisibilityBatchRequestEntry( - Integer.toString(batchId), messageReceiptHandle).withVisibilityTimeout(NACK_TIMEOUT); + ChangeMessageVisibilityBatchRequestEntry changeMessageVisibilityBatchRequestEntry = + new ChangeMessageVisibilityBatchRequestEntry(Integer.toString(batchId), messageReceiptHandle) + .withVisibilityTimeout(NACK_TIMEOUT); nackEntries.add(changeMessageVisibilityBatchRequestEntry); batchId++; } diff --git a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/RangedAcknowledger.java b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/RangedAcknowledger.java index e06790a..5e51764 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/RangedAcknowledger.java +++ b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/RangedAcknowledger.java @@ -19,7 +19,7 @@ import java.util.List; import java.util.Queue; -import javax.jms.JMSException; +import jakarta.jms.JMSException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -52,7 +52,7 @@ public class RangedAcknowledger extends BulkSQSOperation implements Acknowledger public RangedAcknowledger(AmazonSQSMessagingClientWrapper amazonSQSClient, SQSSession session) { this.amazonSQSClient = amazonSQSClient; this.session = session; - this.unAckMessages = new LinkedList(); + this.unAckMessages = new LinkedList<>(); } /** @@ -68,9 +68,9 @@ public void acknowledge(SQSMessage message) throws JMSException { int indexOfMessage = indexOf(ackMessage); - /** + /* * In case the message has already been deleted, warn user about it and - * return. If not then then it should continue with acknowledging all + * return. If not then it should continue with acknowledging all * the messages received before that */ if (indexOfMessage == -1) { @@ -113,7 +113,7 @@ public void notifyMessageReceived(SQSMessage message) throws JMSException { */ @Override public List getUnAckMessages() { - return new ArrayList(unAckMessages); + return new ArrayList<>(unAckMessages); } /** @@ -134,7 +134,7 @@ public void action(String queueUrl, List receiptHandles) throws JMSExcep return; } - List deleteMessageBatchRequestEntries = new ArrayList(); + List deleteMessageBatchRequestEntries = new ArrayList<>(); int batchId = 0; for (String receiptHandle : receiptHandles) { // Remove the message from queue of unAckMessages @@ -148,7 +148,7 @@ public void action(String queueUrl, List receiptHandles) throws JMSExcep DeleteMessageBatchRequest deleteMessageBatchRequest = new DeleteMessageBatchRequest( queueUrl, deleteMessageBatchRequestEntries); - /** + /* * TODO: If one of the batch calls fail, then the remaining messages on * the batch will not be deleted, and will be visible and delivered as * duplicate after visibility timeout expires. diff --git a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/SQSMessageIdentifier.java b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/SQSMessageIdentifier.java index 443b578..bd350ee 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/SQSMessageIdentifier.java +++ b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/SQSMessageIdentifier.java @@ -14,7 +14,7 @@ */ package com.amazon.sqs.javamessaging.acknowledge; -import javax.jms.JMSException; +import jakarta.jms.JMSException; import com.amazon.sqs.javamessaging.message.SQSMessage; @@ -24,13 +24,13 @@ public class SQSMessageIdentifier { // The queueUrl where the message was sent or received from - private String queueUrl; + private final String queueUrl; // The receipt handle returned after the delivery of the message from SQS - private String receiptHandle; + private final String receiptHandle; // The SQS message id assigned on send. - private String sqsMessageId; + private final String sqsMessageId; // The group id to which the message belongs private String groupId; @@ -120,11 +120,8 @@ public boolean equals(Object obj) { } else if (!receiptHandle.equals(other.receiptHandle)) return false; if (sqsMessageId == null) { - if (other.sqsMessageId != null) - return false; - } else if (!sqsMessageId.equals(other.sqsMessageId)) - return false; - return true; + return other.sqsMessageId == null; + } else return sqsMessageId.equals(other.sqsMessageId); } @Override diff --git a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/UnorderedAcknowledger.java b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/UnorderedAcknowledger.java index f9dc6b8..ea17b82 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/acknowledge/UnorderedAcknowledger.java +++ b/src/main/java/com/amazon/sqs/javamessaging/acknowledge/UnorderedAcknowledger.java @@ -19,7 +19,7 @@ import java.util.List; import java.util.Map; -import javax.jms.JMSException; +import jakarta.jms.JMSException; import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; import com.amazon.sqs.javamessaging.SQSSession; @@ -44,7 +44,7 @@ public class UnorderedAcknowledger implements Acknowledger { public UnorderedAcknowledger (AmazonSQSMessagingClientWrapper amazonSQSClient, SQSSession session) { this.amazonSQSClient = amazonSQSClient; this.session = session; - this.unAckMessages = new HashMap(); + this.unAckMessages = new HashMap<>(); } /** @@ -73,7 +73,7 @@ public void notifyMessageReceived(SQSMessage message) throws JMSException { */ @Override public List getUnAckMessages() { - return new ArrayList(unAckMessages.values()); + return new ArrayList<>(unAckMessages.values()); } /** diff --git a/src/main/java/com/amazon/sqs/javamessaging/message/SQSBytesMessage.java b/src/main/java/com/amazon/sqs/javamessaging/message/SQSBytesMessage.java index d638b83..e93157d 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/message/SQSBytesMessage.java +++ b/src/main/java/com/amazon/sqs/javamessaging/message/SQSBytesMessage.java @@ -22,12 +22,12 @@ import java.io.IOException; import java.util.Arrays; -import javax.jms.BytesMessage; -import javax.jms.JMSException; -import javax.jms.MessageEOFException; -import javax.jms.MessageFormatException; -import javax.jms.MessageNotReadableException; -import javax.jms.MessageNotWriteableException; +import jakarta.jms.BytesMessage; +import jakarta.jms.JMSException; +import jakarta.jms.MessageEOFException; +import jakarta.jms.MessageFormatException; +import jakarta.jms.MessageNotReadableException; +import jakarta.jms.MessageNotWriteableException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -42,8 +42,7 @@ * licensed under Apache2.0. Its methods are based largely on those found in * java.io.DataInputStream and * java.io.DataOutputStream. - * - * @see org.apache.activemq.command.ActiveMQStreamMessage + * */ public class SQSBytesMessage extends SQSMessage implements BytesMessage { private static final Log LOG = LogFactory.getLog(SQSBytesMessage.class); @@ -62,9 +61,9 @@ public class SQSBytesMessage extends SQSMessage implements BytesMessage { public SQSBytesMessage(Acknowledger acknowledger, String queueUrl, Message sqsMessage) throws JMSException { super(acknowledger, queueUrl, sqsMessage); try { - /** Bytes is set by the reset() */ + // Bytes are set by the reset() dataOut.write(Base64.decode(sqsMessage.getBody())); - /** Makes it read-only */ + // Makes it read-only reset(); } catch (IOException e) { LOG.error("IOException: Message cannot be written", e); @@ -433,7 +432,7 @@ public int readBytes(byte[] value, int length) throws JMSException { } checkCanRead(); try { - /** + /* * Almost copy of readFully implementation except that EOFException * is not thrown if the stream is at the end of file and no byte is * available @@ -446,7 +445,7 @@ public int readBytes(byte[] value, int length) throws JMSException { } n += count; } - /** + /* * JMS specification mentions that the next read of the stream * returns -1 if the previous read consumed the byte stream and * there are no more bytes left to be read from the stream @@ -778,7 +777,7 @@ public void clearBody() throws JMSException { } /** - * Reads the body of message, which can be either the body returned from the + * Reads the body of message, which can be either the body returned from * the receives message as bytes or the bytes put in bytesOut if it is a * sent message. * diff --git a/src/main/java/com/amazon/sqs/javamessaging/message/SQSMessage.java b/src/main/java/com/amazon/sqs/javamessaging/message/SQSMessage.java index 04dbf3e..a5f4965 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/message/SQSMessage.java +++ b/src/main/java/com/amazon/sqs/javamessaging/message/SQSMessage.java @@ -16,6 +16,7 @@ import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; @@ -23,11 +24,11 @@ import java.util.Map; import java.util.Map.Entry; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageFormatException; -import javax.jms.MessageNotWriteableException; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageFormatException; +import jakarta.jms.MessageNotWriteableException; import com.amazon.sqs.javamessaging.SQSMessageConsumerPrefetch; import com.amazon.sqs.javamessaging.SQSMessagingClientConstants; @@ -56,11 +57,11 @@ *

*

* JMSXDeliveryCount reserved property is supported and set based on the - * approximate receive count observed on the SQS side. + * approximate Receive Count observed on the SQS side. */ public class SQSMessage implements Message { - private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); + private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; // Define constant message types. public static final String BYTE_MESSAGE_TYPE = "byte"; @@ -78,12 +79,13 @@ public class SQSMessage implements Message { private boolean redelivered; private String correlationID; private long expiration = Message.DEFAULT_TIME_TO_LIVE; + private long deliveryTime = Message.DEFAULT_DELIVERY_DELAY; private String messageID; private String type; private SQSQueueDestination replyTo; private Destination destination; - private final Map properties = new HashMap(); + private final Map properties = new HashMap<>(); private boolean writePermissionsForProperties; private boolean writePermissionsForBody; @@ -111,20 +113,16 @@ public class SQSMessage implements Message { * This is called at the receiver side to create a * JMS message from the SQS message received. */ - SQSMessage(Acknowledger acknowledger, String queueUrl, com.amazonaws.services.sqs.model.Message sqsMessage) throws JMSException{ + SQSMessage(Acknowledger acknowledger, String queueUrl, com.amazonaws.services.sqs.model.Message sqsMessage) throws JMSException { this.acknowledger = acknowledger; this.queueUrl = queueUrl; receiptHandle = sqsMessage.getReceiptHandle(); this.setSQSMessageId(sqsMessage.getMessageId()); - Map systemAttributes = sqsMessage.getAttributes(); + Map systemAttributes = sqsMessage.getAttributes(); int receiveCount = Integer.parseInt(systemAttributes.get(APPROXIMATE_RECEIVE_COUNT)); - - /** - * JMSXDeliveryCount is set based on SQS ApproximateReceiveCount - * attribute. - */ - properties.put(JMSX_DELIVERY_COUNT, new JMSMessagePropertyValue( - receiveCount, INT)); + + //JMSXDeliveryCount is set based on SQS ApproximateReceiveCount attribute + properties.put(JMSX_DELIVERY_COUNT, new JMSMessagePropertyValue(receiveCount, INT)); if (receiveCount > 1) { setJMSRedelivered(true); } @@ -141,7 +139,11 @@ public class SQSMessage implements Message { writePermissionsForProperties = false; } - private void mapSystemAttributeToJmsMessageProperty(Map systemAttributes, String systemAttributeName, String jmsMessagePropertyName) throws JMSException { + private void mapSystemAttributeToJmsMessageProperty( + Map systemAttributes, + String systemAttributeName, + String jmsMessagePropertyName + ) throws JMSException { String systemAttributeValue = systemAttributes.get(systemAttributeName); if (systemAttributeValue != null) { properties.put(jmsMessagePropertyName, new JMSMessagePropertyValue(systemAttributeValue, STRING)); @@ -195,15 +197,13 @@ protected void setBodyWritePermissions(boolean enable) { /** * Get SQS Message Group Id (applicable for FIFO queues, available also as JMS property 'JMSXGroupId') - * @throws JMSException */ public String getSQSMessageGroupId() throws JMSException { return getStringProperty(SQSMessagingClientConstants.JMSX_GROUP_ID); } /** - * Get SQS Message Deduplication Id (applicable for FIFO queues, available also as JMS property 'JMS_SQS_DeduplicationId') - * @throws JMSException + * Get SQS Message Deduplication ID (applicable for FIFO queues, available also as JMS property 'JMS_SQS_DeduplicationId') */ public String getSQSMessageDeduplicationId() throws JMSException { return getStringProperty(SQSMessagingClientConstants.JMS_SQS_DEDUPLICATION_ID); @@ -211,7 +211,6 @@ public String getSQSMessageDeduplicationId() throws JMSException { /** * Get SQS Message Sequence Number (applicable for FIFO queues, available also as JMS property 'JMS_SQS_SequenceNumber') - * @throws JMSException */ public String getSQSMessageSequenceNumber() throws JMSException { return getStringProperty(SQSMessagingClientConstants.JMS_SQS_SEQUENCE_NUMBER); @@ -227,7 +226,7 @@ public String getSQSMessageId() { } /** - * Set SQS Message Id, used on send. + * Set SQS Message ID, used on send. * * @param sqsMessageID * messageId assigned by SQS during send. @@ -337,7 +336,7 @@ public void setJMSReplyTo(Destination replyTo) throws JMSException { * message is being sent. *

* When a message is sent, this field is ignored. After completion of the - * send or publish method, the field holds the destination specified by the + * Send or Publish method, the field holds the destination specified by the * method. *

* When a message is received, its JMSDestination value must be equivalent @@ -404,6 +403,16 @@ public void setJMSExpiration(long expiration) throws JMSException { this.expiration = expiration; } + @Override + public long getJMSDeliveryTime() throws JMSException { + return deliveryTime; + } + + @Override + public void setJMSDeliveryTime(long deliveryTime) throws JMSException { + this.deliveryTime = deliveryTime; + } + @Override public int getJMSPriority() throws JMSException { return priority; @@ -415,7 +424,7 @@ public void setJMSPriority(int priority) throws JMSException { } /** - * Clears a message's properties and set the write permissions for + * Clears a message's properties and set the Write permissions for * properties. The message's header fields and body are not cleared. */ @Override @@ -686,22 +695,17 @@ public JMSMessagePropertyValue getJMSMessagePropertyValue(String name) throws JM return properties.get(name); } - private static class PropertyEnum implements Enumeration { - private final Iterator propertyItr; - - public PropertyEnum(Iterator propertyItr) { - this.propertyItr = propertyItr; - } + private record PropertyEnum(Iterator propertyItr) implements Enumeration { @Override public boolean hasMoreElements() { - return propertyItr.hasNext(); - } + return propertyItr.hasNext(); + } @Override public String nextElement() { - return propertyItr.next(); - } + return propertyItr.next(); + } } /** @@ -958,6 +962,16 @@ public void clearBody() throws JMSException { throw new JMSException("SQSMessage does not have any body"); } + @Override + public T getBody(Class c) throws JMSException { + throw new JMSException("Could not get SQSMessage body in " + c.getSimpleName()); + } + + @Override + public boolean isBodyAssignableTo(Class c) throws JMSException { + throw new JMSException("SQSMessage body is not assignable to " + c.getSimpleName()); + } + private boolean isValidPropertyValueType(Object value) { return value instanceof Boolean || value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof Float || @@ -971,59 +985,35 @@ private boolean isValidPropertyValueType(Object value) { */ public static class TypeConversionSupport { - static class ConversionKey { - final Class from; - - final Class to; + record ConversionKey(Class from, Class to) { - public ConversionKey(Class from, Class to) { - this.from = from; - this.to = to; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((from == null) ? 0 : from.hashCode()); - result = prime * result + ((to == null) ? 0 : to.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ConversionKey other = (ConversionKey) obj; - if (from == null) { - if (other.from != null) - return false; - } else if (!from.equals(other.from)) - return false; - if (to == null) { - if (other.to != null) - return false; - } else if (!to.equals(other.to)) - return false; - return true; - } - } + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ConversionKey other = (ConversionKey) obj; + if (from == null) { + if (other.from != null) + return false; + } else if (!from.equals(other.from)) + return false; + if (to == null) { + return other.to == null; + } else return to.equals(other.to); + } + } interface Converter { Object convert(Object value); } - static final private Map CONVERSION_MAP = new HashMap(); + static final private Map CONVERSION_MAP = new HashMap<>(); static { - Converter toStringConverter = new Converter() { - public Object convert(Object value) { - return value.toString(); - } - }; + Converter toStringConverter = Object::toString; CONVERSION_MAP.put(new ConversionKey(Boolean.class, String.class), toStringConverter); CONVERSION_MAP.put(new ConversionKey(Byte.class, String.class), toStringConverter); CONVERSION_MAP.put(new ConversionKey(Short.class, String.class), toStringConverter); @@ -1031,80 +1021,31 @@ public Object convert(Object value) { CONVERSION_MAP.put(new ConversionKey(Long.class, String.class), toStringConverter); CONVERSION_MAP.put(new ConversionKey(Float.class, String.class), toStringConverter); CONVERSION_MAP.put(new ConversionKey(Double.class, String.class), toStringConverter); - - CONVERSION_MAP.put(new ConversionKey(String.class, Boolean.class), new Converter() { - public Object convert(Object value) { - String stringValue = (String) value; - if (Boolean.valueOf(stringValue) || INT_TRUE.equals((String) value)) { - return Boolean.TRUE; - } - return Boolean.FALSE; - } - }); - CONVERSION_MAP.put(new ConversionKey(String.class, Byte.class), new Converter() { - public Object convert(Object value) { - return Byte.valueOf((String) value); - } - }); - CONVERSION_MAP.put(new ConversionKey(String.class, Short.class), new Converter() { - public Object convert(Object value) { - return Short.valueOf((String) value); - } - }); - CONVERSION_MAP.put(new ConversionKey(String.class, Integer.class), new Converter() { - public Object convert(Object value) { - return Integer.valueOf((String) value); - } - }); - CONVERSION_MAP.put(new ConversionKey(String.class, Long.class), new Converter() { - public Object convert(Object value) { - return Long.valueOf((String) value); - } - }); - CONVERSION_MAP.put(new ConversionKey(String.class, Float.class), new Converter() { - public Object convert(Object value) { - return Float.valueOf((String) value); - } - }); - CONVERSION_MAP.put(new ConversionKey(String.class, Double.class), new Converter() { - public Object convert(Object value) { - return Double.valueOf((String) value); + CONVERSION_MAP.put(new ConversionKey(String.class, Boolean.class), value -> { + String stringValue = (String) value; + if (Boolean.parseBoolean(stringValue) || INT_TRUE.equals(value)) { + return Boolean.TRUE; } + return Boolean.FALSE; }); - - Converter longConverter = new Converter() { - public Object convert(Object value) { - return Long.valueOf(((Number) value).longValue()); - } - }; + CONVERSION_MAP.put(new ConversionKey(String.class, Byte.class), value -> Byte.valueOf((String) value)); + CONVERSION_MAP.put(new ConversionKey(String.class, Short.class), value -> Short.valueOf((String) value)); + CONVERSION_MAP.put(new ConversionKey(String.class, Integer.class), value -> Integer.valueOf((String) value)); + CONVERSION_MAP.put(new ConversionKey(String.class, Long.class), value -> Long.valueOf((String) value)); + CONVERSION_MAP.put(new ConversionKey(String.class, Float.class), value -> Float.valueOf((String) value)); + CONVERSION_MAP.put(new ConversionKey(String.class, Double.class), value -> Double.valueOf((String) value)); + + Converter longConverter = value -> ((Number) value).longValue(); CONVERSION_MAP.put(new ConversionKey(Byte.class, Long.class), longConverter); CONVERSION_MAP.put(new ConversionKey(Short.class, Long.class), longConverter); CONVERSION_MAP.put(new ConversionKey(Integer.class, Long.class), longConverter); - CONVERSION_MAP.put(new ConversionKey(Date.class, Long.class), new Converter() { - public Object convert(Object value) { - return Long.valueOf(((Date) value).getTime()); - } - }); + CONVERSION_MAP.put(new ConversionKey(Date.class, Long.class), value -> ((Date) value).getTime()); - Converter intConverter = new Converter() { - public Object convert(Object value) { - return Integer.valueOf(((Number) value).intValue()); - } - }; + Converter intConverter = value -> ((Number) value).intValue(); CONVERSION_MAP.put(new ConversionKey(Byte.class, Integer.class), intConverter); CONVERSION_MAP.put(new ConversionKey(Short.class, Integer.class), intConverter); - - CONVERSION_MAP.put(new ConversionKey(Byte.class, Short.class), new Converter() { - public Object convert(Object value) { - return Short.valueOf(((Number) value).shortValue()); - } - }); - - CONVERSION_MAP.put(new ConversionKey(Float.class, Double.class), new Converter() { - public Object convert(Object value) { - return Double.valueOf(((Number) value).doubleValue()); - } - }); + CONVERSION_MAP.put(new ConversionKey(Byte.class, Short.class), value -> ((Number) value).shortValue()); + CONVERSION_MAP.put(new ConversionKey(Float.class, Double.class), value -> ((Number) value).doubleValue()); } @SuppressWarnings("unchecked") @@ -1115,7 +1056,7 @@ static public T convert(Object value, Class clazz) { if (value.getClass() == clazz) return (T) value; - Converter c = (Converter) CONVERSION_MAP.get(new ConversionKey(value.getClass(), clazz)); + Converter c = CONVERSION_MAP.get(new ConversionKey(value.getClass(), clazz)); if (c == null) return null; return (T) c.convert(value); @@ -1232,11 +1173,10 @@ public String getStringMessageAttributeValue() { /** * This method sets the JMS_SQS_SEQUENCE_NUMBER property on the message. It is exposed explicitly here, so that - * it can be invoked even on read-only message object obtained through receing a message. + * it can be invoked even on read-only message object obtained through receiving a message. * This support the use case of send a received message by using the same JMSMessage object. * * @param sequenceNumber Sequence number to set. If null or empty, the stored sequence number will be removed. - * @throws JMSException */ public void setSequenceNumber(String sequenceNumber) throws JMSException { if (sequenceNumber == null || sequenceNumber.isEmpty()) { @@ -1246,7 +1186,7 @@ public void setSequenceNumber(String sequenceNumber) throws JMSException { } } - /* + /** * Unit Test Utility Functions */ void setWritePermissionsForProperties(boolean writePermissionsForProperties) { diff --git a/src/main/java/com/amazon/sqs/javamessaging/message/SQSObjectMessage.java b/src/main/java/com/amazon/sqs/javamessaging/message/SQSObjectMessage.java index 52e5f11..e6d5a3d 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/message/SQSObjectMessage.java +++ b/src/main/java/com/amazon/sqs/javamessaging/message/SQSObjectMessage.java @@ -21,8 +21,10 @@ import java.io.ObjectOutputStream; import java.io.Serializable; -import javax.jms.JMSException; -import javax.jms.ObjectMessage; +import jakarta.jms.JMSException; +import jakarta.jms.MessageFormatException; +import jakarta.jms.MessageNotWriteableException; +import jakarta.jms.ObjectMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/src/main/java/com/amazon/sqs/javamessaging/message/SQSTextMessage.java b/src/main/java/com/amazon/sqs/javamessaging/message/SQSTextMessage.java index 89e7367..6d67b68 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/message/SQSTextMessage.java +++ b/src/main/java/com/amazon/sqs/javamessaging/message/SQSTextMessage.java @@ -14,8 +14,9 @@ */ package com.amazon.sqs.javamessaging.message; -import javax.jms.JMSException; -import javax.jms.TextMessage; +import jakarta.jms.JMSException; +import jakarta.jms.MessageNotWriteableException; +import jakarta.jms.TextMessage; import com.amazon.sqs.javamessaging.acknowledge.Acknowledger; import com.amazonaws.services.sqs.model.Message; diff --git a/src/main/java/com/amazon/sqs/javamessaging/util/ExponentialBackoffStrategy.java b/src/main/java/com/amazon/sqs/javamessaging/util/ExponentialBackoffStrategy.java index 04cfe29..9df8a33 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/util/ExponentialBackoffStrategy.java +++ b/src/main/java/com/amazon/sqs/javamessaging/util/ExponentialBackoffStrategy.java @@ -20,9 +20,9 @@ */ public class ExponentialBackoffStrategy { - private long delayInterval; - private long initialDelay; - private long maxDelay; + private final long delayInterval; + private final long initialDelay; + private final long maxDelay; public ExponentialBackoffStrategy(long delayInterval, long initialDelay, long maxDelay) { this.delayInterval = delayInterval; @@ -33,7 +33,7 @@ public ExponentialBackoffStrategy(long delayInterval, long initialDelay, long ma /** * Returns the delay before the next attempt. * - * @param retriesAttempted + * @param retriesAttempted number of retries attempted * @return The delay before the next attempt. */ public long delayBeforeNextRetry(int retriesAttempted) { diff --git a/src/main/java/com/amazon/sqs/javamessaging/util/SQSMessagingClientThreadFactory.java b/src/main/java/com/amazon/sqs/javamessaging/util/SQSMessagingClientThreadFactory.java index fbbf61c..33bf128 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/util/SQSMessagingClientThreadFactory.java +++ b/src/main/java/com/amazon/sqs/javamessaging/util/SQSMessagingClientThreadFactory.java @@ -73,7 +73,7 @@ public Thread newThread(Runnable r) { /** * Checks if the thread is member of the thread group * - * @param thread + * @param thread current thread * @return True If there is a thread group and the given thread is member of * the group */ diff --git a/src/main/java/com/amazon/sqs/javamessaging/util/SQSMessagingClientUtil.java b/src/main/java/com/amazon/sqs/javamessaging/util/SQSMessagingClientUtil.java index cb79d49..18f5346 100644 --- a/src/main/java/com/amazon/sqs/javamessaging/util/SQSMessagingClientUtil.java +++ b/src/main/java/com/amazon/sqs/javamessaging/util/SQSMessagingClientUtil.java @@ -51,7 +51,7 @@ public static String serializePropertyName(String name) { if (Character.isLetterOrDigit(ch) || HYPHEN == ch || DOT == ch) { stringBuilder.append(ch); } else { - stringBuilder.append(UNDERSCORE + Integer.toString((int) ch) + UNDERSCORE); + stringBuilder.append(UNDERSCORE).append((int) ch).append(UNDERSCORE); } } return stringBuilder.toString(); diff --git a/src/test/java/com/amazon/sqs/javamessaging/AcknowledgerCommon.java b/src/test/java/com/amazon/sqs/javamessaging/AcknowledgerCommon.java index deb279d..12ec55a 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/AcknowledgerCommon.java +++ b/src/test/java/com/amazon/sqs/javamessaging/AcknowledgerCommon.java @@ -22,16 +22,15 @@ import java.util.List; import java.util.Map; -import javax.jms.JMSException; +import jakarta.jms.JMSException; -import junit.framework.Assert; - -import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; import com.amazon.sqs.javamessaging.acknowledge.Acknowledger; import com.amazon.sqs.javamessaging.message.SQSMessage; import com.amazon.sqs.javamessaging.message.SQSTextMessage; import com.amazonaws.services.sqs.model.Message; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * Parent class for the Acknowledger tests */ @@ -40,7 +39,7 @@ public class AcknowledgerCommon { protected String baseQueueUrl = "queueUrl"; protected Acknowledger acknowledger; protected AmazonSQSMessagingClientWrapper amazonSQSClient; - protected List populatedMessages = new ArrayList(); + protected List populatedMessages = new ArrayList<>(); /* * Generate and populate the list with sqs message from different queues @@ -63,15 +62,15 @@ public void populateMessage(int populateMessageSize) throws JMSException { when(sqsMessage.getReceiptHandle()).thenReturn("ReceiptHandle" + i); when(sqsMessage.getMessageId()).thenReturn("MessageId" + i); // Add mock Attributes - Map mockAttributes = new HashMap(); + Map mockAttributes = new HashMap<>(); mockAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "2"); when(sqsMessage.getAttributes()).thenReturn(mockAttributes); - SQSMessage message = (SQSMessage) new SQSTextMessage(acknowledger, queueUrl, sqsMessage); + SQSMessage message = new SQSTextMessage(acknowledger, queueUrl, sqsMessage); populatedMessages.add(message); acknowledger.notifyMessageReceived(message); } - Assert.assertEquals(populateMessageSize, acknowledger.getUnAckMessages().size()); + assertEquals(populateMessageSize, acknowledger.getUnAckMessages().size()); } } diff --git a/src/test/java/com/amazon/sqs/javamessaging/AmazonSQSMessagingClientWrapperTest.java b/src/test/java/com/amazon/sqs/javamessaging/AmazonSQSMessagingClientWrapperTest.java index afcfd55..00e9a32 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/AmazonSQSMessagingClientWrapperTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/AmazonSQSMessagingClientWrapperTest.java @@ -14,7 +14,6 @@ */ package com.amazon.sqs.javamessaging; -import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.regions.Region; @@ -30,15 +29,17 @@ import com.amazonaws.services.sqs.model.ReceiveMessageRequest; import com.amazonaws.services.sqs.model.SendMessageRequest; -import javax.jms.InvalidDestinationException; -import javax.jms.JMSException; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.eq; +import jakarta.jms.InvalidDestinationException; +import jakarta.jms.JMSException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +//import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -54,496 +55,401 @@ public class AmazonSQSMessagingClientWrapperTest { private AmazonSQSClient amazonSQSClient; private AmazonSQSMessagingClientWrapper wrapper; - @Before + @BeforeEach public void setup() throws JMSException { amazonSQSClient = mock(AmazonSQSClient.class); wrapper = new AmazonSQSMessagingClientWrapper(amazonSQSClient); } - /* + /** * Test constructing client with null amazon sqs client */ - @Test(expected = JMSException.class) - public void testNullSQSClient() throws JMSException { - new AmazonSQSMessagingClientWrapper(null); + @Test + public void testNullSQSClient() { + assertThrows(JMSException.class, () -> new AmazonSQSMessagingClientWrapper(null)); } - /* + /** * Test set endpoint */ @Test public void testSetEndpoint() throws JMSException { - String endpoint = "endpoint"; wrapper.setEndpoint(endpoint); verify(amazonSQSClient).setEndpoint(eq(endpoint)); } - /* + /** * Test set endpoint wrap amazon sqs client exception */ - @Test(expected = JMSException.class) - public void testSetEndpointThrowIllegalArgumentException() throws JMSException { - + @Test + public void testSetEndpointThrowIllegalArgumentException() { String endpoint = "endpoint"; - doThrow(new IllegalArgumentException("iae")) - .when(amazonSQSClient).setEndpoint(eq(endpoint)); - - wrapper.setEndpoint(endpoint); + doThrow(new IllegalArgumentException("iae")).when(amazonSQSClient).setEndpoint(eq(endpoint)); + assertThrows(JMSException.class, () -> wrapper.setEndpoint(endpoint)); } - /* + /** * Test set region */ @Test public void testSetRegion() throws JMSException { - Region region = Region.getRegion(Regions.DEFAULT_REGION); wrapper.setRegion(region); verify(amazonSQSClient).setRegion(eq(region)); } - /* + /** * Test set region wrap amazon sqs client exception */ - @Test(expected = JMSException.class) - public void testSetRegionThrowIllegalArgumentException() throws JMSException { - + @Test + public void testSetRegionThrowIllegalArgumentException() { Region region = Region.getRegion(Regions.DEFAULT_REGION); - doThrow(new IllegalArgumentException("iae")) - .when(amazonSQSClient).setRegion(eq(region)); - - wrapper.setRegion(region); + doThrow(new IllegalArgumentException("iae")).when(amazonSQSClient).setRegion(eq(region)); + assertThrows(JMSException.class, () -> wrapper.setRegion(region)); } - /* + /** * Test delete message wrap amazon sqs client amazon client exception */ - @Test(expected = JMSException.class) - public void testDeleteMessageThrowAmazonClientException() throws JMSException { - + @Test + public void testDeleteMessageThrowAmazonClientException() { DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest(); - doThrow(new AmazonClientException("ace")) - .when(amazonSQSClient).deleteMessage(eq(deleteMessageRequest)); - - wrapper.deleteMessage(deleteMessageRequest); + doThrow(new AmazonClientException("ace")).when(amazonSQSClient).deleteMessage(eq(deleteMessageRequest)); + assertThrows(JMSException.class, () -> wrapper.deleteMessage(deleteMessageRequest)); } - /* + /** * Test delete message wrap amazon sqs client amazon service exception */ - @Test(expected = JMSException.class) - public void testDeleteMessageThrowAmazonServiceException() throws JMSException { - + @Test + public void testDeleteMessageThrowAmazonServiceException() { DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest(); - doThrow(new AmazonServiceException("ase")) - .when(amazonSQSClient).deleteMessage(eq(deleteMessageRequest)); - - wrapper.deleteMessage(deleteMessageRequest); + doThrow(new AmazonServiceException("ase")).when(amazonSQSClient).deleteMessage(eq(deleteMessageRequest)); + assertThrows(JMSException.class, () -> wrapper.deleteMessage(deleteMessageRequest)); } - /* + /** * Test delete message batch wrap amazon sqs client amazon client exception */ - @Test(expected = JMSException.class) - public void testDeleteMessageBatchThrowAmazonClientException() throws JMSException { - + @Test + public void testDeleteMessageBatchThrowAmazonClientException() { DeleteMessageBatchRequest deleteMessageBatchRequest = new DeleteMessageBatchRequest(); - doThrow(new AmazonClientException("ace")) - .when(amazonSQSClient).deleteMessageBatch(eq(deleteMessageBatchRequest)); - - wrapper.deleteMessageBatch(deleteMessageBatchRequest); + doThrow(new AmazonClientException("ace")).when(amazonSQSClient).deleteMessageBatch(eq(deleteMessageBatchRequest)); + assertThrows(JMSException.class, () -> wrapper.deleteMessageBatch(deleteMessageBatchRequest)); } - /* + /** * Test delete message batch wrap amazon sqs client amazon service exception */ - @Test(expected = JMSException.class) - public void testDeleteMessageBatchThrowAmazonServiceException() throws JMSException { - + @Test + public void testDeleteMessageBatchThrowAmazonServiceException() { DeleteMessageBatchRequest deleteMessageBatchRequest = new DeleteMessageBatchRequest(); - doThrow(new AmazonServiceException("ase")) - .when(amazonSQSClient).deleteMessageBatch(eq(deleteMessageBatchRequest)); - - wrapper.deleteMessageBatch(deleteMessageBatchRequest); + doThrow(new AmazonServiceException("ase")).when(amazonSQSClient).deleteMessageBatch(eq(deleteMessageBatchRequest)); + assertThrows(JMSException.class, () -> wrapper.deleteMessageBatch(deleteMessageBatchRequest)); } - /* + /** * Test send message batch wrap amazon sqs client amazon client exception */ - @Test(expected = JMSException.class) - public void testSendMessageThrowAmazonClientException() throws JMSException { - + @Test + public void testSendMessageThrowAmazonClientException() { SendMessageRequest sendMessageRequest = new SendMessageRequest(); - doThrow(new AmazonClientException("ace")) - .when(amazonSQSClient).sendMessage(eq(sendMessageRequest)); - - wrapper.sendMessage(sendMessageRequest); + doThrow(new AmazonClientException("ace")).when(amazonSQSClient).sendMessage(eq(sendMessageRequest)); + assertThrows(JMSException.class, () -> wrapper.sendMessage(sendMessageRequest)); } - /* + /** * Test send message batch wrap amazon sqs client amazon service exception */ - @Test(expected = JMSException.class) - public void testSendMessageThrowAmazonServiceException() throws JMSException { - + @Test + public void testSendMessageThrowAmazonServiceException() { SendMessageRequest sendMessageRequest = new SendMessageRequest(); - doThrow(new AmazonServiceException("ase")) - .when(amazonSQSClient).sendMessage(eq(sendMessageRequest)); - - wrapper.sendMessage(sendMessageRequest); + doThrow(new AmazonServiceException("ase")).when(amazonSQSClient).sendMessage(eq(sendMessageRequest)); + assertThrows(JMSException.class, () -> wrapper.sendMessage(sendMessageRequest)); } - /* + /** * Test getQueueUrl with queue name input */ @Test public void testGetQueueUrlQueueName() throws JMSException { - GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QUEUE_NAME); - wrapper.getQueueUrl(QUEUE_NAME); verify(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); } - /* + /** * Test getQueueUrl with queue name and owner account id input */ @Test public void testGetQueueUrlQueueNameWithAccountId() throws JMSException { - GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QUEUE_NAME); getQueueUrlRequest.setQueueOwnerAWSAccountId(OWNER_ACCOUNT_ID); - wrapper.getQueueUrl(QUEUE_NAME, OWNER_ACCOUNT_ID); verify(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); } - /* + /** * Test getQueueUrl with queue name input wrap amazon sqs client amazon client exception */ - @Test(expected = JMSException.class) + @Test public void testGetQueueUrlQueueNameThrowAmazonClientException() throws JMSException { - GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QUEUE_NAME); - doThrow(new AmazonClientException("ace")) - .when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); - - wrapper.getQueueUrl(QUEUE_NAME); + doThrow(new AmazonClientException("ace")).when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); + assertThrows(JMSException.class, () -> wrapper.getQueueUrl(QUEUE_NAME)); } - /* + /** * Test getQueueUrl with queue name input wrap amazon sqs client amazon service exception */ - @Test(expected = JMSException.class) - public void testGetQueueUrlQueueNameThrowAmazonServiceException() throws JMSException { - + @Test + public void testGetQueueUrlQueueNameThrowAmazonServiceException() { GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QUEUE_NAME); - doThrow(new AmazonServiceException("ase")) - .when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); - - wrapper.getQueueUrl(QUEUE_NAME); + doThrow(new AmazonServiceException("ase")).when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); + assertThrows(JMSException.class, () -> wrapper.getQueueUrl(QUEUE_NAME)); } - /* + /** * Test getQueueUrl with queue name input wrap amazon sqs queue does not exist exception */ - @Test(expected = InvalidDestinationException.class) - public void testGetQueueUrlQueueNameThrowQueueDoesNotExistException() throws JMSException { - + @Test + public void testGetQueueUrlQueueNameThrowQueueDoesNotExistException() { GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QUEUE_NAME); - doThrow(new QueueDoesNotExistException("qdnee")) - .when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); - - wrapper.getQueueUrl(QUEUE_NAME); + doThrow(new QueueDoesNotExistException("qdnee")).when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); + assertThrows(InvalidDestinationException.class, () -> wrapper.getQueueUrl(QUEUE_NAME)); } - /* + /** * Test getQueueUrl with queue name input wrap amazon sqs queue does not exist exception */ - @Test(expected = InvalidDestinationException.class) - public void testGetQueueUrlQueueNameWithAccountIdThrowQueueDoesNotExistException() throws JMSException { - + @Test + public void testGetQueueUrlQueueNameWithAccountIdThrowQueueDoesNotExistException() { GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QUEUE_NAME); getQueueUrlRequest.setQueueOwnerAWSAccountId(OWNER_ACCOUNT_ID); - doThrow(new QueueDoesNotExistException("qdnee")) - .when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); - - wrapper.getQueueUrl(QUEUE_NAME,OWNER_ACCOUNT_ID); + doThrow(new QueueDoesNotExistException("qdnee")).when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); + assertThrows(InvalidDestinationException.class, () -> wrapper.getQueueUrl(QUEUE_NAME,OWNER_ACCOUNT_ID)); } - /* + /** * Test getQueueUrl */ @Test public void testGetQueueUrl() throws JMSException { - GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QUEUE_NAME); - wrapper.getQueueUrl(getQueueUrlRequest); verify(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); } - /* + /** * Test getQueueUrl wrap amazon sqs amazon client exception */ - @Test(expected = JMSException.class) - public void testGetQueueUrlThrowAmazonClientException() throws JMSException { - + @Test + public void testGetQueueUrlThrowAmazonClientException() { GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QUEUE_NAME); - doThrow(new AmazonClientException("ace")) - .when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); - - wrapper.getQueueUrl(getQueueUrlRequest); + doThrow(new AmazonClientException("ace")).when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); + assertThrows(JMSException.class, () -> wrapper.getQueueUrl(getQueueUrlRequest)); } - /* + /** * Test getQueueUrl wrap amazon sqs amazon service exception */ - @Test(expected = JMSException.class) - public void testGetQueueUrlThrowAmazonServiceException() throws JMSException { - + @Test + public void testGetQueueUrlThrowAmazonServiceException() { GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QUEUE_NAME); - doThrow(new AmazonServiceException("ase")) - .when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); - - wrapper.getQueueUrl(QUEUE_NAME); + doThrow(new AmazonServiceException("ase")).when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); + assertThrows(JMSException.class, () -> wrapper.getQueueUrl(QUEUE_NAME)); } - /* + /** * Test queue exist */ @Test public void testQueueExistsWhenQueueIsPresent() throws JMSException { - assertTrue(wrapper.queueExists(QUEUE_NAME)); verify(amazonSQSClient).getQueueUrl(eq(new GetQueueUrlRequest(QUEUE_NAME))); } - /* + /** * Test queue exist when amazon sqs client throws QueueDoesNotExistException */ @Test public void testQueueExistsThrowQueueDoesNotExistException() throws JMSException { - GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QUEUE_NAME); - doThrow(new QueueDoesNotExistException("qdnee")) - .when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); - + doThrow(new QueueDoesNotExistException("qdnee")).when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); assertFalse(wrapper.queueExists(QUEUE_NAME)); } - /* + /** * Test queue exist when amazon sqs client throws AmazonClientException */ - @Test(expected = JMSException.class) - public void testQueueExistsThrowAmazonClientException() throws JMSException { - + @Test + public void testQueueExistsThrowAmazonClientException() { GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QUEUE_NAME); - doThrow(new AmazonClientException("ace")) - .when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); - - wrapper.queueExists(QUEUE_NAME); + doThrow(new AmazonClientException("ace")).when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); + assertThrows(JMSException.class, () -> wrapper.queueExists(QUEUE_NAME)); } - /* + /** * Test queue exist when amazon sqs client throws AmazonServiceException */ - @Test(expected = JMSException.class) - public void testQueueExistsThrowAmazonServiceException() throws JMSException { - + @Test + public void testQueueExistsThrowAmazonServiceException() { GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(QUEUE_NAME); - doThrow(new AmazonServiceException("ase")) - .when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); - - wrapper.queueExists(QUEUE_NAME); + doThrow(new AmazonServiceException("ase")).when(amazonSQSClient).getQueueUrl(eq(getQueueUrlRequest)); + assertThrows(JMSException.class, () -> wrapper.queueExists(QUEUE_NAME)); } - /* + /** * Test create queue with name input */ @Test public void testCreateQueueWithName() throws JMSException { - wrapper.createQueue(QUEUE_NAME); verify(amazonSQSClient).createQueue(new CreateQueueRequest(QUEUE_NAME)); } - /* + /** * Test create queue when amazon sqs client throws AmazonClientException */ - @Test(expected = JMSException.class) - public void testCreateQueueWithNameThrowAmazonClientException() throws JMSException { - - doThrow(new AmazonClientException("ace")) - .when(amazonSQSClient).createQueue(eq(new CreateQueueRequest(QUEUE_NAME))); - - wrapper.createQueue(QUEUE_NAME); + @Test + public void testCreateQueueWithNameThrowAmazonClientException() { + doThrow(new AmazonClientException("ace")).when(amazonSQSClient).createQueue(eq(new CreateQueueRequest(QUEUE_NAME))); + assertThrows(JMSException.class, () -> wrapper.createQueue(QUEUE_NAME)); } - /* + /** * Test create queue when amazon sqs client throws AmazonServiceException */ - @Test(expected = JMSException.class) - public void testCreateQueueWithNameThrowAmazonServiceException() throws JMSException { - - doThrow(new AmazonServiceException("ase")) - .when(amazonSQSClient).createQueue(eq(new CreateQueueRequest(QUEUE_NAME))); - - wrapper.createQueue(QUEUE_NAME); + @Test + public void testCreateQueueWithNameThrowAmazonServiceException() { + doThrow(new AmazonServiceException("ase")).when(amazonSQSClient).createQueue(eq(new CreateQueueRequest(QUEUE_NAME))); + assertThrows(JMSException.class, () -> wrapper.createQueue(QUEUE_NAME)); } - /* + /** * Test create queue */ @Test public void testCreateQueue() throws JMSException { - CreateQueueRequest createQueueRequest = new CreateQueueRequest(QUEUE_NAME); - wrapper.createQueue(createQueueRequest); verify(amazonSQSClient).createQueue(createQueueRequest); } - /* + /** * Test create queue when amazon sqs client throws AmazonClientException */ - @Test(expected = JMSException.class) - public void testCreateQueueThrowAmazonClientException() throws JMSException { - + @Test + public void testCreateQueueThrowAmazonClientException() { CreateQueueRequest createQueueRequest = new CreateQueueRequest(QUEUE_NAME); - doThrow(new AmazonClientException("ace")) - .when(amazonSQSClient).createQueue(eq(createQueueRequest)); - - wrapper.createQueue(createQueueRequest); + doThrow(new AmazonClientException("ace")).when(amazonSQSClient).createQueue(eq(createQueueRequest)); + assertThrows(JMSException.class, () -> wrapper.createQueue(createQueueRequest)); } - /* + /** * Test create queue when amazon sqs client throws AmazonServiceException */ - @Test(expected = JMSException.class) - public void testCreateQueueThrowAmazonServiceException() throws JMSException { - - + @Test + public void testCreateQueueThrowAmazonServiceException() { CreateQueueRequest createQueueRequest = new CreateQueueRequest(QUEUE_NAME); - doThrow(new AmazonServiceException("ase")) - .when(amazonSQSClient).createQueue(eq(createQueueRequest)); - - wrapper.createQueue(createQueueRequest); + doThrow(new AmazonServiceException("ase")).when(amazonSQSClient).createQueue(eq(createQueueRequest)); + assertThrows(JMSException.class, () -> wrapper.createQueue(createQueueRequest)); } - /* + /** * Test receive message */ @Test public void testReceiveMessage() throws JMSException { - ReceiveMessageRequest getQueueUrlRequest = new ReceiveMessageRequest(); wrapper.receiveMessage(getQueueUrlRequest); verify(amazonSQSClient).receiveMessage(getQueueUrlRequest); } - /* + /** * Test receive message when amazon sqs client throws AmazonClientException */ - @Test(expected = JMSException.class) - public void testReceiveMessageThrowAmazonClientException() throws JMSException { - + @Test + public void testReceiveMessageThrowAmazonClientException() { ReceiveMessageRequest getQueueUrlRequest = new ReceiveMessageRequest(); - doThrow(new AmazonClientException("ace")) - .when(amazonSQSClient).receiveMessage(eq(getQueueUrlRequest)); - - wrapper.receiveMessage(getQueueUrlRequest); + doThrow(new AmazonClientException("ace")).when(amazonSQSClient).receiveMessage(eq(getQueueUrlRequest)); + assertThrows(JMSException.class, () -> wrapper.receiveMessage(getQueueUrlRequest)); } - /* + /** * Test receive message when amazon sqs client throws AmazonServiceException */ - @Test(expected = JMSException.class) - public void testReceiveMessageThrowAmazonServiceException() throws JMSException { - + @Test + public void testReceiveMessageThrowAmazonServiceException() { ReceiveMessageRequest getQueueUrlRequest = new ReceiveMessageRequest(); - doThrow(new AmazonServiceException("ase")) - .when(amazonSQSClient).receiveMessage(eq(getQueueUrlRequest)); - - wrapper.receiveMessage(getQueueUrlRequest); + doThrow(new AmazonServiceException("ase")).when(amazonSQSClient).receiveMessage(eq(getQueueUrlRequest)); + assertThrows(JMSException.class, () -> wrapper.receiveMessage(getQueueUrlRequest)); } - /* + /** * Test change message visibility */ @Test public void testChangeMessageVisibility() throws JMSException { - ChangeMessageVisibilityRequest changeMessageVisibilityRequest = new ChangeMessageVisibilityRequest(); wrapper.changeMessageVisibility(changeMessageVisibilityRequest); verify(amazonSQSClient).changeMessageVisibility(changeMessageVisibilityRequest); } - /* + /** * Test change message visibility when amazon sqs client throws AmazonClientException */ - @Test(expected = JMSException.class) - public void testChangeMessageVisibilityThrowAmazonClientException() throws JMSException { - + @Test + public void testChangeMessageVisibilityThrowAmazonClientException() { ChangeMessageVisibilityRequest changeMessageVisibilityRequest = new ChangeMessageVisibilityRequest(); - doThrow(new AmazonClientException("ace")) - .when(amazonSQSClient).changeMessageVisibility(eq(changeMessageVisibilityRequest)); - - wrapper.changeMessageVisibility(changeMessageVisibilityRequest); + doThrow(new AmazonClientException("ace")).when(amazonSQSClient).changeMessageVisibility(eq(changeMessageVisibilityRequest)); + assertThrows(JMSException.class, () -> wrapper.changeMessageVisibility(changeMessageVisibilityRequest)); } - /* + /** * Test change message visibility when amazon sqs client throws AmazonServiceException */ - @Test(expected = JMSException.class) - public void testChangeMessageVisibilityThrowAmazonServiceException() throws JMSException { - + @Test + public void testChangeMessageVisibilityThrowAmazonServiceException() { ChangeMessageVisibilityRequest changeMessageVisibilityRequest = new ChangeMessageVisibilityRequest(); - doThrow(new AmazonServiceException("ase")) - .when(amazonSQSClient).changeMessageVisibility(eq(changeMessageVisibilityRequest)); - - wrapper.changeMessageVisibility(changeMessageVisibilityRequest); + doThrow(new AmazonServiceException("ase")).when(amazonSQSClient).changeMessageVisibility(eq(changeMessageVisibilityRequest)); + assertThrows(JMSException.class, () -> wrapper.changeMessageVisibility(changeMessageVisibilityRequest)); } - /* + /** * Test change message visibility batch */ @Test public void testChangeMessageVisibilityBatch() throws JMSException { - ChangeMessageVisibilityBatchRequest changeMessageVisibilityBatchRequest = new ChangeMessageVisibilityBatchRequest(); wrapper.changeMessageVisibilityBatch(changeMessageVisibilityBatchRequest); verify(amazonSQSClient).changeMessageVisibilityBatch(changeMessageVisibilityBatchRequest); } - /* + /** * Test change message visibility batch when amazon sqs client throws AmazonClientException */ - @Test(expected = JMSException.class) - public void testChangeMessageVisibilityBatchThrowAmazonClientException() throws JMSException { - + @Test + public void testChangeMessageVisibilityBatchThrowAmazonClientException() { ChangeMessageVisibilityBatchRequest changeMessageVisibilityBatchRequest = new ChangeMessageVisibilityBatchRequest(); doThrow(new AmazonClientException("ace")) .when(amazonSQSClient).changeMessageVisibilityBatch(eq(changeMessageVisibilityBatchRequest)); - - wrapper.changeMessageVisibilityBatch(changeMessageVisibilityBatchRequest); + assertThrows(JMSException.class, () -> wrapper.changeMessageVisibilityBatch(changeMessageVisibilityBatchRequest)); } - /* + /** * Test change message visibility batch when amazon sqs client throws AmazonServiceException */ - @Test(expected = JMSException.class) - public void testChangeMessageVisibilityBatchThrowAmazonServiceException() throws JMSException { - + @Test + public void testChangeMessageVisibilityBatchThrowAmazonServiceException() { ChangeMessageVisibilityBatchRequest changeMessageVisibilityBatchRequest = new ChangeMessageVisibilityBatchRequest(); doThrow(new AmazonServiceException("ase")) .when(amazonSQSClient).changeMessageVisibilityBatch(eq(changeMessageVisibilityBatchRequest)); - - wrapper.changeMessageVisibilityBatch(changeMessageVisibilityBatchRequest); + assertThrows(JMSException.class, () -> wrapper.changeMessageVisibilityBatch(changeMessageVisibilityBatchRequest)); } - /* + /** * Test get amazon SQS client */ @Test diff --git a/src/test/java/com/amazon/sqs/javamessaging/AutoAcknowledgerTest.java b/src/test/java/com/amazon/sqs/javamessaging/AutoAcknowledgerTest.java index 4559162..1106713 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/AutoAcknowledgerTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/AutoAcknowledgerTest.java @@ -14,22 +14,21 @@ */ package com.amazon.sqs.javamessaging; -import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; -import com.amazon.sqs.javamessaging.SQSSession; import com.amazon.sqs.javamessaging.acknowledge.AcknowledgeMode; import com.amazon.sqs.javamessaging.acknowledge.AutoAcknowledger; import com.amazon.sqs.javamessaging.acknowledge.SQSMessageIdentifier; import com.amazon.sqs.javamessaging.message.SQSMessage; import com.amazonaws.services.sqs.model.DeleteMessageRequest; -import javax.jms.IllegalStateException; +import jakarta.jms.IllegalStateException; import java.util.Collections; -import org.junit.Test; -import org.junit.Before; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -48,7 +47,7 @@ public class AutoAcknowledgerTest { private AmazonSQSMessagingClientWrapper amazonSQSClient; private SQSSession session; - @Before + @BeforeEach public void before() throws Exception { amazonSQSClient = mock(AmazonSQSMessagingClientWrapper.class); session = mock(SQSSession.class); @@ -61,23 +60,17 @@ public void before() throws Exception { @Test public void testAcknowledge() throws Exception { - /* - * Set up message mock - */ + // Set up message mock SQSMessage message = mock(SQSMessage.class); when(message.getQueueUrl()) .thenReturn(QUEUE_URL); when(message.getReceiptHandle()) .thenReturn(RECEIPT_HANDLE); - /* - * Use the acknowledger to ack the message - */ + // Use the acknowledger to ack the message acknowledger.acknowledge(message); - /* - * Verify results - */ + // Verify results ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(DeleteMessageRequest.class); verify(amazonSQSClient).deleteMessage(argumentCaptor.capture()); assertEquals(1, argumentCaptor.getAllValues().size()); @@ -93,9 +86,7 @@ public void testAcknowledge() throws Exception { @Test public void testAcknowledgeWhenSessionClosed() throws Exception { - /* - * Set up mocks - */ + // Set up mocks doThrow(new IllegalStateException("ise")) .when(session).checkClosed(); @@ -105,15 +96,8 @@ public void testAcknowledgeWhenSessionClosed() throws Exception { when(message.getReceiptHandle()) .thenReturn(RECEIPT_HANDLE); - /* - * Use the acknowledger to ack the message - */ - try { - acknowledger.acknowledge(message); - fail(); - } catch (IllegalStateException ise) { - // Expected exception - } + //Use the acknowledger to ack the message + assertThrows(IllegalStateException.class, () -> acknowledger.acknowledge(message)); } /** @@ -121,7 +105,6 @@ public void testAcknowledgeWhenSessionClosed() throws Exception { */ @Test public void testNotifyMessageReceived() throws Exception { - SQSMessage message = mock(SQSMessage.class); acknowledger.notifyMessageReceived(message); verify(acknowledger).acknowledge(message); @@ -132,7 +115,6 @@ public void testNotifyMessageReceived() throws Exception { */ @Test public void testGetUnAckMessages() throws Exception { - assertEquals(Collections.emptyList(), acknowledger.getUnAckMessages()); } } diff --git a/src/test/java/com/amazon/sqs/javamessaging/BulkSQSOperationTest.java b/src/test/java/com/amazon/sqs/javamessaging/BulkSQSOperationTest.java index cf816f0..3dab866 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/BulkSQSOperationTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/BulkSQSOperationTest.java @@ -17,14 +17,14 @@ import com.amazon.sqs.javamessaging.acknowledge.BulkSQSOperation; import com.amazon.sqs.javamessaging.acknowledge.SQSMessageIdentifier; -import javax.jms.JMSException; +import jakarta.jms.JMSException; import java.util.ArrayList; import java.util.List; -import org.junit.Test; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -39,13 +39,12 @@ public class BulkSQSOperationTest { private BulkSQSOperation bulkAction; - @Before + @BeforeEach public void before() throws Exception { bulkAction = spy(new BulkSQSOperation() { @Override - public void action(String queueUrl, List receiptHandles) throws JMSException { - return; + public void action(String queueUrl, List receiptHandles) { } }); } @@ -54,34 +53,18 @@ public void action(String queueUrl, List receiptHandles) throws JMSExcep * Test illegal index value cases */ @Test - public void testBulkActionIllegalIndexValue() throws Exception { - - List messageIdentifierList = new ArrayList(); - messageIdentifierList.add(new SQSMessageIdentifier(QUEUE_URL, "receiptHandle1", "sqsMessageId1")); - messageIdentifierList.add(new SQSMessageIdentifier(QUEUE_URL, "receiptHandle2", "sqsMessageId2")); - messageIdentifierList.add(new SQSMessageIdentifier(QUEUE_URL, "receiptHandle3", "sqsMessageId3")); - + public void testBulkActionIllegalIndexValue() { + List messageIdentifierList = List.of( + new SQSMessageIdentifier(QUEUE_URL, "receiptHandle1", "sqsMessageId1"), + new SQSMessageIdentifier(QUEUE_URL, "receiptHandle2", "sqsMessageId2"), + new SQSMessageIdentifier(QUEUE_URL, "receiptHandle3", "sqsMessageId3") + ); int negativeSize = -10; - try { - bulkAction.bulkAction(messageIdentifierList, negativeSize); - fail(); - } catch(AssertionError ae) { - // expected exception - } - - try { - bulkAction.bulkAction(messageIdentifierList, 0); - fail(); - } catch(AssertionError ae) { - // expected exception - } - try { - bulkAction.bulkAction(messageIdentifierList, 3); - fail(); - } catch(AssertionError ae) { - // expected exception - } + assertThrows(AssertionError.class, () -> bulkAction.bulkAction(messageIdentifierList, negativeSize)); + assertThrows(AssertionError.class, () -> bulkAction.bulkAction(messageIdentifierList, 0)); + assertThrows(AssertionError.class, () -> bulkAction.bulkAction( + messageIdentifierList, messageIdentifierList.size() + 1)); } /** diff --git a/src/test/java/com/amazon/sqs/javamessaging/ExponentialBackoffStrategyTest.java b/src/test/java/com/amazon/sqs/javamessaging/ExponentialBackoffStrategyTest.java index b6ff45d..56e008e 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/ExponentialBackoffStrategyTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/ExponentialBackoffStrategyTest.java @@ -15,11 +15,9 @@ package com.amazon.sqs.javamessaging; import com.amazon.sqs.javamessaging.util.ExponentialBackoffStrategy; +import org.junit.jupiter.api.Test; -import org.junit.Test; -import org.junit.Before; - -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test the ExponentialBackoffStrategy class @@ -27,27 +25,26 @@ public class ExponentialBackoffStrategyTest { private static final int DELAY_INTERVAL = 10; - private static final int INITAL_DELAY = 20; + private static final int INITIAL_DELAY = 20; private static final int MAX_DELAY = 300; /** * test delay with illegal value of retry attempts */ @Test - public void testDelayBeforeNextRetryNonPositiveRetryAttempt() throws Exception { - - ExponentialBackoffStrategy backoff = new ExponentialBackoffStrategy(DELAY_INTERVAL, INITAL_DELAY, MAX_DELAY); + public void testDelayBeforeNextRetryNonPositiveRetryAttempt() { + ExponentialBackoffStrategy backoff = new ExponentialBackoffStrategy(DELAY_INTERVAL, INITIAL_DELAY, MAX_DELAY); - assertEquals(INITAL_DELAY, backoff.delayBeforeNextRetry(0)); - assertEquals(INITAL_DELAY, backoff.delayBeforeNextRetry(-10)); + assertEquals(INITIAL_DELAY, backoff.delayBeforeNextRetry(0)); + assertEquals(INITIAL_DELAY, backoff.delayBeforeNextRetry(-10)); } /** * test first delay result in delay initial value */ @Test - public void testDelayBeforeNextRetryFirstAttempt() throws Exception { - ExponentialBackoffStrategy backoff = new ExponentialBackoffStrategy(DELAY_INTERVAL, INITAL_DELAY, MAX_DELAY); + public void testDelayBeforeNextRetryFirstAttempt() { + ExponentialBackoffStrategy backoff = new ExponentialBackoffStrategy(DELAY_INTERVAL, INITIAL_DELAY, MAX_DELAY); assertEquals(DELAY_INTERVAL, backoff.delayBeforeNextRetry(1)); } @@ -56,8 +53,8 @@ public void testDelayBeforeNextRetryFirstAttempt() throws Exception { * test delay from 2 to 1000 */ @Test - public void testDelayBeforeNextRetry() throws Exception { - ExponentialBackoffStrategy backoff = new ExponentialBackoffStrategy(DELAY_INTERVAL, INITAL_DELAY, MAX_DELAY); + public void testDelayBeforeNextRetry() { + ExponentialBackoffStrategy backoff = new ExponentialBackoffStrategy(DELAY_INTERVAL, INITIAL_DELAY, MAX_DELAY); assertEquals(20, backoff.delayBeforeNextRetry(2)); assertEquals(40, backoff.delayBeforeNextRetry(3)); diff --git a/src/test/java/com/amazon/sqs/javamessaging/MessageListenerConcurrentOperationTest.java b/src/test/java/com/amazon/sqs/javamessaging/MessageListenerConcurrentOperationTest.java index 0b62090..fed196f 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/MessageListenerConcurrentOperationTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/MessageListenerConcurrentOperationTest.java @@ -14,31 +14,25 @@ */ package com.amazon.sqs.javamessaging; -import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; -import com.amazon.sqs.javamessaging.SQSConnection; -import com.amazon.sqs.javamessaging.SQSMessageConsumer; -import com.amazon.sqs.javamessaging.SQSMessageConsumerPrefetch; -import com.amazon.sqs.javamessaging.SQSQueueDestination; -import com.amazon.sqs.javamessaging.SQSSession; -import com.amazon.sqs.javamessaging.SQSSessionCallbackScheduler; import com.amazon.sqs.javamessaging.acknowledge.AcknowledgeMode; import com.amazon.sqs.javamessaging.acknowledge.Acknowledger; import com.amazon.sqs.javamessaging.acknowledge.NegativeAcknowledger; import com.amazon.sqs.javamessaging.message.SQSMessage; - -import javax.jms.*; -import javax.jms.IllegalStateException; +import jakarta.jms.IllegalStateException; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageListener; +import jakarta.jms.Session; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -59,7 +53,7 @@ public class MessageListenerConcurrentOperationTest { /** * Message listener that creates a producer on the session */ - private MessageListener msgListenerCreatesProducer = new MessageListener() { + private final MessageListener msgListenerCreatesProducer = new MessageListener() { @Override public void onMessage(Message message) { try { @@ -73,7 +67,7 @@ public void onMessage(Message message) { /** * Message listener that creates a consumer on the session */ - private MessageListener msgListenerCreatesConsumer = new MessageListener() { + private final MessageListener msgListenerCreatesConsumer = new MessageListener() { @Override public void onMessage(Message message) { try { @@ -84,7 +78,7 @@ public void onMessage(Message message) { } }; - @Before + @BeforeEach public void Setup() throws JMSException { Acknowledger acknowledger = mock(Acknowledger.class); @@ -98,15 +92,15 @@ public void Setup() throws JMSException { SQSMessageConsumer consumer = mock(SQSMessageConsumer.class); - SQSMessageConsumerPrefetch preftecher = new SQSMessageConsumerPrefetch(sqsSessionRunnable, acknowledger, negativeAcknowledger, sqsDestination, + SQSMessageConsumerPrefetch prefetcher = new SQSMessageConsumerPrefetch(sqsSessionRunnable, acknowledger, negativeAcknowledger, sqsDestination, amazonSQSClient, NUMBER_OF_MESSAGES_TO_PREFETCH); - preftecher.setMessageConsumer(consumer); + prefetcher.setMessageConsumer(consumer); msgManager = mock(SQSMessageConsumerPrefetch.MessageManager.class); - when(msgManager.getMessage()) + when(msgManager.message()) .thenReturn(mock(SQSMessage.class)); - when(msgManager.getPrefetchManager()) - .thenReturn(preftecher); + when(msgManager.prefetchManager()) + .thenReturn(prefetcher); } /** @@ -290,8 +284,9 @@ public void verify() { } } - public void testConcurrentExecution(final MessageListener msgListener, final ConcurrentOperation operation) throws JMSException, InterruptedException { - + public void testConcurrentExecution( + final MessageListener msgListener, + final ConcurrentOperation operation) throws JMSException, InterruptedException { long start = System.currentTimeMillis(); // Start the session @@ -300,37 +295,24 @@ public void testConcurrentExecution(final MessageListener msgListener, final Con final CyclicBarrier startBarrier = new CyclicBarrier(2); final CountDownLatch finishLatch = new CountDownLatch(1); - Thread t1 = new Thread(new Runnable() { - @Override - public void run() { - try { - startBarrier.await(); - operation.applyOperation(); - } catch (JMSException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (BrokenBarrierException e) { - e.printStackTrace(); - } - finishLatch.countDown(); + Thread t1 = new Thread(() -> { + try { + startBarrier.await(); + operation.applyOperation(); + } catch (JMSException | InterruptedException | BrokenBarrierException e) { + e.printStackTrace(); } + finishLatch.countDown(); }); // Start the callback scheduler - Thread t2 = new Thread(new Runnable() { - @Override - public void run() { - - try { - startBarrier.await(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (BrokenBarrierException e) { - e.printStackTrace(); - } - session.getSqsSessionRunnable().scheduleCallBacks(msgListener, Collections.singletonList(msgManager)); + Thread t2 = new Thread(() -> { + try { + startBarrier.await(); + } catch (InterruptedException | BrokenBarrierException e) { + e.printStackTrace(); } + session.getSqsSessionRunnable().scheduleCallBacks(msgListener, Collections.singletonList(msgManager)); }); t1.start(); @@ -346,11 +328,11 @@ public void run() { */ private interface ConcurrentOperation { - public abstract void setup() throws JMSException; + void setup() throws JMSException; - public abstract void applyOperation() throws JMSException; + void applyOperation() throws JMSException; - public abstract void verify(); + void verify(); } } diff --git a/src/test/java/com/amazon/sqs/javamessaging/ModifyWaitTimeSecondsTest.java b/src/test/java/com/amazon/sqs/javamessaging/ModifyWaitTimeSecondsTest.java index 1c3d863..1bfd1fa 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/ModifyWaitTimeSecondsTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/ModifyWaitTimeSecondsTest.java @@ -22,7 +22,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class ModifyWaitTimeSecondsTest { - @DisplayName("Should be able to modify SQSMessageConsumerPrefetch.WAIT_TIME_SECONDS via Reflection") @Test public void waitTimeSecondsShouldBeModifiableViaReflection() throws NoSuchFieldException, IllegalAccessException { diff --git a/src/test/java/com/amazon/sqs/javamessaging/NegativeAcknowledgerTest.java b/src/test/java/com/amazon/sqs/javamessaging/NegativeAcknowledgerTest.java index afff08a..004b488 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/NegativeAcknowledgerTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/NegativeAcknowledgerTest.java @@ -14,28 +14,25 @@ */ package com.amazon.sqs.javamessaging; -import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; -import com.amazon.sqs.javamessaging.PrefetchManager; -import com.amazon.sqs.javamessaging.SQSMessageConsumerPrefetch; -import com.amazon.sqs.javamessaging.acknowledge.AcknowledgeMode; import com.amazon.sqs.javamessaging.acknowledge.NegativeAcknowledger; import com.amazon.sqs.javamessaging.message.SQSMessage; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchRequest; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchRequestEntry; +import jakarta.jms.JMSException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; -import javax.jms.JMSException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyList; -import static org.mockito.Matchers.eq; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -47,13 +44,12 @@ * Test the NegativeAcknowledger class */ public class NegativeAcknowledgerTest extends AcknowledgerCommon { - private static final String QUEUE_URL = "queueUrl"; private NegativeAcknowledger negativeAcknowledger; - @Before - public void setupRanded() throws JMSException { + @BeforeEach + public void setupRanded() { amazonSQSClient = mock(AmazonSQSMessagingClientWrapper.class); negativeAcknowledger = spy(new NegativeAcknowledger(amazonSQSClient)); } @@ -64,24 +60,15 @@ public void setupRanded() throws JMSException { @Test public void testNackBulkAction() throws JMSException { - /* - * Set up the message queue - */ - List receiptHandles = new ArrayList(); - receiptHandles.add("r0"); - receiptHandles.add("r1"); - receiptHandles.add("r2"); + // Set up the message queue + List receiptHandles = List.of("r0", "r1", "r2"); ArrayDeque messageQueue = addSQSMessageToQueue(3); - /* - * Nack the messages in bulk actions - */ + // Nack the messages in bulk actions negativeAcknowledger.bulkAction(messageQueue, QUEUE_URL); - /* - * Verify results - */ + // Verify results verify(negativeAcknowledger).action(QUEUE_URL, receiptHandles); } @@ -91,19 +78,13 @@ public void testNackBulkAction() throws JMSException { @Test public void testNackBulkActionLargeBatch() throws JMSException { - /* - * Set up the message queue - */ + // Set up the message queue ArrayDeque messageQueue = addSQSMessageToQueue(13); - /* - * Nack the messages in bulk actions - */ + // Nack the messages in bulk actions negativeAcknowledger.bulkAction(messageQueue, QUEUE_URL); - /* - * Verify results - */ + // Verify results verify(negativeAcknowledger, times(2)).action(eq(QUEUE_URL), anyList()); } @@ -112,8 +93,6 @@ public void testNackBulkActionLargeBatch() throws JMSException { */ @Test public void testAction() throws JMSException { - - List receiptHandles = new ArrayList(); receiptHandles.add("r0"); receiptHandles.add("r1"); @@ -132,7 +111,7 @@ public void testAction() throws JMSException { assertEquals(receiptHandles.size(), captureList.size()); for (ChangeMessageVisibilityBatchRequestEntry item : captureList) { - receiptHandles.contains(item.getReceiptHandle()); + assertTrue(receiptHandles.contains(item.getReceiptHandle())); } } @@ -141,10 +120,8 @@ public void testAction() throws JMSException { */ @Test public void testActionEmptyReceiptHandles() throws JMSException { - negativeAcknowledger.action(QUEUE_URL, null); - - negativeAcknowledger.action(QUEUE_URL, Collections.EMPTY_LIST); + negativeAcknowledger.action(QUEUE_URL, Collections.emptyList()); verify(amazonSQSClient, never()).changeMessageVisibilityBatch(any(ChangeMessageVisibilityBatchRequest.class)); } @@ -153,7 +130,6 @@ public void testActionEmptyReceiptHandles() throws JMSException { * Utility function */ private ArrayDeque addSQSMessageToQueue(int count) { - ArrayDeque messageQueue = new ArrayDeque(); diff --git a/src/test/java/com/amazon/sqs/javamessaging/RangedAcknowledgerTest.java b/src/test/java/com/amazon/sqs/javamessaging/RangedAcknowledgerTest.java index c29af73..8686666 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/RangedAcknowledgerTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/RangedAcknowledgerTest.java @@ -14,9 +14,6 @@ */ package com.amazon.sqs.javamessaging; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -26,19 +23,19 @@ import java.util.List; import java.util.Map; -import javax.jms.JMSException; +import jakarta.jms.JMSException; -import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; -import com.amazon.sqs.javamessaging.SQSSession; import com.amazon.sqs.javamessaging.acknowledge.AcknowledgeMode; import com.amazon.sqs.javamessaging.acknowledge.SQSMessageIdentifier; import com.amazon.sqs.javamessaging.message.SQSMessage; import com.amazonaws.services.sqs.model.DeleteMessageBatchRequest; -import junit.framework.Assert; - -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -47,7 +44,7 @@ */ public class RangedAcknowledgerTest extends AcknowledgerCommon { - @Before + @BeforeEach public void setupRanded() throws JMSException { amazonSQSClient = mock(AmazonSQSMessagingClientWrapper.class); acknowledger = AcknowledgeMode.ACK_RANGE.createAcknowledger(amazonSQSClient, mock(SQSSession.class)); @@ -62,7 +59,7 @@ public void testForget() throws JMSException { populateMessage(populateMessageSize); acknowledger.forgetUnAckMessages(); - Assert.assertEquals(0, acknowledger.getUnAckMessages().size()); + assertEquals(0, acknowledger.getUnAckMessages().size()); } /** @@ -76,7 +73,7 @@ public void testFullAck() throws JMSException { testAcknowledge(populateMessageSize, ackMessage); - Assert.assertEquals(0, acknowledger.getUnAckMessages().size()); + assertEquals(0, acknowledger.getUnAckMessages().size()); } /** @@ -151,9 +148,9 @@ public void testAcknowledge(int populateMessageSize, int indexOfMessageToAck) th SQSMessage message = populatedMessages.get(i); SQSMessageIdentifier sqsMessageIdentifier = new SQSMessageIdentifier(message.getQueueUrl(), message.getReceiptHandle(), message.getSQSMessageId()); - Assert.assertFalse(acknowledger.getUnAckMessages().contains(sqsMessageIdentifier)); + assertFalse(acknowledger.getUnAckMessages().contains(sqsMessageIdentifier)); } - Assert.assertEquals((populateMessageSize - indexOfMessageToAck - 1), acknowledger.getUnAckMessages().size()); + assertEquals((populateMessageSize - indexOfMessageToAck - 1), acknowledger.getUnAckMessages().size()); } } diff --git a/src/test/java/com/amazon/sqs/javamessaging/SQSConnectionFactoryTest.java b/src/test/java/com/amazon/sqs/javamessaging/SQSConnectionFactoryTest.java index 6cfa632..fbf89e9 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/SQSConnectionFactoryTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/SQSConnectionFactoryTest.java @@ -14,17 +14,17 @@ */ package com.amazon.sqs.javamessaging; -import javax.jms.JMSException; +import jakarta.jms.JMSException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.amazonaws.regions.Regions; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; -import static org.mockito.Mockito.*; -import static org.junit.Assert.*; - +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.mock; public class SQSConnectionFactoryTest { @@ -36,7 +36,7 @@ public void canUseDeprecatedBuilderToCreateFactory() throws JMSException { } @Test - public void canCreateFactoryWithDefaultProviderSettings() throws JMSException { + public void canCreateFactoryWithDefaultProviderSettings() { SQSConnectionFactory factory = new SQSConnectionFactory(new ProviderConfiguration()); //cannot actually attempt to create a connection because the default client builder depends on environment settings or instance configuration to be present //which we cannot guarantee on the builder fleet diff --git a/src/test/java/com/amazon/sqs/javamessaging/SQSConnectionTest.java b/src/test/java/com/amazon/sqs/javamessaging/SQSConnectionTest.java index bec4e41..93d5e20 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/SQSConnectionTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/SQSConnectionTest.java @@ -14,16 +14,15 @@ */ package com.amazon.sqs.javamessaging; -import javax.jms.*; -import javax.jms.IllegalStateException; - -import org.junit.Before; -import org.junit.Test; - -import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; -import com.amazon.sqs.javamessaging.SQSConnection; -import com.amazon.sqs.javamessaging.SQSQueueDestination; -import com.amazon.sqs.javamessaging.SQSSession; +import jakarta.jms.ExceptionListener; +import jakarta.jms.IllegalStateException; +import jakarta.jms.InvalidClientIDException; +import jakarta.jms.JMSException; +import jakarta.jms.Queue; +import jakarta.jms.Session; +import jakarta.jms.Topic; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; @@ -31,8 +30,14 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; /** * Test the SQSConnectionTest class @@ -45,13 +50,12 @@ public class SQSConnectionTest { private AmazonSQSMessagingClientWrapper amazonSQSClientJMSWrapper; private SQSConnection sqsConnection; private SQSQueueDestination destination; - private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); + private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); private SQSSession session1; private SQSSession session2; - @Before + @BeforeEach public void setup() throws JMSException { - destination = new SQSQueueDestination(QUEUE_NAME, QUEUE_URL); int numberOfMessagesToPrefetch = 10; @@ -69,81 +73,67 @@ public void setup() throws JMSException { */ @Test public void testUnsupportedFeatures() { - - try { - sqsConnection.createConnectionConsumer(destination, "messageSelector", null, 10); - fail(); - } catch (JMSException jmse) { - // expected - } - - try { - Topic topic = mock(Topic.class); - sqsConnection.createDurableConnectionConsumer(topic, "subscriptionName", "messageSelector", null, 10); - fail(); - } catch (JMSException jmse) { - // expected - } - - try { - Queue queue = mock(Queue.class); - sqsConnection.createConnectionConsumer(queue, "messageSelector", null, 10); - fail(); - } catch (JMSException jmse) { - // expected - } + Topic topic = mock(Topic.class); + Queue queue = mock(Queue.class); + + assertThrows(JMSException.class, + () -> sqsConnection.createConnectionConsumer( + destination, + "messageSelector", + null, + 10) + ); + + assertThrows(JMSException.class, + () -> sqsConnection.createDurableConnectionConsumer( + topic, + "subscriptionName", + "messageSelector", + null, + 10) + ); + + assertThrows(JMSException.class, + () -> sqsConnection.createConnectionConsumer( + queue, + "messageSelector", + null, + 10) + ); } /** * Test set client id when connection is closing */ @Test - public void testSetClientIdWhenClosing() throws JMSException { - - sqsConnection.setClosing(true); + public void testSetClientIdWhenClosing() { + sqsConnection.setClosing(); - try { - sqsConnection.setClientID("clientId"); - fail(); - } catch (IllegalStateException ise) { - assertEquals("Connection is closed or closing", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsConnection.setClientID("clientId"), + "Connection is closed or closing"); } /** * Test set client id on an invalid client id */ @Test - public void testSetClientIdInvalidClientId() throws JMSException { - - try { - sqsConnection.setClientID(null); - fail(); - } catch (InvalidClientIDException ice) { - assertEquals("ClientID is empty", ice.getMessage()); - } + public void testSetClientIdInvalidClientId() { + assertThrows(InvalidClientIDException.class, () -> sqsConnection.setClientID(null), + "ClientID is empty"); - try { - sqsConnection.setClientID(""); - fail(); - } catch (InvalidClientIDException ice) { - assertEquals("ClientID is empty", ice.getMessage()); - } + assertThrows(InvalidClientIDException.class, () -> sqsConnection.setClientID(""), + "ClientID is empty"); } /** * Test set client id when action on connection is already made */ @Test - public void testSetClientIdActionTaken() throws JMSException { - + public void testSetClientIdActionTaken() { sqsConnection.setActionOnConnectionTaken(true); - try { - sqsConnection.setClientID("id"); - fail(); - } catch (IllegalStateException ise) { - assertEquals("Client ID cannot be set after any action on the connection is taken", ise.getMessage()); - } + + assertThrows(IllegalStateException.class, () -> sqsConnection.setClientID("id"), + "Client ID cannot be set after any action on the connection is taken"); } /** @@ -151,15 +141,10 @@ public void testSetClientIdActionTaken() throws JMSException { */ @Test public void testSetClientId() throws JMSException { - sqsConnection.setClientID("id"); - try { - sqsConnection.setClientID("id2"); - fail(); - } catch (IllegalStateException ise) { - assertEquals("ClientID is already set", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsConnection.setClientID("id2"), + "ClientID is already set"); assertEquals("id", sqsConnection.getClientID()); } @@ -168,16 +153,11 @@ public void testSetClientId() throws JMSException { */ @Test public void testClosing() throws JMSException { - sqsConnection.checkClosing(); + sqsConnection.setClosing(); - sqsConnection.setClosing(true); - try { - sqsConnection.checkClosing(); - fail(); - } catch (IllegalStateException ise) { - assertEquals("Connection is closed or closing", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsConnection.checkClosing(), + "Connection is closed or closing"); } /** @@ -185,16 +165,11 @@ public void testClosing() throws JMSException { */ @Test public void testCheckClosed() throws JMSException { - sqsConnection.checkClosed(); - sqsConnection.setClosed(true); - try { - sqsConnection.checkClosed(); - fail(); - } catch (IllegalStateException ise) { - assertEquals("Connection is closed", ise.getMessage()); - } + + assertThrows(IllegalStateException.class, () -> sqsConnection.checkClosed(), + "Connection is closed"); } /** @@ -202,9 +177,7 @@ public void testCheckClosed() throws JMSException { */ @Test public void testExceptionListener() throws JMSException { - ExceptionListener listener = mock(ExceptionListener.class); - sqsConnection.setExceptionListener(listener); assertTrue(sqsConnection.isActionOnConnectionTaken()); @@ -217,19 +190,13 @@ public void testExceptionListener() throws JMSException { @Test public void testCloseWhenAlreadyClosed() throws JMSException { - /* - * Set up connection - */ + // Set up connection sqsConnection.setClosed(true); - /* - * Do close - */ + // Do close sqsConnection.close(); - /* - * Verify results - */ + // Verify results verify(session1, never()).close(); verify(session2, never()).close(); } @@ -240,38 +207,31 @@ public void testCloseWhenAlreadyClosed() throws JMSException { @Test public void testCloseWhenClosing() throws JMSException, InterruptedException { - /* - * Set up connection and mocks - */ - sqsConnection.setClosing(true); + // Set up connection and mocks + sqsConnection.setClosing(); final CountDownLatch beforeCloseCall= new CountDownLatch(1); final CountDownLatch passedCloseCall = new CountDownLatch(1); - /* - * call close in different thread - */ - executorService.execute(new Runnable() { - @Override - public void run() { - try { - beforeCloseCall.countDown(); - sqsConnection.close(); - passedCloseCall.countDown(); - } catch (JMSException e) { - e.printStackTrace(); - } + // call close in different thread + executorService.execute(() -> { + try { + beforeCloseCall.countDown(); + sqsConnection.close(); + passedCloseCall.countDown(); + } catch (JMSException e) { + e.printStackTrace(); } }); // Yield execution to allow the connection to wait - assertEquals(true, beforeCloseCall.await(10, TimeUnit.SECONDS)); + assertTrue(beforeCloseCall.await(10, TimeUnit.SECONDS)); Thread.sleep(10); - // Release the lock and ensure that we are still waiting since the did not run + // Release the lock and ensure that we are still waiting since the thread did not run synchronized (sqsConnection.getStateLock()) { sqsConnection.getStateLock().notifyAll(); } - assertEquals(false, passedCloseCall.await(2, TimeUnit.SECONDS)); + assertFalse(passedCloseCall.await(2, TimeUnit.SECONDS)); // Simulate connection closed sqsConnection.setClosed(true); @@ -289,19 +249,14 @@ public void run() { * Test close */ @Test - public void testClose() throws JMSException, InterruptedException { + public void testClose() throws JMSException { - /* - * Close - */ + // Close sqsConnection.close(); - /* - * Verify results - */ + // Verify results verify(session1).close(); verify(session1).close(); - assertTrue(sqsConnection.getSessions().isEmpty()); } @@ -309,30 +264,25 @@ public void testClose() throws JMSException, InterruptedException { * Test close from the callback thread */ @Test - public void testCloseThreadGroup() throws JMSException, InterruptedException { + public void testCloseThreadGroup() throws InterruptedException { final AtomicBoolean flag = new AtomicBoolean(false); final CountDownLatch passedCloseCall = new CountDownLatch(1); - Thread t = SQSSession.SESSION_THREAD_FACTORY.newThread(new Runnable() { - @Override - public void run() { - try { - sqsConnection.close(); - } catch (IllegalStateException e) { - flag.set(true); - } catch (JMSException e) { - e.printStackTrace(); - } - passedCloseCall.countDown(); + Thread t = SQSSession.SESSION_THREAD_FACTORY.newThread(() -> { + try { + sqsConnection.close(); + } catch (IllegalStateException e) { + flag.set(true); + } catch (JMSException e) { + e.printStackTrace(); } + passedCloseCall.countDown(); }); t.start(); - /* - * Verify results - */ + // Verify results passedCloseCall.await(); assertTrue(flag.get()); } @@ -343,24 +293,14 @@ public void run() { @Test public void testStopNoOpIfAlreadyClosed() throws JMSException { - /* - * Set up connection - */ + // Set up connection sqsConnection.close(); - /* - * stop consumer - */ - try { - sqsConnection.stop(); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Connection is closed", ise.getMessage()); - } + // stop consumer + assertThrows(IllegalStateException.class, () -> sqsConnection.stop(), + "Connection is closed"); - /* - * Verify results - */ + // Verify results verify(session1, never()).stop(); verify(session2, never()).stop(); } @@ -371,19 +311,13 @@ public void testStopNoOpIfAlreadyClosed() throws JMSException { @Test public void testStopNoOpIfNotRunning() throws JMSException { - /* - * Set up connection - */ + // Set up connection sqsConnection.setRunning(false); - /* - * stop connection - */ + // stop connection sqsConnection.stop(); - /* - * Verify results - */ + // Verify results verify(session1, never()).stop(); verify(session2, never()).stop(); } @@ -394,33 +328,25 @@ public void testStopNoOpIfNotRunning() throws JMSException { @Test public void testStopThreadGroup() throws JMSException, InterruptedException { - /* - * Set up connection - */ + // Set up connection final AtomicBoolean flag = new AtomicBoolean(false); final CountDownLatch passedStopCall = new CountDownLatch(1); sqsConnection.setRunning(true); - Thread t = SQSSession.SESSION_THREAD_FACTORY.newThread(new Runnable() { - @Override - public void run() { - - try { - sqsConnection.close(); - } catch (IllegalStateException e) { - flag.set(true); - } catch (JMSException e) { - e.printStackTrace(); - } - passedStopCall.countDown(); + Thread t = SQSSession.SESSION_THREAD_FACTORY.newThread(() -> { + try { + sqsConnection.close(); + } catch (IllegalStateException e) { + flag.set(true); + } catch (JMSException e) { + e.printStackTrace(); } + passedStopCall.countDown(); }); t.start(); - /* - * Verify results - */ + // Verify results passedStopCall.await(); assertTrue(flag.get()); verify(session1, never()).stop(); @@ -431,24 +357,15 @@ public void run() { * Test stop when connection is closing */ @Test - public void testStopWhenClosing() throws JMSException, InterruptedException { + public void testStopWhenClosing() throws JMSException { - /* - * Set up connection - */ - sqsConnection.setClosing(true); + // Set up connection + sqsConnection.setClosing(); sqsConnection.setRunning(true); - try { - sqsConnection.stop(); - fail(); - } catch (IllegalStateException e) { - //expected - } + assertThrows(IllegalStateException.class, () -> sqsConnection.stop()); - /* - * Verify results - */ + // Verify results verify(session1, never()).stop(); verify(session2, never()).stop(); } @@ -459,9 +376,7 @@ public void testStopWhenClosing() throws JMSException, InterruptedException { @Test public void testStopBlocksOnStateLock() throws InterruptedException, IllegalStateException { - /* - * Set up the latches and mocks - */ + // Set up the latches and mocks final CountDownLatch mainRelease = new CountDownLatch(1); final CountDownLatch holdStateLock = new CountDownLatch(1); final CountDownLatch beforeConnectionStopCall = new CountDownLatch(1); @@ -469,34 +384,28 @@ public void testStopBlocksOnStateLock() throws InterruptedException, IllegalStat sqsConnection.setRunning(true); // Run a thread to hold the stateLock - executorService.execute(new Runnable() { - @Override - public void run() { - try { - synchronized (sqsConnection.getStateLock()) { - holdStateLock.countDown(); - mainRelease.await(); - } - } catch (InterruptedException e) { - e.printStackTrace(); + executorService.execute(() -> { + try { + synchronized (sqsConnection.getStateLock()) { + holdStateLock.countDown(); + mainRelease.await(); } + } catch (InterruptedException e) { + e.printStackTrace(); } }); // Waiting for the thread to hold state lock holdStateLock.await(); - // Run another thread that tries to start the connection while state lock is been held - executorService.execute(new Runnable() { - @Override - public void run() { - try { - beforeConnectionStopCall.countDown(); - sqsConnection.stop(); - passedConnectionStopCall.countDown(); - } catch (JMSException e) { - e.printStackTrace(); - } + // Run another thread that tries to start the connection while state lock is being held + executorService.execute(() -> { + try { + beforeConnectionStopCall.countDown(); + sqsConnection.stop(); + passedConnectionStopCall.countDown(); + } catch (JMSException e) { + e.printStackTrace(); } }); @@ -504,7 +413,7 @@ public void run() { Thread.sleep(10); // Ensure that we wait on state lock - assertEquals(false, passedConnectionStopCall.await(2, TimeUnit.SECONDS)); + assertFalse(passedConnectionStopCall.await(2, TimeUnit.SECONDS)); // Release the thread holding the state lock mainRelease.countDown(); @@ -523,24 +432,14 @@ public void run() { @Test public void testStartNoOpIfAlreadyClosed() throws JMSException { - /* - * Set up conenction - */ + // Set up connection sqsConnection.close(); - /* - * Start connection - */ - try { - sqsConnection.start(); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Connection is closed", ise.getMessage()); - } + // Start connection + assertThrows(IllegalStateException.class, () -> sqsConnection.start(), + "Connection is closed"); - /* - * Verify results - */ + // Verify results verify(session1, never()).start(); verify(session2, never()).start(); } @@ -551,24 +450,14 @@ public void testStartNoOpIfAlreadyClosed() throws JMSException { @Test public void testStartNoOpIfClosing() throws JMSException { - /* - * Set up session - */ - sqsConnection.setClosing(true); + // Set up session + sqsConnection.setClosing(); - /* - * Start connection - */ - try { - sqsConnection.start(); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Connection is closed or closing", ise.getMessage()); - } + // Start connection + assertThrows(IllegalStateException.class, () -> sqsConnection.start(), + "Connection is closed or closing"); - /* - * Verify results - */ + // Verify results verify(session1, never()).start(); verify(session2, never()).start(); } @@ -579,19 +468,13 @@ public void testStartNoOpIfClosing() throws JMSException { @Test public void testStartNoOpIfRunning() throws JMSException { - /* - * Set up session - */ + // Set up session sqsConnection.setRunning(true); - /* - * Start connection - */ + // Start connection sqsConnection.start(); - /* - * Verify results - */ + // Verify results verify(session1, never()).start(); verify(session2, never()).start(); } @@ -602,43 +485,35 @@ public void testStartNoOpIfRunning() throws JMSException { @Test public void testStartBlocksOnStateLock() throws InterruptedException, IllegalStateException { - /* - * Set up the latches and mocks - */ + // Set up the latches and mocks final CountDownLatch mainRelease = new CountDownLatch(1); final CountDownLatch holdStateLock = new CountDownLatch(1); final CountDownLatch beforeConnectionStartCall = new CountDownLatch(1); final CountDownLatch passedConnectionStartCall = new CountDownLatch(1); // Run a thread to hold the stateLock - executorService.execute(new Runnable() { - @Override - public void run() { - try { - synchronized (sqsConnection.getStateLock()) { - holdStateLock.countDown(); - mainRelease.await(); - } - } catch (InterruptedException e) { - e.printStackTrace(); + executorService.execute(() -> { + try { + synchronized (sqsConnection.getStateLock()) { + holdStateLock.countDown(); + mainRelease.await(); } + } catch (InterruptedException e) { + e.printStackTrace(); } }); // Waiting for the thread to hold state lock holdStateLock.await(); - // Run another thread that tries to start the connection while state lock is been held - executorService.execute(new Runnable() { - @Override - public void run() { - try { - beforeConnectionStartCall.countDown(); - sqsConnection.start(); - passedConnectionStartCall.countDown(); - } catch (JMSException e) { - e.printStackTrace(); - } + // Run another thread that tries to start the connection while state lock is being held + executorService.execute(() -> { + try { + beforeConnectionStartCall.countDown(); + sqsConnection.start(); + passedConnectionStartCall.countDown(); + } catch (JMSException e) { + e.printStackTrace(); } }); @@ -646,7 +521,7 @@ public void run() { Thread.sleep(10); // Ensure that we wait on state lock - assertEquals(false, passedConnectionStartCall.await(2, TimeUnit.SECONDS)); + assertFalse(passedConnectionStartCall.await(2, TimeUnit.SECONDS)); // Release the thread holding the state lock mainRelease.countDown(); @@ -665,31 +540,17 @@ public void run() { @Test public void testCreateSessionNoOpIfAlreadyClosed() throws JMSException { - /* - * Set up connection - */ + // Set up connection sqsConnection.setClosed(true); - /* - * Create session - */ - try { - sqsConnection.createSession(true, 1); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Connection is closed", ise.getMessage()); - } + // Create session + assertThrows(IllegalStateException.class, () -> sqsConnection.createSession(true, 1), + "Connection is closed"); - try { - sqsConnection.createSession(false, 1); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Connection is closed", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsConnection.createSession(false, 1), + "Connection is closed"); - /* - * Verify results - */ + // Verify results verify(session1, never()).start(); verify(session2, never()).start(); } @@ -699,24 +560,13 @@ public void testCreateSessionNoOpIfAlreadyClosed() throws JMSException { */ @Test public void testCreateSessionUnsupportedFeatures() throws JMSException { + assertThrows(JMSException.class, () -> sqsConnection.createSession(true, Session.AUTO_ACKNOWLEDGE), + "SQSSession does not support transacted"); - try { - sqsConnection.createSession(true, Session.AUTO_ACKNOWLEDGE); - fail(); - } catch(JMSException ise) { - assertEquals("SQSSession does not support transacted", ise.getMessage()); - } - - try { - sqsConnection.createSession(false, Session.SESSION_TRANSACTED); - fail(); - } catch(JMSException ise) { - assertEquals("SQSSession does not support transacted", ise.getMessage()); - } + assertThrows(JMSException.class, () -> sqsConnection.createSession(false, Session.SESSION_TRANSACTED), + "SQSSession does not support transacted"); - /* - * Verify results - */ + // Verify results verify(session1, never()).start(); verify(session2, never()).start(); } @@ -725,26 +575,16 @@ public void testCreateSessionUnsupportedFeatures() throws JMSException { * Test create session when connection is closing */ @Test - public void testCreateSessionWhenClosing() throws JMSException { + public void testCreateSessionWhenClosing() { - /* - * Set up connection - */ - sqsConnection.setClosing(true); + // Set up connection + sqsConnection.setClosing(); - /* - * Start connection - */ - try { - sqsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Connection is closed or closing", ise.getMessage()); - } + // Start connection + assertThrows(IllegalStateException.class, () -> sqsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE), + "Connection is closed or closing"); - /* - * Verify results - */ + // Verify results assertEquals(2, sqsConnection.getSessions().size()); } @@ -752,21 +592,13 @@ public void testCreateSessionWhenClosing() throws JMSException { * Test create session */ @Test - public void testCreateSessionUnknownAckMode() throws JMSException { + public void testCreateSessionUnknownAckMode() { - /* - * Craete session - */ - try { - sqsConnection.createSession(false, 42); - } catch (JMSException jmse) { - assertEquals("Unrecognized acknowledgeMode. Cannot create Session.", jmse.getMessage()); - } + // Create session + assertThrows(JMSException.class, () -> sqsConnection.createSession(false, 42), + "Unrecognized acknowledgeMode. Cannot create Session."); - - /* - * Verify results - */ + // Verify results assertEquals(2, sqsConnection.getSessions().size()); } @@ -775,7 +607,6 @@ public void testCreateSessionUnknownAckMode() throws JMSException { */ @Test public void testCreateSessionWhenConnectionRunning() throws JMSException { - sqsConnection.setRunning(true); SQSSession session = (SQSSession)sqsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -803,9 +634,8 @@ public void testCreateSessionWhenConnectionRunning() throws JMSException { assertTrue(sqsConnection.getSessions().contains(session)); assertTrue(session.isRunning()); - /* - * Verify results - */ + + // Verify results assertEquals(6, sqsConnection.getSessions().size()); } @@ -814,7 +644,6 @@ public void testCreateSessionWhenConnectionRunning() throws JMSException { */ @Test public void testCreateSessionWhenConnectionStopped() throws JMSException { - sqsConnection.setRunning(false); SQSSession session = (SQSSession)sqsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -852,45 +681,37 @@ public void testCreateSessionWhenConnectionStopped() throws JMSException { * Test CreateSession blocks on state lock */ @Test - public void testCreateSessionBlocksOnStateLock() throws InterruptedException, IllegalStateException { + public void testCreateSessionBlocksOnStateLock() throws InterruptedException { - /* - * Set up the latches and mocks - */ + // Set up the latches and mocks final CountDownLatch mainRelease = new CountDownLatch(1); final CountDownLatch holdStateLock = new CountDownLatch(1); final CountDownLatch beforeCreateSessionStartCall = new CountDownLatch(1); final CountDownLatch passedCreateSessionStartCall = new CountDownLatch(1); // Run a thread to hold the stateLock - executorService.execute(new Runnable() { - @Override - public void run() { - try { - synchronized (sqsConnection.getStateLock()) { - holdStateLock.countDown(); - mainRelease.await(); - } - } catch (InterruptedException e) { - e.printStackTrace(); + executorService.execute(() -> { + try { + synchronized (sqsConnection.getStateLock()) { + holdStateLock.countDown(); + mainRelease.await(); } + } catch (InterruptedException e) { + e.printStackTrace(); } }); // Waiting for the thread to hold state lock holdStateLock.await(); - // Run another thread that tries to start the connection while state lock is been held - executorService.execute(new Runnable() { - @Override - public void run() { - try { - beforeCreateSessionStartCall.countDown(); - sqsConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - passedCreateSessionStartCall.countDown(); - } catch (JMSException e) { - e.printStackTrace(); - } + // Run another thread that tries to start the connection while state lock is being held + executorService.execute(() -> { + try { + beforeCreateSessionStartCall.countDown(); + sqsConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + passedCreateSessionStartCall.countDown(); + } catch (JMSException e) { + e.printStackTrace(); } }); @@ -898,7 +719,7 @@ public void run() { Thread.sleep(10); // Ensure that we wait on state lock - assertEquals(false, passedCreateSessionStartCall.await(2, TimeUnit.SECONDS)); + assertFalse(passedCreateSessionStartCall.await(2, TimeUnit.SECONDS)); assertEquals(2, sqsConnection.getSessions().size()); // Release the thread holding the state lock diff --git a/src/test/java/com/amazon/sqs/javamessaging/SQSMessageConsumerPrefetchFifoTest.java b/src/test/java/com/amazon/sqs/javamessaging/SQSMessageConsumerPrefetchFifoTest.java index 014691f..18865a2 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/SQSMessageConsumerPrefetchFifoTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/SQSMessageConsumerPrefetchFifoTest.java @@ -14,11 +14,6 @@ */ package com.amazon.sqs.javamessaging; -import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; -import com.amazon.sqs.javamessaging.SQSConnection; -import com.amazon.sqs.javamessaging.SQSMessageConsumerPrefetch; -import com.amazon.sqs.javamessaging.SQSQueueDestination; -import com.amazon.sqs.javamessaging.SQSSessionCallbackScheduler; import com.amazon.sqs.javamessaging.acknowledge.Acknowledger; import com.amazon.sqs.javamessaging.acknowledge.NegativeAcknowledger; import com.amazon.sqs.javamessaging.message.SQSBytesMessage; @@ -26,31 +21,30 @@ import com.amazon.sqs.javamessaging.message.SQSObjectMessage; import com.amazon.sqs.javamessaging.message.SQSTextMessage; import com.amazon.sqs.javamessaging.util.ExponentialBackoffStrategy; +import com.amazonaws.services.sqs.model.MessageAttributeValue; +import com.amazonaws.services.sqs.model.ReceiveMessageRequest; +import com.amazonaws.services.sqs.model.ReceiveMessageResult; import com.amazonaws.util.Base64; -import com.amazonaws.services.sqs.model.*; - -import javax.jms.*; +import jakarta.jms.JMSException; +import jakarta.jms.ObjectMessage; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.mockito.ArgumentMatcher; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.argThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -59,48 +53,26 @@ /** * Test the SQSMessageConsumerPrefetchTest class */ -@RunWith(Parameterized.class) public class SQSMessageConsumerPrefetchFifoTest { - private static final String NAMESPACE = "123456789012"; private static final String QUEUE_NAME = "QueueName.fifo"; private static final String QUEUE_URL = NAMESPACE + "/" + QUEUE_NAME; - private Acknowledger acknowledger; private NegativeAcknowledger negativeAcknowledger; - private SQSSessionCallbackScheduler sqsSessionRunnable; private SQSMessageConsumerPrefetch consumerPrefetch; - private ExponentialBackoffStrategy backoffStrategy; private AmazonSQSMessagingClientWrapper amazonSQSClient; - @Parameters - public static List getParameters() { - return Arrays.asList(new Object[][] { {0}, {1}, {5}, {10}, {15} }); - } - - private final int numberOfMessagesToPrefetch; - - public SQSMessageConsumerPrefetchFifoTest(int numberOfMessagesToPrefetch) { - this.numberOfMessagesToPrefetch = numberOfMessagesToPrefetch; - } - - @Before - public void setup() { - + public void init(int numberOfMessagesToPrefetch) { amazonSQSClient = mock(AmazonSQSMessagingClientWrapper.class); SQSConnection parentSQSConnection = mock(SQSConnection.class); when(parentSQSConnection.getWrappedAmazonSQSClient()).thenReturn(amazonSQSClient); - sqsSessionRunnable = mock(SQSSessionCallbackScheduler.class); - - acknowledger = mock(Acknowledger.class); - + SQSSessionCallbackScheduler sqsSessionRunnable = mock(SQSSessionCallbackScheduler.class); + Acknowledger acknowledger = mock(Acknowledger.class); negativeAcknowledger = mock(NegativeAcknowledger.class); - - backoffStrategy = mock(ExponentialBackoffStrategy.class); - + ExponentialBackoffStrategy backoffStrategy = mock(ExponentialBackoffStrategy.class); SQSQueueDestination sqsDestination = new SQSQueueDestination(QUEUE_NAME, QUEUE_URL); consumerPrefetch = @@ -113,15 +85,14 @@ public void setup() { /** * Test one full prefetch operation works as expected */ - @Test - public void testOneFullPrefetch() throws InterruptedException, JMSException { - - /* - * Set up consumer prefetch and mocks - */ + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testOneFullPrefetch(int numberOfMessagesToPrefetch) throws InterruptedException, JMSException { + init(numberOfMessagesToPrefetch); + // Set up consumer prefetch and mocks final int numMessages = numberOfMessagesToPrefetch > 0 ? numberOfMessagesToPrefetch : 1; - List messages = new ArrayList(); + List messages = new ArrayList<>(); for (int i = 0; i < numMessages; i++) { messages.add(createValidFifoMessage(i, "G" + i)); } @@ -131,22 +102,25 @@ public void testOneFullPrefetch() throws InterruptedException, JMSException { // Mock SQS call for receive message and return messages final int receiveMessageLimit = Math.min(10, numMessages); - when(amazonSQSClient.receiveMessage(argThat(new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - if (!(argument instanceof ReceiveMessageRequest)) - return false; - ReceiveMessageRequest other = (ReceiveMessageRequest)argument; - - return other.getQueueUrl().equals(QUEUE_URL) - && other.getMaxNumberOfMessages() == receiveMessageLimit - && other.getMessageAttributeNames().size() == 1 - && other.getMessageAttributeNames().get(0).equals(SQSMessageConsumerPrefetch.ALL) - && other.getWaitTimeSeconds() == SQSMessageConsumerPrefetch.WAIT_TIME_SECONDS - && other.getReceiveRequestAttemptId() != null - && other.getReceiveRequestAttemptId().length() > 0; - } - }))) + when(amazonSQSClient.receiveMessage(argThat(new BaseMatcher<>() { + + @Override + public void describeTo(Description description) { + + } + @Override + public boolean matches(Object argument) { + if (!(argument instanceof ReceiveMessageRequest other)) + return false; + return other.getQueueUrl().equals(QUEUE_URL) + && other.getMaxNumberOfMessages() == receiveMessageLimit + && other.getMessageAttributeNames().size() == 1 + && other.getMessageAttributeNames().get(0).equals(SQSMessageConsumerPrefetch.ALL) + && other.getWaitTimeSeconds() == SQSMessageConsumerPrefetch.WAIT_TIME_SECONDS + && other.getReceiveRequestAttemptId() != null + && other.getReceiveRequestAttemptId().length() > 0; + } + }))) .thenReturn(new ReceiveMessageResult().withMessages(messages)); // Mock isClosed and exit after a single prefetch loop @@ -156,19 +130,11 @@ public boolean matches(Object argument) { .thenReturn(false) .thenReturn(true); - /* - * Request a message (only relevant when prefetching is off). - */ + // Request a message (only relevant when prefetching is off). consumerPrefetch.requestMessage(); - - /* - * Run the prefetch - */ - consumerPrefetch.run(); - /* - * Verify the results - */ + // Run the prefetch + consumerPrefetch.run(); // Ensure Consumer was started verify(consumerPrefetch).waitForStart(); @@ -177,7 +143,7 @@ public boolean matches(Object argument) { verify(consumerPrefetch).waitForPrefetch(); // Ensure no message was nack - verify(negativeAcknowledger).action(QUEUE_URL, new ArrayList()); + verify(negativeAcknowledger).action(QUEUE_URL, new ArrayList<>()); // Ensure retries attempt was not increased assertEquals(0, consumerPrefetch.retriesAttempted); @@ -187,11 +153,27 @@ public boolean matches(Object argument) { int index = 0; for (SQSMessageConsumerPrefetch.MessageManager messageManager : consumerPrefetch.messageQueue) { com.amazonaws.services.sqs.model.Message mockedMessage = messages.get(index); - SQSMessage sqsMessage = (SQSMessage)messageManager.getMessage(); - assertEquals("Receipt handle is the same", mockedMessage.getReceiptHandle(), sqsMessage.getReceiptHandle()); - assertEquals("Group id is the same", mockedMessage.getAttributes().get(SQSMessagingClientConstants.MESSAGE_GROUP_ID), sqsMessage.getStringProperty(SQSMessagingClientConstants.JMSX_GROUP_ID)); - assertEquals("Sequence number is the same", mockedMessage.getAttributes().get(SQSMessagingClientConstants.SEQUENCE_NUMBER), sqsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_SEQUENCE_NUMBER)); - assertEquals("Deduplication id is the same", mockedMessage.getAttributes().get(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID), sqsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_DEDUPLICATION_ID)); + SQSMessage sqsMessage = (SQSMessage)messageManager.message(); + assertEquals( + mockedMessage.getReceiptHandle(), + sqsMessage.getReceiptHandle(), + "Receipt handle is the same" + ); + assertEquals( + mockedMessage.getAttributes().get(SQSMessagingClientConstants.MESSAGE_GROUP_ID), + sqsMessage.getStringProperty(SQSMessagingClientConstants.JMSX_GROUP_ID), + "Group id is the same" + ); + assertEquals( + mockedMessage.getAttributes().get(SQSMessagingClientConstants.SEQUENCE_NUMBER), + sqsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_SEQUENCE_NUMBER), + "Sequence number is the same" + ); + assertEquals( + mockedMessage.getAttributes().get(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID), + sqsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_DEDUPLICATION_ID), + "Deduplication id is the same" + ); index++; } @@ -200,42 +182,48 @@ public boolean matches(Object argument) { /** * Test ConvertToJMSMessage when message type is not set in the message attribute */ - @Test - public void testConvertToJMSMessageNoTypeAttribute() throws JMSException { + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testConvertToJMSMessageNoTypeAttribute(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); - /* - * Set up consumer prefetch and mocks - */ + // Set up consumer prefetch and mocks com.amazonaws.services.sqs.model.Message message = createValidFifoMessage(1, "G"); + // Return message attribute with no message type attribute message.setBody("MessageBody"); - /* - * Convert the SQS message to JMS Message - */ - javax.jms.Message jmsMessage = consumerPrefetch.convertToJMSMessage(message); + // Convert the SQS message to JMS Message + jakarta.jms.Message jmsMessage = consumerPrefetch.convertToJMSMessage(message); - /* - * Verify results - */ + // Verify results assertTrue(jmsMessage instanceof SQSTextMessage); assertEquals(((SQSTextMessage) jmsMessage).getText(), "MessageBody"); - assertEquals(message.getAttributes().get(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID), jmsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_DEDUPLICATION_ID)); - assertEquals(message.getAttributes().get(SQSMessagingClientConstants.SEQUENCE_NUMBER), jmsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_SEQUENCE_NUMBER)); - assertEquals(message.getAttributes().get(SQSMessagingClientConstants.MESSAGE_GROUP_ID), jmsMessage.getStringProperty(SQSMessagingClientConstants.JMSX_GROUP_ID)); + assertEquals( + message.getAttributes().get(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID), + jmsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_DEDUPLICATION_ID) + ); + assertEquals( + message.getAttributes().get(SQSMessagingClientConstants.SEQUENCE_NUMBER), + jmsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_SEQUENCE_NUMBER) + ); + assertEquals( + message.getAttributes().get(SQSMessagingClientConstants.MESSAGE_GROUP_ID), + jmsMessage.getStringProperty(SQSMessagingClientConstants.JMSX_GROUP_ID) + ); } /** * Test ConvertToJMSMessage with byte message type */ - @Test - public void testConvertToJMSMessageByteTypeAttribute() throws JMSException, IOException { - - /* - * Set up consumer prefetch and mocks - */ + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testConvertToJMSMessageByteTypeAttribute(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); + // Set up consumer prefetch and mocks com.amazonaws.services.sqs.model.Message message = createValidFifoMessage(1, "G"); + // Return message attributes with message type 'BYTE' MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.BYTE_MESSAGE_TYPE); @@ -245,34 +233,39 @@ public void testConvertToJMSMessageByteTypeAttribute() throws JMSException, IOEx byte[] byteArray = new byte[] { 1, 0, 'a', 65 }; message.setBody(Base64.encodeAsString(byteArray)); - /* - * Convert the SQS message to JMS Message - */ - javax.jms.Message jmsMessage = consumerPrefetch.convertToJMSMessage(message); + // Convert the SQS message to JMS Message + jakarta.jms.Message jmsMessage = consumerPrefetch.convertToJMSMessage(message); - /* - * Verify results - */ + // Verify results assertTrue(jmsMessage instanceof SQSBytesMessage); for (byte b : byteArray) { assertEquals(b, ((SQSBytesMessage)jmsMessage).readByte()); } - assertEquals(message.getAttributes().get(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID), jmsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_DEDUPLICATION_ID)); - assertEquals(message.getAttributes().get(SQSMessagingClientConstants.SEQUENCE_NUMBER), jmsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_SEQUENCE_NUMBER)); - assertEquals(message.getAttributes().get(SQSMessagingClientConstants.MESSAGE_GROUP_ID), jmsMessage.getStringProperty(SQSMessagingClientConstants.JMSX_GROUP_ID)); + assertEquals( + message.getAttributes().get(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID), + jmsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_DEDUPLICATION_ID) + ); + assertEquals( + message.getAttributes().get(SQSMessagingClientConstants.SEQUENCE_NUMBER), + jmsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_SEQUENCE_NUMBER) + ); + assertEquals( + message.getAttributes().get(SQSMessagingClientConstants.MESSAGE_GROUP_ID), + jmsMessage.getStringProperty(SQSMessagingClientConstants.JMSX_GROUP_ID) + ); } /** * Test ConvertToJMSMessage with byte message that contains illegal sqs message body */ - @Test - public void testConvertToJMSMessageByteTypeIllegalBody() throws JMSException, IOException { - - /* - * Set up consumer prefetch and mocks - */ + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testConvertToJMSMessageByteTypeIllegalBody(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); + // Set up consumer prefetch and mocks com.amazonaws.services.sqs.model.Message message = createValidFifoMessage(1, "G"); + // Return message attributes with message type 'BYTE' MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.BYTE_MESSAGE_TYPE); @@ -281,27 +274,19 @@ public void testConvertToJMSMessageByteTypeIllegalBody() throws JMSException, IO // Return illegal message body for byte message type message.setBody("Text Message"); - /* - * Convert the SQS message to JMS Message - */ - try { - consumerPrefetch.convertToJMSMessage(message); - fail("Expect JMSException"); - } catch (JMSException jmse) { - // Expected JMS exception - } + // Convert the SQS message to JMS Message + assertThrows(JMSException.class, () -> consumerPrefetch.convertToJMSMessage(message)); } /** * Test ConvertToJMSMessage with an object message */ - @Test - public void testConvertToJMSMessageObjectTypeAttribute() throws JMSException, IOException { - - /* - * Set up consumer prefetch and mocks - */ + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testConvertToJMSMessageObjectTypeAttribute(int numberOfMessagesToPrefetch) throws JMSException, IOException { + init(numberOfMessagesToPrefetch); + // Set up consumer prefetch and mocks com.amazonaws.services.sqs.model.Message message = createValidFifoMessage(1, "G"); // Return message attributes with message type 'OBJECT' MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); @@ -310,7 +295,7 @@ public void testConvertToJMSMessageObjectTypeAttribute() throws JMSException, IO message.getMessageAttributes().put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); // Encode an object to byte array - Integer integer = new Integer("10"); + Integer integer = 10; ByteArrayOutputStream array = new ByteArrayOutputStream(10); ObjectOutputStream oStream = new ObjectOutputStream(array); oStream.writeObject(integer); @@ -318,14 +303,10 @@ public void testConvertToJMSMessageObjectTypeAttribute() throws JMSException, IO message.setBody(Base64.encodeAsString(array.toByteArray())); - /* - * Convert the SQS message to JMS Message - */ - javax.jms.Message jmsMessage = consumerPrefetch.convertToJMSMessage(message); + // Convert the SQS message to JMS Message + jakarta.jms.Message jmsMessage = consumerPrefetch.convertToJMSMessage(message); - /* - * Verify results - */ + // Verify results assertTrue(jmsMessage instanceof SQSObjectMessage); assertEquals(integer, ((SQSObjectMessage) jmsMessage).getObject()); assertEquals(message.getAttributes().get(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID), jmsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_DEDUPLICATION_ID)); @@ -336,13 +317,12 @@ public void testConvertToJMSMessageObjectTypeAttribute() throws JMSException, IO /** * Test ConvertToJMSMessage with an object message that contains illegal sqs message body */ - @Test - public void testConvertToJMSMessageObjectIllegalBody() throws JMSException, IOException { - - /* - * Set up consumer prefetch and mocks - */ + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testConvertToJMSMessageObjectIllegalBody(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); + // Set up consumer prefetch and mocks com.amazonaws.services.sqs.model.Message message = createValidFifoMessage(1, "G"); // Return message attributes with message type 'OBJECT' MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); @@ -351,69 +331,70 @@ public void testConvertToJMSMessageObjectIllegalBody() throws JMSException, IOEx message.getMessageAttributes().put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); message.setBody("Some text that does not represent an object"); - /* - * Convert the SQS message to JMS Message - */ + // Convert the SQS message to JMS Message ObjectMessage jmsMessage = (ObjectMessage) consumerPrefetch.convertToJMSMessage(message); - /* - * Verify results - */ - try { - jmsMessage.getObject(); - fail("Expect JMSException"); - } catch (JMSException jmse) { - // Expected JMS exception - } + // Verify results + assertThrows(JMSException.class, jmsMessage::getObject); } /** * Test ConvertToJMSMessage with text message with text type attribute */ - @Test - public void testConvertToJMSMessageTextTypeAttribute() throws JMSException, IOException { - - /* - * Set up consumer prefetch and mocks - */ + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testConvertToJMSMessageTextTypeAttribute(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); + // Set up consumer prefetch and mocks com.amazonaws.services.sqs.model.Message message = createValidFifoMessage(1, "G"); + // Return message attributes with message type 'TEXT' MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.TEXT_MESSAGE_TYPE); messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING); message.getMessageAttributes().put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); message.setBody("MessageBody"); - - /* - * Convert the SQS message to JMS Message - */ - javax.jms.Message jmsMessage = consumerPrefetch.convertToJMSMessage(message); - - /* - * Verify results - */ + + // Convert the SQS message to JMS Message + jakarta.jms.Message jmsMessage = consumerPrefetch.convertToJMSMessage(message); + + // Verify results assertTrue(jmsMessage instanceof SQSTextMessage); assertEquals(message.getBody(), "MessageBody"); - assertEquals(message.getAttributes().get(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID), jmsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_DEDUPLICATION_ID)); - assertEquals(message.getAttributes().get(SQSMessagingClientConstants.SEQUENCE_NUMBER), jmsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_SEQUENCE_NUMBER)); - assertEquals(message.getAttributes().get(SQSMessagingClientConstants.MESSAGE_GROUP_ID), jmsMessage.getStringProperty(SQSMessagingClientConstants.JMSX_GROUP_ID)); + assertEquals(message.getAttributes().get(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID), + jmsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_DEDUPLICATION_ID)); + assertEquals(message.getAttributes().get(SQSMessagingClientConstants.SEQUENCE_NUMBER), + jmsMessage.getStringProperty(SQSMessagingClientConstants.JMS_SQS_SEQUENCE_NUMBER)); + assertEquals(message.getAttributes().get(SQSMessagingClientConstants.MESSAGE_GROUP_ID), + jmsMessage.getStringProperty(SQSMessagingClientConstants.JMSX_GROUP_ID)); } - /* + /** * Utility functions */ - private com.amazonaws.services.sqs.model.Message createValidFifoMessage(int messageNumber, String groupId) { - Map mapAttributes = new HashMap(); - mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); - mapAttributes.put(SQSMessagingClientConstants.SEQUENCE_NUMBER, "10000000000000000000" + messageNumber); - mapAttributes.put(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID, "d" + messageNumber); - mapAttributes.put(SQSMessagingClientConstants.MESSAGE_GROUP_ID, groupId); + Map mapAttributes = Map.of( + SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1", + SQSMessagingClientConstants.SEQUENCE_NUMBER, "10000000000000000000" + messageNumber, + SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID, "d" + messageNumber, + SQSMessagingClientConstants.MESSAGE_GROUP_ID, groupId); return new com.amazonaws.services.sqs.model.Message() .withReceiptHandle("r" + messageNumber) .withAttributes(mapAttributes); } + /** + * MethodSource + */ + private static Stream prefetchParameters() { + return Stream.of( + Arguments.of(0), + Arguments.of(1), + Arguments.of(5), + Arguments.of(10), + Arguments.of(15) + ); + } } diff --git a/src/test/java/com/amazon/sqs/javamessaging/SQSMessageConsumerPrefetchTest.java b/src/test/java/com/amazon/sqs/javamessaging/SQSMessageConsumerPrefetchTest.java index 0dafd5d..8671b4c 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/SQSMessageConsumerPrefetchTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/SQSMessageConsumerPrefetchTest.java @@ -14,14 +14,16 @@ */ package com.amazon.sqs.javamessaging; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.eq; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; @@ -37,34 +39,28 @@ import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.IntStream; +import java.util.stream.Stream; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.ObjectMessage; - -import org.joda.time.DateTime; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageListener; +import jakarta.jms.ObjectMessage; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import com.amazon.sqs.javamessaging.SQSMessageConsumerPrefetch.MessageManager; @@ -84,19 +80,11 @@ * Test the SQSMessageConsumerPrefetchTest class */ @SuppressWarnings("unchecked") -@RunWith(Parameterized.class) public class SQSMessageConsumerPrefetchTest { private static final String NAMESPACE = "123456789012"; private static final String QUEUE_NAME = "QueueName"; private static final String QUEUE_URL = NAMESPACE + "/" + QUEUE_NAME; - - @Parameters - public static List getParameters() { - return Arrays.asList(new Object[][] { {0}, {1}, {5}, {10}, {15} }); - } - - private final int numberOfMessagesToPrefetch; private Acknowledger acknowledger; private NegativeAcknowledger negativeAcknowledger; @@ -104,16 +92,10 @@ public static List getParameters() { private SQSMessageConsumerPrefetch consumerPrefetch; private ExponentialBackoffStrategy backoffStrategy; - private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); private AmazonSQSMessagingClientWrapper amazonSQSClient; - public SQSMessageConsumerPrefetchTest(int numberOfMessagesToPrefetch) { - this.numberOfMessagesToPrefetch = numberOfMessagesToPrefetch; - } - - @Before - public void setup() { - + public void init(int numberOfMessagesToPrefetch) { amazonSQSClient = mock(AmazonSQSMessagingClientWrapper.class); SQSConnection parentSQSConnection = mock(SQSConnection.class); @@ -129,8 +111,7 @@ public void setup() { SQSQueueDestination sqsDestination = new SQSQueueDestination(QUEUE_NAME, QUEUE_URL); - consumerPrefetch = - spy(new SQSMessageConsumerPrefetch(sqsSessionRunnable, acknowledger, negativeAcknowledger, + consumerPrefetch = spy(new SQSMessageConsumerPrefetch(sqsSessionRunnable, acknowledger, negativeAcknowledger, sqsDestination, amazonSQSClient, numberOfMessagesToPrefetch)); consumerPrefetch.backoffStrategy = backoffStrategy; @@ -139,9 +120,10 @@ public void setup() { /** * Test one full prefetch operation works as expected */ - @Test - public void testEndToEnd() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testEndToEnd(int numberOfMessagesToPrefetch) throws InterruptedException, JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ @@ -151,51 +133,40 @@ public void testEndToEnd() throws InterruptedException, JMSException { // Create messages return from SQS final int numMessages = numberOfMessagesToPrefetch > 0 ? numberOfMessagesToPrefetch : 1; - final List receipt = new ArrayList(); - for (int i = 0; i < numMessages; ++i) { - receipt.add("r" + i); - } + final List receipt = createReceiptHandlersList(numMessages); ReceiveMessageResult receivedMessageResult = createReceiveMessageResult(receipt); // Mock SQS call for receive message and return messages int receiveMessageLimit = Math.min(10, numMessages); when(amazonSQSClient.receiveMessage( - eq(new ReceiveMessageRequest(QUEUE_URL) - .withMaxNumberOfMessages(receiveMessageLimit) - .withAttributeNames(SQSMessageConsumerPrefetch.ALL) - .withMessageAttributeNames(SQSMessageConsumerPrefetch.ALL) - .withWaitTimeSeconds(SQSMessageConsumerPrefetch.WAIT_TIME_SECONDS)))) - .thenReturn(receivedMessageResult); + eq(new ReceiveMessageRequest(QUEUE_URL) + .withMaxNumberOfMessages(receiveMessageLimit) + .withAttributeNames(SQSMessageConsumerPrefetch.ALL) + .withMessageAttributeNames(SQSMessageConsumerPrefetch.ALL) + .withWaitTimeSeconds(SQSMessageConsumerPrefetch.WAIT_TIME_SECONDS)))) + .thenReturn(receivedMessageResult); // Mock isClosed and exit after a single prefetch loop when(consumerPrefetch.isClosed()) - .thenReturn(false) - .thenReturn(false) - .thenReturn(false) - .thenAnswer(new Answer() { - - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - // Ensure message queue was filled with expected messages - //after we return 'isClosed() == true' we will empty the prefetch queue while nacking messages - assertEquals(numMessages, consumerPrefetch.messageQueue.size()); - for (SQSMessageConsumerPrefetch.MessageManager messageManager : consumerPrefetch.messageQueue) { - SQSMessage sqsMessage = (SQSMessage)messageManager.getMessage(); - assertTrue(receipt.contains(sqsMessage.getReceiptHandle())); - } - - return true; - } - }); + .thenReturn(false) + .thenReturn(false) + .thenReturn(false) + .thenAnswer((Answer) invocation -> { + // Ensure message queue was filled with expected messages + // after we return 'isClosed() == true' we will empty the prefetch queue while nacking messages + assertEquals(numMessages, consumerPrefetch.messageQueue.size()); + for (MessageManager messageManager : consumerPrefetch.messageQueue) { + SQSMessage sqsMessage = (SQSMessage)messageManager.message(); + assertTrue(receipt.contains(sqsMessage.getReceiptHandle())); + } + return true; + }); - /* - * Request a message (only relevant when prefetching is off). - */ + // Request a message (only relevant when prefetching is off). consumerPrefetch.requestMessage(); - /* - * Run the prefetch - */ + + // Run the prefetch consumerPrefetch.run(); /* @@ -209,7 +180,7 @@ public Boolean answer(InvocationOnMock invocation) throws Throwable { verify(consumerPrefetch).waitForPrefetch(); // Ensure no message was nack - verify(negativeAcknowledger).action(QUEUE_URL, new ArrayList()); + verify(negativeAcknowledger).action(QUEUE_URL, new ArrayList<>()); // Ensure retries attempt was not increased assertEquals(0, consumerPrefetch.retriesAttempted); @@ -217,7 +188,7 @@ public Boolean answer(InvocationOnMock invocation) throws Throwable { // Ensure message queue was filled with expected messages assertEquals(numMessages, consumerPrefetch.messageQueue.size()); for (SQSMessageConsumerPrefetch.MessageManager messageManager : consumerPrefetch.messageQueue) { - SQSMessage sqsMessage = (SQSMessage)messageManager.getMessage(); + SQSMessage sqsMessage = (SQSMessage)messageManager.message(); assertTrue(receipt.contains(sqsMessage.getReceiptHandle())); } } @@ -225,9 +196,10 @@ public Boolean answer(InvocationOnMock invocation) throws Throwable { /** * Test that a get message is not called when consumer is closed while waiting for prefetch */ - @Test - public void testStopWhenConsumerClosedDuringWaitForPrefetch() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testStopWhenConsumerClosedDuringWaitForPrefetch(int numberOfMessagesToPrefetch) throws InterruptedException, JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ @@ -273,16 +245,16 @@ public void testStopWhenConsumerClosedDuringWaitForPrefetch() throws Interrupted /** * Test prefetch is stopped after Interrupt in waitForStart */ - @Test - public void testStopAfterInterruptWaitForStart() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testStopAfterInterruptWaitForStart(int numberOfMessagesToPrefetch) throws InterruptedException, JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ consumerPrefetch.start(); - doThrow(new InterruptedException("Interrupt")) - .when(consumerPrefetch).waitForStart(); + doThrow(new InterruptedException("Interrupt")).when(consumerPrefetch).waitForStart(); /* * Run the prefetch @@ -298,7 +270,7 @@ public void testStopAfterInterruptWaitForStart() throws InterruptedException, JM verify(consumerPrefetch, never()).waitForPrefetch(); verify(consumerPrefetch, never()).getMessages(anyInt(), anyInt()); - verify(consumerPrefetch, never()).processReceivedMessages(any(List.class)); + verify(consumerPrefetch, never()).processReceivedMessages(anyList()); // Ensure retries attempt was not increased assertEquals(0, consumerPrefetch.retriesAttempted); @@ -307,37 +279,31 @@ public void testStopAfterInterruptWaitForStart() throws InterruptedException, JM /** * Test prefetch is stopped after Error in waitForStart */ - @Test - public void testStopAfterErrorWaitForStart() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testStopAfterErrorWaitForStart(int numberOfMessagesToPrefetch) throws InterruptedException, JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ consumerPrefetch.start(); - doThrow(new Error("error")) - .when(consumerPrefetch).waitForStart(); + doThrow(new Error("error")).when(consumerPrefetch).waitForStart(); /* * Run the prefetch */ - try { - consumerPrefetch.run(); - fail("expect exception"); - } catch (RuntimeException e) { - // Expected exception - } + assertThrows(RuntimeException.class, () -> consumerPrefetch.run()); /* * Verify the results */ - verify(consumerPrefetch).waitForStart(); verify(consumerPrefetch).nackQueueMessages(); verify(consumerPrefetch, never()).waitForPrefetch(); verify(consumerPrefetch, never()).getMessages(anyInt(), anyInt()); - verify(consumerPrefetch, never()).processReceivedMessages(any(List.class)); + verify(consumerPrefetch, never()).processReceivedMessages(anyList()); // Ensure retries attempt was not increased assertEquals(0, consumerPrefetch.retriesAttempted); @@ -346,18 +312,17 @@ public void testStopAfterErrorWaitForStart() throws InterruptedException, JMSExc /** * Test prefetch is stopped after Interrupt in waitForPrefetch */ - @Test - public void testStopAfterInterruptWaitForPrefetch() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testStopAfterInterruptWaitForPrefetch(int numberOfMessagesToPrefetch) throws InterruptedException, JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ consumerPrefetch.start(); - doNothing() - .when(consumerPrefetch).waitForStart(); - doThrow(new InterruptedException("Interrupt")) - .when(consumerPrefetch).waitForPrefetch(); + doNothing().when(consumerPrefetch).waitForStart(); + doThrow(new InterruptedException("Interrupt")).when(consumerPrefetch).waitForPrefetch(); /* * Run the prefetch @@ -373,7 +338,7 @@ public void testStopAfterInterruptWaitForPrefetch() throws InterruptedException, verify(consumerPrefetch).nackQueueMessages(); verify(consumerPrefetch, never()).getMessages(anyInt(), anyInt()); - verify(consumerPrefetch, never()).processReceivedMessages(any(List.class)); + verify(consumerPrefetch, never()).processReceivedMessages(anyList()); // Ensure retries attempt was not increased assertEquals(0, consumerPrefetch.retriesAttempted); @@ -382,28 +347,22 @@ public void testStopAfterInterruptWaitForPrefetch() throws InterruptedException, /** * Test prefetch is stopped after Error in waitForPrefetch */ - @Test - public void testStopAfterErrorWaitForPrefetch() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testStopAfterErrorWaitForPrefetch(int numberOfMessagesToPrefetch) throws InterruptedException, JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ consumerPrefetch.start(); - doNothing() - .when(consumerPrefetch).waitForStart(); - doThrow(new Error("error")) - .when(consumerPrefetch).waitForPrefetch(); + doNothing().when(consumerPrefetch).waitForStart(); + doThrow(new Error("error")).when(consumerPrefetch).waitForPrefetch(); /* * Run the prefetch */ - try { - consumerPrefetch.run(); - fail("expect error"); - } catch (RuntimeException e) { - // Expected exception - } + assertThrows(RuntimeException.class, () -> consumerPrefetch.run()); /* * Verify the results @@ -414,7 +373,7 @@ public void testStopAfterErrorWaitForPrefetch() throws InterruptedException, JMS verify(consumerPrefetch).nackQueueMessages(); verify(consumerPrefetch, never()).getMessages(anyInt(), anyInt()); - verify(consumerPrefetch, never()).processReceivedMessages(any(List.class)); + verify(consumerPrefetch, never()).processReceivedMessages(anyList()); // Ensure retries attempt was not increased assertEquals(0, consumerPrefetch.retriesAttempted); @@ -423,20 +382,18 @@ public void testStopAfterErrorWaitForPrefetch() throws InterruptedException, JMS /** * Test prefetch is stopped after Interrupt in getMessages */ - @Test - public void testStopAfterInterruptGetMessages() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testStopAfterInterruptGetMessages(int numberOfMessagesToPrefetch) throws InterruptedException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ consumerPrefetch.start(); - doNothing() - .when(consumerPrefetch).waitForStart(); - doNothing() - .when(consumerPrefetch).waitForPrefetch(); - doThrow(new InterruptedException("Interrupt")) - .when(consumerPrefetch).getMessagesWithBackoff(anyInt()); + doNothing().when(consumerPrefetch).waitForStart(); + doNothing().when(consumerPrefetch).waitForPrefetch(); + doThrow(new InterruptedException("Interrupt")).when(consumerPrefetch).getMessagesWithBackoff(anyInt()); /* * Run the prefetch @@ -446,13 +403,11 @@ public void testStopAfterInterruptGetMessages() throws InterruptedException, JMS /* * Verify the results */ - verify(consumerPrefetch).waitForStart(); verify(consumerPrefetch).waitForPrefetch(); verify(consumerPrefetch).nackQueueMessages(); verify(consumerPrefetch).getMessagesWithBackoff(anyInt()); - - verify(consumerPrefetch, never()).processReceivedMessages(any(List.class)); + verify(consumerPrefetch, never()).processReceivedMessages(anyList()); // Ensure retries attempt was not increased assertEquals(0, consumerPrefetch.retriesAttempted); @@ -461,41 +416,32 @@ public void testStopAfterInterruptGetMessages() throws InterruptedException, JMS /** * Test prefetch is stopped after Error in waitForPrefetch */ - @Test - public void testStopAfterErrorGetMessages() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testStopAfterErrorGetMessages(int numberOfMessagesToPrefetch) throws InterruptedException, JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ consumerPrefetch.start(); - doNothing() - .when(consumerPrefetch).waitForStart(); - doNothing() - .when(consumerPrefetch).waitForPrefetch(); - doThrow(new Error("error")) - .when(consumerPrefetch).getMessages(anyInt(), anyInt()); + doNothing().when(consumerPrefetch).waitForStart(); + doNothing().when(consumerPrefetch).waitForPrefetch(); + doThrow(new Error("error")).when(consumerPrefetch).getMessages(anyInt(), anyInt()); /* * Run the prefetch */ - try { - consumerPrefetch.run(); - fail("expect error"); - } catch (RuntimeException e) { - // Expected exception - } + assertThrows(RuntimeException.class, () -> consumerPrefetch.run()); /* * Verify the results */ - verify(consumerPrefetch).waitForStart(); verify(consumerPrefetch).waitForPrefetch(); verify(consumerPrefetch).nackQueueMessages(); verify(consumerPrefetch).getMessages(anyInt(), anyInt()); - - verify(consumerPrefetch, never()).processReceivedMessages(any(List.class)); + verify(consumerPrefetch, never()).processReceivedMessages(anyList()); // Ensure retries attempt was not increased assertEquals(0, consumerPrefetch.retriesAttempted); @@ -504,9 +450,10 @@ public void testStopAfterErrorGetMessages() throws InterruptedException, JMSExce /** * Test Run when consumer is closed */ - @Test - public void testRunExitOnClose() { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testRunExitOnClose(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); consumerPrefetch.close(); /* @@ -520,9 +467,10 @@ public void testRunExitOnClose() { /** * Test SetMessageListener to Null */ - @Test - public void testSetNullMessageListener() { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testSetNullMessageListener(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); consumerPrefetch.setMessageListener(null); verifyNoMoreInteractions(sqsSessionRunnable); } @@ -530,18 +478,17 @@ public void testSetNullMessageListener() { /** * Test SetMessageListener when message were prefetched */ - @Test - public void testSetMessageListener() { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testSetMessageListener(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); SQSMessageConsumerPrefetch.MessageManager msgManager1 = mock(SQSMessageConsumerPrefetch.MessageManager.class); Message message1 = mock(Message.class); - when(msgManager1.getMessage()) - .thenReturn(message1); + when(msgManager1.message()).thenReturn(message1); SQSMessageConsumerPrefetch.MessageManager msgManager2 = mock(SQSMessageConsumerPrefetch.MessageManager.class); Message message2 = mock(Message.class); - when(msgManager2.getMessage()) - .thenReturn(message2); + when(msgManager2.message()).thenReturn(message2); consumerPrefetch.messageQueue.add(msgManager1); consumerPrefetch.messageQueue.add(msgManager2); @@ -552,7 +499,7 @@ public void testSetMessageListener() { assertTrue(consumerPrefetch.messageQueue.isEmpty()); - List expectedList = new ArrayList(); + List expectedList = new ArrayList<>(); expectedList.add(msgManager1); expectedList.add(msgManager2); verify(sqsSessionRunnable).scheduleCallBacks(msgListener, expectedList); @@ -563,9 +510,10 @@ public void testSetMessageListener() { /** * Test getting message listener */ - @Test - public void testGetMessageListener() { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testGetMessageListener(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); MessageListener msgListener = mock(MessageListener.class); consumerPrefetch.setMessageListener(msgListener); @@ -575,9 +523,10 @@ public void testGetMessageListener() { /** * Test WaitForStart when preftech already started */ - @Test - public void testWaitForStartCurrentStateStart() throws javax.jms.IllegalStateException, InterruptedException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testWaitForStartCurrentStateStart(int numberOfMessagesToPrefetch) throws InterruptedException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ @@ -587,32 +536,30 @@ public void testWaitForStartCurrentStateStart() throws javax.jms.IllegalStateExc /* * call waitForStart in different thread */ - executorService.execute(new Runnable() { - @Override - public void run() { - try { - consumerPrefetch.waitForStart(); + executorService.execute(() -> { + try { + consumerPrefetch.waitForStart(); - // Indicate that we no longer waiting - passedWaitForStartCall.countDown(); - } catch (InterruptedException e) { - e.printStackTrace(); - } + // Indicate that we no longer waiting + passedWaitForStartCall.countDown(); + } catch (InterruptedException e) { + e.printStackTrace(); } }); /* * verify result */ - assertEquals(true, passedWaitForStartCall.await(10, TimeUnit.SECONDS)); + assertTrue(passedWaitForStartCall.await(10, TimeUnit.SECONDS)); } /** * Test WaitForStart when preftech already closed */ - @Test - public void testWaitForStartCurrentStateClose() throws javax.jms.IllegalStateException, InterruptedException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testWaitForStartCurrentStateClose(int numberOfMessagesToPrefetch) throws InterruptedException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ @@ -622,33 +569,31 @@ public void testWaitForStartCurrentStateClose() throws javax.jms.IllegalStateExc /* * call waitForStart in different thread */ - executorService.execute(new Runnable() { - @Override - public void run() { - try { - consumerPrefetch.waitForStart(); + executorService.execute(() -> { + try { + consumerPrefetch.waitForStart(); - // Indicate that we no longer waiting - passedWaitForStartCall.countDown(); - } catch (InterruptedException e) { - e.printStackTrace(); - } + // Indicate that we no longer waiting + passedWaitForStartCall.countDown(); + } catch (InterruptedException e) { + e.printStackTrace(); } }); /* * verify result */ - assertEquals(true, passedWaitForStartCall.await(10, TimeUnit.SECONDS)); + assertTrue(passedWaitForStartCall.await(10, TimeUnit.SECONDS)); } /** * Test WaitForStart when preftech state is updated to started while another thread is waiting * for the prefetch to start */ - @Test - public void testWaitForStartUpdateStateToStart() throws javax.jms.IllegalStateException, InterruptedException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testWaitForStartUpdateStateToStart(int numberOfMessagesToPrefetch) throws InterruptedException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ @@ -658,21 +603,18 @@ public void testWaitForStartUpdateStateToStart() throws javax.jms.IllegalStateEx /* * call waitForStart in different thread */ - executorService.execute(new Runnable() { - @Override - public void run() { - try { - beforeWaitForStartCall.countDown(); - consumerPrefetch.waitForStart(); - passedWaitForStart.countDown(); - } catch (InterruptedException e) { - e.printStackTrace(); - } + executorService.execute(() -> { + try { + beforeWaitForStartCall.countDown(); + consumerPrefetch.waitForStart(); + passedWaitForStart.countDown(); + } catch (InterruptedException e) { + e.printStackTrace(); } }); // Yield execution to allow the consumer to wait - assertEquals(true, beforeWaitForStartCall.await(10, TimeUnit.SECONDS)); + assertTrue(beforeWaitForStartCall.await(10, TimeUnit.SECONDS)); Thread.sleep(10); // Update the state and notify @@ -683,15 +625,16 @@ public void run() { */ // Ensure consumer is not waiting to move to start state - assertEquals(false, passedWaitForStart.await(10, TimeUnit.SECONDS)); + assertFalse(passedWaitForStart.await(10, TimeUnit.SECONDS)); } /** * Test WaitForStart when waiting thread is interrupted */ - @Test - public void testWaitForStartInterrupted() throws javax.jms.IllegalStateException, InterruptedException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testWaitForStartInterrupted(int numberOfMessagesToPrefetch) throws InterruptedException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ @@ -701,23 +644,20 @@ public void testWaitForStartInterrupted() throws javax.jms.IllegalStateException /* * call waitForStart in different thread */ - Thread t = new Thread(new Runnable() { - @Override - public void run() { - try { - beforeWaitForStartCall.countDown(); - consumerPrefetch.waitForStart(); - } catch (InterruptedException e) { - recvInterruptedExceptionLatch.countDown(); - e.printStackTrace(); - } + Thread t = new Thread(() -> { + try { + beforeWaitForStartCall.countDown(); + consumerPrefetch.waitForStart(); + } catch (InterruptedException e) { + recvInterruptedExceptionLatch.countDown(); + e.printStackTrace(); } }); t.start(); // Yield execution to allow the consumer to wait - assertEquals(true, beforeWaitForStartCall.await(10, TimeUnit.SECONDS)); + assertTrue(beforeWaitForStartCall.await(10, TimeUnit.SECONDS)); Thread.sleep(10); // Interrupt waiting thread @@ -726,15 +666,16 @@ public void run() { /* * verify result */ - assertEquals(true, recvInterruptedExceptionLatch.await(10, TimeUnit.SECONDS)); + assertTrue(recvInterruptedExceptionLatch.await(10, TimeUnit.SECONDS)); } /** * Test WaitForPrefetch and ensure that message are not prefetch when limit has already reached */ - @Test - public void testWaitForPrefetchLimitReached() throws InterruptedException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testWaitForPrefetchLimitReached(int numberOfMessagesToPrefetch) throws InterruptedException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ @@ -745,41 +686,39 @@ public void testWaitForPrefetchLimitReached() throws InterruptedException { /* * call waitForPrefetch in different thread */ - executorService.execute(new Runnable() { - @Override - public void run() { - try { - beforeWaitForPrefetchCall.countDown(); - consumerPrefetch.waitForPrefetch(); - passedWaitForPrefetch.countDown(); - } catch (InterruptedException e) { - e.printStackTrace(); - } + executorService.execute(() -> { + try { + beforeWaitForPrefetchCall.countDown(); + consumerPrefetch.waitForPrefetch(); + passedWaitForPrefetch.countDown(); + } catch (InterruptedException e) { + e.printStackTrace(); } }); // Yield execution to allow the consumer to wait - assertEquals(true, beforeWaitForPrefetchCall.await(10, TimeUnit.SECONDS)); + assertTrue(beforeWaitForPrefetchCall.await(10, TimeUnit.SECONDS)); Thread.sleep(10); // Release the local and ensure that we are still waiting since the prefetch message still equal to the limit consumerPrefetch.notifyStateChange(); - assertEquals(false, passedWaitForPrefetch.await(3, TimeUnit.SECONDS)); + assertFalse(passedWaitForPrefetch.await(3, TimeUnit.SECONDS)); // Simulate messages were processes consumerPrefetch.messagesPrefetched = numberOfMessagesToPrefetch - 1; // Release the local and ensure that we no longer waiting since the prefetch message is below the limit consumerPrefetch.notifyStateChange(); - assertEquals(true, passedWaitForPrefetch.await(3, TimeUnit.SECONDS)); + assertTrue(passedWaitForPrefetch.await(3, TimeUnit.SECONDS)); } /** * Test WaitForPrefetch when prefetch consumer is closed */ - @Test - public void testWaitForPrefetchIsClosed() throws InterruptedException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testWaitForPrefetchIsClosed(int numberOfMessagesToPrefetch) throws InterruptedException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ @@ -789,33 +728,31 @@ public void testWaitForPrefetchIsClosed() throws InterruptedException { final CountDownLatch beforeWaitForPrefetchCall = new CountDownLatch(1); final CountDownLatch passedWaitForPrefetch = new CountDownLatch(1); - executorService.execute(new Runnable() { - @Override - public void run() { - try { - beforeWaitForPrefetchCall.countDown(); - consumerPrefetch.waitForPrefetch(); - passedWaitForPrefetch.countDown(); - } catch (InterruptedException e) { - e.printStackTrace(); - } + executorService.execute(() -> { + try { + beforeWaitForPrefetchCall.countDown(); + consumerPrefetch.waitForPrefetch(); + passedWaitForPrefetch.countDown(); + } catch (InterruptedException e) { + e.printStackTrace(); } }); // Yield execution to allow the consumer to wait - assertEquals(true, beforeWaitForPrefetchCall.await(10, TimeUnit.SECONDS)); + assertTrue(beforeWaitForPrefetchCall.await(10, TimeUnit.SECONDS)); Thread.sleep(10); // Validate we do not wait when the consumer is closed - assertEquals(true, passedWaitForPrefetch.await(3, TimeUnit.SECONDS)); + assertTrue(passedWaitForPrefetch.await(3, TimeUnit.SECONDS)); } /** * Test WaitForPrefetch when waiting thread is interrupted */ - @Test - public void testWaitForPrefetchInterrupted() throws InterruptedException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testWaitForPrefetchInterrupted(int numberOfMessagesToPrefetch) throws InterruptedException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ @@ -823,47 +760,45 @@ public void testWaitForPrefetchInterrupted() throws InterruptedException { final CountDownLatch beforeWaitForPrefetchCall = new CountDownLatch(1); final CountDownLatch recvInterruptedExceptionLatch = new CountDownLatch(1); - Thread t = new Thread(new Runnable() { - @Override - public void run() { - try { - beforeWaitForPrefetchCall.countDown(); - consumerPrefetch.waitForPrefetch(); - } catch (InterruptedException e) { - recvInterruptedExceptionLatch.countDown(); - e.printStackTrace(); - } + Thread t = new Thread(() -> { + try { + beforeWaitForPrefetchCall.countDown(); + consumerPrefetch.waitForPrefetch(); + } catch (InterruptedException e) { + recvInterruptedExceptionLatch.countDown(); + e.printStackTrace(); } }); t.start(); - assertEquals(true, beforeWaitForPrefetchCall.await(10, TimeUnit.SECONDS)); + assertTrue(beforeWaitForPrefetchCall.await(10, TimeUnit.SECONDS)); Thread.sleep(10); t.interrupt(); // Validate that we no longer waiting due to the interrupt - assertEquals(true, recvInterruptedExceptionLatch.await(10, TimeUnit.SECONDS)); + assertTrue(recvInterruptedExceptionLatch.await(10, TimeUnit.SECONDS)); } /** * Test ConvertToJMSMessage when message type is not set in the message attribute */ - @Test - public void testConvertToJMSMessageNoTypeAttribute() throws JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testConvertToJMSMessageNoTypeAttribute(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ - Map mapAttributes = new HashMap(); + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); com.amazonaws.services.sqs.model.Message message = mock(com.amazonaws.services.sqs.model.Message.class); // Return message attribute with no message type attribute when(message.getMessageAttributes()) - .thenReturn(new HashMap()); + .thenReturn(new HashMap<>()); when(message.getAttributes()) .thenReturn(mapAttributes); when(message.getBody()) @@ -872,7 +807,7 @@ public void testConvertToJMSMessageNoTypeAttribute() throws JMSException { /* * Convert the SQS message to JMS Message */ - javax.jms.Message jsmMessage = consumerPrefetch.convertToJMSMessage(message); + jakarta.jms.Message jsmMessage = consumerPrefetch.convertToJMSMessage(message); /* * Verify results @@ -884,20 +819,21 @@ public void testConvertToJMSMessageNoTypeAttribute() throws JMSException { /** * Test ConvertToJMSMessage with byte message type */ - @Test - public void testConvertToJMSMessageByteTypeAttribute() throws JMSException, IOException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testConvertToJMSMessageByteTypeAttribute(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ - Map mapMessageAttributes = new HashMap(); + Map mapMessageAttributes = new HashMap<>(); MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.BYTE_MESSAGE_TYPE); messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING); mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); - Map mapAttributes = new HashMap(); + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); com.amazonaws.services.sqs.model.Message message = mock(com.amazonaws.services.sqs.model.Message.class); @@ -912,7 +848,7 @@ public void testConvertToJMSMessageByteTypeAttribute() throws JMSException, IOEx /* * Convert the SQS message to JMS Message */ - javax.jms.Message jsmMessage = consumerPrefetch.convertToJMSMessage(message); + jakarta.jms.Message jsmMessage = consumerPrefetch.convertToJMSMessage(message); /* * Verify results @@ -926,21 +862,21 @@ public void testConvertToJMSMessageByteTypeAttribute() throws JMSException, IOEx /** * Test ConvertToJMSMessage with byte message that contains illegal sqs message body */ - @Test - public void testConvertToJMSMessageByteTypeIllegalBody() throws JMSException, IOException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testConvertToJMSMessageByteTypeIllegalBody(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ - - Map mapMessageAttributes = new HashMap(); + Map mapMessageAttributes = new HashMap<>(); MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.BYTE_MESSAGE_TYPE); messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING); mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); - Map mapAttributes = new HashMap(); + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); com.amazonaws.services.sqs.model.Message message = mock(com.amazonaws.services.sqs.model.Message.class); @@ -954,36 +890,31 @@ public void testConvertToJMSMessageByteTypeIllegalBody() throws JMSException, IO /* * Convert the SQS message to JMS Message */ - try { - consumerPrefetch.convertToJMSMessage(message); - fail("Expect JMSException"); - } catch (JMSException jmse) { - // Expected JMS exception - } + assertThrows(JMSException.class, () -> consumerPrefetch.convertToJMSMessage(message)); } /** * Test ConvertToJMSMessage with an object message */ - @Test - public void testConvertToJMSMessageObjectTypeAttribute() throws JMSException, IOException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testConvertToJMSMessageObjectTypeAttribute(int numberOfMessagesToPrefetch) throws JMSException, IOException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ - - Map mapMessageAttributes = new HashMap(); + Map mapMessageAttributes = new HashMap<>(); MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.OBJECT_MESSAGE_TYPE); messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING); mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); - Map mapAttributes = new HashMap(); + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); // Encode an object to byte array - Integer integer = new Integer("10"); + Integer integer = 10; ByteArrayOutputStream array = new ByteArrayOutputStream(10); ObjectOutputStream oStream = new ObjectOutputStream(array); oStream.writeObject(integer); @@ -998,7 +929,7 @@ public void testConvertToJMSMessageObjectTypeAttribute() throws JMSException, IO /* * Convert the SQS message to JMS Message */ - javax.jms.Message jsmMessage = consumerPrefetch.convertToJMSMessage(message); + jakarta.jms.Message jsmMessage = consumerPrefetch.convertToJMSMessage(message); /* * Verify results @@ -1010,21 +941,21 @@ public void testConvertToJMSMessageObjectTypeAttribute() throws JMSException, IO /** * Test ConvertToJMSMessage with an object message that contains illegal sqs message body */ - @Test - public void testConvertToJMSMessageObjectIllegalBody() throws JMSException, IOException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testConvertToJMSMessageObjectIllegalBody(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ - - Map mapMessageAttributes = new HashMap(); + Map mapMessageAttributes = new HashMap<>(); MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.OBJECT_MESSAGE_TYPE); messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING); mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); - Map mapAttributes = new HashMap(); + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); com.amazonaws.services.sqs.model.Message message = mock(com.amazonaws.services.sqs.model.Message.class); @@ -1036,39 +967,34 @@ public void testConvertToJMSMessageObjectIllegalBody() throws JMSException, IOEx /* * Convert the SQS message to JMS Message */ - ObjectMessage jsmMessage = (ObjectMessage) consumerPrefetch.convertToJMSMessage(message); + ObjectMessage jmsMessage = (ObjectMessage) consumerPrefetch.convertToJMSMessage(message); /* * Verify results */ - try { - jsmMessage.getObject(); - fail("Expect JMSException"); - } catch (JMSException jmse) { - // Expected JMS exception - } + assertThrows(JMSException.class, jmsMessage::getObject); } /** * Test ConvertToJMSMessage with text message with text type attribute */ - @Test - public void testConvertToJMSMessageTextTypeAttribute() throws JMSException, IOException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testConvertToJMSMessageTextTypeAttribute(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ - - Map mapMessageAttributes = new HashMap(); + Map mapMessageAttributes = new HashMap<>(); MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.TEXT_MESSAGE_TYPE); messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING); mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); - Map mapAttributes = new HashMap(); + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); - Long now = DateTime.now().getMillis(); - mapAttributes.put(SQSMessagingClientConstants.SENT_TIMESTAMP, now.toString()); + long now = System.currentTimeMillis(); + mapAttributes.put(SQSMessagingClientConstants.SENT_TIMESTAMP, Long.toString(now)); com.amazonaws.services.sqs.model.Message message = mock(com.amazonaws.services.sqs.model.Message.class); @@ -1080,22 +1006,23 @@ public void testConvertToJMSMessageTextTypeAttribute() throws JMSException, IOEx /* * Convert the SQS message to JMS Message */ - javax.jms.Message jsmMessage = consumerPrefetch.convertToJMSMessage(message); + jakarta.jms.Message jmsMessage = consumerPrefetch.convertToJMSMessage(message); /* * Verify results */ - assertTrue(jsmMessage instanceof SQSTextMessage); + assertTrue(jmsMessage instanceof SQSTextMessage); assertEquals(message.getBody(), "MessageBody"); - assertEquals(jsmMessage.getJMSTimestamp(), now.longValue()); + assertEquals(jmsMessage.getJMSTimestamp(), now); } /** * Test received messages when consumer prefetch has not started */ - @Test - public void testReceiveWhenNotStarted() throws JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testReceiveWhenNotStarted(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); consumerPrefetch.running = false; assertNull(consumerPrefetch.receive()); @@ -1114,9 +1041,10 @@ public void testReceiveWhenNotStarted() throws JMSException { /** * Test received messages when consumer prefetch has is closed */ - @Test - public void testReceiveWhenClosed() throws JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testReceiveWhenClosed(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); consumerPrefetch.closed = true; assertNull(consumerPrefetch.receive()); @@ -1135,9 +1063,10 @@ public void testReceiveWhenClosed() throws JMSException { /** * Test received messages */ - @Test - public void testReceiveMessagePrefetch() throws JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testReceiveMessagePrefetch(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ @@ -1155,7 +1084,7 @@ public void testReceiveMessagePrefetch() throws JMSException { /* * Verify results */ - receiptHandlers.contains(msg.getReceiptHandle()); + assertTrue(receiptHandlers.contains(msg.getReceiptHandle())); verify(acknowledger).notifyMessageReceived(msg); verify(consumerPrefetch, times(2)).notifyStateChange(); @@ -1166,9 +1095,10 @@ public void testReceiveMessagePrefetch() throws JMSException { /** * Test received messages */ - @Test - public void testReceiveNoWaitPrefetch() throws JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testReceiveNoWaitPrefetch(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and mocks */ @@ -1186,7 +1116,7 @@ public void testReceiveNoWaitPrefetch() throws JMSException { /* * Verify results */ - receiptHandlers.contains(msg.getReceiptHandle()); + assertTrue(receiptHandlers.contains(msg.getReceiptHandle())); verify(acknowledger).notifyMessageReceived(msg); verify(consumerPrefetch, times(2)).notifyStateChange(); @@ -1197,11 +1127,12 @@ public void testReceiveNoWaitPrefetch() throws JMSException { /** * Test received messages call wait for messages and exists when consumer prefterch is closed */ - @Test - public void testReceiveMessageEmptyThenClosed() throws InterruptedException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testReceiveMessageEmptyThenClosed(int numberOfMessagesToPrefetch) throws InterruptedException { + init(numberOfMessagesToPrefetch); /* - * Set up consumer prefetch and lactches + * Set up consumer prefetch and latches */ consumerPrefetch.running = true; final CountDownLatch beforeReceiveCall = new CountDownLatch(1); @@ -1211,33 +1142,30 @@ public void testReceiveMessageEmptyThenClosed() throws InterruptedException { /* * Call receive messages */ - executorService.execute(new Runnable() { - @Override - public void run() { - try { - beforeReceiveCall.countDown(); - Message msg = consumerPrefetch.receive(0); - if (msg == null) { - noMessageReturned.set(true); - } - passedReceiveCall.countDown(); - } catch (JMSException e) { - e.printStackTrace(); + executorService.execute(() -> { + try { + beforeReceiveCall.countDown(); + Message msg = consumerPrefetch.receive(0); + if (msg == null) { + noMessageReturned.set(true); } + passedReceiveCall.countDown(); + } catch (JMSException e) { + e.printStackTrace(); } }); - assertEquals(true, beforeReceiveCall.await(10, TimeUnit.SECONDS)); + assertTrue(beforeReceiveCall.await(10, TimeUnit.SECONDS)); Thread.sleep(10); // Update the state and notify consumerPrefetch.close(); // Wait till receive execution finishes - assertEquals(true, passedReceiveCall.await(10, TimeUnit.SECONDS)); + assertTrue(passedReceiveCall.await(10, TimeUnit.SECONDS)); // Validate that after session is closed receive returns null - assertEquals(true, noMessageReturned.get()); + assertTrue(noMessageReturned.get()); // Ensure the messagesRequested counter is reset correctly assertEquals(0, consumerPrefetch.messagesRequested); @@ -1246,9 +1174,10 @@ public void run() { /** * Test received messages wait when no message are prefetch and return newly added message */ - @Test - public void testReceiveMessageEmptyThenAddMessage() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testReceiveMessageEmptyThenAddMessage(int numberOfMessagesToPrefetch) throws InterruptedException, JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and latches */ @@ -1262,36 +1191,33 @@ public void testReceiveMessageEmptyThenAddMessage() throws InterruptedException, /* * Call receive messages */ - executorService.execute(new Runnable() { - @Override - public void run() { - try { - beforeReceiveCall.countDown(); - SQSMessage msg = (SQSMessage) consumerPrefetch.receive(0); - if ((msg != null) && (msg.getReceiptHandle().equals(receiptHandle))) { - messageReceived.set(true); - } - passedReceiveCall.countDown(); - } catch (JMSException e) { - e.printStackTrace(); + executorService.execute(() -> { + try { + beforeReceiveCall.countDown(); + SQSMessage msg = (SQSMessage) consumerPrefetch.receive(0); + if ((msg != null) && (msg.getReceiptHandle().equals(receiptHandle))) { + messageReceived.set(true); } + passedReceiveCall.countDown(); + } catch (JMSException e) { + e.printStackTrace(); } }); - assertEquals(true, beforeReceiveCall.await(10, TimeUnit.SECONDS)); + assertTrue(beforeReceiveCall.await(10, TimeUnit.SECONDS)); Thread.sleep(10); // Add message to the internal queue - List receiptHandlers = new ArrayList(); + List receiptHandlers = new ArrayList<>(); receiptHandlers.add(receiptHandle); addMessagesToQueue(receiptHandlers); consumerPrefetch.notifyStateChange(); // Wait till receive execution finishes - assertEquals(true, passedReceiveCall.await(10, TimeUnit.SECONDS)); + assertTrue(passedReceiveCall.await(10, TimeUnit.SECONDS)); - // Validate that after adding a single message it was receive correctly - assertEquals(true, messageReceived.get()); + // Validate that after adding a single message it was received correctly + assertTrue(messageReceived.get()); // Ensure the messagesRequested counter is reset correctly assertEquals(0, consumerPrefetch.messagesRequested); @@ -1300,9 +1226,10 @@ public void run() { /** * Test received messages with timeout */ - @Test - public void testReceiveMessageTimeout() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testReceiveMessageTimeout(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and time stamps */ @@ -1320,8 +1247,10 @@ public void testReceiveMessageTimeout() throws InterruptedException, JMSExceptio // verify that we did not exit early long measuredTime = System.currentTimeMillis() - startTime; - assertTrue(String.format("Expected wait time = %1$s ms and has to be less than or equal to measured time = %2$s ms", waitTime, measuredTime), waitTime <= measuredTime); - + assertTrue(waitTime <= measuredTime, String.format( + "Expected wait time = %1$s ms and has to be less than or equal to measured time = %2$s ms", + waitTime, measuredTime)); + // Ensure the messagesRequested counter is reset correctly assertEquals(0, consumerPrefetch.messagesRequested); } @@ -1329,9 +1258,10 @@ public void testReceiveMessageTimeout() throws InterruptedException, JMSExceptio /** * Test received messages with timeout */ - @Test - public void testReceiveNoWaitEmpty() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testReceiveNoWaitEmpty(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch and time stamps */ @@ -1356,22 +1286,21 @@ public void testReceiveNoWaitEmpty() throws InterruptedException, JMSException { /** * Test process received messages with empty input */ - @Test - public void testProcessReceivedMessagesEmptyInput() { - - consumerPrefetch.processReceivedMessages(new ArrayList()); + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testProcessReceivedMessagesEmptyInput(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); + consumerPrefetch.processReceivedMessages(new ArrayList<>()); verifyNoMoreInteractions(sqsSessionRunnable); } /** * Test process received messages */ - @Test - public void testProcessReceivedMessages() throws JMSException { - - Map mapAttributes = new HashMap(); - mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testProcessReceivedMessages(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); List receiptHandlers = createReceiptHandlersList(3); List messages = createSQSServiceMessages(receiptHandlers); @@ -1388,20 +1317,21 @@ public void testProcessReceivedMessages() throws JMSException { while (!consumerPrefetch.messageQueue.isEmpty()) { SQSMessageConsumerPrefetch.MessageManager msgManager = consumerPrefetch.messageQueue.pollFirst(); - SQSMessage msg = (SQSMessage)msgManager.getMessage(); - receiptHandlers.contains(msg.getReceiptHandle()); + SQSMessage msg = (SQSMessage) msgManager.message(); + assertTrue(receiptHandlers.contains(msg.getReceiptHandle())); } - verify(negativeAcknowledger).action(QUEUE_URL, new ArrayList()); + verify(negativeAcknowledger).action(QUEUE_URL, new ArrayList<>()); } /** * Test process messages when message listener is set */ - @Test - public void testProcessReceivedMessagesWithMessageListener() throws JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testProcessReceivedMessagesWithMessageListener(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); /* * Set up mocks and consumer */ @@ -1409,9 +1339,6 @@ public void testProcessReceivedMessagesWithMessageListener() throws JMSException consumerPrefetch.setMessageListener(msgListener); // Create messages - Map mapAttributes = new HashMap(); - mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); - List receiptHandlers = createReceiptHandlersList(3); List messages = createSQSServiceMessages(receiptHandlers); @@ -1424,7 +1351,7 @@ public void testProcessReceivedMessagesWithMessageListener() throws JMSException /* * Verify results */ - ArgumentCaptor captor = ArgumentCaptor.forClass(List.class); + ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); verify(sqsSessionRunnable, times(1)).scheduleCallBacks(eq(msgListener), captor.capture()); assertEquals(3, captor.getValue().size()); @@ -1432,31 +1359,27 @@ public void testProcessReceivedMessagesWithMessageListener() throws JMSException assertEquals(0, consumerPrefetch.messageQueue.size()); assertEquals(3, consumerPrefetch.messagesPrefetched); - verify(negativeAcknowledger).action(QUEUE_URL, new ArrayList()); + verify(negativeAcknowledger).action(QUEUE_URL, List.of()); } /** * Test process messages when message listener is set */ - @Test - public void testProcessReceivedMessagesThrowsException() throws JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testProcessReceivedMessagesThrowsException(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); /* * Set up mocks and consumer */ // Create messages - Map mapAttributes = new HashMap(); - mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); - List receiptHandlers = createReceiptHandlersList(3); List messages = createSQSServiceMessages(receiptHandlers); - when(consumerPrefetch.convertToJMSMessage(messages.get(1))) - .thenThrow(new JMSException("Exception")); - when(consumerPrefetch.convertToJMSMessage(messages.get(2))) - .thenThrow(new JMSException("Exception")); + when(consumerPrefetch.convertToJMSMessage(messages.get(1))).thenThrow(new JMSException("Exception")); + when(consumerPrefetch.convertToJMSMessage(messages.get(2))).thenThrow(new JMSException("Exception")); /* * Process messages @@ -1471,7 +1394,7 @@ public void testProcessReceivedMessagesThrowsException() throws JMSException { assertEquals(1, consumerPrefetch.messageQueue.size()); assertEquals(1, consumerPrefetch.messagesPrefetched); - List failedMessages = new ArrayList(); + List failedMessages = new ArrayList<>(); failedMessages.add("r1"); failedMessages.add("r2"); verify(negativeAcknowledger).action(QUEUE_URL, failedMessages); @@ -1480,9 +1403,10 @@ public void testProcessReceivedMessagesThrowsException() throws JMSException { /** * Test process messages when message listener is set */ - @Test - public void testProcessReceivedMessagesNegativeAcknowledgerThrowJMSException() throws JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testProcessReceivedMessagesNegativeAcknowledgerThrowJMSException(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); /* * Set up mocks and consumer */ @@ -1493,9 +1417,6 @@ public void testProcessReceivedMessagesNegativeAcknowledgerThrowJMSException() t .when(negativeAcknowledger).action(eq(QUEUE_URL), any(List.class)); // Create messages - Map mapAttributes = new HashMap(); - mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); - List receiptHandlers = createReceiptHandlersList(3); List messages = createSQSServiceMessages(receiptHandlers); @@ -1507,7 +1428,7 @@ public void testProcessReceivedMessagesNegativeAcknowledgerThrowJMSException() t /* * Verify results */ - ArgumentCaptor captor = ArgumentCaptor.forClass(List.class); + ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); verify(sqsSessionRunnable, times(1)).scheduleCallBacks(eq(msgListener), captor.capture()); assertEquals(3, captor.getValue().size()); @@ -1515,15 +1436,16 @@ public void testProcessReceivedMessagesNegativeAcknowledgerThrowJMSException() t assertEquals(0, consumerPrefetch.messageQueue.size()); assertEquals(3, consumerPrefetch.messagesPrefetched); - verify(negativeAcknowledger).action(QUEUE_URL, new ArrayList()); + verify(negativeAcknowledger).action(QUEUE_URL, List.of()); } /** * Test Get Messages */ - @Test - public void testGetMessages() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testGetMessages(int numberOfMessagesToPrefetch) throws InterruptedException, JMSException { + init(numberOfMessagesToPrefetch); /* * Set up mocks and consumer */ @@ -1536,18 +1458,13 @@ public void testGetMessages() throws InterruptedException, JMSException { .withMessageAttributeNames(SQSMessageConsumerPrefetch.ALL) .withWaitTimeSeconds(SQSMessageConsumerPrefetch.WAIT_TIME_SECONDS); - List messages = new ArrayList(); - messages.add(new com.amazonaws.services.sqs.model.Message().withReceiptHandle("r1")); - messages.add(new com.amazonaws.services.sqs.model.Message().withReceiptHandle("r2")); - messages.add(new com.amazonaws.services.sqs.model.Message().withReceiptHandle("r3")); - messages.add(new com.amazonaws.services.sqs.model.Message().withReceiptHandle("r4")); - messages.add(new com.amazonaws.services.sqs.model.Message().withReceiptHandle("r5")); + List messages = IntStream.range(1, 6) + .mapToObj(a -> new com.amazonaws.services.sqs.model.Message().withReceiptHandle("r" + a)) + .toList(); - ReceiveMessageResult receivedMessageResult = - new ReceiveMessageResult().withMessages(messages); + ReceiveMessageResult receivedMessageResult = new ReceiveMessageResult().withMessages(messages); - when(amazonSQSClient.receiveMessage(receiveMessageRequest)) - .thenReturn(receivedMessageResult); + when(amazonSQSClient.receiveMessage(receiveMessageRequest)).thenReturn(receivedMessageResult); /* * Get messages @@ -1564,35 +1481,26 @@ public void testGetMessages() throws InterruptedException, JMSException { /** * Test Get Messages with illegal prefetch size */ - @Test - public void testGetMessagesIllegalPrefetchSize() throws JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testGetMessagesIllegalPrefetchSize(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); int negativeSize = -10; - try { - consumerPrefetch.getMessages(negativeSize, 0); - fail(); - } catch(AssertionError ae) { - // expected exception - } - try { - consumerPrefetch.getMessages(0, 0); - fail(); - } catch(AssertionError ae) { - // expected exception - } + assertThrows(AssertionError.class, () -> consumerPrefetch.getMessages(negativeSize, 0)); + assertThrows(AssertionError.class, () -> consumerPrefetch.getMessages(0, 0)); } /** * Test Get Messages throws JMS exception */ - @Test - public void testGetMessagesJMSException() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testGetMessagesJMSException(int numberOfMessagesToPrefetch) throws InterruptedException, JMSException { + init(numberOfMessagesToPrefetch); /* * Set up mocks and consumer */ - int retriesAttempted = 3; int prefetchBatchSize = 5; long firstSleepTime = 100L; @@ -1601,14 +1509,12 @@ public void testGetMessagesJMSException() throws InterruptedException, JMSExcept when(amazonSQSClient.receiveMessage(any(ReceiveMessageRequest.class))) .thenThrow(new JMSException("test exception")); - when(backoffStrategy.delayBeforeNextRetry(retriesAttempted)) - .thenReturn(firstSleepTime); + when(backoffStrategy.delayBeforeNextRetry(retriesAttempted)).thenReturn(firstSleepTime); when(backoffStrategy.delayBeforeNextRetry(retriesAttempted + 1)) .thenReturn(secondSleepTime); consumerPrefetch.getMessagesWithBackoff(prefetchBatchSize); - consumerPrefetch.getMessagesWithBackoff(prefetchBatchSize); /* @@ -1623,13 +1529,13 @@ public void testGetMessagesJMSException() throws InterruptedException, JMSExcept /** * Test Get Messages interrupted */ - @Test - public void testGetMessagesInterruptDuringBackoff() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testGetMessagesInterruptDuringBackoff(int numberOfMessagesToPrefetch) throws InterruptedException, JMSException { + init(numberOfMessagesToPrefetch); /* * Set up mocks and consumer */ - int retriesAttempted = 3; final int prefetchBatchSize = 5; consumerPrefetch.retriesAttempted = retriesAttempted; @@ -1643,21 +1549,18 @@ public void testGetMessagesInterruptDuringBackoff() throws InterruptedException, /* * Get messages on a different execution thread */ - Thread t = new Thread(new Runnable() { - @Override - public void run() { - try { - beforeGetMessagesCall.countDown(); - consumerPrefetch.getMessagesWithBackoff(prefetchBatchSize); - } catch (InterruptedException e) { - recvInterruptedExceptionLatch.countDown(); - e.printStackTrace(); - } + Thread t = new Thread(() -> { + try { + beforeGetMessagesCall.countDown(); + consumerPrefetch.getMessagesWithBackoff(prefetchBatchSize); + } catch (InterruptedException e) { + recvInterruptedExceptionLatch.countDown(); + e.printStackTrace(); } }); t.start(); - assertEquals(true, beforeGetMessagesCall.await(5, TimeUnit.SECONDS)); + assertTrue(beforeGetMessagesCall.await(5, TimeUnit.SECONDS)); Thread.sleep(10); /* @@ -1665,35 +1568,32 @@ public void run() { */ t.interrupt(); - assertEquals(true, recvInterruptedExceptionLatch.await(5, TimeUnit.SECONDS)); + assertTrue(recvInterruptedExceptionLatch.await(5, TimeUnit.SECONDS)); } /** * Test Get Messages throws error */ - @Test - public void testGetMessagesError() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testGetMessagesError(int numberOfMessagesToPrefetch) throws JMSException { + init(numberOfMessagesToPrefetch); int retriesAttempted = 3; int prefetchBatchSize = 5; consumerPrefetch.retriesAttempted = retriesAttempted; - when(amazonSQSClient.receiveMessage(any(ReceiveMessageRequest.class))) - .thenThrow(new Error()); + when(amazonSQSClient.receiveMessage(any(ReceiveMessageRequest.class))).thenThrow(new Error()); - try { - consumerPrefetch.getMessages(prefetchBatchSize, 0); - } catch (Error e) { - // Expected error exception - } + assertThrows(Error.class, () -> consumerPrefetch.getMessages(prefetchBatchSize, 0)); } /** * Test start when consumer prefetch is already closed */ - @Test - public void testStartAlreadyClosed() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testStartAlreadyClosed(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch */ @@ -1713,9 +1613,10 @@ public void testStartAlreadyClosed() throws InterruptedException, JMSException { /** * Test start when consumer prefetch is already started */ - @Test - public void testStartAlreadyStarted() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testStartAlreadyStarted(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch */ @@ -1735,9 +1636,10 @@ public void testStartAlreadyStarted() throws InterruptedException, JMSException /** * Test start update the state lock */ - @Test - public void testStart() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testStart(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); /* * CAll Start */ @@ -1753,9 +1655,10 @@ public void testStart() throws InterruptedException, JMSException { /** * Test stop when consumer prefetch is already closed */ - @Test - public void testStopAlreadyClosed() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testStopAlreadyClosed(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch */ @@ -1775,9 +1678,10 @@ public void testStopAlreadyClosed() throws InterruptedException, JMSException { /** * Test stop when consumer prefetch is not started */ - @Test - public void testStopAlreadyStarted() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testStopAlreadyStarted(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); /* * CAll Start */ @@ -1792,9 +1696,10 @@ public void testStopAlreadyStarted() throws InterruptedException, JMSException { /** * Test stop update the state lock */ - @Test - public void testStop() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testStop(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch */ @@ -1815,9 +1720,10 @@ public void testStop() throws InterruptedException, JMSException { /** * Test stop when consumer prefetch is already closed */ - @Test - public void testCloseAlreadyClosed() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testCloseAlreadyClosed(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); /* * Set up consumer prefetch */ @@ -1837,9 +1743,10 @@ public void testCloseAlreadyClosed() throws InterruptedException, JMSException { /** * Test stop when consumer prefetch is not started */ - @Test - public void testClose() throws InterruptedException, JMSException { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testClose(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); /* * CAll Start */ @@ -1856,17 +1763,16 @@ public void testClose() throws InterruptedException, JMSException { * Test that concurrent receive requests results in fetching more messages * from the queue with a single request, even if prefetching is set lower or even to 0. */ - @Test - public void testRequestedMessageTracking() throws InterruptedException, JMSException, ExecutionException { + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testRequestedMessageTracking(int numberOfMessagesToPrefetch) throws InterruptedException, JMSException { + init(numberOfMessagesToPrefetch); int concurrentReceives = 3; int receiveBatchSize = Math.min(SQSMessagingClientConstants.MAX_BATCH, Math.max(concurrentReceives, numberOfMessagesToPrefetch)); // Create messages return from SQS - final List receipt = new ArrayList(); - for (int i = 0; i < receiveBatchSize; ++i) { - receipt.add("r" + i); - } + List receipt = createReceiptHandlersList(receiveBatchSize); ReceiveMessageResult receivedMessageResult = createReceiveMessageResult(receipt); // Mock SQS call for receive message and return messages @@ -1879,27 +1785,21 @@ public void testRequestedMessageTracking() throws InterruptedException, JMSExcep .thenReturn(receivedMessageResult); final CountDownLatch allReceivesWaiting = new CountDownLatch(concurrentReceives); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - invocation.callRealMethod(); - allReceivesWaiting.countDown(); - return null; - } + doAnswer((Answer) invocation -> { + invocation.callRealMethod(); + allReceivesWaiting.countDown(); + return null; }).when(consumerPrefetch).requestMessage(); // Close the prefetcher immediately after completing one loop - final List> receivedMessageFutures = new ArrayList>(); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - invocation.callRealMethod(); - for (Future messageFuture : receivedMessageFutures) { - Assert.assertNotNull(messageFuture.get()); - } - consumerPrefetch.close(); - return null; + final List> receivedMessageFutures = new ArrayList<>(); + doAnswer((Answer) invocation -> { + invocation.callRealMethod(); + for (Future messageFuture : receivedMessageFutures) { + assertNotNull(messageFuture.get()); } + consumerPrefetch.close(); + return null; }).when(consumerPrefetch).processReceivedMessages(any(List.class)); // Set running to true first so that the receive calls don't terminate early @@ -1907,19 +1807,14 @@ public Object answer(InvocationOnMock invocation) throws Throwable { ExecutorService receiveExecutor = Executors.newFixedThreadPool(concurrentReceives); for (int i = 0; i < concurrentReceives; i++) { - receivedMessageFutures.add(receiveExecutor.submit(new Callable() { - @Override - public Message call() throws Exception { - return consumerPrefetch.receive(); - } - })); + receivedMessageFutures.add(receiveExecutor.submit(() -> consumerPrefetch.receive())); } // Wait to make sure the receive calls have gotten far enough to // wait on the message queue allReceivesWaiting.await(); - Assert.assertEquals(concurrentReceives, consumerPrefetch.messagesRequested); + assertEquals(concurrentReceives, consumerPrefetch.messagesRequested); consumerPrefetch.run(); } @@ -1931,9 +1826,10 @@ public Message call() throws Exception { * do this work in order to get pre-fetch going even when * number of messages to pre-fetch is set to 0. */ - @Test - public void testSetMessageListenerBeforeStart() { - + @ParameterizedTest + @MethodSource("prefetchParameters") + public void testSetMessageListenerBeforeStart(int numberOfMessagesToPrefetch) { + init(numberOfMessagesToPrefetch); MessageListener msgListener = mock(MessageListener.class); consumerPrefetch.setMessageListener(msgListener); consumerPrefetch.start(); @@ -1945,62 +1841,63 @@ public void testSetMessageListenerBeforeStart() { */ private void addMessagesToQueue(List receiptHandlers) throws JMSException { - - Map mapAttributes = new HashMap(); + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); for (String receiptHandler : receiptHandlers) { - SQSMessageConsumerPrefetch.MessageManager msgManager = mock(SQSMessageConsumerPrefetch.MessageManager.class); com.amazonaws.services.sqs.model.Message message = new com.amazonaws.services.sqs.model.Message().withReceiptHandle(receiptHandler) .withAttributes(mapAttributes); Message m1 = consumerPrefetch.convertToJMSMessage(message); - when(msgManager.getMessage()).thenReturn(m1); + when(msgManager.message()).thenReturn(m1); consumerPrefetch.messageQueue.add(msgManager); } } - private List - createSQSServiceMessages(List receiptHandlers) throws JMSException { - - Map mapAttributes = new HashMap(); + private List createSQSServiceMessages(List receiptHandlers) { + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); - List resultList = - new ArrayList(); + List resultList = new ArrayList<>(); for (String receiptHandler : receiptHandlers) { - - resultList.add( - new com.amazonaws.services.sqs.model.Message().withReceiptHandle(receiptHandler) - .withAttributes(mapAttributes)); + resultList.add(new com.amazonaws.services.sqs.model.Message() + .withReceiptHandle(receiptHandler) + .withAttributes(mapAttributes) + ); } return resultList; } private ReceiveMessageResult createReceiveMessageResult(List receiptList) { - - Map mapAttributes = new HashMap(); + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); - List messages = new ArrayList(); + List messages = new ArrayList<>(); for (String receipt : receiptList) { messages.add(new com.amazonaws.services.sqs.model.Message() .withReceiptHandle(receipt) - .withAttributes(mapAttributes)); + .withAttributes(mapAttributes) + ); } return new ReceiveMessageResult().withMessages(messages); } private List createReceiptHandlersList(int count) { - List receiptHandlers = new ArrayList(); - for (int i = 0; i < count; ++i) { - receiptHandlers.add("r" + i); - } - return receiptHandlers; + return IntStream.range(0, count).mapToObj(a -> "r" + a).toList(); + } + + private static Stream prefetchParameters() { + return Stream.of( + Arguments.of(0), + Arguments.of(1), + Arguments.of(5), + Arguments.of(10), + Arguments.of(15) + ); } } diff --git a/src/test/java/com/amazon/sqs/javamessaging/SQSMessageConsumerTest.java b/src/test/java/com/amazon/sqs/javamessaging/SQSMessageConsumerTest.java index 9ffdc08..d0c0505 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/SQSMessageConsumerTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/SQSMessageConsumerTest.java @@ -14,34 +14,26 @@ */ package com.amazon.sqs.javamessaging; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import javax.jms.JMSException; -import javax.jms.MessageListener; - -import com.amazon.sqs.javamessaging.SQSConnection; -import com.amazon.sqs.javamessaging.SQSMessageConsumer; -import com.amazon.sqs.javamessaging.SQSMessageConsumerPrefetch; -import com.amazon.sqs.javamessaging.SQSQueueDestination; -import com.amazon.sqs.javamessaging.SQSSession; -import com.amazon.sqs.javamessaging.SQSSessionCallbackScheduler; import com.amazon.sqs.javamessaging.acknowledge.AcknowledgeMode; import com.amazon.sqs.javamessaging.acknowledge.Acknowledger; import com.amazon.sqs.javamessaging.acknowledge.NegativeAcknowledger; -import com.amazon.sqs.javamessaging.acknowledge.SQSMessageIdentifier; import com.amazon.sqs.javamessaging.util.SQSMessagingClientThreadFactory; +import jakarta.jms.JMSException; +import jakarta.jms.MessageListener; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -55,7 +47,6 @@ public class SQSMessageConsumerTest { private static final String QUEUE_URL_1 = "QueueUrl1"; - private static final String QUEUE_URL_2 = "queueUrl2"; private static final String QUEUE_NAME = "QueueName"; private SQSMessageConsumer consumer; @@ -64,13 +55,13 @@ public class SQSMessageConsumerTest { private SQSSessionCallbackScheduler sqsSessionRunnable; private Acknowledger acknowledger; - private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5); + private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5); private SQSMessageConsumerPrefetch sqsMessageConsumerPrefetch; private NegativeAcknowledger negativeAcknowledger; private SQSMessagingClientThreadFactory threadFactory; private SQSQueueDestination destination; - @Before + @BeforeEach public void setup() throws JMSException{ sqsConnection = mock(SQSConnection.class); @@ -98,13 +89,7 @@ public void setup() throws JMSException{ */ @Test public void testGetMessageSelectorNotSupported() { - - try { - consumer.getMessageSelector(); - fail(); - } catch(JMSException jmse) { - assertEquals("Unsupported Method", jmse.getMessage()); - } + assertThrows(JMSException.class, () -> consumer.getMessageSelector(), "Unsupported Method"); } /** @@ -148,24 +133,20 @@ public void testCloseBlocksInProgressCallback() throws InterruptedException, JMS sqsSession.startingCallback(consumer); // Run another thread that tries to close the consumer while activeConsumerInCallback is set - executorService.execute(new Runnable() { - - @Override - public void run() { - beforeConsumerStopCall.countDown(); - try { - consumer.close(); - } catch (JMSException e) { - fail(); - } - passedConsumerStopCall.countDown(); + executorService.execute(() -> { + beforeConsumerStopCall.countDown(); + try { + consumer.close(); + } catch (JMSException e) { + fail(); } + passedConsumerStopCall.countDown(); }); beforeConsumerStopCall.await(); Thread.sleep(10); // Ensure that we wait on activeConsumerInCallback - assertEquals(false, passedConsumerStopCall.await(2, TimeUnit.SECONDS)); + assertFalse(passedConsumerStopCall.await(2, TimeUnit.SECONDS)); // Release the activeConsumerInCallback sqsSession.finishedCallback(); @@ -173,7 +154,7 @@ public void run() { // Ensure that the consumer close completed passedConsumerStopCall.await(); - assertEquals(true, consumer.closed); + assertTrue(consumer.closed); } @@ -203,7 +184,7 @@ public void testStartNoOpIfAlreadyClosed() throws JMSException { * Test do close results in no op when the consumer is already closed */ @Test - public void testDoCloseNoOpWhenAlreadyClosed() throws InterruptedException, JMSException { + public void testDoCloseNoOpWhenAlreadyClosed() { /* * Set up consumer @@ -226,8 +207,7 @@ public void testDoCloseNoOpWhenAlreadyClosed() throws InterruptedException, JMSE * Test do close */ @Test - public void testDoClose() throws InterruptedException, JMSException { - + public void testDoClose() { consumer = new SQSMessageConsumer(sqsConnection, sqsSession, sqsSessionRunnable, destination, acknowledger, negativeAcknowledger, threadFactory, sqsMessageConsumerPrefetch); @@ -248,7 +228,7 @@ public void testDoClose() throws InterruptedException, JMSException { * Test close results in no op when the consumer is already closed */ @Test - public void testCloseNoOpWhenAlreadyClosed() throws InterruptedException, JMSException { + public void testCloseNoOpWhenAlreadyClosed() throws JMSException { /* * Set up consumer @@ -273,7 +253,7 @@ public void testCloseNoOpWhenAlreadyClosed() throws InterruptedException, JMSExc * we do not close but set a consumer close after callback */ @Test - public void testCloseCalledFromCallbackExecutionThread() throws InterruptedException, JMSException { + public void testCloseCalledFromCallbackExecutionThread() throws JMSException { /* * Set up consumer @@ -300,7 +280,7 @@ public void testCloseCalledFromCallbackExecutionThread() throws InterruptedExcep * Test consumer close */ @Test - public void testClose() throws InterruptedException, JMSException { + public void testClose() throws JMSException { /* * Set up consumer @@ -324,7 +304,7 @@ public void testClose() throws InterruptedException, JMSException { * Test set message listener fails when consumer is already closed */ @Test - public void testSetMessageListenerAlreadyClosed() throws InterruptedException, JMSException { + public void testSetMessageListenerAlreadyClosed() throws JMSException { /* * Set up consumer @@ -351,7 +331,7 @@ public void testSetMessageListenerAlreadyClosed() throws InterruptedException, J * Test receive fails when consumer is already closed */ @Test - public void testReceiveAlreadyClosed() throws InterruptedException, JMSException { + public void testReceiveAlreadyClosed() throws JMSException { /* * Set up consumer @@ -378,7 +358,7 @@ public void testReceiveAlreadyClosed() throws InterruptedException, JMSException * Test set message listener fails when consumer is already closed */ @Test - public void testReceiveWithTimeoutAlreadyClosed() throws InterruptedException, JMSException { + public void testReceiveWithTimeoutAlreadyClosed() throws JMSException { /* * Set up consumer @@ -407,7 +387,7 @@ public void testReceiveWithTimeoutAlreadyClosed() throws InterruptedException, J * Test set message listener fails when consumer is already closed */ @Test - public void testReceiveNoWaitAlreadyClosed() throws InterruptedException, JMSException { + public void testReceiveNoWaitAlreadyClosed() throws JMSException { /* * Set up consumer @@ -420,20 +400,14 @@ public void testReceiveNoWaitAlreadyClosed() throws InterruptedException, JMSExc /* * Call receive no wait */ - try { - - consumer.receiveNoWait(); - fail(); - } catch (JMSException ex) { - assertEquals("Consumer is closed", ex.getMessage()); - } + assertThrows(JMSException.class, () -> consumer.receiveNoWait(), "Consumer is closed"); } /** * Test set message listener */ @Test - public void testSetMessageListener() throws InterruptedException, JMSException { + public void testSetMessageListener() throws JMSException { /* * Set up consumer @@ -458,7 +432,7 @@ public void testSetMessageListener() throws InterruptedException, JMSException { * Test get message listener */ @Test - public void testGetMessageListener() throws InterruptedException, JMSException { + public void testGetMessageListener() throws JMSException { /* * Set up consumer @@ -481,7 +455,7 @@ public void testGetMessageListener() throws InterruptedException, JMSException { * Test get message listener */ @Test - public void testGetQueue() throws InterruptedException, JMSException { + public void testGetQueue() throws JMSException { /* * Set up consumer @@ -496,7 +470,7 @@ public void testGetQueue() throws InterruptedException, JMSException { * Test receive */ @Test - public void testReceive() throws InterruptedException, JMSException { + public void testReceive() throws JMSException { /* * Set up consumer @@ -519,7 +493,7 @@ public void testReceive() throws InterruptedException, JMSException { * Test receive with timeout */ @Test - public void testReceiveWithTimeout() throws InterruptedException, JMSException { + public void testReceiveWithTimeout() throws JMSException { /* * Set up consumer @@ -544,7 +518,7 @@ public void testReceiveWithTimeout() throws InterruptedException, JMSException { * Test receive no wait */ @Test - public void testReceiveNoWait() throws InterruptedException, JMSException { + public void testReceiveNoWait() throws JMSException { /* * Set up consumer diff --git a/src/test/java/com/amazon/sqs/javamessaging/SQSMessageProducerFifoTest.java b/src/test/java/com/amazon/sqs/javamessaging/SQSMessageProducerFifoTest.java index b76d5ef..038ab1e 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/SQSMessageProducerFifoTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/SQSMessageProducerFifoTest.java @@ -15,10 +15,6 @@ package com.amazon.sqs.javamessaging; -import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; -import com.amazon.sqs.javamessaging.SQSMessageProducer; -import com.amazon.sqs.javamessaging.SQSQueueDestination; -import com.amazon.sqs.javamessaging.SQSSession; import com.amazon.sqs.javamessaging.acknowledge.Acknowledger; import com.amazon.sqs.javamessaging.message.SQSBytesMessage; import com.amazon.sqs.javamessaging.message.SQSMessage; @@ -28,8 +24,10 @@ import com.amazonaws.services.sqs.model.SendMessageRequest; import com.amazonaws.services.sqs.model.SendMessageResult; import com.amazonaws.util.Base64; - -import javax.jms.JMSException; +import jakarta.jms.JMSException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatcher; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -37,13 +35,10 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentMatcher; -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.argThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -68,13 +63,10 @@ public class SQSMessageProducerFifoTest { private AmazonSQSMessagingClientWrapper amazonSQSClient; private Acknowledger acknowledger; - @Before + @BeforeEach public void setup() throws JMSException { - amazonSQSClient = mock(AmazonSQSMessagingClientWrapper.class); - acknowledger = mock(Acknowledger.class); - sqsSession = mock(SQSSession.class); destination = new SQSQueueDestination(QUEUE_NAME, QUEUE_URL); producer = spy(new SQSMessageProducer(amazonSQSClient, sqsSession, destination)); @@ -116,7 +108,6 @@ public void testPropertyToMessageAttributeWithEmpty() throws JMSException { */ @Test public void testPropertyToMessageAttribute() throws JMSException { - internalTestPropertyToMessageAttribute(new SQSTextMessage()); internalTestPropertyToMessageAttribute(new SQSObjectMessage()); @@ -147,7 +138,7 @@ public void internalTestPropertyToMessageAttribute(SQSMessage sqsText) throws JM sqsText.setFloatProperty(floatProperty, (float)5.0); sqsText.setDoubleProperty(doubleProperty, 6.0); sqsText.setStringProperty(stringProperty, "seven"); - sqsText.setObjectProperty(objectProperty, new Integer(8)); + sqsText.setObjectProperty(objectProperty, 8); MessageAttributeValue messageAttributeValueBoolean = new MessageAttributeValue(); messageAttributeValueBoolean.setDataType("Number.Boolean"); @@ -202,7 +193,6 @@ public void internalTestPropertyToMessageAttribute(SQSMessage sqsText) throws JM assertEquals(messageAttributeValueDouble, messageAttribute.get(doubleProperty)); assertEquals(messageAttributeValueString, messageAttribute.get(stringProperty)); assertEquals(messageAttributeValueObject, messageAttribute.get(objectProperty)); - } /** @@ -210,7 +200,6 @@ public void internalTestPropertyToMessageAttribute(SQSMessage sqsText) throws JM */ @Test public void testSendInternalSQSTextMessage() throws JMSException { - String messageBody = "MyText1"; SQSTextMessage msg = spy(new SQSTextMessage(messageBody)); msg.setStringProperty(SQSMessagingClientConstants.JMSX_GROUP_ID, GROUP_ID); @@ -221,7 +210,8 @@ public void testSendInternalSQSTextMessage() throws JMSException { producer.sendInternal(destination, msg); - verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, messageBody, SQSMessage.TEXT_MESSAGE_TYPE, GROUP_ID, DEDUP_ID))); + verify(amazonSQSClient).sendMessage(argThat(new SendMessageRequestMatcher( + QUEUE_URL, messageBody, SQSMessage.TEXT_MESSAGE_TYPE, GROUP_ID, DEDUP_ID))); verify(msg).setJMSDestination(destination); verify(msg).setJMSMessageID("ID:" + MESSAGE_ID); verify(msg).setSQSMessageId(MESSAGE_ID); @@ -237,13 +227,13 @@ public void testSendInternalSQSTextMessageFromReceivedMessage() throws JMSExcept /* * Set up non JMS sqs message */ - Map mapMessageAttributes = new HashMap(); + Map mapMessageAttributes = new HashMap<>(); MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.TEXT_MESSAGE_TYPE); messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING); mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); - Map mapAttributes = new HashMap(); + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); mapAttributes.put(SQSMessagingClientConstants.MESSAGE_GROUP_ID, GROUP_ID); mapAttributes.put(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID, DEDUP_ID); @@ -262,7 +252,8 @@ public void testSendInternalSQSTextMessageFromReceivedMessage() throws JMSExcept producer.sendInternal(destination, msg); - verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, "MessageBody", SQSMessage.TEXT_MESSAGE_TYPE, GROUP_ID, DEDUP_ID))); + verify(amazonSQSClient).sendMessage(argThat(new SendMessageRequestMatcher( + QUEUE_URL, "MessageBody", SQSMessage.TEXT_MESSAGE_TYPE, GROUP_ID, DEDUP_ID))); verify(msg).setJMSDestination(destination); verify(msg).setJMSMessageID("ID:" + MESSAGE_ID); verify(msg).setSQSMessageId(MESSAGE_ID); @@ -274,8 +265,7 @@ public void testSendInternalSQSTextMessageFromReceivedMessage() throws JMSExcept */ @Test public void testSendInternalSQSObjectMessage() throws JMSException { - - HashSet set = new HashSet(); + HashSet set = new HashSet<>(); set.add("data1"); SQSObjectMessage msg = spy(new SQSObjectMessage(set)); @@ -288,7 +278,7 @@ public void testSendInternalSQSObjectMessage() throws JMSException { producer.sendInternal(destination, msg); - verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, msgBody, SQSMessage.OBJECT_MESSAGE_TYPE, GROUP_ID, DEDUP_ID))); + verify(amazonSQSClient).sendMessage(argThat(new SendMessageRequestMatcher(QUEUE_URL, msgBody, SQSMessage.OBJECT_MESSAGE_TYPE, GROUP_ID, DEDUP_ID))); verify(msg).setJMSDestination(destination); verify(msg).setJMSMessageID("ID:" + MESSAGE_ID); verify(msg).setSQSMessageId(MESSAGE_ID); @@ -304,21 +294,21 @@ public void testSendInternalSQSObjectMessageFromReceivedMessage() throws JMSExce /* * Set up non JMS sqs message */ - Map mapMessageAttributes = new HashMap(); + Map mapMessageAttributes = new HashMap<>(); MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.OBJECT_MESSAGE_TYPE); messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING); mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); - Map mapAttributes = new HashMap(); + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); mapAttributes.put(SQSMessagingClientConstants.MESSAGE_GROUP_ID, GROUP_ID); mapAttributes.put(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID, DEDUP_ID); mapAttributes.put(SQSMessagingClientConstants.SEQUENCE_NUMBER, SEQ_NUMBER); // Encode an object to byte array - Integer integer = new Integer("10"); + Integer integer = 10; ByteArrayOutputStream array = new ByteArrayOutputStream(10); ObjectOutputStream oStream = new ObjectOutputStream(array); oStream.writeObject(integer); @@ -338,7 +328,8 @@ public void testSendInternalSQSObjectMessageFromReceivedMessage() throws JMSExce producer.sendInternal(destination, msg); - verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, messageBody, SQSMessage.OBJECT_MESSAGE_TYPE, GROUP_ID, DEDUP_ID))); + verify(amazonSQSClient).sendMessage(argThat(new SendMessageRequestMatcher( + QUEUE_URL, messageBody, SQSMessage.OBJECT_MESSAGE_TYPE, GROUP_ID, DEDUP_ID))); verify(msg).setJMSDestination(destination); verify(msg).setJMSMessageID("ID:" + MESSAGE_ID); verify(msg).setSQSMessageId(MESSAGE_ID); @@ -363,7 +354,8 @@ public void testSendInternalSQSByteMessage() throws JMSException { producer.sendInternal(destination, msg); String messageBody = "AA=="; - verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, messageBody, SQSMessage.BYTE_MESSAGE_TYPE, GROUP_ID, DEDUP_ID))); + verify(amazonSQSClient).sendMessage(argThat(new SendMessageRequestMatcher( + QUEUE_URL, messageBody, SQSMessage.BYTE_MESSAGE_TYPE, GROUP_ID, DEDUP_ID))); verify(msg).setJMSDestination(destination); verify(msg).setJMSMessageID("ID:" + MESSAGE_ID); @@ -375,22 +367,22 @@ public void testSendInternalSQSByteMessage() throws JMSException { * Test sendInternal input with SQSByteMessage */ @Test - public void testSendInternalSQSByteMessageFromReceivedMessage() throws JMSException, IOException { + public void testSendInternalSQSByteMessageFromReceivedMessage() throws JMSException { /* * Set up non JMS sqs message */ - Map mapMessageAttributes = new HashMap(); + Map mapMessageAttributes = new HashMap<>(); MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.BYTE_MESSAGE_TYPE); messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING); mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); - Map mapAttributes = new HashMap(); - mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); - mapAttributes.put(SQSMessagingClientConstants.MESSAGE_GROUP_ID, GROUP_ID); - mapAttributes.put(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID, DEDUP_ID); - mapAttributes.put(SQSMessagingClientConstants.SEQUENCE_NUMBER, SEQ_NUMBER); + Map mapAttributes = Map.of( + SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1", + SQSMessagingClientConstants.MESSAGE_GROUP_ID, GROUP_ID, + SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID, DEDUP_ID, + SQSMessagingClientConstants.SEQUENCE_NUMBER, SEQ_NUMBER); byte[] byteArray = new byte[] { 1, 0, 'a', 65 }; String messageBody = Base64.encodeAsString(byteArray); @@ -407,39 +399,20 @@ public void testSendInternalSQSByteMessageFromReceivedMessage() throws JMSExcept producer.sendInternal(destination, msg); - verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, messageBody, SQSMessage.BYTE_MESSAGE_TYPE, GROUP_ID, DEDUP_ID))); + verify(amazonSQSClient).sendMessage(argThat(new SendMessageRequestMatcher( + QUEUE_URL, messageBody, SQSMessage.BYTE_MESSAGE_TYPE, GROUP_ID, DEDUP_ID))); verify(msg).setJMSDestination(destination); verify(msg).setJMSMessageID("ID:" + MESSAGE_ID); verify(msg).setSQSMessageId(MESSAGE_ID); verify(msg).setSequenceNumber(SEQ_NUMBER_2); } - private class sendMessageRequestMatcher extends ArgumentMatcher { - - private String queueUrl; - private String messagesBody; - private String messageType; - private String groupId; - private String deduplicationId; - - private sendMessageRequestMatcher(String queueUrl, String messagesBody, String messageType, String groupId, String deduplicationId) { - this.queueUrl = queueUrl; - this.messagesBody = messagesBody; - this.messageType = messageType; - this.groupId = groupId; - this.deduplicationId = deduplicationId; - } - + private record SendMessageRequestMatcher(String queueUrl, String messageBody, String messageType, String groupId, + String deduplicationId) implements ArgumentMatcher { @Override - public boolean matches(Object argument) { - - if (!(argument instanceof SendMessageRequest)) { - return false; - } - - SendMessageRequest request = (SendMessageRequest)argument; + public boolean matches(SendMessageRequest request) { assertEquals(queueUrl, request.getQueueUrl()); - assertEquals(messagesBody, request.getMessageBody()); + assertEquals(messageBody, request.getMessageBody()); String messageType = request.getMessageAttributes().get(SQSMessage.JMS_SQS_MESSAGE_TYPE).getStringValue(); assertEquals(this.messageType, messageType); assertEquals(this.groupId, request.getMessageGroupId()); diff --git a/src/test/java/com/amazon/sqs/javamessaging/SQSMessageProducerTest.java b/src/test/java/com/amazon/sqs/javamessaging/SQSMessageProducerTest.java index 497d144..7e1075b 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/SQSMessageProducerTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/SQSMessageProducerTest.java @@ -15,49 +15,42 @@ package com.amazon.sqs.javamessaging; -import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; -import com.amazon.sqs.javamessaging.SQSConnection; -import com.amazon.sqs.javamessaging.SQSMessageProducer; -import com.amazon.sqs.javamessaging.SQSQueueDestination; -import com.amazon.sqs.javamessaging.SQSSession; import com.amazon.sqs.javamessaging.acknowledge.Acknowledger; import com.amazon.sqs.javamessaging.message.SQSBytesMessage; import com.amazon.sqs.javamessaging.message.SQSMessage; import com.amazon.sqs.javamessaging.message.SQSObjectMessage; import com.amazon.sqs.javamessaging.message.SQSTextMessage; -import com.amazonaws.services.sqs.model.DeleteMessageRequest; import com.amazonaws.services.sqs.model.MessageAttributeValue; import com.amazonaws.services.sqs.model.SendMessageRequest; import com.amazonaws.services.sqs.model.SendMessageResult; import com.amazonaws.util.Base64; - -import javax.jms.InvalidDestinationException; -import javax.jms.JMSException; -import javax.jms.IllegalStateException; -import javax.jms.Message; -import javax.jms.Queue; -import javax.jms.Destination; +import jakarta.jms.Destination; +import jakarta.jms.IllegalStateException; +import jakarta.jms.InvalidDestinationException; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.Queue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.ArgumentMatcher; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; +import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.ArgumentMatcher; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.argThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -70,7 +63,6 @@ * Test the SQSMessageProducerTest class */ public class SQSMessageProducerTest { - public static final String QUEUE_URL = "QueueUrl"; public static final String QUEUE_NAME = "QueueName"; public static final String MESSAGE_ID_1 = "MessageId1"; @@ -83,14 +75,11 @@ public class SQSMessageProducerTest { private AmazonSQSMessagingClientWrapper amazonSQSClient; private Acknowledger acknowledger; - @Before + @BeforeEach public void setup() throws JMSException { - amazonSQSClient = mock(AmazonSQSMessagingClientWrapper.class); sqsConnection = mock(SQSConnection.class); - acknowledger = mock(Acknowledger.class); - sqsSession = mock(SQSSession.class); destination = new SQSQueueDestination(QUEUE_NAME, QUEUE_URL); producer = spy(new SQSMessageProducer(amazonSQSClient, sqsSession, destination)); @@ -101,12 +90,8 @@ public void setup() throws JMSException { */ @Test public void testCheckIfDestinationAlreadySet() throws JMSException { - - try { - producer.checkIfDestinationAlreadySet(); - } catch (UnsupportedOperationException uoe) { - assertEquals("MessageProducer already specified a destination at creation time.", uoe.getMessage()); - } + assertThrows(UnsupportedOperationException.class, () -> producer.checkIfDestinationAlreadySet(), + "MessageProducer already specified a destination at creation time."); producer = spy(new SQSMessageProducer(amazonSQSClient, sqsSession, null)); producer.checkIfDestinationAlreadySet(); @@ -122,11 +107,8 @@ public void testCheckClosed() throws JMSException { * Check exception is thrown when producer is closed */ producer.isClosed().set(true); - try { - producer.checkClosed(); - } catch (IllegalStateException ise) { - assertEquals("The producer is closed.", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> producer.checkClosed(), + "The producer is closed."); /* * Check no op when producer is closed @@ -167,7 +149,7 @@ public void testPropertyToMessageAttributeWithEmpty() throws JMSException { SQSMessage sqsByte = new SQSBytesMessage(); Map messageAttributeByte = producer.propertyToMessageAttribute(sqsByte); - assertEquals(0, messageAttributeObject.size()); + assertEquals(0, messageAttributeByte.size()); } /** @@ -175,7 +157,6 @@ public void testPropertyToMessageAttributeWithEmpty() throws JMSException { */ @Test public void testPropertyToMessageAttribute() throws JMSException { - internalTestPropertyToMessageAttribute(new SQSTextMessage()); internalTestPropertyToMessageAttribute(new SQSObjectMessage()); @@ -206,7 +187,7 @@ public void internalTestPropertyToMessageAttribute(SQSMessage sqsText) throws JM sqsText.setFloatProperty(floatProperty, (float)5.0); sqsText.setDoubleProperty(doubleProperty, 6.0); sqsText.setStringProperty(stringProperty, "seven"); - sqsText.setObjectProperty(objectProperty, new Integer(8)); + sqsText.setObjectProperty(objectProperty, 8); MessageAttributeValue messageAttributeValueBoolean = new MessageAttributeValue(); messageAttributeValueBoolean.setDataType("Number.Boolean"); @@ -265,40 +246,27 @@ public void internalTestPropertyToMessageAttribute(SQSMessage sqsText) throws JM assertEquals(messageAttributeValueDouble, messageAttribute.get(doubleProperty)); assertEquals(messageAttributeValueString, messageAttribute.get(stringProperty)); assertEquals(messageAttributeValueObject, messageAttribute.get(objectProperty)); - } /** * Test sendInternal input of Non SQS message */ @Test - public void testSendInternalNonSQSMessage() throws JMSException { - + public void testSendInternalNonSQSMessage() { Message msg = mock(Message.class); - try { - producer.sendInternal(destination, msg); - fail(); - } catch (JMSException jmse) { - // expected - } + assertThrows(JMSException.class, () -> producer.sendInternal(destination, msg)); } /** * Test sendInternal input of Non SQS message */ @Test - public void testSendInternalAlreadyClosed() throws JMSException { - + public void testSendInternalAlreadyClosed() { producer.isClosed().set(true); SQSMessage msg = mock(SQSMessage.class); - try { - producer.sendInternal(destination, msg); - fail(); - } catch (JMSException jmse) { - // expected - } + assertThrows(JMSException.class, () -> producer.sendInternal(destination, msg)); } /** @@ -306,15 +274,9 @@ public void testSendInternalAlreadyClosed() throws JMSException { */ @Test public void testSendInternalNoMessageBody() throws JMSException { - SQSMessage msg = mock(SQSMessage.class); - try { - producer.sendInternal(destination, msg); - fail(); - } catch (JMSException jmse) { - //expected - } + assertThrows(JMSException.class, () -> producer.sendInternal(destination, msg)); verify(msg).setJMSDestination(destination); } @@ -324,7 +286,6 @@ public void testSendInternalNoMessageBody() throws JMSException { */ @Test public void testSendInternalSQSTextMessage() throws JMSException { - String messageBody1 = "MyText1"; String messageBody2 = "MyText2"; SQSTextMessage msg = spy(new SQSTextMessage(messageBody1)); @@ -338,13 +299,14 @@ public void testSendInternalSQSTextMessage() throws JMSException { producer.sendInternal(destination, msg); /* - * Re send the message + * Resend the message */ msg.setText(messageBody2); producer.sendInternal(destination, msg); List messagesBody = Arrays.asList(messageBody1, messageBody2); - verify(amazonSQSClient, times(2)).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, messagesBody, messageAttributes))); + verify(amazonSQSClient, times(2)).sendMessage(argThat( + new SendMessageRequestMatcher(QUEUE_URL, messagesBody, messageAttributes))); verify(msg, times(2)).setJMSDestination(destination); verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_1); verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_2); @@ -361,13 +323,13 @@ public void testSendInternalSQSTextMessageFromReceivedMessage() throws JMSExcept /* * Set up non JMS sqs message */ - Map mapMessageAttributes = new HashMap(); + Map mapMessageAttributes = new HashMap<>(); MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.TEXT_MESSAGE_TYPE); messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING); mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); - Map mapAttributes = new HashMap(); + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); com.amazonaws.services.sqs.model.Message message = @@ -383,8 +345,9 @@ public void testSendInternalSQSTextMessageFromReceivedMessage() throws JMSExcept producer.sendInternal(destination, msg); - List messagesBody = Arrays.asList("MessageBody"); - verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, messagesBody, mapMessageAttributes))); + List messagesBody = List.of("MessageBody"); + verify(amazonSQSClient).sendMessage(argThat( + new SendMessageRequestMatcher(QUEUE_URL, messagesBody, mapMessageAttributes))); verify(msg).setJMSDestination(destination); verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_1); verify(msg).setSQSMessageId(MESSAGE_ID_1); @@ -395,17 +358,9 @@ public void testSendInternalSQSTextMessageFromReceivedMessage() throws JMSExcept */ @Test public void testSendInternalSQSObjectMessage() throws JMSException { - - HashSet set1 = new HashSet(); - set1.add("data1"); - HashSet set2 = new HashSet(); - set2.add("data2"); - - SQSObjectMessage msg = spy(new SQSObjectMessage(set1)); + SQSObjectMessage msg = spy(new SQSObjectMessage((Serializable) Set.of("data1"))); String megBody1 = msg.getMessageBody(); - Map messageAttributes = createMessageAttribute("object"); - when(amazonSQSClient.sendMessage(any(SendMessageRequest.class))) .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_1)) .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_2)); @@ -413,10 +368,10 @@ public void testSendInternalSQSObjectMessage() throws JMSException { producer.sendInternal(destination, msg); /* - * Re send the message + * Resend the message */ msg.clearBody(); - msg.setObject(set2); + msg.setObject((Serializable) Set.of("data2")); String megBody2 = msg.getMessageBody(); producer.sendInternal(destination, msg); @@ -441,18 +396,18 @@ public void testSendInternalSQSObjectMessageFromReceivedMessage() throws JMSExce /* * Set up non JMS sqs message */ - Map mapMessageAttributes = new HashMap(); + Map mapMessageAttributes = new HashMap<>(); MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.OBJECT_MESSAGE_TYPE); messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING); mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); - Map mapAttributes = new HashMap(); + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); // Encode an object to byte array - Integer integer = new Integer("10"); + Integer integer = 10; ByteArrayOutputStream array = new ByteArrayOutputStream(10); ObjectOutputStream oStream = new ObjectOutputStream(array); oStream.writeObject(integer); @@ -475,7 +430,7 @@ public void testSendInternalSQSObjectMessageFromReceivedMessage() throws JMSExce producer.sendInternal(destination, msg); - verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, Arrays.asList(messageBody), + verify(amazonSQSClient).sendMessage(argThat(new SendMessageRequestMatcher(QUEUE_URL, List.of(messageBody), messageAttributes))); verify(msg).setJMSDestination(destination); verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_1); @@ -487,14 +442,12 @@ public void testSendInternalSQSObjectMessageFromReceivedMessage() throws JMSExce */ @Test public void testSendInternalSQSByteMessage() throws JMSException { - SQSBytesMessage msg = spy(new SQSBytesMessage()); - msg.writeByte((byte)0); + msg.writeByte((byte) 0); msg.reset(); Map messageAttributes = createMessageAttribute("byte"); - String messageId = "MessageId"; when(amazonSQSClient.sendMessage(any(SendMessageRequest.class))) .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_1)) .thenReturn(new SendMessageResult().withMessageId(MESSAGE_ID_2)); @@ -502,15 +455,15 @@ public void testSendInternalSQSByteMessage() throws JMSException { producer.sendInternal(destination, msg); /* - * Re send the message + * Resend the message */ msg.clearBody(); msg.writeInt(42); producer.sendInternal(destination, msg); List messagesBody = Arrays.asList("AA==", "AAAAKg=="); - verify(amazonSQSClient, times(2)).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, messagesBody, - messageAttributes))); + verify(amazonSQSClient, times(2)).sendMessage(argThat( + new SendMessageRequestMatcher(QUEUE_URL, messagesBody, messageAttributes))); verify(msg, times(2)).setJMSDestination(destination); verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_1); @@ -523,18 +476,18 @@ public void testSendInternalSQSByteMessage() throws JMSException { * Test sendInternal input with SQSByteMessage */ @Test - public void testSendInternalSQSByteMessageFromReceivedMessage() throws JMSException, IOException { + public void testSendInternalSQSByteMessageFromReceivedMessage() throws JMSException { /* * Set up non JMS sqs message */ - Map mapMessageAttributes = new HashMap(); + Map mapMessageAttributes = new HashMap<>(); MessageAttributeValue messageAttributeValue = new MessageAttributeValue(); messageAttributeValue.setStringValue(SQSMessage.BYTE_MESSAGE_TYPE); messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING); mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); - Map mapAttributes = new HashMap(); + Map mapAttributes = new HashMap<>(); mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); byte[] byteArray = new byte[] { 1, 0, 'a', 65 }; @@ -555,7 +508,7 @@ public void testSendInternalSQSByteMessageFromReceivedMessage() throws JMSExcept producer.sendInternal(destination, msg); - verify(amazonSQSClient).sendMessage(argThat(new sendMessageRequestMatcher(QUEUE_URL, Arrays.asList(messageBody), + verify(amazonSQSClient).sendMessage(argThat(new SendMessageRequestMatcher(QUEUE_URL, List.of(messageBody), messageAttributes))); verify(msg).setJMSDestination(destination); verify(msg).setJMSMessageID("ID:" + MESSAGE_ID_1); @@ -575,32 +528,15 @@ public void testGetQueue() throws JMSException { */ @Test public void testSendNonSQSDestination() throws JMSException { - Queue queue = mock(Queue.class); - SQSTextMessage msg = spy(new SQSTextMessage("MyText")); - try { - producer.send(queue, msg); - fail(); - } catch (InvalidDestinationException ide) { - // expected - } + assertThrows(InvalidDestinationException.class, () -> producer.send(queue, msg)); Destination destination = mock(Destination.class); - try { - producer.send(destination, msg); - fail(); - } catch (InvalidDestinationException ide) { - // expected - } - try { - producer.send(null, msg); - fail(); - } catch (InvalidDestinationException ide) { - // expected - } + assertThrows(InvalidDestinationException.class, () -> producer.send(destination, msg)); + assertThrows(InvalidDestinationException.class, () -> producer.send(null, msg)); } /** @@ -608,15 +544,9 @@ public void testSendNonSQSDestination() throws JMSException { */ @Test public void testSendDestinationAlreadySpecified() throws JMSException { - SQSTextMessage msg = spy(new SQSTextMessage("MyText")); - try { - producer.send(destination, msg); - fail(); - } catch (UnsupportedOperationException ide) { - // expected - } + assertThrows(UnsupportedOperationException.class, () -> producer.send(destination, msg)); verify(producer).checkIfDestinationAlreadySet(); } @@ -626,12 +556,10 @@ public void testSendDestinationAlreadySpecified() throws JMSException { */ @Test public void testSendWithDestination() throws JMSException { - SQSTextMessage msg = spy(new SQSTextMessage("MyText")); producer = spy(new SQSMessageProducer(amazonSQSClient, sqsSession, null)); - doNothing() - .when(producer).sendInternal(destination, msg); + doNothing().when(producer).sendInternal(destination, msg); producer.send(destination, msg); @@ -644,16 +572,13 @@ public void testSendWithDestination() throws JMSException { */ @Test public void testSendDropUnsupportedFeatures() throws JMSException { - int deliveryMode = 1; int priority = 1; long timeToLive = 1; SQSTextMessage msg = spy(new SQSTextMessage("MyText")); - doNothing() - .when(producer).send(destination, msg); - doNothing() - .when(producer).send(msg); + doNothing().when(producer).send(destination, msg); + doNothing().when(producer).send(msg); producer.send(destination, msg, deliveryMode, priority, timeToLive); producer.send(msg, deliveryMode, priority, timeToLive); @@ -667,11 +592,9 @@ public void testSendDropUnsupportedFeatures() throws JMSException { */ @Test public void testSendWithoutDestination() throws JMSException { - SQSTextMessage msg = spy(new SQSTextMessage("MyText")); - doNothing() - .when(producer).sendInternal(destination, msg); + doNothing().when(producer).sendInternal(destination, msg); producer.send(msg); verify(producer).sendInternal(destination, msg); @@ -682,7 +605,6 @@ public void testSendWithoutDestination() throws JMSException { */ @Test public void testCloseAlreadyClosed() throws JMSException { - producer.isClosed().set(true); producer.close(); @@ -695,7 +617,6 @@ public void testCloseAlreadyClosed() throws JMSException { */ @Test public void testClose() throws JMSException { - producer.close(); verify(sqsSession).removeProducer(producer); @@ -721,27 +642,13 @@ public void testSetDeliveryDelay() throws JMSException { @Test - public void testSetDeliveryDelayInvalidDelays() throws JMSException { - try { - producer.setDeliveryDelay(-1); - fail(); - } catch (IllegalArgumentException ide) { - // expected - } - - try { - producer.setDeliveryDelay(TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)); - fail(); - } catch (IllegalArgumentException ide) { - // expected - } - - try { - producer.setDeliveryDelay(20); - fail(); - } catch (IllegalArgumentException ide) { - // expected - } + public void testSetDeliveryDelayInvalidDelays() { + assertThrows(IllegalArgumentException.class, () -> producer.setDeliveryDelay(-1)); + + assertThrows(IllegalArgumentException.class, () -> + producer.setDeliveryDelay(TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS))); + + assertThrows(IllegalArgumentException.class, () -> producer.setDeliveryDelay(20)); } @@ -750,35 +657,18 @@ private Map createMessageAttribute(String type) { messageAttributeValue.setDataType("String"); messageAttributeValue.setStringValue(type); - Map messageAttributes = new HashMap(); - messageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); - return messageAttributes; + return Map.of(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue); } - private class sendMessageRequestMatcher extends ArgumentMatcher { - - private String queueUrl; - private List messagesBody; - private Map messageAttributes; - - private sendMessageRequestMatcher(String queueUrl, List messagesBody, - Map messageAttributes) { - this.queueUrl = queueUrl; - this.messagesBody = messagesBody; - this.messageAttributes = messageAttributes; - } + private record SendMessageRequestMatcher( + String queueUrl, List messagesBody, Map messageAttributes + ) implements ArgumentMatcher { @Override - public boolean matches(Object argument) { - - if (!(argument instanceof SendMessageRequest)) { - return false; - } - - SendMessageRequest reqeust = (SendMessageRequest)argument; - assertEquals(queueUrl, reqeust.getQueueUrl()); - assertTrue(messagesBody.contains(reqeust.getMessageBody())); - assertEquals(messageAttributes , reqeust.getMessageAttributes()); + public boolean matches(SendMessageRequest request) { + assertEquals(queueUrl, request.getQueueUrl()); + assertTrue(messagesBody.contains(request.getMessageBody())); + assertEquals(messageAttributes , request.getMessageAttributes()); return true; } } diff --git a/src/test/java/com/amazon/sqs/javamessaging/SQSMessagingClientUtilTest.java b/src/test/java/com/amazon/sqs/javamessaging/SQSMessagingClientUtilTest.java index 8d5a4be..3b1b313 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/SQSMessagingClientUtilTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/SQSMessagingClientUtilTest.java @@ -15,16 +15,14 @@ package com.amazon.sqs.javamessaging; import com.amazon.sqs.javamessaging.util.SQSMessagingClientUtil; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test the SQSMessagingClientUtilTest class */ public class SQSMessagingClientUtilTest { - String text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-.~!@#$%^&*()`][}{\\|\";'> sqsSessionRunnable.nackQueuedMessages()); } /** @@ -225,48 +180,32 @@ public void testNackQueueMessage() throws JMSException { MessageListener msgListener = mock(MessageListener.class); SQSMessage sqsMessage1 = mock(SQSMessage.class); - when(sqsMessage1.getReceiptHandle()) - .thenReturn("r1"); - when(sqsMessage1.getSQSMessageId()) - .thenReturn("messageId1"); - when(sqsMessage1.getQueueUrl()) - .thenReturn(QUEUE_URL_1); + when(sqsMessage1.getReceiptHandle()).thenReturn("r1"); + when(sqsMessage1.getSQSMessageId()).thenReturn("messageId1"); + when(sqsMessage1.getQueueUrl()).thenReturn(QUEUE_URL_1); SQSMessageConsumerPrefetch.MessageManager msgManager1 = mock(SQSMessageConsumerPrefetch.MessageManager.class); - when(msgManager1.getMessage()) - .thenReturn(sqsMessage1); + when(msgManager1.message()).thenReturn(sqsMessage1); - when(msgManager1.getPrefetchManager()) - .thenReturn(mock(PrefetchManager.class)); + when(msgManager1.prefetchManager()).thenReturn(mock(PrefetchManager.class)); SQSMessage sqsMessage2 = mock(SQSMessage.class); - when(sqsMessage2.getReceiptHandle()) - .thenReturn("r2"); - when(sqsMessage2.getSQSMessageId()) - .thenReturn("messageId2"); - when(sqsMessage2.getQueueUrl()) - .thenReturn(QUEUE_URL_2); + when(sqsMessage2.getReceiptHandle()).thenReturn("r2"); + when(sqsMessage2.getSQSMessageId()).thenReturn("messageId2"); + when(sqsMessage2.getQueueUrl()).thenReturn(QUEUE_URL_2); SQSMessageConsumerPrefetch.MessageManager msgManager2 = mock(SQSMessageConsumerPrefetch.MessageManager.class); - when(msgManager2.getMessage()) - .thenReturn(sqsMessage2); - - when(msgManager2.getPrefetchManager()) - .thenReturn(mock(PrefetchManager.class)); + when(msgManager2.message()).thenReturn(sqsMessage2); + when(msgManager2.prefetchManager()).thenReturn(mock(PrefetchManager.class)); SQSSession.CallbackEntry entry1 = new SQSSession.CallbackEntry(msgListener, msgManager1); SQSSession.CallbackEntry entry2 = new SQSSession.CallbackEntry(msgListener, msgManager2); - when(callbackQueue.isEmpty()) - .thenReturn(false) - .thenReturn(false) - .thenReturn(true); + when(callbackQueue.isEmpty()).thenReturn(false).thenReturn(false).thenReturn(true); - when(callbackQueue.pollFirst()) - .thenReturn(entry1) - .thenReturn(entry2); + when(callbackQueue.pollFirst()).thenReturn(entry1).thenReturn(entry2); - List nackMessageIdentifiers = new ArrayList(); + List nackMessageIdentifiers = new ArrayList<>(); nackMessageIdentifiers.add(new SQSMessageIdentifier(QUEUE_URL_1, "r1", "messageId1")); nackMessageIdentifiers.add(new SQSMessageIdentifier(QUEUE_URL_2, "r2", "messageId2")); @@ -290,26 +229,20 @@ public void testStartingCallbackThrowJMSException() throws JMSException, Interru /* * Set up mocks */ - doThrow(new JMSException("closed")) - .when(sqsSession).startingCallback(consumer); + doThrow(new JMSException("closed")).when(sqsSession).startingCallback(consumer); - doNothing() - .when(sqsSessionRunnable).nackQueuedMessages(); + doNothing().when(sqsSessionRunnable).nackQueuedMessages(); PrefetchManager prefetchManager = mock(PrefetchManager.class); - when(prefetchManager.getMessageConsumer()) - .thenReturn(consumer); + when(prefetchManager.getMessageConsumer()).thenReturn(consumer); SQSMessageConsumerPrefetch.MessageManager msgManager1 = mock(SQSMessageConsumerPrefetch.MessageManager.class); - when(msgManager1.getMessage()) - .thenReturn(mock(SQSMessage.class)); - when(msgManager1.getPrefetchManager()) - .thenReturn(prefetchManager); + when(msgManager1.message()).thenReturn(mock(SQSMessage.class)); + when(msgManager1.prefetchManager()).thenReturn(prefetchManager); SQSSession.CallbackEntry entry1 = new SQSSession.CallbackEntry(null, msgManager1); - when(callbackQueue.pollFirst()) - .thenReturn(entry1); + when(callbackQueue.pollFirst()).thenReturn(entry1); /* * Nack the messages, exit the loop @@ -334,7 +267,7 @@ public void testCallbackQueueEntryMessageListenerEmpty() throws JMSException, In * Set up mocks */ doNothing() - .doThrow(new JMSException("Closing")) + .doThrow(new JMSException("Closing")) .when(sqsSession).startingCallback(any(SQSMessageConsumer.class)); SQSMessageConsumerPrefetch.MessageManager msgManager1 = createMessageManager(1); @@ -343,12 +276,8 @@ public void testCallbackQueueEntryMessageListenerEmpty() throws JMSException, In SQSSession.CallbackEntry entry1 = new SQSSession.CallbackEntry(null, msgManager1); SQSSession.CallbackEntry entry2 = new SQSSession.CallbackEntry(null, msgManager2); - when(callbackQueue.pollFirst()) - .thenReturn(entry1) - .thenReturn(entry2); - - when(callbackQueue.isEmpty()) - .thenReturn(true); + when(callbackQueue.pollFirst()).thenReturn(entry1).thenReturn(entry2); + when(callbackQueue.isEmpty()).thenReturn(true); // Setup ConsumerCloseAfterCallback SQSMessageConsumer messageConsumer = mock(SQSMessageConsumer.class); @@ -378,7 +307,6 @@ public void testCallbackQueueEntryMessageListenerEmpty() throws JMSException, In // Verify do close is called on set ConsumerCloseAfterCallback verify(messageConsumer).doClose(); - verify(sqsSession).finishedCallback(); } @@ -392,30 +320,23 @@ public void testCallbackQueueEntryMessageAckThrowsJMSException() throws JMSExcep * Set up mocks */ doNothing() - .doThrow(new JMSException("Closing")) + .doThrow(new JMSException("Closing")) .when(sqsSession).startingCallback(consumer); SQSMessage sqsMessage1 = mock(SQSMessage.class); - when(sqsMessage1.getReceiptHandle()) - .thenReturn("r1"); - when(sqsMessage1.getSQSMessageId()) - .thenReturn("messageId1"); - when(sqsMessage1.getQueueUrl()) - .thenReturn(QUEUE_URL_1); + when(sqsMessage1.getReceiptHandle()).thenReturn("r1"); + when(sqsMessage1.getSQSMessageId()).thenReturn("messageId1"); + when(sqsMessage1.getQueueUrl()).thenReturn(QUEUE_URL_1); PrefetchManager prefetchManager = mock(PrefetchManager.class); - when(prefetchManager.getMessageConsumer()) - .thenReturn(consumer); + when(prefetchManager.getMessageConsumer()).thenReturn(consumer); SQSMessageConsumerPrefetch.MessageManager msgManager1 = mock(SQSMessageConsumerPrefetch.MessageManager.class); - when(msgManager1.getMessage()) - .thenReturn(sqsMessage1); - when(msgManager1.getPrefetchManager()) - .thenReturn(prefetchManager); + when(msgManager1.message()).thenReturn(sqsMessage1); + when(msgManager1.prefetchManager()).thenReturn(prefetchManager); // Throw an exception when try to acknowledge the message - doThrow(new JMSException("Exception")) - .when(sqsMessage1).acknowledge(); + doThrow(new JMSException("Exception")).when(sqsMessage1).acknowledge(); MessageListener msgListener = mock(MessageListener.class); SQSSession.CallbackEntry entry1 = new SQSSession.CallbackEntry(msgListener, msgManager1); @@ -423,12 +344,9 @@ public void testCallbackQueueEntryMessageAckThrowsJMSException() throws JMSExcep SQSMessageConsumerPrefetch.MessageManager msgManager2 = createMessageManager(2); SQSSession.CallbackEntry entry2 = new SQSSession.CallbackEntry(msgListener, msgManager2); - when(callbackQueue.pollFirst()) - .thenReturn(entry1) - .thenReturn(entry2); + when(callbackQueue.pollFirst()).thenReturn(entry1).thenReturn(entry2); - when(callbackQueue.isEmpty()) - .thenReturn(true); + when(callbackQueue.isEmpty()).thenReturn(true); /* * Nack the messages, exception expected @@ -467,26 +385,20 @@ public void testCallbackQueueEntryMessageNAckThrowsJMSException() throws JMSExce * Set up mocks */ doNothing() - .doThrow(new JMSException("Closing")) + .doThrow(new JMSException("Closing")) .when(sqsSession).startingCallback(consumer); SQSMessage sqsMessage1 = mock(SQSMessage.class); - when(sqsMessage1.getReceiptHandle()) - .thenReturn("r1"); - when(sqsMessage1.getSQSMessageId()) - .thenReturn("messageId1"); - when(sqsMessage1.getQueueUrl()) - .thenReturn(QUEUE_URL_1); + when(sqsMessage1.getReceiptHandle()).thenReturn("r1"); + when(sqsMessage1.getSQSMessageId()).thenReturn("messageId1"); + when(sqsMessage1.getQueueUrl()).thenReturn(QUEUE_URL_1); PrefetchManager prefetchManager = mock(PrefetchManager.class); - when(prefetchManager.getMessageConsumer()) - .thenReturn(consumer); + when(prefetchManager.getMessageConsumer()).thenReturn(consumer); SQSMessageConsumerPrefetch.MessageManager msgManager1 = mock(SQSMessageConsumerPrefetch.MessageManager.class); - when(msgManager1.getMessage()) - .thenReturn(sqsMessage1); - when(msgManager1.getPrefetchManager()) - .thenReturn(prefetchManager); + when(msgManager1.message()).thenReturn(sqsMessage1); + when(msgManager1.prefetchManager()).thenReturn(prefetchManager); // Set message listener as null to force a nack SQSSession.CallbackEntry entry1 = new SQSSession.CallbackEntry(null, msgManager1); @@ -494,15 +406,11 @@ public void testCallbackQueueEntryMessageNAckThrowsJMSException() throws JMSExce SQSMessageConsumerPrefetch.MessageManager msgManager2 = createMessageManager(2); SQSSession.CallbackEntry entry2 = new SQSSession.CallbackEntry(null, msgManager2); - when(callbackQueue.pollFirst()) - .thenReturn(entry1) - .thenReturn(entry2); - when(callbackQueue.isEmpty()) - .thenReturn(true); + when(callbackQueue.pollFirst()).thenReturn(entry1).thenReturn(entry2); + when(callbackQueue.isEmpty()).thenReturn(true); // Throw an exception when try to negative acknowledge the message - doThrow(new JMSException("Exception")) - .when(negativeAcknowledger).action(QUEUE_URL_1, Collections.singletonList("r1")); + doThrow(new JMSException("Exception")).when(negativeAcknowledger).action(QUEUE_URL_1, Collections.singletonList("r1")); /* * Nack the messages, exception expected @@ -532,12 +440,12 @@ public void testCallbackQueueEntryMessageNAckThrowsJMSException() throws JMSExce * Test schedule callback */ @Test - public void testScheduleCallBack() throws JMSException, InterruptedException { + public void testScheduleCallBack() { /* * Set up mocks */ - sqsSessionRunnable.callbackQueue = new ArrayDeque(); + sqsSessionRunnable.callbackQueue = new ArrayDeque<>(); MessageListener msgListener = mock(MessageListener.class); SQSMessageConsumerPrefetch.MessageManager msgManager = mock(SQSMessageConsumerPrefetch.MessageManager.class); @@ -550,8 +458,9 @@ public void testScheduleCallBack() throws JMSException, InterruptedException { SQSSession.CallbackEntry entry = sqsSessionRunnable.callbackQueue.pollFirst(); - assertEquals(msgListener, entry.getMessageListener()); - assertEquals(msgManager, entry.getMessageManager()); + assertNotNull(entry); + assertEquals(msgListener, entry.messageListener()); + assertEquals(msgManager, entry.messageManager()); } /** @@ -560,7 +469,7 @@ public void testScheduleCallBack() throws JMSException, InterruptedException { @Test public void testMessageNotAckWithClientAckMode() throws JMSException, InterruptedException { - /** + /* * Set up mocks */ sqsSessionRunnable = spy(new SQSSessionCallbackScheduler(sqsSession, @@ -573,30 +482,22 @@ public void testMessageNotAckWithClientAckMode() throws JMSException, Interrupte .when(sqsSession).startingCallback(consumer); SQSMessage sqsMessage1 = mock(SQSMessage.class); - when(sqsMessage1.getReceiptHandle()) - .thenReturn("r1"); - when(sqsMessage1.getSQSMessageId()) - .thenReturn("messageId1"); - when(sqsMessage1.getQueueUrl()) - .thenReturn(QUEUE_URL_1); + when(sqsMessage1.getReceiptHandle()).thenReturn("r1"); + when(sqsMessage1.getSQSMessageId()).thenReturn("messageId1"); + when(sqsMessage1.getQueueUrl()).thenReturn(QUEUE_URL_1); PrefetchManager prefetchManager = mock(PrefetchManager.class); - when(prefetchManager.getMessageConsumer()) - .thenReturn(consumer); + when(prefetchManager.getMessageConsumer()).thenReturn(consumer); SQSMessageConsumerPrefetch.MessageManager msgManager1 = mock(SQSMessageConsumerPrefetch.MessageManager.class); - when(msgManager1.getMessage()) - .thenReturn(sqsMessage1); - when(msgManager1.getPrefetchManager()) - .thenReturn(prefetchManager); + when(msgManager1.message()).thenReturn(sqsMessage1); + when(msgManager1.prefetchManager()).thenReturn(prefetchManager); MessageListener msgListener = mock(MessageListener.class); SQSSession.CallbackEntry entry1 = new SQSSession.CallbackEntry(msgListener, msgManager1); - when(callbackQueue.pollFirst()) - .thenReturn(entry1); - when(callbackQueue.isEmpty()) - .thenReturn(true); + when(callbackQueue.pollFirst()).thenReturn(entry1); + when(callbackQueue.isEmpty()).thenReturn(true); /* * Start the callback @@ -619,9 +520,10 @@ public void testMessageNotAckWithClientAckMode() throws JMSException, Interrupte * Test that no auto ack messages occurs when client acknowledge is set */ @Test - public void testWhenListenerThrowsWhenAutoAckThenCallbackQueuePurgedFromMessagesWithSameQueueAndGroup() throws JMSException, InterruptedException { + public void testWhenListenerThrowsWhenAutoAckThenCallbackQueuePurgedFromMessagesWithSameQueueAndGroup() + throws JMSException, InterruptedException { - /** + /* * Set up mocks */ sqsSessionRunnable = spy(new SQSSessionCallbackScheduler(sqsSession, @@ -630,7 +532,7 @@ public void testWhenListenerThrowsWhenAutoAckThenCallbackQueuePurgedFromMessages MessageListener messageListener = mock(MessageListener.class); doThrow(RuntimeException.class) - .when(messageListener).onMessage(any(javax.jms.Message.class)); + .when(messageListener).onMessage(any(jakarta.jms.Message.class)); List messages = new ArrayList(); messages.add(createFifoMessageManager("queue1", "group1", "message1", "handle1")); @@ -651,7 +553,7 @@ public void testWhenListenerThrowsWhenAutoAckThenCallbackQueuePurgedFromMessages ArgumentCaptor indexOfMessageCaptor = ArgumentCaptor.forClass(Integer.class); verify(negativeAcknowledger, times(3)).bulkAction(messageIdentifierListCaptor.capture(), indexOfMessageCaptor.capture()); List nackedMessages = messageIdentifierListCaptor.getAllValues().get(0); - int nackedMessagesSize = indexOfMessageCaptor.getAllValues().get(0).intValue(); + int nackedMessagesSize = indexOfMessageCaptor.getAllValues().get(0); //failing to process 'message1' should nack all messages for queue1 and group1, that is 'message1', 'message2' and 'message5' assertEquals(3, nackedMessagesSize); @@ -660,12 +562,13 @@ public void testWhenListenerThrowsWhenAutoAckThenCallbackQueuePurgedFromMessages assertEquals("message5", nackedMessages.get(2).getSQSMessageID()); } - private SQSMessageConsumerPrefetch.MessageManager createFifoMessageManager(String queueUrl, String groupId, String messageId, String receiptHandle) throws JMSException { + private SQSMessageConsumerPrefetch.MessageManager createFifoMessageManager( + String queueUrl, String groupId, String messageId, String receiptHandle) throws JMSException { Message message = new Message(); message.setBody("body"); message.setMessageId(messageId); message.setReceiptHandle(receiptHandle); - Map attributes = new HashMap(); + Map attributes = new HashMap<>(); attributes.put(SQSMessagingClientConstants.SEQUENCE_NUMBER, "728374687246872364"); attributes.put(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID, messageId); attributes.put(SQSMessagingClientConstants.MESSAGE_GROUP_ID, groupId); @@ -675,28 +578,21 @@ private SQSMessageConsumerPrefetch.MessageManager createFifoMessageManager(Strin PrefetchManager prefetchManager = mock(PrefetchManager.class); when(prefetchManager.getMessageConsumer()) .thenReturn(consumer); - SQSMessageConsumerPrefetch.MessageManager msgManager = new SQSMessageConsumerPrefetch.MessageManager(prefetchManager, sqsMessage); - return msgManager; + return new SQSMessageConsumerPrefetch.MessageManager(prefetchManager, sqsMessage); } private SQSMessageConsumerPrefetch.MessageManager createMessageManager(int index) { SQSMessage sqsMessage = mock(SQSMessage.class); - when(sqsMessage.getReceiptHandle()) - .thenReturn("r" + index); - when(sqsMessage.getSQSMessageId()) - .thenReturn("messageId" + index); - when(sqsMessage.getQueueUrl()) - .thenReturn(QUEUE_URL_PREFIX + index); + when(sqsMessage.getReceiptHandle()).thenReturn("r" + index); + when(sqsMessage.getSQSMessageId()).thenReturn("messageId" + index); + when(sqsMessage.getQueueUrl()).thenReturn(QUEUE_URL_PREFIX + index); PrefetchManager prefetchManager = mock(PrefetchManager.class); - when(prefetchManager.getMessageConsumer()) - .thenReturn(consumer); + when(prefetchManager.getMessageConsumer()).thenReturn(consumer); SQSMessageConsumerPrefetch.MessageManager msgManager = mock(SQSMessageConsumerPrefetch.MessageManager.class); - when(msgManager.getMessage()) - .thenReturn(sqsMessage); - when(msgManager.getPrefetchManager()) - .thenReturn(prefetchManager); + when(msgManager.message()).thenReturn(sqsMessage); + when(msgManager.prefetchManager()).thenReturn(prefetchManager); return msgManager; } } diff --git a/src/test/java/com/amazon/sqs/javamessaging/SQSSessionTest.java b/src/test/java/com/amazon/sqs/javamessaging/SQSSessionTest.java index dbd36b3..1df1c41 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/SQSSessionTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/SQSSessionTest.java @@ -14,17 +14,7 @@ */ package com.amazon.sqs.javamessaging; -import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; -import com.amazon.sqs.javamessaging.PrefetchManager; -import com.amazon.sqs.javamessaging.SQSConnection; -import com.amazon.sqs.javamessaging.SQSMessageConsumer; -import com.amazon.sqs.javamessaging.SQSMessageConsumerPrefetch; -import com.amazon.sqs.javamessaging.SQSMessageProducer; -import com.amazon.sqs.javamessaging.SQSQueueDestination; -import com.amazon.sqs.javamessaging.SQSSession; import com.amazon.sqs.javamessaging.acknowledge.AcknowledgeMode; -import com.amazon.sqs.javamessaging.acknowledge.SQSMessageIdentifier; -import com.amazon.sqs.javamessaging.message.SQSMessage; import com.amazon.sqs.javamessaging.message.SQSObjectMessage; import com.amazon.sqs.javamessaging.message.SQSTextMessage; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchRequest; @@ -32,43 +22,38 @@ import com.amazonaws.services.sqs.model.GetQueueUrlResult; import com.amazonaws.services.sqs.model.ReceiveMessageRequest; import com.amazonaws.services.sqs.model.ReceiveMessageResult; +import jakarta.jms.Destination; +import jakarta.jms.IllegalStateException; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageProducer; +import jakarta.jms.ObjectMessage; +import jakarta.jms.Queue; +import jakarta.jms.TextMessage; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.ArgumentMatcher; -import javax.jms.Destination; -import javax.jms.IllegalStateException; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.ObjectMessage; -import javax.jms.Queue; -import javax.jms.TextMessage; - -import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.ArgumentMatcher; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.argThat; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -89,39 +74,35 @@ public class SQSSessionTest { private SQSConnection parentSQSConnection; private Set messageConsumers; private Set messageProducers; - private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); + private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); private SQSMessageConsumer consumer1; private SQSMessageConsumer consumer2; private SQSMessageProducer producer1; private SQSMessageProducer producer2; private AmazonSQSMessagingClientWrapper sqsClientJMSWrapper; - @Before + @BeforeEach public void setup() throws JMSException { - sqsClientJMSWrapper = mock(AmazonSQSMessagingClientWrapper.class); parentSQSConnection = mock(SQSConnection.class); - when(parentSQSConnection.getWrappedAmazonSQSClient()) - .thenReturn(sqsClientJMSWrapper); - - messageConsumers = new HashSet(); - messageProducers = new HashSet(); + when(parentSQSConnection.getWrappedAmazonSQSClient()).thenReturn(sqsClientJMSWrapper); consumer1 = mock(SQSMessageConsumer.class); - when(consumer1.getQueue()).thenReturn(new SQSQueueDestination("name1", "url1")); consumer2 = mock(SQSMessageConsumer.class); + + when(consumer1.getQueue()).thenReturn(new SQSQueueDestination("name1", "url1")); when(consumer2.getQueue()).thenReturn(new SQSQueueDestination("name2", "url2")); - messageConsumers.add(consumer1); - messageConsumers.add(consumer2); + + messageConsumers = new HashSet<>(Set.of(consumer1, consumer2)); producer1 = mock(SQSMessageProducer.class); producer2 = mock(SQSMessageProducer.class); - messageProducers.add(producer1); - messageProducers.add(producer2); + + messageProducers = new HashSet<>(Set.of(producer1, producer2)); sqsSession = spy(new SQSSession(parentSQSConnection, AcknowledgeMode.ACK_AUTO, - messageConsumers, messageProducers)); + messageConsumers, messageProducers)); } /** @@ -139,12 +120,7 @@ public void testStopNoOpIfAlreadyClosed() throws JMSException { /* * stop consumer */ - try { - sqsSession.stop(); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Session is closed", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsSession.stop(), "Session is closed"); /* * Verify results @@ -157,7 +133,7 @@ public void testStopNoOpIfAlreadyClosed() throws JMSException { * Test stop is a no op if closing */ @Test - public void testStopNoOpIfClosing() throws JMSException { + public void testStopNoOpIfClosing() { /* * Set up session @@ -167,12 +143,7 @@ public void testStopNoOpIfClosing() throws JMSException { /* * stop consumer */ - try { - sqsSession.stop(); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Session is closed or closing", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsSession.stop(), "Session is closed or closing"); /* * Verify results @@ -185,7 +156,7 @@ public void testStopNoOpIfClosing() throws JMSException { * Test start is a no op if closing */ @Test - public void testStartNoOpIfClosing() throws JMSException { + public void testStartNoOpIfClosing() { /* * Set up session @@ -195,12 +166,7 @@ public void testStartNoOpIfClosing() throws JMSException { /* * stop consumer */ - try { - sqsSession.start(); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Session is closed or closing", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsSession.start(), "Session is closed or closing"); /* * Verify results @@ -228,12 +194,7 @@ public void testStartNoOpIfAlreadyClosed() throws JMSException { /* * stop consumer */ - try { - sqsSession.start(); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Session is closed", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsSession.start(), "Session is closed"); /* * Verify results @@ -257,34 +218,28 @@ public void testStopBlocksOnStateLock() throws InterruptedException { final CountDownLatch passedSessionStopCall = new CountDownLatch(1); // Run a thread to hold the stateLock - executorService.execute(new Runnable() { - @Override - public void run() { - try { - synchronized (sqsSession.getStateLock()) { - holdStateLock.countDown(); - mainRelease.await(); - } - } catch (InterruptedException e) { - e.printStackTrace(); + executorService.execute(() -> { + try { + synchronized (sqsSession.getStateLock()) { + holdStateLock.countDown(); + mainRelease.await(); } + } catch (InterruptedException e) { + e.printStackTrace(); } }); // Waiting for the thread to hold state lock holdStateLock.await(); - // Run another thread that tries to stop the session while state lock is been held - executorService.execute(new Runnable() { - @Override - public void run() { - beforeSessionStopCall.countDown(); - try { - sqsSession.stop(); - passedSessionStopCall.countDown(); - } catch (IllegalStateException e) { - e.printStackTrace(); - } + // Run another thread that tries to stop the session while state lock is being held + executorService.execute(() -> { + beforeSessionStopCall.countDown(); + try { + sqsSession.stop(); + passedSessionStopCall.countDown(); + } catch (IllegalStateException e) { + e.printStackTrace(); } }); @@ -292,7 +247,7 @@ public void run() { Thread.sleep(10); // Ensure that we wait on state lock - assertEquals(false, passedSessionStopCall.await(2, TimeUnit.SECONDS)); + assertFalse(passedSessionStopCall.await(2, TimeUnit.SECONDS)); // Release the thread holding the state lock mainRelease.countDown(); @@ -319,34 +274,28 @@ public void testStartBlocksOnStateLock() throws InterruptedException { final CountDownLatch passedSessionStartCall = new CountDownLatch(1); // Run a thread to hold the stateLock - executorService.execute(new Runnable() { - @Override - public void run() { - try { - synchronized (sqsSession.getStateLock()) { - holdStateLock.countDown(); - mainRelease.await(); - } - } catch (InterruptedException e) { - e.printStackTrace(); + executorService.execute(() -> { + try { + synchronized (sqsSession.getStateLock()) { + holdStateLock.countDown(); + mainRelease.await(); } + } catch (InterruptedException e) { + e.printStackTrace(); } }); // Waiting for the thread to hold state lock holdStateLock.await(); - // Run another thread that tries to start the session while state lock is been held - executorService.execute(new Runnable() { - @Override - public void run() { - try { - beforeSessionStartCall.countDown(); - sqsSession.start(); - passedSessionStartCall.countDown(); - } catch (IllegalStateException e) { - e.printStackTrace(); - } + // Run another thread that tries to start the session while state lock is being held + executorService.execute(() -> { + try { + beforeSessionStartCall.countDown(); + sqsSession.start(); + passedSessionStartCall.countDown(); + } catch (IllegalStateException e) { + e.printStackTrace(); } }); @@ -354,7 +303,7 @@ public void run() { Thread.sleep(10); // Ensure that we wait on state lock - assertEquals(false, passedSessionStartCall.await(2, TimeUnit.SECONDS)); + assertFalse(passedSessionStartCall.await(2, TimeUnit.SECONDS)); // Release the thread holding the state lock mainRelease.countDown(); @@ -373,103 +322,45 @@ public void run() { public void testUnsupportedFeature() throws JMSException { assertFalse(sqsSession.getTransacted()); - try { - sqsSession.commit(); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.commit(), SQSMessagingClientConstants.UNSUPPORTED_METHOD); - try { - sqsSession.rollback(); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.rollback(), SQSMessagingClientConstants.UNSUPPORTED_METHOD); - try { - sqsSession.unsubscribe("test"); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.unsubscribe("test"), + SQSMessagingClientConstants.UNSUPPORTED_METHOD); - try { - sqsSession.createTopic("topic"); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createTopic("topic"), + SQSMessagingClientConstants.UNSUPPORTED_METHOD); - try { - sqsSession.createDurableSubscriber(null, "name"); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createDurableSubscriber(null, "name"), + SQSMessagingClientConstants.UNSUPPORTED_METHOD); - try { - sqsSession.createDurableSubscriber(null, "name", "messageSelector", false); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createDurableSubscriber(null, "name", "messageSelector", false), + SQSMessagingClientConstants.UNSUPPORTED_METHOD); - try { - sqsSession.createBrowser(null); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createBrowser(null), + SQSMessagingClientConstants.UNSUPPORTED_METHOD); - try { - sqsSession.createBrowser(null, "messageSelector"); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createBrowser(null, "messageSelector"), + SQSMessagingClientConstants.UNSUPPORTED_METHOD); - try { - sqsSession.createTemporaryQueue(); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createTemporaryQueue(), + SQSMessagingClientConstants.UNSUPPORTED_METHOD); - try { - sqsSession.createTemporaryTopic(); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createTemporaryTopic(), + SQSMessagingClientConstants.UNSUPPORTED_METHOD); - try { - sqsSession.getMessageListener(); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.getMessageListener(), + SQSMessagingClientConstants.UNSUPPORTED_METHOD); - try { - sqsSession.setMessageListener(null); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.setMessageListener(null), + SQSMessagingClientConstants.UNSUPPORTED_METHOD); - try { - sqsSession.createStreamMessage(); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createStreamMessage(), + SQSMessagingClientConstants.UNSUPPORTED_METHOD); - try { - sqsSession.createMapMessage(); - fail(); - } catch (JMSException e) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, e.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createMapMessage(), + SQSMessagingClientConstants.UNSUPPORTED_METHOD); } /** @@ -488,7 +379,7 @@ public void testWaitForAllCallbackCompleteBlocksOnStateLock() throws Interrupted sqsSession = new SQSSession(parentSQSConnection, AcknowledgeMode.ACK_AUTO, messageConsumers, messageProducers); sqsSession.start(); - MessageListener msgListener = mock(MessageListener.class); + SQSMessageConsumerPrefetch.MessageManager msgManager = mock(SQSMessageConsumerPrefetch.MessageManager.class); PrefetchManager prefetchManager = new PrefetchManager() { @@ -512,30 +403,25 @@ public SQSMessageConsumer getMessageConsumer() { } }; - when(msgManager.getPrefetchManager()) - .thenReturn(prefetchManager); + when(msgManager.prefetchManager()).thenReturn(prefetchManager); sqsSession.getSqsSessionRunnable().scheduleCallBacks(null, Collections.singletonList(msgManager)); // Waiting for the thread to hold state lock holdStateLock.await(); - // Run another thread that tries to close the consumer while state lock is been held - executorService.execute(new Runnable() { - @Override - public void run() { - beforeSessionWaitCall.countDown(); - sqsSession.waitForCallbackComplete(); - passedSessionWaitCall.countDown(); - - } + // Run another thread that tries to close the consumer while state lock is being held + executorService.execute(() -> { + beforeSessionWaitCall.countDown(); + sqsSession.waitForCallbackComplete(); + passedSessionWaitCall.countDown(); }); beforeSessionWaitCall.await(); Thread.sleep(10); // Ensure that we wait on state lock this time is longer then waitForAllCallbackComplete timeoutMillis input - assertEquals(false, passedSessionWaitCall.await(1, TimeUnit.SECONDS)); + assertFalse(passedSessionWaitCall.await(1, TimeUnit.SECONDS)); // Release the state lock mainRelease.countDown(); @@ -562,24 +448,21 @@ public void testWaitForAllCallbackComplete() throws InterruptedException, JMSExc /* * call waitForAllCallbackComplete in different thread */ - executorService.execute(new Runnable() { - @Override - public void run() { - beforeWaitCall.countDown(); - sqsSession.waitForCallbackComplete(); - passedWaitCall.countDown(); - } + executorService.execute(() -> { + beforeWaitCall.countDown(); + sqsSession.waitForCallbackComplete(); + passedWaitCall.countDown(); }); // Yield execution to allow the consumer to wait - assertEquals(true, beforeWaitCall.await(10, TimeUnit.SECONDS)); + assertTrue(beforeWaitCall.await(10, TimeUnit.SECONDS)); Thread.sleep(10); // Release the lock and ensure that we are still waiting since the prefetch message still equal to the limit synchronized (sqsSession.getStateLock()) { sqsSession.getStateLock().notifyAll(); } - assertEquals(false, passedWaitCall.await(1, TimeUnit.SECONDS)); + assertFalse(passedWaitCall.await(1, TimeUnit.SECONDS)); // Simulate callback finished sqsSession.finishedCallback(); @@ -590,7 +473,7 @@ public void run() { * Test finishedCallback decrease callbackCounter */ @Test - public void testFinishedCallback() throws InterruptedException, JMSException { + public void testFinishedCallback() throws JMSException { /* * Set up session @@ -605,7 +488,7 @@ public void testFinishedCallback() throws InterruptedException, JMSException { /* * verify result */ - assertEquals(false, sqsSession.isCallbackActive()); + assertFalse(sqsSession.isCallbackActive()); } /** @@ -627,14 +510,14 @@ public void testStartingCallbackNoOpIfAlreadyClosed() throws InterruptedExceptio /* * Verify results */ - assertEquals(false, sqsSession.isCallbackActive()); + assertFalse(sqsSession.isCallbackActive()); } /** * Test startingCallback is a no op if closing */ @Test - public void testStartingCallbackNoOpIfClosing() throws InterruptedException { + public void testStartingCallbackNoOpIfClosing() { /* * Set up session @@ -645,12 +528,7 @@ public void testStartingCallbackNoOpIfClosing() throws InterruptedException { /* * Starting Callback */ - try { - sqsSession.startingCallback(consumer1); - fail(); - } catch (JMSException e) { - e.printStackTrace(); - } + assertThrows(JMSException.class, () -> sqsSession.startingCallback(consumer1)); } /** @@ -669,30 +547,25 @@ public void testStartingCallback() throws InterruptedException { /* * call startingCallback in different thread */ - executorService.execute(new Runnable() { - @Override - public void run() { - try { - beforeWaitCall.countDown(); - sqsSession.startingCallback(consumer1); - passedWaitCall.countDown(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (JMSException e) { - e.printStackTrace(); - } + executorService.execute(() -> { + try { + beforeWaitCall.countDown(); + sqsSession.startingCallback(consumer1); + passedWaitCall.countDown(); + } catch (InterruptedException | JMSException e) { + e.printStackTrace(); } }); // Yield execution to allow the session to wait - assertEquals(true, beforeWaitCall.await(10, TimeUnit.SECONDS)); + assertTrue(beforeWaitCall.await(10, TimeUnit.SECONDS)); Thread.sleep(10); // Release the lock and ensure that we are still waiting since the did not run synchronized (sqsSession.getStateLock()) { sqsSession.getStateLock().notifyAll(); } - assertEquals(false, passedWaitCall.await(2, TimeUnit.SECONDS)); + assertFalse(passedWaitCall.await(2, TimeUnit.SECONDS)); // Simulate callback finished sqsSession.setRunning(true); @@ -701,7 +574,7 @@ public void run() { sqsSession.getStateLock().notifyAll(); } passedWaitCall.await(); - assertEquals(true, sqsSession.isCallbackActive()); + assertTrue(sqsSession.isCallbackActive()); } /** @@ -709,7 +582,6 @@ public void run() { */ @Test public void testRemoveConsumer() { - assertEquals(2, messageConsumers.size()); /* @@ -729,7 +601,6 @@ public void testRemoveConsumer() { */ @Test public void testRemoveProducer() { - assertEquals(2, messageProducers.size()); /* @@ -749,7 +620,7 @@ public void testRemoveProducer() { * Test create queue when session is already closed */ @Test - public void testCreateQueueWhenAlreadyClosed() throws JMSException { + public void testCreateQueueWhenAlreadyClosed() { /* * Set up session @@ -759,12 +630,7 @@ public void testCreateQueueWhenAlreadyClosed() throws JMSException { /* * Create queue */ - try { - sqsSession.createQueue("Test"); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Session is closed", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsSession.createQueue("Test"), "Session is closed"); } /** @@ -772,7 +638,6 @@ public void testCreateQueueWhenAlreadyClosed() throws JMSException { */ @Test public void testCreateQueue() throws JMSException { - GetQueueUrlResult result = new GetQueueUrlResult().withQueueUrl(QUEUE_URL); when(sqsClientJMSWrapper.getQueueUrl(QUEUE_NAME)) .thenReturn(result); @@ -785,7 +650,7 @@ public void testCreateQueue() throws JMSException { /* * Verify results */ - assert(queue instanceof SQSQueueDestination); + assertTrue(queue instanceof SQSQueueDestination); assertEquals(QUEUE_NAME, queue.getQueueName()); assertEquals(QUEUE_URL, ((SQSQueueDestination) queue).getQueueUrl()); } @@ -795,10 +660,8 @@ public void testCreateQueue() throws JMSException { */ @Test public void testCreateQueueWithOwnerAccountId() throws JMSException { - GetQueueUrlResult result = new GetQueueUrlResult().withQueueUrl(QUEUE_URL); - when(sqsClientJMSWrapper.getQueueUrl(QUEUE_NAME, OWNER_ACCOUNT_ID)) - .thenReturn(result); + when(sqsClientJMSWrapper.getQueueUrl(QUEUE_NAME, OWNER_ACCOUNT_ID)).thenReturn(result); /* * Create queue @@ -808,7 +671,7 @@ public void testCreateQueueWithOwnerAccountId() throws JMSException { /* * Verify results */ - assert(queue instanceof SQSQueueDestination); + assertTrue(queue instanceof SQSQueueDestination); assertEquals(QUEUE_NAME, queue.getQueueName()); assertEquals(QUEUE_URL, ((SQSQueueDestination) queue).getQueueUrl()); } @@ -817,7 +680,7 @@ public void testCreateQueueWithOwnerAccountId() throws JMSException { * Test create consumer when session is already closed */ @Test - public void testCreateConsumerProducerWhenAlreadyClosed() throws JMSException { + public void testCreateConsumerProducerWhenAlreadyClosed() { /* * Set up session @@ -829,29 +692,20 @@ public void testCreateConsumerProducerWhenAlreadyClosed() throws JMSException { /* * Create consumer */ - try { - sqsSession.createConsumer(destination); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Session is closed", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsSession.createConsumer(destination), "Session is closed"); /* * Create producer */ - try { - sqsSession.createProducer(destination); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Session is closed", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsSession.createProducer(destination), "Session is closed"); + } /** * Test create consumer when session is closing */ @Test - public void testCreateConsumerProducerWhenClosing() throws JMSException { + public void testCreateConsumerProducerWhenClosing() { /* * Set up session @@ -862,29 +716,20 @@ public void testCreateConsumerProducerWhenClosing() throws JMSException { /* * Create consumer */ - try { - sqsSession.createConsumer(destination); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Session is closed or closing", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsSession.createConsumer(destination), "Session is closed or closing"); /* * Create producer */ - try { - sqsSession.createProducer(destination); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Session is closed or closing", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsSession.createProducer(destination), "Session is closed or closing"); + } /** * Test create consumer when destination is non SQSQueueDestination */ @Test - public void testCreateConsumerProducerNonSQSQueueDestination() throws JMSException { + public void testCreateConsumerProducerNonSQSQueueDestination() { /* * Set up session @@ -894,22 +739,14 @@ public void testCreateConsumerProducerNonSQSQueueDestination() throws JMSExcepti /* * Create consumer */ - try { - sqsSession.createConsumer(destination); - fail(); - } catch(JMSException jmse) { - assertEquals("Actual type of Destination/Queue has to be SQSQueueDestination", jmse.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createConsumer(destination), + "Actual type of Destination/Queue has to be SQSQueueDestination"); - /* + /* * Create producer */ - try { - sqsSession.createProducer(destination); - fail(); - } catch(JMSException jmse) { - assertEquals("Actual type of Destination/Queue has to be SQSQueueDestination", jmse.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createProducer(destination), + "Actual type of Destination/Queue has to be SQSQueueDestination"); } /** @@ -924,8 +761,7 @@ public void testCreateConsumerNotRunning() throws JMSException { SQSMessageConsumer consumer3 = mock(SQSMessageConsumer.class); SQSQueueDestination destination = new SQSQueueDestination(QUEUE_NAME, QUEUE_URL); sqsSession.setRunning(false); - doReturn(consumer3) - .when(sqsSession).createSQSMessageConsumer(destination); + doReturn(consumer3).when(sqsSession).createSQSMessageConsumer(destination); /* * Create consumer @@ -952,8 +788,7 @@ public void testCreateConsumerRunning() throws JMSException { SQSMessageConsumer consumer3 = mock(SQSMessageConsumer.class); SQSQueueDestination destination = new SQSQueueDestination(QUEUE_NAME, QUEUE_URL); sqsSession.setRunning(true); - doReturn(consumer3) - .when(sqsSession).createSQSMessageConsumer(destination); + doReturn(consumer3).when(sqsSession).createSQSMessageConsumer(destination); /* * Create consumer @@ -969,10 +804,10 @@ public void testCreateConsumerRunning() throws JMSException { } /** - * Test create consumer with non null message selector + * Test create consumer with non-null message selector */ @Test - public void testCreateConsumerNonNullMessageSelector() throws JMSException { + public void testCreateConsumerNonNullMessageSelector() { /* * Set up session @@ -986,19 +821,11 @@ public void testCreateConsumerNonNullMessageSelector() throws JMSException { /* * Create consumer */ - try { - sqsSession.createConsumer(destination, "Selector"); - fail(); - } catch(JMSException jmse) { - assertEquals("SQSSession does not support MessageSelector. This should be null.", jmse.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createConsumer(destination, "Selector"), + "SQSSession does not support MessageSelector. This should be null."); - try { - sqsSession.createConsumer(destination, "Selector", true); - fail(); - } catch(JMSException jmse) { - assertEquals("SQSSession does not support MessageSelector. This should be null.", jmse.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createConsumer(destination, "Selector", true), + "SQSSession does not support MessageSelector. This should be null."); } /** @@ -1013,8 +840,7 @@ public void testCreateConsumerWithMessageSelector() throws JMSException { SQSMessageConsumer consumer3 = mock(SQSMessageConsumer.class); SQSQueueDestination destination = new SQSQueueDestination(QUEUE_NAME, QUEUE_URL); sqsSession.setRunning(true); - doReturn(consumer3) - .when(sqsSession).createSQSMessageConsumer(destination); + doReturn(consumer3).when(sqsSession).createSQSMessageConsumer(destination); /* * Create consumer @@ -1084,13 +910,10 @@ public void testRecover() throws JMSException, InterruptedException { MessageConsumer consumer1 = sqsSession.createConsumer(sqsSession.createQueue("queue1")); MessageConsumer consumer2 = sqsSession.createConsumer(sqsSession.createQueue("queue2")); final CountDownLatch listenerRelease = new CountDownLatch(1); - consumer2.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - listenerRelease.await(); - } catch (InterruptedException e) { - } + consumer2.setMessageListener(message -> { + try { + listenerRelease.await(); + } catch (InterruptedException ignored) { } }); @@ -1129,14 +952,12 @@ public void onMessage(Message message) { ArgumentCaptor changeVisibilityCaptor = ArgumentCaptor.forClass(ChangeMessageVisibilityBatchRequest.class); verify(sqsClientJMSWrapper, times(2)).changeMessageVisibilityBatch(changeVisibilityCaptor.capture()); - List changeVisibilityRequests = changeVisibilityCaptor.getAllValues(); - - Set handles = new HashSet(); - for (ChangeMessageVisibilityBatchRequest request : changeVisibilityRequests) { - for (ChangeMessageVisibilityBatchRequestEntry entry : request.getEntries()) { - handles.add(entry.getReceiptHandle()); - } - } + + Set handles = changeVisibilityCaptor.getAllValues().stream() + .map(ChangeMessageVisibilityBatchRequest::getEntries) + .flatMap(Collection::stream) + .map(ChangeMessageVisibilityBatchRequestEntry::getReceiptHandle) + .collect(Collectors.toSet()); assertEquals(4, handles.size()); assertTrue(handles.contains("queue1-group1-message1")); @@ -1149,35 +970,25 @@ public void onMessage(Message message) { sqsSession.close(); } - private static class ReceiveRequestMatcher extends ArgumentMatcher { - private String queueUrl; - - public ReceiveRequestMatcher(String queueUrl) { - this.queueUrl = queueUrl; - } + private record ReceiveRequestMatcher(String queueUrl) implements ArgumentMatcher { @Override - public boolean matches(Object argument) { - if (argument instanceof ReceiveMessageRequest) { - ReceiveMessageRequest request = (ReceiveMessageRequest)argument; - return queueUrl.equals(request.getQueueUrl()); - } else { - return false; - } + public boolean matches(ReceiveMessageRequest request) { + return request != null && queueUrl.equals(request.getQueueUrl()); } - } - private com.amazonaws.services.sqs.model.Message createFifoMessage(String groupId, String messageId, String receiptHandle) throws JMSException { + private com.amazonaws.services.sqs.model.Message createFifoMessage(String groupId, String messageId, String receiptHandle) { com.amazonaws.services.sqs.model.Message message = new com.amazonaws.services.sqs.model.Message(); message.setBody("body"); message.setMessageId(messageId); message.setReceiptHandle(receiptHandle); - Map attributes = new HashMap(); - attributes.put(SQSMessagingClientConstants.SEQUENCE_NUMBER, "728374687246872364"); - attributes.put(SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID, messageId); - attributes.put(SQSMessagingClientConstants.MESSAGE_GROUP_ID, groupId); - attributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "0"); + Map attributes = Map.of( + SQSMessagingClientConstants.SEQUENCE_NUMBER, "728374687246872364", + SQSMessagingClientConstants.MESSAGE_DEDUPLICATION_ID, messageId, + SQSMessagingClientConstants.MESSAGE_GROUP_ID, groupId, + SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "0" + ); message.setAttributes(attributes); return message; } @@ -1186,7 +997,7 @@ private com.amazonaws.services.sqs.model.Message createFifoMessage(String groupI * Test recover when session is already closed */ @Test - public void testRecoverWhenAlreadyClosed() throws JMSException { + public void testRecoverWhenAlreadyClosed() { /* * Set up session @@ -1196,12 +1007,7 @@ public void testRecoverWhenAlreadyClosed() throws JMSException { /* * Recover */ - try { - sqsSession.recover(); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Session is closed", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsSession.recover(), "Session is closed"); } /** @@ -1235,7 +1041,7 @@ public void testDoCloseWhenAlreadyClosed() throws JMSException { * Test close when session is closing */ @Test - public void testDoCloseWhenClosing() throws JMSException, InterruptedException { + public void testDoCloseWhenClosing() throws InterruptedException { /* * Set up session and mocks @@ -1247,28 +1053,25 @@ public void testDoCloseWhenClosing() throws JMSException, InterruptedException { /* * call doClose in different thread */ - executorService.execute(new Runnable() { - @Override - public void run() { - try { - beforeDoCloseCall.countDown(); - sqsSession.doClose(); - passedDoCloseCall.countDown(); - } catch (JMSException e) { - e.printStackTrace(); - } + executorService.execute(() -> { + try { + beforeDoCloseCall.countDown(); + sqsSession.doClose(); + passedDoCloseCall.countDown(); + } catch (JMSException e) { + e.printStackTrace(); } }); // Yield execution to allow the session to wait - assertEquals(true, beforeDoCloseCall.await(10, TimeUnit.SECONDS)); + assertTrue(beforeDoCloseCall.await(10, TimeUnit.SECONDS)); Thread.sleep(10); // Release the lock and ensure that we are still waiting since the did not run synchronized (sqsSession.getStateLock()) { sqsSession.getStateLock().notifyAll(); } - assertEquals(false, passedDoCloseCall.await(2, TimeUnit.SECONDS)); + assertFalse(passedDoCloseCall.await(2, TimeUnit.SECONDS)); // Simulate session closed sqsSession.setClosed(true); @@ -1284,8 +1087,7 @@ public void run() { * Test do close */ @Test - public void testDoClose() throws JMSException, InterruptedException { - + public void testDoClose() throws JMSException { sqsSession = new SQSSession(parentSQSConnection, AcknowledgeMode.ACK_AUTO, messageConsumers, messageProducers); /* * Do close @@ -1342,23 +1144,20 @@ public void testClose() throws JMSException, InterruptedException { sqsSession.setActiveConsumerInCallback(consumer1); // Run thread that tries to close the session while activeConsumerInCallback is set - executorService.execute(new Runnable() { - @Override - public void run() { - beforeCloseCall.countDown(); - try { - sqsSession.close(); - passedCloseCall.countDown(); - } catch (JMSException e) { - e.printStackTrace(); - } + executorService.execute(() -> { + beforeCloseCall.countDown(); + try { + sqsSession.close(); + passedCloseCall.countDown(); + } catch (JMSException e) { + e.printStackTrace(); } }); beforeCloseCall.await(); // Ensure that we wait on activeConsumerInCallback - assertEquals(false, passedCloseCall.await(2, TimeUnit.SECONDS)); + assertFalse(passedCloseCall.await(2, TimeUnit.SECONDS)); // Release the activeConsumerInCallback sqsSession.finishedCallback(); @@ -1366,7 +1165,7 @@ public void run() { // Ensure that the session close completed passedCloseCall.await(); - assertEquals(true, sqsSession.isClosed()); + assertTrue(sqsSession.isClosed()); } /** @@ -1384,19 +1183,14 @@ public void testCloseFromActiveCallbackThread() throws JMSException, Interrupted /* * Verify result */ - try { - sqsSession.close(); - fail(); - } catch (IllegalStateException ise) { - // expected - } + assertThrows(IllegalStateException.class, () -> sqsSession.close()); } /** * Test create receiver */ @Test - public void testCreateReceiver() throws JMSException, InterruptedException { + public void testCreateReceiver() throws JMSException { SQSQueueDestination destination = new SQSQueueDestination(QUEUE_NAME, QUEUE_URL); /* @@ -1415,7 +1209,7 @@ public void testCreateReceiver() throws JMSException, InterruptedException { * Test create sender */ @Test - public void testCreateSender() throws JMSException, InterruptedException { + public void testCreateSender() throws JMSException { SQSQueueDestination destination = new SQSQueueDestination(QUEUE_NAME, QUEUE_URL); /* @@ -1433,36 +1227,26 @@ public void testCreateSender() throws JMSException, InterruptedException { * Test create message */ @Test - public void testCreateMessage() throws JMSException, InterruptedException { + public void testCreateMessage() { /* * Create message */ - try { - sqsSession.createMessage(); - fail(); - } catch(JMSException jsme) { - assertEquals(SQSMessagingClientConstants.UNSUPPORTED_METHOD, jsme.getMessage()); - } + assertThrows(JMSException.class, () -> sqsSession.createMessage(), SQSMessagingClientConstants.UNSUPPORTED_METHOD); } /** * Test create byte message */ @Test - public void testCreateObjectMessage() throws JMSException, InterruptedException { + public void testCreateObjectMessage() throws JMSException { sqsSession.setClosed(true); /* * Create bytes message */ - try { - sqsSession.createObjectMessage(); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Session is closed", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsSession.createObjectMessage(), "Session is closed"); sqsSession.setClosed(false); @@ -1470,7 +1254,6 @@ public void testCreateObjectMessage() throws JMSException, InterruptedException assertTrue(msg1 instanceof SQSObjectMessage); - String myObject = "MyObject"; ObjectMessage msg2 = sqsSession.createObjectMessage(myObject); @@ -1482,19 +1265,14 @@ public void testCreateObjectMessage() throws JMSException, InterruptedException * Test create byte message */ @Test - public void testCreateTextMessage() throws JMSException, InterruptedException { + public void testCreateTextMessage() throws JMSException { sqsSession.setClosed(true); /* * Create bytes message */ - try { - sqsSession.createTextMessage(); - fail(); - } catch(IllegalStateException ise) { - assertEquals("Session is closed", ise.getMessage()); - } + assertThrows(IllegalStateException.class, () -> sqsSession.createTextMessage(), "Session is closed"); sqsSession.setClosed(false); diff --git a/src/test/java/com/amazon/sqs/javamessaging/UnorderedAcknowledgerTest.java b/src/test/java/com/amazon/sqs/javamessaging/UnorderedAcknowledgerTest.java index 2459777..bee574b 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/UnorderedAcknowledgerTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/UnorderedAcknowledgerTest.java @@ -14,34 +14,30 @@ */ package com.amazon.sqs.javamessaging; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import javax.jms.JMSException; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; -import com.amazon.sqs.javamessaging.SQSSession; import com.amazon.sqs.javamessaging.acknowledge.AcknowledgeMode; import com.amazon.sqs.javamessaging.message.SQSMessage; import com.amazonaws.services.sqs.model.DeleteMessageRequest; +import jakarta.jms.JMSException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import java.util.ArrayList; import java.util.List; import java.util.Random; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + /** * Test the UnorderedAcknowledgerTest class */ public class UnorderedAcknowledgerTest extends AcknowledgerCommon { - @Before + @BeforeEach public void setupUnordered() throws JMSException { amazonSQSClient = mock(AmazonSQSMessagingClientWrapper.class); acknowledger = AcknowledgeMode.ACK_UNORDERED.createAcknowledger(amazonSQSClient, mock(SQSSession.class)); @@ -68,9 +64,8 @@ public void testAcknowledge() throws JMSException { populateMessage(populateMessageSize); int counter = 0; - List populatedMessagesCopy = new ArrayList(populatedMessages); + List populatedMessagesCopy = new ArrayList<>(populatedMessages); while (!populatedMessagesCopy.isEmpty()) { - int rand = new Random().nextInt(populatedMessagesCopy.size()); SQSMessage message = populatedMessagesCopy.remove(rand); message.acknowledge(); diff --git a/src/test/java/com/amazon/sqs/javamessaging/message/SQSBytesMessageTest.java b/src/test/java/com/amazon/sqs/javamessaging/message/SQSBytesMessageTest.java index e3a2eec..4361f93 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/message/SQSBytesMessageTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/message/SQSBytesMessageTest.java @@ -14,43 +14,37 @@ */ package com.amazon.sqs.javamessaging.message; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; +import com.amazon.sqs.javamessaging.SQSMessagingClientConstants; +import com.amazon.sqs.javamessaging.SQSSession; +import com.amazonaws.services.sqs.model.Message; +import com.amazonaws.util.Base64; +import jakarta.jms.JMSException; +import jakarta.jms.MessageEOFException; +import jakarta.jms.MessageFormatException; +import jakarta.jms.MessageNotReadableException; +import jakarta.jms.MessageNotWriteableException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.util.HashMap; import java.util.HashSet; import java.util.Map; -import javax.jms.JMSException; -import javax.jms.MessageEOFException; -import javax.jms.MessageFormatException; -import javax.jms.MessageNotReadableException; -import javax.jms.MessageNotWriteableException; - -import org.junit.Before; -import org.junit.Test; - -import com.amazon.sqs.javamessaging.SQSMessagingClientConstants; -import com.amazon.sqs.javamessaging.SQSSession; -import com.amazon.sqs.javamessaging.message.SQSBytesMessage; -import com.amazonaws.util.Base64; - -import com.amazonaws.services.sqs.model.Message; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; /** * Test the SQSBytesMessageTest class @@ -58,14 +52,10 @@ public class SQSBytesMessageTest { private SQSSession mockSQSSession; - - private final static Map MESSAGE_SYSTEM_ATTRIBUTES; - static { - MESSAGE_SYSTEM_ATTRIBUTES = new HashMap(); - MESSAGE_SYSTEM_ATTRIBUTES.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); - } + private final static Map MESSAGE_SYSTEM_ATTRIBUTES = Map.of( + SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1"); - @Before + @BeforeEach public void setUp() { mockSQSSession = mock(SQSSession.class); } @@ -129,74 +119,20 @@ public void testReadWrite() throws JMSException { /* * Validate MessageEOFException is thrown when reaching end of file */ - try { - receivedByteMsg.readBoolean(); - fail(); - } catch (MessageEOFException exception) { - } - - try { - receivedByteMsg.readUnsignedByte(); - fail(); - } catch (MessageEOFException exception) { - } + assertThrows(MessageEOFException.class, receivedByteMsg::readBoolean); + assertThrows(MessageEOFException.class, receivedByteMsg::readUnsignedByte); byte[] arr = new byte[10]; assertEquals(-1, receivedByteMsg.readBytes(arr, 10)); - - try { - receivedByteMsg.readByte(); - fail(); - } catch (MessageEOFException exception) { - } - - try { - receivedByteMsg.readShort(); - fail(); - } catch (MessageEOFException exception) { - } - - try { - receivedByteMsg.readUnsignedShort(); - fail(); - } catch (MessageEOFException exception) { - } - - try { - receivedByteMsg.readInt(); - fail(); - } catch (MessageEOFException exception) { - } - - try { - receivedByteMsg.readLong(); - fail(); - } catch (MessageEOFException exception) { - } - - try { - receivedByteMsg.readFloat(); - fail(); - } catch (MessageEOFException exception) { - } - - try { - receivedByteMsg.readDouble(); - fail(); - } catch (MessageEOFException exception) { - } - - try { - receivedByteMsg.readChar(); - fail(); - } catch (MessageEOFException exception) { - } - - try { - receivedByteMsg.readUTF(); - fail(); - } catch (MessageEOFException exception) { - } + assertThrows(MessageEOFException.class, receivedByteMsg::readByte); + assertThrows(MessageEOFException.class, receivedByteMsg::readShort); + assertThrows(MessageEOFException.class, receivedByteMsg::readUnsignedShort); + assertThrows(MessageEOFException.class, receivedByteMsg::readInt); + assertThrows(MessageEOFException.class, receivedByteMsg::readLong); + assertThrows(MessageEOFException.class, receivedByteMsg::readFloat); + assertThrows(MessageEOFException.class, receivedByteMsg::readDouble); + assertThrows(MessageEOFException.class, receivedByteMsg::readChar); + assertThrows(MessageEOFException.class, receivedByteMsg::readUTF); } /** @@ -213,94 +149,27 @@ public void testReadIOException() throws JMSException, IOException { InputStream is = mock(InputStream.class); DataInputStream dis = new DataInputStream(is); - when(is.read()) - .thenThrow(ioException); + when(is.read()).thenThrow(ioException); - when(is.read(any(byte[].class), anyInt(), anyInt())) - .thenThrow(ioException); + when(is.read(any(byte[].class), anyInt(), anyInt())).thenThrow(ioException); SQSBytesMessage msg = spy(new SQSBytesMessage()); - doNothing() - .when(msg).checkCanRead(); + doNothing().when(msg).checkCanRead(); msg.setDataIn(dis); - try { - msg.readBoolean(); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.readByte(); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.readUnsignedByte(); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.readShort(); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.readUnsignedShort(); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.readInt(); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.readLong(); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.readFloat(); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.readDouble(); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.readChar(); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.readUTF(); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } + assertThrows(JMSException.class, msg::readBoolean); + assertThrows(JMSException.class, msg::readBoolean); + assertThrows(JMSException.class, msg::readByte); + assertThrows(JMSException.class, msg::readUnsignedByte); + assertThrows(JMSException.class, msg::readShort); + assertThrows(JMSException.class, msg::readUnsignedShort); + assertThrows(JMSException.class, msg::readInt); + assertThrows(JMSException.class, msg::readLong); + assertThrows(JMSException.class, msg::readFloat); + assertThrows(JMSException.class, msg::readDouble); + assertThrows(JMSException.class, msg::readChar); + assertThrows(JMSException.class, msg::readUTF); } /** @@ -317,19 +186,13 @@ public void testWriteIOException() throws JMSException, IOException { OutputStream os = mock(OutputStream.class); DataOutputStream dos = new DataOutputStream(os); - - SQSBytesMessage msg = spy(new SQSBytesMessage()); - doNothing() - .when(msg).checkCanRead(); + doNothing().when(msg).checkCanRead(); msg.setDataOut(dos); - doThrow(ioException) - .when(os).write(anyInt()); - - doThrow(ioException) - .when(os).write(any(byte[].class), anyInt(), anyInt()); + doThrow(ioException).when(os).write(anyInt()); + doThrow(ioException).when(os).write(any(byte[].class), anyInt(), anyInt()); try { msg.writeBoolean(true); fail(); @@ -337,68 +200,21 @@ public void testWriteIOException() throws JMSException, IOException { assertEquals(ioException, exception.getCause()); } - try { - msg.writeByte((byte)1); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.writeShort((short)1); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.writeInt(1); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.writeLong(1290772974281L); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.writeFloat(3.1457f); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.writeDouble(2.1768); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.writeChar('a'); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } - - try { - msg.writeUTF("test"); - fail(); - } catch (JMSException exception) { - assertEquals(ioException, exception.getCause()); - } + assertThrows(JMSException.class, () -> msg.writeByte((byte)1)); + assertThrows(JMSException.class, () -> msg.writeShort((short)1)); + assertThrows(JMSException.class, () -> msg.writeInt(1)); + assertThrows(JMSException.class, () -> msg.writeLong(1290772974281L)); + assertThrows(JMSException.class, () -> msg.writeFloat(3.1457f)); + assertThrows(JMSException.class, () -> msg.writeDouble(2.1768)); + assertThrows(JMSException.class, () -> msg.writeChar('a')); + assertThrows(JMSException.class, () -> msg.writeUTF("test")); } /** * Test write object function */ @Test - public void testWriteObject() throws JMSException, IOException { + public void testWriteObject() throws JMSException { SQSBytesMessage msg = new SQSBytesMessage(); byte[] byteArray = new byte[] { 1, 0, 'a', 65 }; @@ -450,22 +266,12 @@ public void testWriteObject() throws JMSException, IOException { /* * Check write object error cases */ - try { - msg.writeObject(new HashSet()); - fail(); - } catch(MessageFormatException exception) { - // expected - } + assertThrows(MessageFormatException.class, () -> msg.writeObject(new HashSet())); /* * Check write object error cases */ - try { - msg.writeObject(null); - fail(); - } catch(NullPointerException exception) { - // expected - } + assertThrows(NullPointerException.class, () -> msg.writeObject(null)); } /** @@ -473,7 +279,6 @@ public void testWriteObject() throws JMSException, IOException { */ @Test public void testClearBody() throws JMSException, IOException { - SQSBytesMessage msg = new SQSBytesMessage(); byte[] byteArray = new byte[] { 1, 0, 'a', 65 }; @@ -486,11 +291,7 @@ public void testClearBody() throws JMSException, IOException { /* * Verify message is in write-only mode */ - try { - msg.readBytes(readByteArray); - } catch(MessageNotReadableException exception) { - assertEquals("Message is not readable", exception.getMessage()); - } + assertThrows(MessageNotReadableException.class, () -> msg.readBytes(readByteArray), "Message is not readable"); msg.writeBytes(byteArray); } @@ -498,28 +299,29 @@ public void testClearBody() throws JMSException, IOException { /** * Test after reset the message is read only mode */ - @Test(expected = MessageNotWriteableException.class) + @Test public void testNotWriteable() throws JMSException { SQSBytesMessage msg = new SQSBytesMessage(); byte[] byteArray = new byte[] { 'a', 0, 34, 65 }; msg.writeBytes(byteArray); msg.reset(); + assertEquals('a', msg.readByte()); - msg.writeInt(10); + assertThrows(MessageNotWriteableException.class, () -> msg.writeInt(10)); } /** * Test before reset the message is not readable */ - @Test(expected = MessageNotReadableException.class) + @Test public void testReadable() throws JMSException { when(mockSQSSession.createBytesMessage()).thenReturn(new SQSBytesMessage()); SQSBytesMessage msg = (SQSBytesMessage) mockSQSSession.createBytesMessage(); byte[] byteArray = new byte[] { 'a', 0, 34, 65 }; msg.writeBytes(byteArray); - - msg.readInt(); + + assertThrows(MessageNotReadableException.class, msg::readInt); } } diff --git a/src/test/java/com/amazon/sqs/javamessaging/message/SQSMessageTest.java b/src/test/java/com/amazon/sqs/javamessaging/message/SQSMessageTest.java index dab640c..6eb9a78 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/message/SQSMessageTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/message/SQSMessageTest.java @@ -14,30 +14,34 @@ */ package com.amazon.sqs.javamessaging.message; -import static com.amazon.sqs.javamessaging.SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT; -import static com.amazon.sqs.javamessaging.SQSMessagingClientConstants.JMSX_DELIVERY_COUNT; -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import javax.jms.JMSException; - import com.amazon.sqs.javamessaging.SQSMessagingClientConstants; import com.amazon.sqs.javamessaging.SQSSession; import com.amazon.sqs.javamessaging.acknowledge.Acknowledger; -import com.amazon.sqs.javamessaging.message.SQSMessage; import com.amazonaws.services.sqs.model.MessageAttributeValue; -import org.junit.Before; -import org.junit.Test; - -import javax.jms.Message; -import javax.jms.MessageFormatException; -import javax.jms.MessageNotWriteableException; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageFormatException; +import jakarta.jms.MessageNotWriteableException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; -import junit.framework.Assert; - -import java.util.*; +import static com.amazon.sqs.javamessaging.SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT; +import static com.amazon.sqs.javamessaging.SQSMessagingClientConstants.JMSX_DELIVERY_COUNT; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; /** * Test the SQSMessageTest class @@ -56,7 +60,7 @@ public class SQSMessageTest { final String myCustomString = "myCustomString"; final String myNumber = "myNumber"; - @Before + @BeforeEach public void setup() { mockSQSSession = mock(SQSSession.class); } @@ -80,53 +84,53 @@ public void testProperty() throws JMSException { message.setStringProperty("myString", "StringValue"); message.setStringProperty("myNumber", "500"); - Assert.assertTrue(message.propertyExists("myTrueBoolean")); - Assert.assertEquals(message.getObjectProperty("myTrueBoolean"), true); - Assert.assertEquals(message.getBooleanProperty("myTrueBoolean"), true); + assertTrue(message.propertyExists("myTrueBoolean")); + assertEquals(message.getObjectProperty("myTrueBoolean"), true); + assertTrue(message.getBooleanProperty("myTrueBoolean")); - Assert.assertTrue(message.propertyExists("myFalseBoolean")); - Assert.assertEquals(message.getObjectProperty("myFalseBoolean"), false); - Assert.assertEquals(message.getBooleanProperty("myFalseBoolean"), false); + assertTrue(message.propertyExists("myFalseBoolean")); + assertEquals(message.getObjectProperty("myFalseBoolean"), false); + assertFalse(message.getBooleanProperty("myFalseBoolean")); - Assert.assertTrue(message.propertyExists("myInteger")); - Assert.assertEquals(message.getObjectProperty("myInteger"), 100); - Assert.assertEquals(message.getIntProperty("myInteger"), 100); + assertTrue(message.propertyExists("myInteger")); + assertEquals(message.getObjectProperty("myInteger"), 100); + assertEquals(message.getIntProperty("myInteger"), 100); - Assert.assertTrue(message.propertyExists("myDouble")); - Assert.assertEquals(message.getObjectProperty("myDouble"), 2.1768); - Assert.assertEquals(message.getDoubleProperty("myDouble"), 2.1768); + assertTrue(message.propertyExists("myDouble")); + assertEquals(message.getObjectProperty("myDouble"), 2.1768); + assertEquals(message.getDoubleProperty("myDouble"), 2.1768); - Assert.assertTrue(message.propertyExists("myFloat")); - Assert.assertEquals(message.getObjectProperty("myFloat"), 3.1457f); - Assert.assertEquals(message.getFloatProperty("myFloat"), 3.1457f); + assertTrue(message.propertyExists("myFloat")); + assertEquals(message.getObjectProperty("myFloat"), 3.1457f); + assertEquals(message.getFloatProperty("myFloat"), 3.1457f); - Assert.assertTrue(message.propertyExists("myLong")); - Assert.assertEquals(message.getObjectProperty("myLong"), 1290772974281L); - Assert.assertEquals(message.getLongProperty("myLong"), 1290772974281L); + assertTrue(message.propertyExists("myLong")); + assertEquals(message.getObjectProperty("myLong"), 1290772974281L); + assertEquals(message.getLongProperty("myLong"), 1290772974281L); - Assert.assertTrue(message.propertyExists("myShort")); - Assert.assertEquals(message.getObjectProperty("myShort"), (short) 123); - Assert.assertEquals(message.getShortProperty("myShort"), (short) 123); + assertTrue(message.propertyExists("myShort")); + assertEquals(message.getObjectProperty("myShort"), (short) 123); + assertEquals(message.getShortProperty("myShort"), (short) 123); - Assert.assertTrue(message.propertyExists("myByteProperty")); - Assert.assertEquals(message.getObjectProperty("myByteProperty"), (byte) 'a'); - Assert.assertEquals(message.getByteProperty("myByteProperty"), (byte) 'a'); + assertTrue(message.propertyExists("myByteProperty")); + assertEquals(message.getObjectProperty("myByteProperty"), (byte) 'a'); + assertEquals(message.getByteProperty("myByteProperty"), (byte) 'a'); - Assert.assertTrue(message.propertyExists("myString")); - Assert.assertEquals(message.getObjectProperty("myString"), "StringValue"); - Assert.assertEquals(message.getStringProperty("myString"), "StringValue"); - - Assert.assertTrue(message.propertyExists("myNumber")); - Assert.assertEquals(message.getObjectProperty("myNumber"), "500"); - Assert.assertEquals(message.getStringProperty("myNumber"), "500"); - Assert.assertEquals(message.getLongProperty("myNumber"), 500L); - Assert.assertEquals(message.getFloatProperty("myNumber"), 500f); - Assert.assertEquals(message.getShortProperty("myNumber"), (short) 500); - Assert.assertEquals(message.getDoubleProperty("myNumber"), 500d); - Assert.assertEquals(message.getIntProperty("myNumber"), 500); + assertTrue(message.propertyExists("myString")); + assertEquals(message.getObjectProperty("myString"), "StringValue"); + assertEquals(message.getStringProperty("myString"), "StringValue"); + + assertTrue(message.propertyExists("myNumber")); + assertEquals(message.getObjectProperty("myNumber"), "500"); + assertEquals(message.getStringProperty("myNumber"), "500"); + assertEquals(message.getLongProperty("myNumber"), 500L); + assertEquals(message.getFloatProperty("myNumber"), 500f); + assertEquals(message.getShortProperty("myNumber"), (short) 500); + assertEquals(message.getDoubleProperty("myNumber"), 500d); + assertEquals(message.getIntProperty("myNumber"), 500); // Validate property names - Set propertyNamesSet = new HashSet(Arrays.asList( + Set propertyNamesSet = Set.of( "myTrueBoolean", "myFalseBoolean", "myInteger", @@ -136,9 +140,10 @@ public void testProperty() throws JMSException { "myShort", "myByteProperty", "myNumber", - "myString")); + "myString" + ); - Enumeration propertyNames = message.getPropertyNames(); + Enumeration propertyNames = message.getPropertyNames(); int counter = 0; while (propertyNames.hasMoreElements()) { assertTrue(propertyNamesSet.contains(propertyNames.nextElement())); @@ -147,15 +152,15 @@ public void testProperty() throws JMSException { assertEquals(propertyNamesSet.size(), counter); message.clearProperties(); - Assert.assertFalse(message.propertyExists("myTrueBoolean")); - Assert.assertFalse(message.propertyExists("myInteger")); - Assert.assertFalse(message.propertyExists("myDouble")); - Assert.assertFalse(message.propertyExists("myFloat")); - Assert.assertFalse(message.propertyExists("myLong")); - Assert.assertFalse(message.propertyExists("myShort")); - Assert.assertFalse(message.propertyExists("myByteProperty")); - Assert.assertFalse(message.propertyExists("myString")); - Assert.assertFalse(message.propertyExists("myNumber")); + assertFalse(message.propertyExists("myTrueBoolean")); + assertFalse(message.propertyExists("myInteger")); + assertFalse(message.propertyExists("myDouble")); + assertFalse(message.propertyExists("myFloat")); + assertFalse(message.propertyExists("myLong")); + assertFalse(message.propertyExists("myShort")); + assertFalse(message.propertyExists("myByteProperty")); + assertFalse(message.propertyExists("myString")); + assertFalse(message.propertyExists("myNumber")); propertyNames = message.getPropertyNames(); assertFalse(propertyNames.hasMoreElements()); @@ -167,27 +172,15 @@ public void testProperty() throws JMSException { @Test public void testCheckPropertyWritePermissions() throws JMSException { SQSMessage msg = new SQSMessage(); - - msg.checkBodyWritePermissions(); - msg.setBodyWritePermissions(false); - try { - msg.checkBodyWritePermissions(); - } catch (MessageNotWriteableException exception) { - assertEquals("Message body is not writable", exception.getMessage()); - } + assertThrows(MessageNotWriteableException.class, msg::checkBodyWritePermissions, "Message body is not writable"); msg.checkPropertyWritePermissions(); - msg.setWritePermissionsForProperties(false); - try { - msg.checkPropertyWritePermissions(); - } catch (MessageNotWriteableException exception) { - assertEquals("Message properties are not writable", exception.getMessage()); - } + assertThrows(MessageNotWriteableException.class, msg::checkPropertyWritePermissions, "Message properties are not writable"); } /** @@ -195,33 +188,20 @@ public void testCheckPropertyWritePermissions() throws JMSException { */ @Test public void testGetPrimitiveProperty() throws JMSException { - SQSMessage msg = spy(new SQSMessage()); - when(msg.getObjectProperty("testProperty")) - .thenReturn(null); - - try { - msg.getPrimitiveProperty(null, String.class); - } catch (NullPointerException npe) { - assertEquals("Property name is null", npe.getMessage()); - } + SQSMessage msg = spy(new SQSMessage()); + when(msg.getObjectProperty("testProperty")).thenReturn(null); - try { - msg.getPrimitiveProperty("testProperty", List.class); - } catch (NumberFormatException exp) { - assertEquals("Value of property with name testProperty is null.", exp.getMessage()); - } + assertThrows(NullPointerException.class, () -> msg.getPrimitiveProperty(null, String.class), + "Property name is null"); - try { - msg.getPrimitiveProperty("testProperty", Double.class); - } catch (NullPointerException exp) { - assertEquals("Value of property with name testProperty is null.", exp.getMessage()); - } + assertThrows(NumberFormatException.class, () -> msg.getPrimitiveProperty("testProperty", List.class), + "Value of property with name testProperty is null."); - try { - msg.getPrimitiveProperty("testProperty", Float.class); - } catch (NullPointerException exp) { - assertEquals("Value of property with name testProperty is null.", exp.getMessage()); - } + assertThrows(NullPointerException.class, () -> msg.getPrimitiveProperty("testProperty", Double.class), + "Value of property with name testProperty is null."); + + assertThrows(NullPointerException.class, () -> msg.getPrimitiveProperty("testProperty", Float.class), + "Value of property with name testProperty is null."); assertFalse(msg.getPrimitiveProperty("testProperty", Boolean.class)); assertNull(msg.getPrimitiveProperty("testProperty", String.class)); @@ -232,45 +212,27 @@ public void testGetPrimitiveProperty() throws JMSException { */ @Test public void testSetObjectProperty() throws JMSException { - SQSMessage msg = spy(new SQSMessage()); + SQSMessage msg = spy(new SQSMessage()); - try { - msg.setObjectProperty(null, 1); - } catch (IllegalArgumentException exception) { - assertEquals("Property name can not be null or empty.", exception.getMessage()); - } + assertThrows(IllegalArgumentException.class, () -> msg.setObjectProperty(null, 1), + "Property name can not be null or empty."); - try { - msg.setObjectProperty("", 1); - } catch (IllegalArgumentException exception) { - assertEquals("Property name can not be null or empty.", exception.getMessage()); - } + assertThrows(IllegalArgumentException.class, () -> msg.setObjectProperty("", 1), + "Property name can not be null or empty."); - try { - msg.setObjectProperty("Property", null); - } catch (IllegalArgumentException exception) { - assertEquals("Property value can not be null or empty.", exception.getMessage()); - } + assertThrows(IllegalArgumentException.class, () -> msg.setObjectProperty("Property", null), + "Property value can not be null or empty."); - try { - msg.setObjectProperty("Property", ""); - } catch (IllegalArgumentException exception) { - assertEquals("Property value can not be null or empty.", exception.getMessage()); - } + assertThrows(IllegalArgumentException.class, () -> msg.setObjectProperty("Property", ""), + "Property value can not be null or empty."); - try { - msg.setObjectProperty("Property", new HashSet()); - } catch (MessageFormatException exception) { - assertEquals("Value of property with name Property has incorrect type java.util.HashSet.", - exception.getMessage()); - } + assertThrows(MessageFormatException.class, () -> msg.setObjectProperty("Property", new HashSet()), + "Value of property with name Property has incorrect type java.util.HashSet."); msg.setWritePermissionsForProperties(false); - try { - msg.setObjectProperty("Property", "1"); - } catch (MessageNotWriteableException exception) { - assertEquals("Message properties are not writable", exception.getMessage()); - } + + assertThrows(MessageNotWriteableException.class, () -> msg.setObjectProperty("Property", "1"), + "Message properties are not writable"); msg.setWritePermissionsForProperties(true); msg.setObjectProperty("Property", "1"); @@ -286,54 +248,53 @@ public void testSQSMessageAttributeToProperty() throws JMSException { Acknowledger ack = mock(Acknowledger.class); - Map systemAttributes = new HashMap(); - systemAttributes.put(APPROXIMATE_RECEIVE_COUNT, "100"); + Map systemAttributes = Map.of(APPROXIMATE_RECEIVE_COUNT, "100"); - Map messageAttributes = new HashMap(); + Map messageAttributes = new HashMap<>(); messageAttributes.put(myTrueBoolean, new MessageAttributeValue() - .withDataType(SQSMessagingClientConstants.BOOLEAN) - .withStringValue("1")); + .withDataType(SQSMessagingClientConstants.BOOLEAN) + .withStringValue("1")); messageAttributes.put(myFalseBoolean, new MessageAttributeValue() - .withDataType(SQSMessagingClientConstants.BOOLEAN) - .withStringValue("0")); + .withDataType(SQSMessagingClientConstants.BOOLEAN) + .withStringValue("0")); messageAttributes.put(myInteger, new MessageAttributeValue() - .withDataType(SQSMessagingClientConstants.INT) - .withStringValue("100")); + .withDataType(SQSMessagingClientConstants.INT) + .withStringValue("100")); messageAttributes.put(myDouble, new MessageAttributeValue() - .withDataType(SQSMessagingClientConstants.DOUBLE) - .withStringValue("2.1768")); + .withDataType(SQSMessagingClientConstants.DOUBLE) + .withStringValue("2.1768")); messageAttributes.put(myFloat, new MessageAttributeValue() - .withDataType(SQSMessagingClientConstants.FLOAT) - .withStringValue("3.1457")); + .withDataType(SQSMessagingClientConstants.FLOAT) + .withStringValue("3.1457")); messageAttributes.put(myLong, new MessageAttributeValue() - .withDataType(SQSMessagingClientConstants.LONG) - .withStringValue("1290772974281")); + .withDataType(SQSMessagingClientConstants.LONG) + .withStringValue("1290772974281")); messageAttributes.put(myShort, new MessageAttributeValue() - .withDataType(SQSMessagingClientConstants.SHORT) - .withStringValue("123")); + .withDataType(SQSMessagingClientConstants.SHORT) + .withStringValue("123")); messageAttributes.put(myByte, new MessageAttributeValue() - .withDataType(SQSMessagingClientConstants.BYTE) - .withStringValue("1")); + .withDataType(SQSMessagingClientConstants.BYTE) + .withStringValue("1")); messageAttributes.put(myString, new MessageAttributeValue() - .withDataType(SQSMessagingClientConstants.STRING) - .withStringValue("StringValue")); + .withDataType(SQSMessagingClientConstants.STRING) + .withStringValue("StringValue")); messageAttributes.put(myCustomString, new MessageAttributeValue() - .withDataType(SQSMessagingClientConstants.NUMBER + ".custom") - .withStringValue("['one', 'two']")); + .withDataType(SQSMessagingClientConstants.NUMBER + ".custom") + .withStringValue("['one', 'two']")); messageAttributes.put(myNumber, new MessageAttributeValue() - .withDataType(SQSMessagingClientConstants.NUMBER) - .withStringValue("500")); + .withDataType(SQSMessagingClientConstants.NUMBER) + .withStringValue("500")); com.amazonaws.services.sqs.model.Message sqsMessage = new com.amazonaws.services.sqs.model.Message() .withMessageAttributes(messageAttributes) @@ -343,58 +304,58 @@ public void testSQSMessageAttributeToProperty() throws JMSException { SQSMessage message = new SQSMessage(ack, "QueueUrl", sqsMessage); - Assert.assertTrue(message.propertyExists(myTrueBoolean)); - Assert.assertEquals(message.getObjectProperty(myTrueBoolean), true); - Assert.assertEquals(message.getBooleanProperty(myTrueBoolean), true); + assertTrue(message.propertyExists(myTrueBoolean)); + assertEquals(message.getObjectProperty(myTrueBoolean), true); + assertTrue(message.getBooleanProperty(myTrueBoolean)); - Assert.assertTrue(message.propertyExists(myFalseBoolean)); - Assert.assertEquals(message.getObjectProperty(myFalseBoolean), false); - Assert.assertEquals(message.getBooleanProperty(myFalseBoolean), false); + assertTrue(message.propertyExists(myFalseBoolean)); + assertEquals(message.getObjectProperty(myFalseBoolean), false); + assertFalse(message.getBooleanProperty(myFalseBoolean)); - Assert.assertTrue(message.propertyExists(myInteger)); - Assert.assertEquals(message.getObjectProperty(myInteger), 100); - Assert.assertEquals(message.getIntProperty(myInteger), 100); + assertTrue(message.propertyExists(myInteger)); + assertEquals(message.getObjectProperty(myInteger), 100); + assertEquals(message.getIntProperty(myInteger), 100); - Assert.assertTrue(message.propertyExists(myDouble)); - Assert.assertEquals(message.getObjectProperty(myDouble), 2.1768); - Assert.assertEquals(message.getDoubleProperty(myDouble), 2.1768); + assertTrue(message.propertyExists(myDouble)); + assertEquals(message.getObjectProperty(myDouble), 2.1768); + assertEquals(message.getDoubleProperty(myDouble), 2.1768); - Assert.assertTrue(message.propertyExists(myFloat)); - Assert.assertEquals(message.getObjectProperty(myFloat), 3.1457f); - Assert.assertEquals(message.getFloatProperty(myFloat), 3.1457f); + assertTrue(message.propertyExists(myFloat)); + assertEquals(message.getObjectProperty(myFloat), 3.1457f); + assertEquals(message.getFloatProperty(myFloat), 3.1457f); - Assert.assertTrue(message.propertyExists(myLong)); - Assert.assertEquals(message.getObjectProperty(myLong), 1290772974281L); - Assert.assertEquals(message.getLongProperty(myLong), 1290772974281L); + assertTrue(message.propertyExists(myLong)); + assertEquals(message.getObjectProperty(myLong), 1290772974281L); + assertEquals(message.getLongProperty(myLong), 1290772974281L); - Assert.assertTrue(message.propertyExists(myShort)); - Assert.assertEquals(message.getObjectProperty(myShort), (short) 123); - Assert.assertEquals(message.getShortProperty(myShort), (short) 123); + assertTrue(message.propertyExists(myShort)); + assertEquals(message.getObjectProperty(myShort), (short) 123); + assertEquals(message.getShortProperty(myShort), (short) 123); - Assert.assertTrue(message.propertyExists(myByte)); - Assert.assertEquals(message.getObjectProperty(myByte), (byte) 1); - Assert.assertEquals(message.getByteProperty(myByte), (byte) 1); + assertTrue(message.propertyExists(myByte)); + assertEquals(message.getObjectProperty(myByte), (byte) 1); + assertEquals(message.getByteProperty(myByte), (byte) 1); - Assert.assertTrue(message.propertyExists(myString)); - Assert.assertEquals(message.getObjectProperty(myString), "StringValue"); - Assert.assertEquals(message.getStringProperty(myString), "StringValue"); + assertTrue(message.propertyExists(myString)); + assertEquals(message.getObjectProperty(myString), "StringValue"); + assertEquals(message.getStringProperty(myString), "StringValue"); - Assert.assertTrue(message.propertyExists(myCustomString)); - Assert.assertEquals(message.getObjectProperty(myCustomString), "['one', 'two']"); - Assert.assertEquals(message.getStringProperty(myCustomString), "['one', 'two']"); + assertTrue(message.propertyExists(myCustomString)); + assertEquals(message.getObjectProperty(myCustomString), "['one', 'two']"); + assertEquals(message.getStringProperty(myCustomString), "['one', 'two']"); - Assert.assertTrue(message.propertyExists(myNumber)); - Assert.assertEquals(message.getObjectProperty(myNumber), "500"); - Assert.assertEquals(message.getStringProperty(myNumber), "500"); - Assert.assertEquals(message.getIntProperty(myNumber), 500); - Assert.assertEquals(message.getShortProperty(myNumber), (short) 500); - Assert.assertEquals(message.getLongProperty(myNumber), 500l); - Assert.assertEquals(message.getFloatProperty(myNumber), 500f); - Assert.assertEquals(message.getDoubleProperty(myNumber), 500d); + assertTrue(message.propertyExists(myNumber)); + assertEquals(message.getObjectProperty(myNumber), "500"); + assertEquals(message.getStringProperty(myNumber), "500"); + assertEquals(message.getIntProperty(myNumber), 500); + assertEquals(message.getShortProperty(myNumber), (short) 500); + assertEquals(message.getLongProperty(myNumber), 500L); + assertEquals(message.getFloatProperty(myNumber), 500f); + assertEquals(message.getDoubleProperty(myNumber), 500d); // Validate property names - Set propertyNamesSet = new HashSet(Arrays.asList( + Set propertyNamesSet = Set.of( myTrueBoolean, myFalseBoolean, myInteger, @@ -406,9 +367,10 @@ public void testSQSMessageAttributeToProperty() throws JMSException { myString, myCustomString, myNumber, - JMSX_DELIVERY_COUNT)); + JMSX_DELIVERY_COUNT + ); - Enumeration propertyNames = message.getPropertyNames(); + Enumeration propertyNames = message.getPropertyNames(); int counter = 0; while (propertyNames.hasMoreElements()) { assertTrue(propertyNamesSet.contains(propertyNames.nextElement())); @@ -417,15 +379,15 @@ public void testSQSMessageAttributeToProperty() throws JMSException { assertEquals(propertyNamesSet.size(), counter); message.clearProperties(); - Assert.assertFalse(message.propertyExists("myTrueBoolean")); - Assert.assertFalse(message.propertyExists("myInteger")); - Assert.assertFalse(message.propertyExists("myDouble")); - Assert.assertFalse(message.propertyExists("myFloat")); - Assert.assertFalse(message.propertyExists("myLong")); - Assert.assertFalse(message.propertyExists("myShort")); - Assert.assertFalse(message.propertyExists("myByteProperty")); - Assert.assertFalse(message.propertyExists("myString")); - Assert.assertFalse(message.propertyExists("myNumber")); + assertFalse(message.propertyExists("myTrueBoolean")); + assertFalse(message.propertyExists("myInteger")); + assertFalse(message.propertyExists("myDouble")); + assertFalse(message.propertyExists("myFloat")); + assertFalse(message.propertyExists("myLong")); + assertFalse(message.propertyExists("myShort")); + assertFalse(message.propertyExists("myByteProperty")); + assertFalse(message.propertyExists("myString")); + assertFalse(message.propertyExists("myNumber")); propertyNames = message.getPropertyNames(); assertFalse(propertyNames.hasMoreElements()); diff --git a/src/test/java/com/amazon/sqs/javamessaging/message/SQSObjectMessageTest.java b/src/test/java/com/amazon/sqs/javamessaging/message/SQSObjectMessageTest.java index 67fe82b..98ee0c6 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/message/SQSObjectMessageTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/message/SQSObjectMessageTest.java @@ -14,22 +14,18 @@ */ package com.amazon.sqs.javamessaging.message; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import jakarta.jms.JMSException; +import jakarta.jms.ObjectMessage; +import org.junit.jupiter.api.Test; import java.io.Serializable; -import java.util.HashMap; import java.util.Map; -import javax.jms.JMSException; -import javax.jms.ObjectMessage; - -import org.junit.Assert; -import org.junit.Test; - -import com.amazon.sqs.javamessaging.message.SQSObjectMessage; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Test the SQSObjectMessageTest class @@ -41,13 +37,12 @@ public class SQSObjectMessageTest { */ @Test public void testSetObject() throws JMSException { - Map expectedPayload = new HashMap(); - expectedPayload.put("testKey", "testValue"); + Map expectedPayload = Map.of("testKey", "testValue"); ObjectMessage objectMessage = new SQSObjectMessage(); objectMessage.setObject((Serializable) expectedPayload); - Map actualPayload = (HashMap) objectMessage.getObject(); + Map actualPayload = (Map) objectMessage.getObject(); assertEquals(expectedPayload, actualPayload); } @@ -56,12 +51,10 @@ public void testSetObject() throws JMSException { */ @Test public void testCreateMessageWithObject() throws JMSException { - Map expectedPayload = new HashMap(); - expectedPayload.put("testKey", "testValue"); - + Map expectedPayload = Map.of("testKey", "testValue"); ObjectMessage objectMessage = new SQSObjectMessage((Serializable) expectedPayload); - Map actualPayload = (HashMap) objectMessage.getObject(); + Map actualPayload = (Map) objectMessage.getObject(); assertEquals(expectedPayload, actualPayload); } @@ -70,25 +63,21 @@ public void testCreateMessageWithObject() throws JMSException { */ @Test public void testObjectSerialization() throws JMSException { - Map expectedPayload = new HashMap(); - expectedPayload.put("testKey", "testValue"); - + Map expectedPayload = Map.of("testKey", "testValue"); SQSObjectMessage sqsObjectMessage = new SQSObjectMessage(); + String serialized = SQSObjectMessage.serialize((Serializable) expectedPayload); - String serialized = sqsObjectMessage.serialize((Serializable) expectedPayload); - - assertNotNull("Serialized object should not be null.", serialized); - Assert.assertFalse("Serialized object should not be empty.", "".equals(serialized)); + assertNotNull(serialized, "Serialized object should not be null."); + assertNotEquals("", serialized, "Serialized object should not be empty."); - Map deserialized = (Map) sqsObjectMessage.deserialize(serialized); + Map deserialized = (Map) SQSObjectMessage.deserialize(serialized); - assertNotNull("Deserialized object should not be null.", deserialized); - assertEquals("Serialized object should be equal to original object.", expectedPayload, deserialized); + assertNotNull(deserialized, "Deserialized object should not be null."); + assertEquals(expectedPayload, deserialized, "Serialized object should be equal to original object."); sqsObjectMessage.clearBody(); assertNull(sqsObjectMessage.getMessageBody()); - } /** @@ -97,16 +86,9 @@ public void testObjectSerialization() throws JMSException { @Test public void testDeserializeIllegalInput() throws JMSException { String wrongString = "Wrong String"; - SQSObjectMessage sqsObjectMessage = new SQSObjectMessage(); - - try { - sqsObjectMessage.deserialize(wrongString); - fail(); - } catch (JMSException exception) { - } - - assertNull(sqsObjectMessage.deserialize(null)); - assertNull(sqsObjectMessage.serialize(null)); + assertThrows(JMSException.class, () -> SQSObjectMessage.deserialize(wrongString)); + assertNull(SQSObjectMessage.deserialize(null)); + assertNull(SQSObjectMessage.serialize(null)); } } diff --git a/src/test/java/com/amazon/sqs/javamessaging/message/SQSTextMessageTest.java b/src/test/java/com/amazon/sqs/javamessaging/message/SQSTextMessageTest.java index d1f5b9b..982e242 100644 --- a/src/test/java/com/amazon/sqs/javamessaging/message/SQSTextMessageTest.java +++ b/src/test/java/com/amazon/sqs/javamessaging/message/SQSTextMessageTest.java @@ -14,14 +14,11 @@ */ package com.amazon.sqs.javamessaging.message; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import jakarta.jms.JMSException; +import org.junit.jupiter.api.Test; -import javax.jms.JMSException; - -import org.junit.Test; - -import com.amazon.sqs.javamessaging.message.SQSTextMessage; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Test the SQSTextMessageTest class