From 7ff52d6c24ffb8da74a69ed0392dd45fd6a9caf5 Mon Sep 17 00:00:00 2001 From: Kilemonn Date: Tue, 5 Dec 2023 22:53:46 +1100 Subject: [PATCH] Remove all usages of type and queue type and use sub-queue instead. --- .../authentication/AuthenticationMatrix.kt | 4 +- .../AuthenticationMatrixDocument.kt | 2 +- .../authentication/RestrictionMode.kt | 12 +- .../authenticator/MultiQueueAuthenticator.kt | 54 +- .../MultiQueueAuthorisationException.kt | 2 +- .../configuration/QueueConfiguration.kt | 28 +- .../filter/JwtAuthenticationFilter.kt | 8 +- .../messagequeue/message/QueueMessage.kt | 19 +- .../message/QueueMessageDocument.kt | 6 +- .../kilemon/messagequeue/queue/MultiQueue.kt | 192 +++--- .../queue/cache/redis/RedisMultiQueue.kt | 81 ++- .../exception/DuplicateMessageException.kt | 2 +- .../queue/inmemory/InMemoryMultiQueue.kt | 101 ++- .../queue/nosql/mongo/MongoMultiQueue.kt | 39 +- .../repository/MongoQueueMessageRepository.kt | 46 +- .../messagequeue/queue/sql/SqlMultiQueue.kt | 38 +- .../repository/SqlQueueMessageRepository.kt | 48 +- .../rest/controller/AuthController.kt | 59 +- .../rest/controller/MessageQueueController.kt | 167 ++--- .../rest/controller/RestParameters.kt | 2 +- .../rest/response/MessageResponse.kt | 6 +- .../settings/MessageQueueSettings.kt | 9 +- .../MultiQueueAuthenticatorTest.kt | 76 +-- .../inmemory/InMemoryAuthenticatorTest.kt | 18 +- .../MultiQueueAuthorisationExceptionTest.kt | 2 +- .../messagequeue/message/QueueMessageTest.kt | 52 +- .../messagequeue/queue/MultiQueueTest.kt | 403 ++++++------ .../redis/RedisStandAloneMultiQueueTest.kt | 20 +- .../inmemory/InMemoryMockMultiQueueTest.kt | 4 +- .../queue/nosql/mongo/MongoMultiQueueTest.kt | 2 - .../rest/controller/AuthControllerTest.kt | 162 ++--- .../controller/MessageQueueControllerTest.kt | 584 +++++++++--------- .../rest/controller/SettingsControllerTest.kt | 12 +- .../RestResponseExceptionHandlerTest.kt | 6 +- .../MessageQueueSettingsDefaultTest.kt | 4 +- .../settings/MessageQueueSettingsTest.kt | 2 +- 36 files changed, 1137 insertions(+), 1135 deletions(-) diff --git a/src/main/kotlin/au/kilemon/messagequeue/authentication/AuthenticationMatrix.kt b/src/main/kotlin/au/kilemon/messagequeue/authentication/AuthenticationMatrix.kt index 1a48fda..fe29fdf 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/authentication/AuthenticationMatrix.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/authentication/AuthenticationMatrix.kt @@ -6,8 +6,8 @@ import javax.persistence.* /** * An object that holds subqueue authentication information. - * If a specific sub queue is in restricted mode it will have a matching [AuthenticationMatrix] created which will - * be checked to verify if a specific sub queue can be operated on. + * If a specific sub-queue is in restricted mode it will have a matching [AuthenticationMatrix] created which will + * be checked to verify if a specific sub-queue can be operated on. * This object is used for `In-memory`, `SQL` and `Redis`. * * @author github.com/Kilemonn diff --git a/src/main/kotlin/au/kilemon/messagequeue/authentication/AuthenticationMatrixDocument.kt b/src/main/kotlin/au/kilemon/messagequeue/authentication/AuthenticationMatrixDocument.kt index 4559df8..6514ac4 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/authentication/AuthenticationMatrixDocument.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/authentication/AuthenticationMatrixDocument.kt @@ -5,7 +5,7 @@ import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document /** - * A holder object for the restricted sub queues. Refer to [AuthenticationMatrix]. + * A holder object for the restricted sub-queues. Refer to [AuthenticationMatrix]. * This is used only for `Mongo`. * * @author github.com/Kilemonn diff --git a/src/main/kotlin/au/kilemon/messagequeue/authentication/RestrictionMode.kt b/src/main/kotlin/au/kilemon/messagequeue/authentication/RestrictionMode.kt index 04d9d55..d647367 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/authentication/RestrictionMode.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/authentication/RestrictionMode.kt @@ -2,29 +2,29 @@ package au.kilemon.messagequeue.authentication /** * An enum class used to represent the different types of `MultiQueueAuthentication`. - * This will drive whether authentication is available and for which sub queues. + * This will drive whether authentication is available and for which sub-queues. * * @author github.com/Kilemonn */ enum class RestrictionMode { /** - * This is the default, which enforces no authentication on any sub queue, messages can be enqueued and dequeued + * This is the default, which enforces no authentication on any sub-queue, messages can be enqueued and dequeued * as required by any called without any form of authentication. */ NONE, /** - * This is a hybrid mode where sub queues can be created without authentication, but other sub queues can + * This is a hybrid mode where sub-queues can be created without authentication, but other sub-queues can * be created with it (if they do not already exist). - * Any sub queue created with authentication will not be accessible without a token, sub queues created without a + * Any sub-queue created with authentication will not be accessible without a token, sub-queues created without a * token will continue to be accessible without one. */ HYBRID, /** - * This is a restricted mode that forces any sub queue to be pre-created and a token will be given before messages - * can be stored or accessed in any sub queue. + * This is a restricted mode that forces any sub-queue to be pre-created and a token will be given before messages + * can be stored or accessed in any sub-queue. */ RESTRICTED; } diff --git a/src/main/kotlin/au/kilemon/messagequeue/authentication/authenticator/MultiQueueAuthenticator.kt b/src/main/kotlin/au/kilemon/messagequeue/authentication/authenticator/MultiQueueAuthenticator.kt index 467a476..6cf05aa 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/authentication/authenticator/MultiQueueAuthenticator.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/authentication/authenticator/MultiQueueAuthenticator.kt @@ -8,7 +8,7 @@ import org.slf4j.Logger import org.springframework.beans.factory.annotation.Autowired /** - * The base Authenticator class. This is responsible to tracking which sub queues are marked as restricted and + * The base Authenticator class. This is responsible to tracking which sub-queues are marked as restricted and * maintaining this underlying collection within the specified storage medium. * * @author github.com/Kilemonn @@ -18,24 +18,24 @@ abstract class MultiQueueAuthenticator: HasLogger abstract override val LOG: Logger @Autowired - private lateinit var multiQueueAuthenticationType: RestrictionMode + private lateinit var restrictionMode: RestrictionMode /** - * @return [multiQueueAuthenticationType] + * @return [restrictionMode] */ - fun getAuthenticationType(): RestrictionMode + fun getRestrictionMode(): RestrictionMode { - return multiQueueAuthenticationType + return restrictionMode } /** * Used only for tests to update the set [RestrictionMode]. * - * @param authenticationType the new [RestrictionMode] to set + * @param restrictionMode the new [RestrictionMode] to set */ - fun setAuthenticationType(authenticationType: RestrictionMode) + fun setRestrictionMode(restrictionMode: RestrictionMode) { - multiQueueAuthenticationType = authenticationType + this.restrictionMode = restrictionMode } /** @@ -50,8 +50,8 @@ abstract class MultiQueueAuthenticator: HasLogger } /** - * Determines whether based on the currently set [getAuthenticationType] and the provided [subQueue] and - * [JwtAuthenticationFilter.getSubQueue] to determine if the user is able to interact with the requested sub queue. + * Determines whether based on the currently set [getRestrictionMode] and the provided [subQueue] and + * [JwtAuthenticationFilter.getSubQueue] to determine if the user is able to interact with the requested sub-queue. * * @param subQueue the sub-queue identifier that is being requested access to * @param throwException `true` to throw an exception if the [subQueue] cannot be accessed, otherwise the return @@ -67,7 +67,7 @@ abstract class MultiQueueAuthenticator: HasLogger { if (throwException) { - throw MultiQueueAuthorisationException(subQueue, getAuthenticationType()) + throw MultiQueueAuthorisationException(subQueue, getRestrictionMode()) } return false } @@ -87,7 +87,7 @@ abstract class MultiQueueAuthenticator: HasLogger } else { - // If we are in hybrid mode and the sub queue is not restricted we should let it pass + // If we are in hybrid mode and the sub-queue is not restricted we should let it pass return true } } @@ -101,33 +101,33 @@ abstract class MultiQueueAuthenticator: HasLogger if (throwException) { - throw MultiQueueAuthorisationException(subQueue, getAuthenticationType()) + throw MultiQueueAuthorisationException(subQueue, getRestrictionMode()) } return false } /** - * Indicates whether [multiQueueAuthenticationType] is set to [RestrictionMode.NONE]. + * Indicates whether [restrictionMode] is set to [RestrictionMode.NONE]. */ fun isInNoneMode(): Boolean { - return getAuthenticationType() == RestrictionMode.NONE + return getRestrictionMode() == RestrictionMode.NONE } /** - * Indicates whether [multiQueueAuthenticationType] is set to [RestrictionMode.HYBRID]. + * Indicates whether [restrictionMode] is set to [RestrictionMode.HYBRID]. */ fun isInHybridMode(): Boolean { - return getAuthenticationType() == RestrictionMode.HYBRID + return getRestrictionMode() == RestrictionMode.HYBRID } /** - * Indicates whether [multiQueueAuthenticationType] is set to [RestrictionMode.RESTRICTED]. + * Indicates whether [restrictionMode] is set to [RestrictionMode.RESTRICTED]. */ fun isInRestrictedMode(): Boolean { - return getAuthenticationType() == RestrictionMode.RESTRICTED + return getRestrictionMode() == RestrictionMode.RESTRICTED } /** @@ -163,26 +163,26 @@ abstract class MultiQueueAuthenticator: HasLogger * This will delegate to [addRestrictedEntryInternal]. * * @param subQueue the sub-queue identifier to make restricted - * @return `true` if the sub queue identifier was added to the restriction set, otherwise `false` if there was + * @return `true` if the sub-queue identifier was added to the restriction set, otherwise `false` if there was * no underlying change made. If [isInNoneMode] is set this will always return `false`. */ fun addRestrictedEntry(subQueue: String): Boolean { if (isInNoneMode()) { - LOG.trace("Skipping adding restricted entry for [{}] since the authentication type is set to [{}].", subQueue, getAuthenticationType()) + LOG.trace("Skipping adding restricted entry for [{}] since the restriction mode is set to [{}].", subQueue, getRestrictionMode()) return false } else { return if (isRestricted(subQueue)) { - LOG.trace("Restriction for sub queue [{}] was not increased as it is already restricted.", subQueue) + LOG.trace("Restriction for sub-queue [{}] was not increased as it is already restricted.", subQueue) false } else { - LOG.info("Adding restriction to sub queue [{}].", subQueue) + LOG.info("Adding restriction to sub-queue [{}].", subQueue) addRestrictedEntryInternal(subQueue) true } @@ -208,19 +208,19 @@ abstract class MultiQueueAuthenticator: HasLogger { return if (isInNoneMode()) { - LOG.trace("Skipping removing restricted entry for [{}] since the authentication type is set to [{}].", subQueue, getAuthenticationType()) + LOG.trace("Skipping removing restricted entry for [{}] since the restriction mode is set to [{}].", subQueue, getRestrictionMode()) false } else { return if (isRestricted(subQueue)) { - LOG.info("Removing restriction to sub queue [{}].", subQueue) + LOG.info("Removing restriction to sub-queue [{}].", subQueue) removeRestrictionInternal(subQueue) } else { - LOG.trace("Restriction for sub queue [{}] was not removed as it is currently unrestricted.", subQueue) + LOG.trace("Restriction for sub-queue [{}] was not removed as it is currently unrestricted.", subQueue) false } @@ -243,7 +243,7 @@ abstract class MultiQueueAuthenticator: HasLogger /** * Clear the underlying restriction storage entries. (This is mainly used for testing). * - * @return the amount of sub queue restrictions that were cleared + * @return the amount of sub-queue restrictions that were cleared */ abstract fun clearRestrictedSubQueues(): Long } diff --git a/src/main/kotlin/au/kilemon/messagequeue/authentication/exception/MultiQueueAuthorisationException.kt b/src/main/kotlin/au/kilemon/messagequeue/authentication/exception/MultiQueueAuthorisationException.kt index 4d28a83..04589a7 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/authentication/exception/MultiQueueAuthorisationException.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/authentication/exception/MultiQueueAuthorisationException.kt @@ -9,7 +9,7 @@ import au.kilemon.messagequeue.authentication.RestrictionMode * * @author github.com/Kilemonn */ -class MultiQueueAuthorisationException(subQueue: String, authenticationType: RestrictionMode) : Exception(String.format(MESSAGE_FORMAT, subQueue, authenticationType)) +class MultiQueueAuthorisationException(subQueue: String, restrictionMode: RestrictionMode) : Exception(String.format(MESSAGE_FORMAT, subQueue, restrictionMode)) { companion object { diff --git a/src/main/kotlin/au/kilemon/messagequeue/configuration/QueueConfiguration.kt b/src/main/kotlin/au/kilemon/messagequeue/configuration/QueueConfiguration.kt index 8854b3b..71b7af9 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/configuration/QueueConfiguration.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/configuration/QueueConfiguration.kt @@ -49,7 +49,7 @@ class QueueConfiguration : HasLogger private lateinit var redisTemplate: RedisTemplate /** - * Initialise the [MultiQueue] [Bean] based on the [MessageQueueSettings.multiQueueType]. + * Initialise the [MultiQueue] [Bean] based on the [MessageQueueSettings.storageMedium]. */ @Bean open fun getMultiQueue(): MultiQueue @@ -58,7 +58,7 @@ class QueueConfiguration : HasLogger // Default to in-memory var queue: MultiQueue = InMemoryMultiQueue() - when (messageQueueSettings.multiQueueType.uppercase()) { + when (messageQueueSettings.storageMedium.uppercase()) { StorageMedium.REDIS.toString() -> { queue = RedisMultiQueue(messageQueueSettings.redisPrefix, redisTemplate) } @@ -70,44 +70,44 @@ class QueueConfiguration : HasLogger } } - LOG.info("Initialising [{}] queue as the [{}] is set to [{}].", queue::class.java.name, MessageQueueSettings.STORAGE_MEDIUM, messageQueueSettings.multiQueueType) + LOG.info("Initialising [{}] queue as the [{}] is set to [{}].", queue::class.java.name, MessageQueueSettings.STORAGE_MEDIUM, messageQueueSettings.storageMedium) return queue } /** - * Initialise the [RestrictionMode] which drives how sub queues are accessed and created. + * Initialise the [RestrictionMode] which drives how sub-queues are accessed and created. */ @Bean - open fun getMultiQueueAuthenticationType(): RestrictionMode + open fun getRestrictionMode(): RestrictionMode { - var authenticationType = RestrictionMode.NONE + var restrictionMode = RestrictionMode.NONE - if (messageQueueSettings.multiQueueAuthentication.isNotBlank()) + if (messageQueueSettings.restrictionMode.isNotBlank()) { try { - authenticationType = RestrictionMode.valueOf(messageQueueSettings.multiQueueAuthentication.uppercase()) + restrictionMode = RestrictionMode.valueOf(messageQueueSettings.restrictionMode.uppercase()) } catch (ex: Exception) { - LOG.warn("Unable to initialise appropriate authentication type with provided value [{}], falling back to default [{}].", messageQueueSettings.multiQueueAuthentication, RestrictionMode.NONE, ex) + LOG.warn("Unable to initialise appropriate restriction mode with provided value [{}], falling back to default [{}].", messageQueueSettings.restrictionMode, RestrictionMode.NONE, ex) } } - LOG.info("Using [{}] authentication as the [{}] is set to [{}].", authenticationType, MessageQueueSettings.RESTRICTION_MODE, messageQueueSettings.multiQueueAuthentication) + LOG.info("Using [{}] restriction mode as the [{}] is set to [{}].", restrictionMode, MessageQueueSettings.RESTRICTION_MODE, messageQueueSettings.restrictionMode) - return authenticationType + return restrictionMode } /** - * Initialise the [MultiQueueAuthenticator] [Bean] based on the [MessageQueueSettings.multiQueueType]. + * Initialise the [MultiQueueAuthenticator] [Bean] based on the [MessageQueueSettings.storageMedium]. */ @Bean open fun getMultiQueueAuthenticator(): MultiQueueAuthenticator { var authenticator: MultiQueueAuthenticator = InMemoryAuthenticator() - when (messageQueueSettings.multiQueueType.uppercase()) { + when (messageQueueSettings.storageMedium.uppercase()) { StorageMedium.REDIS.toString() -> { authenticator = RedisAuthenticator() } @@ -119,7 +119,7 @@ class QueueConfiguration : HasLogger } } - LOG.info("Initialising [{}] authenticator as the [{}] is set to [{}].", authenticator::class.java.name, MessageQueueSettings.STORAGE_MEDIUM, messageQueueSettings.multiQueueType) + LOG.info("Initialising [{}] authenticator as the [{}] is set to [{}].", authenticator::class.java.name, MessageQueueSettings.STORAGE_MEDIUM, messageQueueSettings.storageMedium) return authenticator } diff --git a/src/main/kotlin/au/kilemon/messagequeue/filter/JwtAuthenticationFilter.kt b/src/main/kotlin/au/kilemon/messagequeue/filter/JwtAuthenticationFilter.kt index b6e9623..f7c221c 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/filter/JwtAuthenticationFilter.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/filter/JwtAuthenticationFilter.kt @@ -101,13 +101,13 @@ class JwtAuthenticationFilter: OncePerRequestFilter(), HasLogger { if (tokenIsPresentAndQueueIsRestricted(subQueue, authenticator)) { - LOG.trace("Accepted request for sub queue [{}].", subQueue.get()) + LOG.trace("Accepted request for sub-queue [{}].", subQueue.get()) filterChain.doFilter(request, response) } else { val token = if (subQueue.isPresent) subQueue.get() else "null" - LOG.error("Failed to manipulate sub queue [{}] with provided token as the authentication level is set to [{}].", token, authenticator.getAuthenticationType()) + LOG.error("Failed to manipulate sub-queue [{}] with provided token as the authentication level is set to [{}].", token, authenticator.getRestrictionMode()) handlerExceptionResolver.resolveException(request, response, null, MultiQueueAuthenticationException()) return } @@ -156,13 +156,13 @@ class JwtAuthenticationFilter: OncePerRequestFilter(), HasLogger /** * Set the provided [Optional][String] into the [MDC] as [JwtAuthenticationFilter.SUB_QUEUE] if it is not [Optional.empty]. * - * @param subQueue an optional sub queue identifier, if it is not [Optional.empty] it will be placed into the [MDC] + * @param subQueue an optional sub-queue identifier, if it is not [Optional.empty] it will be placed into the [MDC] */ fun setSubQueue(subQueue: Optional) { if (subQueue.isPresent) { - LOG.trace("Setting resolved sub queue from token into request context [{}].", subQueue.get()) + LOG.trace("Setting resolved sub-queue from token into request context [{}].", subQueue.get()) MDC.put(SUB_QUEUE, subQueue.get()) } } diff --git a/src/main/kotlin/au/kilemon/messagequeue/message/QueueMessage.kt b/src/main/kotlin/au/kilemon/messagequeue/message/QueueMessage.kt index 3c15fdc..a395a86 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/message/QueueMessage.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/message/QueueMessage.kt @@ -8,7 +8,7 @@ import javax.persistence.* /** * A base [QueueMessage] object which will wrap any object that is placed into the `MultiQueue`. - * This object wraps a [Any] type `T` which is the payload to be stored in the queue. (This is actually a [Serializable] but causes issues in initialisation + * This object wraps an [Any] which is the payload to be stored in the queue. (This is actually a [Serializable] but causes issues in initialisation * if the type is an `interface`. This needs to be [Serializable] if you want to use it with `Redis` or anything else). * * This is used for `InMemory`, `Redis` and `SQL` queues. @@ -17,7 +17,7 @@ import javax.persistence.* */ @Entity @Table(name = QueueMessage.TABLE_NAME) // TODO: Schema configuration schema = "\${${MessageQueueSettings.SQL_SCHEMA}:${MessageQueueSettings.SQL_SCHEMA_DEFAULT}}") -class QueueMessage(payload: Any?, @Column(nullable = false) var type: String, @Column(name = "assignedto") var assignedTo: String? = null): Serializable +class QueueMessage(payload: Any?, @Column(name = "subqueue", nullable = false) var subQueue: String, @Column(name = "assignedto") var assignedTo: String? = null): Serializable { companion object { @@ -52,7 +52,7 @@ class QueueMessage(payload: Any?, @Column(nullable = false) var type: String, @C constructor(queueMessageDocument: QueueMessageDocument) : this() { - this.type = queueMessageDocument.type + this.subQueue = queueMessageDocument.subQueue this.uuid = queueMessageDocument.uuid this.id = queueMessageDocument.id this.payload = queueMessageDocument.payload @@ -94,7 +94,7 @@ class QueueMessage(payload: Any?, @Column(nullable = false) var type: String, @C { // Create a temporary object since the object is edited in place if we are using the in-memory queue val newMessage = QueueMessage() - newMessage.type = type + newMessage.subQueue = subQueue newMessage.assignedTo = assignedTo newMessage.uuid = uuid newMessage.payload = "***" // Mark as stars to indicate that it is there but not returned @@ -107,9 +107,10 @@ class QueueMessage(payload: Any?, @Column(nullable = false) var type: String, @C /** * Overriding to only include specific properties when checking if messages are equal. * This checks the following are equal in order to return `true`: - * - UUID - * - payload value - * - type + * - [uuid] + * - [payload] + * - [payloadBytes] + * - [subQueue] */ override fun equals(other: Any?): Boolean { @@ -120,7 +121,7 @@ class QueueMessage(payload: Any?, @Column(nullable = false) var type: String, @C return other.uuid == this.uuid && (this.payload == other.payload || this.payloadBytes.contentEquals(other.payloadBytes)) - && this.type == other.type + && this.subQueue == other.subQueue } /** @@ -129,7 +130,7 @@ class QueueMessage(payload: Any?, @Column(nullable = false) var type: String, @C override fun hashCode(): Int { var result = payload?.hashCode() ?: 0 result = 31 * result + (payloadBytes?.hashCode() ?: 0) - result = 31 * result + type.hashCode() + result = 31 * result + subQueue.hashCode() result = 31 * result + uuid.hashCode() return result } diff --git a/src/main/kotlin/au/kilemon/messagequeue/message/QueueMessageDocument.kt b/src/main/kotlin/au/kilemon/messagequeue/message/QueueMessageDocument.kt index 749deed..1a9c39f 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/message/QueueMessageDocument.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/message/QueueMessageDocument.kt @@ -3,9 +3,7 @@ package au.kilemon.messagequeue.message import com.fasterxml.jackson.annotation.JsonIgnore import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document -import org.springframework.util.SerializationUtils import java.util.* -import javax.persistence.* /** * This is used for `No-SQL` queues. @@ -13,7 +11,7 @@ import javax.persistence.* * @author github.com/Kilemonn */ @Document(value = QueueMessageDocument.DOCUMENT_NAME) -class QueueMessageDocument(var payload: Any?, var type: String, var assignedTo: String? = null) +class QueueMessageDocument(var payload: Any?, var subQueue: String, var assignedTo: String? = null) { companion object { @@ -34,7 +32,7 @@ class QueueMessageDocument(var payload: Any?, var type: String, var assignedTo: constructor(queueMessage: QueueMessage) : this() { val resolvedQueueMessage = queueMessage.resolvePayloadObject() - this.type = resolvedQueueMessage.type + this.subQueue = resolvedQueueMessage.subQueue this.uuid = resolvedQueueMessage.uuid this.id = resolvedQueueMessage.id this.payload = resolvedQueueMessage.payload diff --git a/src/main/kotlin/au/kilemon/messagequeue/queue/MultiQueue.kt b/src/main/kotlin/au/kilemon/messagequeue/queue/MultiQueue.kt index 6ec19c2..bd93c55 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/queue/MultiQueue.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/queue/MultiQueue.kt @@ -17,7 +17,7 @@ import kotlin.collections.HashSet /** * A [MultiQueue] base class, which extends [Queue]. - * It contains various extra methods for interfacing with the [MultiQueue] using the [String] as a queue type identifier + * It contains various extra methods for interfacing with the [MultiQueue] using the [String] as a sub-queue identifier * to manipulate the appropriate underlying [Queue]s. * * @author github.com/Kilemonn @@ -38,7 +38,7 @@ abstract class MultiQueue: Queue, HasLogger /** * Get the underlying size of the [MultiQueue]. - * This is done by summing the length of each [getQueueForType] for each key in [keys]. + * This is done by summing the length of each [getSubQueue] for each key in [keys]. * * This is to allow the underlying storage to be the source of truth instead of any temporary counters, since the underlying storage could * change at any timeout without direct interaction from the [MultiQueue]. @@ -47,7 +47,7 @@ abstract class MultiQueue: Queue, HasLogger get() { var internalSize = 0 keys(false).forEach { key -> - internalSize += getQueueForType(key).size + internalSize += getSubQueue(key).size } return internalSize } @@ -66,7 +66,7 @@ abstract class MultiQueue: Queue, HasLogger * * @return the current value of the index before it was incremented */ - abstract fun getNextQueueIndex(queueType: String): Optional + abstract fun getNextSubQueueIndex(subQueue: String): Optional /** * A wrapper for the [MultiQueue.persistMessageInternal] so this method can be synchronised. @@ -97,128 +97,128 @@ abstract class MultiQueue: Queue, HasLogger abstract fun persistMessageInternal(message: QueueMessage) /** - * Retrieves or creates a new [Queue] of type [QueueMessage] for the provided [String]. - * If the underlying [Queue] does not exist for the provided [String] then a new [Queue] will + * Retrieves or creates a new [Queue] of [QueueMessage] for the provided [subQueue]. + * If the underlying [Queue] does not exist for the provided [subQueue] then a new [Queue] will * be created. * - * **This method should not be called directly, please use [getQueueForType]** + * **This method should not be called directly, please use [getSubQueue]** * - * @param queueType the identifier of the sub-queue [Queue] + * @param subQueue the identifier of the sub-queue [Queue] * @return the [Queue] matching the provided [String] */ - abstract fun getQueueForTypeInternal(queueType: String): Queue + abstract fun getSubQueueInternal(subQueue: String): Queue /** * Retrieves or creates a new [Queue] of type [QueueMessage] for the provided [String]. * If the underlying [Queue] does not exist for the provided [String] then a new [Queue] will * be created. * - * @param queueType the identifier of the sub-queue [Queue] + * @param subQueue the identifier of the sub-queue [Queue] * @return the [Queue] matching the provided [String] - * @throws IllegalSubQueueIdentifierException If the provided [queueType] is part of the [MultiQueueAuthenticator.getReservedSubQueues] + * @throws IllegalSubQueueIdentifierException If the provided [subQueue] is part of the [MultiQueueAuthenticator.getReservedSubQueues] */ @Throws(IllegalSubQueueIdentifierException::class) - fun getQueueForType(queueType: String): Queue + fun getSubQueue(subQueue: String): Queue { - if (!multiQueueAuthenticator.isInNoneMode() && multiQueueAuthenticator.getReservedSubQueues().contains(queueType)) + if (!multiQueueAuthenticator.isInNoneMode() && multiQueueAuthenticator.getReservedSubQueues().contains(subQueue)) { - throw IllegalSubQueueIdentifierException(queueType) + throw IllegalSubQueueIdentifierException(subQueue) } - return getQueueForTypeInternal(queueType) + return getSubQueueInternal(subQueue) } /** - * Retrieves only assigned messages in the sub-queue for the provided [queueType]. + * Retrieves only assigned messages in the sub-queue for the provided [subQueue]. * - * By default, this calls [getQueueForType] and iterates through this to determine if the [QueueMessage.assignedTo] + * By default, this calls [getSubQueue] and iterates through this to determine if the [QueueMessage.assignedTo] * field is `not-null`, if [assignedTo] is `null` or is equal to the provided [assignedTo] if it is `not-null`. * - * @param queueType the identifier of the sub-queue [Queue] + * @param subQueue the identifier of the sub-queue [Queue] * @param assignedTo to further filter the messages returned this can be provided * @return a limited version of the [Queue] containing only assigned messages */ - open fun getAssignedMessagesForType(queueType: String, assignedTo: String?): Queue + open fun getAssignedMessagesInSubQueue(subQueue: String, assignedTo: String?): Queue { - val queue = ConcurrentLinkedQueue() - val queueForType = getQueueForType(queueType) + val assignedMessages = ConcurrentLinkedQueue() + val queue = getSubQueue(subQueue) if (assignedTo == null) { - queue.addAll(queueForType.stream().filter { message -> message.assignedTo != null }.collect(Collectors.toList())) + assignedMessages.addAll(queue.stream().filter { message -> message.assignedTo != null }.collect(Collectors.toList())) } else { - queue.addAll(queueForType.stream().filter { message -> message.assignedTo == assignedTo }.collect(Collectors.toList())) + assignedMessages.addAll(queue.stream().filter { message -> message.assignedTo == assignedTo }.collect(Collectors.toList())) } - return queue + return assignedMessages } /** - * Retrieves only unassigned messages in the sub-queue for the provided [queueType]. + * Retrieves only unassigned messages in the sub-queue for the provided [subQueue]. * - * By default, this iterates over [getQueueForType] and includes only entries where [QueueMessage.assignedTo] is `null`. + * By default, this iterates over [getSubQueue] and includes only entries where [QueueMessage.assignedTo] is `null`. * - * @param queueType the identifier of the sub-queue [Queue] + * @param subQueue the identifier of the sub-queue [Queue] * @return a limited version of the [Queue] containing only unassigned messages */ - open fun getUnassignedMessagesForType(queueType:String): Queue + open fun getUnassignedMessagesInSubQueue(subQueue: String): Queue { - val queue = ConcurrentLinkedQueue() - val queueForType = getQueueForType(queueType) - queue.addAll(queueForType.stream().filter { message -> message.assignedTo == null }.collect(Collectors.toList())) - return queue + val unassignedMessages = ConcurrentLinkedQueue() + val queue = getSubQueue(subQueue) + unassignedMessages.addAll(queue.stream().filter { message -> message.assignedTo == null }.collect(Collectors.toList())) + return unassignedMessages } /** * Get a map of assignee identifiers and the sub-queue identifier that they own messages in. - * If the [queueType] is provided this will iterate over all sub-queues and call [getOwnersAndKeysMapForType] for each of them. - * Otherwise, it will only call [getOwnersAndKeysMapForType] on the provided [queueType] if it is not null. + * If the [subQueue] is provided this will iterate over all sub-queues and call [getOwnersAndKeysMapForSubQueue] for each of them. + * Otherwise, it will only call [getOwnersAndKeysMapForSubQueue] on the provided [subQueue] if it is not null. * - * @param queueType the queue type retrieve the [Map] from + * @param subQueue to retrieve the [Map] from * @return the [Map] of assignee identifiers mapped to a list of the sub-queue identifiers that they own any messages in */ - fun getOwnersAndKeysMap(queueType: String?): Map> + fun getOwnersAndKeysMap(subQueue: String?): Map> { val responseMap = HashMap>() - if (queueType != null) + if (subQueue != null) { - LOG.debug("Getting owners map for sub-queue with identifier [{}].", queueType) - getOwnersAndKeysMapForType(queueType, responseMap) + LOG.debug("Getting owners map for sub-queue with identifier [{}].", subQueue) + getOwnersAndKeysMapForSubQueue(subQueue, responseMap) } else { LOG.debug("Getting owners map for all sub-queues.") val keys = keys(false) - keys.forEach { key -> getOwnersAndKeysMapForType(key, responseMap) } + keys.forEach { key -> getOwnersAndKeysMapForSubQueue(key, responseMap) } } return responseMap } /** * Add an entry to the provided [Map] if any of the messages in the sub-queue are assigned. - * The [QueueMessage.type] is appended to the [Set] under it's [QueueMessage.assignedTo] identifier. + * The [QueueMessage.subQueue] is appended to the [Set] under it's [QueueMessage.assignedTo] identifier. * - * @param queueType the sub-queue to iterate and update the map from + * @param subQueue the sub-queue to iterate and update the map from * @param responseMap the map to update */ - fun getOwnersAndKeysMapForType(queueType: String, responseMap: HashMap>) + fun getOwnersAndKeysMapForSubQueue(subQueue: String, responseMap: HashMap>) { - val queueForType: Queue = getAssignedMessagesForType(queueType, null) - queueForType.forEach { message -> - val type = message.type + val queue: Queue = getAssignedMessagesInSubQueue(subQueue, null) + queue.forEach { message -> + val subQueueID = message.subQueue val assigned = message.assignedTo if (assigned != null) { - LOG.trace("Appending sub-queue identifier [{}] to map for assignee ID [{}].", type, assigned) + LOG.trace("Appending sub-queue identifier [{}] to map for assignee ID [{}].", subQueueID, assigned) if (!responseMap.contains(assigned)) { - val set = hashSetOf(type) + val set = hashSetOf(subQueueID) responseMap[assigned] = set } else { // Set should not be null since we initialise and set it if the key is contained - responseMap[assigned]!!.add(type) + responseMap[assigned]!!.add(subQueueID) } } } @@ -262,48 +262,48 @@ abstract class MultiQueue: Queue, HasLogger * * This method should update the [size] property as part of the clearing of the sub-queue. * - * @param queueType the [String] of the [Queue] to clear + * @param subQueue the [String] of the [Queue] to clear * @return the number of entries removed */ - abstract fun clearForTypeInternal(queueType: String): Int + abstract fun clearSubQueueInternal(subQueue: String): Int /** - * Call to [MultiQueue.clearForTypeInternal]. + * Call to [MultiQueue.clearSubQueueInternal]. * - * @param queueType the [String] of the [Queue] to clear + * @param subQueue the [String] of the [Queue] to clear * @return the number of entries removed */ - fun clearForType(queueType: String): Int + fun clearSubQueue(subQueue: String): Int { - return clearForTypeInternal(queueType) + return clearSubQueueInternal(subQueue) } /** * Indicates whether the underlying [Queue] for the provided [String] is empty. By calling [Queue.isEmpty]. * - * @param queueType the [String] of the [Queue] to check whether it is empty + * @param subQueue the [String] of the [Queue] to check whether it is empty * @return `true` if the [Queue] for the [String] is empty, otherwise `false` */ - abstract fun isEmptyForType(queueType: String): Boolean + abstract fun isEmptySubQueue(subQueue: String): Boolean /** * Calls [Queue.poll] on the underlying [Queue] for the provided [String]. * This will retrieve **AND** remove the head element of the [Queue]. * - * @param queueType [String] of the [Queue] to poll + * @param subQueue [String] of the [Queue] to poll * @return the head element or `null` */ - open fun pollForType(queueType: String): Optional + open fun pollSubQueue(subQueue: String): Optional { - val head = pollInternal(queueType) + val head = pollInternal(subQueue) if (head.isPresent) { removeInternal(head.get()) - LOG.debug("Found and removed head element with UUID [{}] from queue with type [{}].", head.get().uuid, queueType) + LOG.debug("Found and removed head element with UUID [{}] from sub-queue [{}].", head.get().uuid, subQueue) } else { - LOG.debug("No head element found when polling queue with type [{}].", queueType) + LOG.debug("No head element found when polling sub-queue [{}].", subQueue) } return head } @@ -312,32 +312,32 @@ abstract class MultiQueue: Queue, HasLogger * The internal poll method to be called. * This is not to be called directly. * - * This method should return the first element in the queue for the provided [queueType]. + * This method should return the first element in the queue for the provided [subQueue]. * *The caller will remove this element*. * - * @param queueType the sub-queue to poll + * @param subQueue the sub-queue to poll * @return the first message wrapped as an [Optional] otherwise [Optional.empty] */ - abstract fun pollInternal(queueType: String): Optional + abstract fun pollInternal(subQueue: String): Optional /** * Calls [Queue.peek] on the underlying [Queue] for the provided [String]. * This will retrieve the head element of the [Queue] without removing it. * - * @param queueType [String] of the [Queue] to peek + * @param subQueue [String] of the [Queue] to peek * @return the head element or `null` */ - fun peekForType(queueType: String): Optional + fun peekSubQueue(subQueue: String): Optional { - val queueForType: Queue = getQueueForType(queueType) - val peeked = Optional.ofNullable(queueForType.peek()) + val queue: Queue = getSubQueue(subQueue) + val peeked = Optional.ofNullable(queue.peek()) if (peeked.isPresent) { - LOG.debug("Found head element with UUID [{}] from queue with type [{}].", peeked.get().uuid, queueType) + LOG.debug("Found head element with UUID [{}] from sub-queue [{}].", peeked.get().uuid, subQueue) } else { - LOG.debug("No head element found when peeking queue with type [{}].", queueType) + LOG.debug("No head element found when peeking sub-queue [{}].", subQueue) } return peeked } @@ -347,7 +347,7 @@ abstract class MultiQueue: Queue, HasLogger * **Should be called directly, please using [keys].** * * @param includeEmpty *true* to include any empty queues which one had elements in them, otherwise *false* to only include keys from queues which have elements. - * @return a [HashSet] of the available `QueueTypes` that have entries in the [MultiQueue]. + * @return a [HashSet] of the available `Sub-Queues` that have entries in the [MultiQueue]. */ abstract fun keysInternal(includeEmpty: Boolean = true): HashSet @@ -355,7 +355,7 @@ abstract class MultiQueue: Queue, HasLogger * Delegates to [keysInternal] and removes any keys that match in the [MultiQueueAuthenticator.getReservedSubQueues]. * * @param includeEmpty *true* to include any empty queues which one had elements in them, otherwise *false* to only include keys from queues which have elements. - * @return a [Set] of the available `QueueTypes` that have entries in the [MultiQueue]. + * @return a [Set] of the available `Sub-Queues` that have entries in the [MultiQueue]. */ fun keys(includeEmpty: Boolean = true): Set { @@ -367,10 +367,10 @@ abstract class MultiQueue: Queue, HasLogger } /** - * Returns the `queueType` that the [QueueMessage] with the provided [UUID] exists in. + * Returns the `sub-queue` that the [QueueMessage] with the provided [UUID] exists in. * * @param uuid the [UUID] (as a [String]) to look up - * @return the `queueType` [String] if a [QueueMessage] exists with the provided [UUID] otherwise [Optional.empty] + * @return the `sub-queue` [String] if a [QueueMessage] exists with the provided [UUID] otherwise [Optional.empty] */ abstract fun containsUUID(uuid: String): Optional @@ -380,27 +380,27 @@ abstract class MultiQueue: Queue, HasLogger /** * Override [add] method to declare [Throws] [DuplicateMessageException] annotation. * - * [Synchronized] so that the call to [MultiQueue.getNextQueueIndex] does not cause issues, since retrieving the next index does + * [Synchronized] so that the call to [MultiQueue.getNextSubQueueIndex] does not cause issues, since retrieving the next index does * not force it to be auto incremented or unusable by another thread. * * @throws [DuplicateMessageException] if a message already exists with the same [QueueMessage.uuid] in `any` other queue. - * @throws [IllegalSubQueueIdentifierException] if the [QueueMessage.type] is invalid or reserved + * @throws [IllegalSubQueueIdentifierException] if the [QueueMessage.subQueue] is invalid or reserved */ @Throws(DuplicateMessageException::class, IllegalSubQueueIdentifierException::class) @Synchronized override fun add(element: QueueMessage): Boolean { - if (multiQueueAuthenticator.getReservedSubQueues().contains(element.type)) + if (multiQueueAuthenticator.getReservedSubQueues().contains(element.subQueue)) { - throw IllegalSubQueueIdentifierException(element.type) + throw IllegalSubQueueIdentifierException(element.subQueue) } - val elementIsMappedToType = containsUUID(element.uuid) - if ( !elementIsMappedToType.isPresent) + val subQueueMessageAlreadyExistsIn = containsUUID(element.uuid) + if ( !subQueueMessageAlreadyExistsIn.isPresent) { if (element.id == null) { - val index = getNextQueueIndex(element.type) + val index = getNextSubQueueIndex(element.subQueue) if (index.isPresent) { element.id = index.get() @@ -409,20 +409,20 @@ abstract class MultiQueue: Queue, HasLogger val wasAdded = addInternal(element) return if (wasAdded) { - LOG.debug("Added new message with uuid [{}] to queue with type [{}].", element.uuid, element.type) + LOG.debug("Added new message with uuid [{}] to sub-queue [{}].", element.uuid, element.subQueue) true } else { - LOG.error("Failed to add message with uuid [{}] to queue with type [{}].", element.uuid, element.type) + LOG.error("Failed to add message with uuid [{}] to sub-queue [{}].", element.uuid, element.subQueue) false } } else { - val existingQueueType = elementIsMappedToType.get() - LOG.warn("Did not add new message with uuid [{}] to queue with type [{}] as it already exists in queue with type [{}].", element.uuid, element.type, existingQueueType) - throw DuplicateMessageException(element.uuid, existingQueueType) + val existingSubQueue = subQueueMessageAlreadyExistsIn.get() + LOG.warn("Did not add new message with uuid [{}] to sub-queue [{}] as it already exists in sub-queue [{}].", element.uuid, element.subQueue, existingSubQueue) + throw DuplicateMessageException(element.uuid, existingSubQueue) } } @@ -440,11 +440,11 @@ abstract class MultiQueue: Queue, HasLogger val wasRemoved = removeInternal(element) if (wasRemoved) { - LOG.debug("Removed element with UUID [{}] from queue with type [{}].", element.uuid, element.type) + LOG.debug("Removed element with UUID [{}] from sub-queue [{}].", element.uuid, element.subQueue) } else { - LOG.error("Failed to remove element with UUID [{}] from queue with type [{}].", element.uuid, element.type) + LOG.error("Failed to remove element with UUID [{}] from sub-queue [{}].", element.uuid, element.subQueue) } return wasRemoved } @@ -464,8 +464,8 @@ abstract class MultiQueue: Queue, HasLogger { return false } - val queueForType: Queue = getQueueForType(element.type) - return queueForType.contains(element) + val queue: Queue = getSubQueue(element.subQueue) + return queue.contains(element) } override fun containsAll(elements: Collection): Boolean @@ -496,7 +496,7 @@ abstract class MultiQueue: Queue, HasLogger for (key: String in keys(false)) { // The queue should never be new or created since we passed `false` into `keys()` above. - val queueForKey: Queue = getQueueForType(key) + val queueForKey: Queue = getSubQueue(key) for(entry: QueueMessage in queueForKey) { if ( !elements.contains(entry)) @@ -533,11 +533,11 @@ abstract class MultiQueue: Queue, HasLogger } /** - * @return `true` any of the [keys] returns `false` for [isEmptyForType], otherwise `false`. + * @return `true` any of the [keys] returns `false` for [isEmptySubQueue], otherwise `false`. */ override fun isEmpty(): Boolean { - val anyHasElements = keys(false).stream().anyMatch { key -> !isEmptyForType(key) } + val anyHasElements = keys(false).stream().anyMatch { key -> !isEmptySubQueue(key) } return !anyHasElements } @@ -547,10 +547,10 @@ abstract class MultiQueue: Queue, HasLogger var removedEntryCount = 0 for (key in keys) { - val amountRemovedForQueue = clearForType(key) + val amountRemovedForQueue = clearSubQueue(key) removedEntryCount += amountRemovedForQueue } - LOG.debug("Cleared multi-queue, removed [{}] message entries over [{}] queue types.", removedEntryCount, keys) + LOG.debug("Cleared multi-queue, removed [{}] message entries over [{}] sub-queues.", removedEntryCount, keys) } /** diff --git a/src/main/kotlin/au/kilemon/messagequeue/queue/cache/redis/RedisMultiQueue.kt b/src/main/kotlin/au/kilemon/messagequeue/queue/cache/redis/RedisMultiQueue.kt index e034c24..722c5e0 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/queue/cache/redis/RedisMultiQueue.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/queue/cache/redis/RedisMultiQueue.kt @@ -1,6 +1,5 @@ package au.kilemon.messagequeue.queue.cache.redis -import au.kilemon.messagequeue.authentication.authenticator.cache.redis.RedisAuthenticator import au.kilemon.messagequeue.logging.HasLogger import au.kilemon.messagequeue.message.QueueMessage import au.kilemon.messagequeue.queue.MultiQueue @@ -11,9 +10,7 @@ import org.springframework.data.redis.core.RedisTemplate import org.springframework.data.redis.core.ScanOptions import java.util.* import java.util.concurrent.ConcurrentLinkedQueue -import java.util.concurrent.atomic.AtomicLong import java.util.stream.Collectors -import kotlin.collections.HashMap import kotlin.collections.HashSet /** @@ -28,18 +25,18 @@ class RedisMultiQueue(private val prefix: String = "", private val redisTemplate override val LOG: Logger = this.initialiseLogger() /** - * Append the [MessageQueueSettings.redisPrefix] to the provided [queueType] [String]. + * Append the [MessageQueueSettings.redisPrefix] to the provided [subQueue] [String]. * - * @param queueType the [String] to add the prefix to - * @return a [String] with the provided [queueType] type with the [MessageQueueSettings.redisPrefix] appended to the beginning. + * @param subQueue the [String] to add the prefix to + * @return a [String] with the provided [subQueue] with the [MessageQueueSettings.redisPrefix] appended to the beginning. */ - private fun appendPrefix(queueType: String): String + private fun appendPrefix(subQueue: String): String { - if (hasPrefix() && !queueType.startsWith(getPrefix())) + if (hasPrefix() && !subQueue.startsWith(getPrefix())) { - return "${getPrefix()}$queueType" + return "${getPrefix()}$subQueue" } - return queueType + return subQueue } /** @@ -77,12 +74,12 @@ class RedisMultiQueue(private val prefix: String = "", private val redisTemplate } /** - * Attempts to append the prefix before requesting the underlying redis entry if the provided [queueType] is not prefixed with [MessageQueueSettings.redisPrefix]. + * Attempts to append the prefix before requesting the underlying redis entry if the provided [subQueue] is not prefixed with [MessageQueueSettings.redisPrefix]. */ - override fun getQueueForTypeInternal(queueType: String): Queue + override fun getSubQueueInternal(subQueue: String): Queue { val queue = ConcurrentLinkedQueue() - val set = redisTemplate.opsForSet().members(appendPrefix(queueType)) + val set = redisTemplate.opsForSet().members(appendPrefix(subQueue)) if (!set.isNullOrEmpty()) { queue.addAll(set.toSortedSet { message1, message2 -> (message1.id ?: 0).minus(message2.id ?: 0).toInt() }) @@ -90,10 +87,10 @@ class RedisMultiQueue(private val prefix: String = "", private val redisTemplate return queue } - override fun getAssignedMessagesForType(queueType: String, assignedTo: String?): Queue + override fun getAssignedMessagesInSubQueue(subQueue: String, assignedTo: String?): Queue { val queue = ConcurrentLinkedQueue() - val existingQueue = getQueueForType(queueType) + val existingQueue = getSubQueue(subQueue) if (existingQueue.isNotEmpty()) { if (assignedTo == null) @@ -115,30 +112,30 @@ class RedisMultiQueue(private val prefix: String = "", private val redisTemplate override fun getMessageByUUID(uuid: String): Optional { - val queueType = containsUUID(uuid) - if (queueType.isPresent) + val subQueue = containsUUID(uuid) + if (subQueue.isPresent) { - val queueForType: Queue = getQueueForType(queueType.get()) - return queueForType.stream().filter { message -> message.uuid == uuid }.findFirst() + val queue: Queue = getSubQueue(subQueue.get()) + return queue.stream().filter { message -> message.uuid == uuid }.findFirst() } return Optional.empty() } override fun addInternal(element: QueueMessage): Boolean { - val result = redisTemplate.opsForSet().add(appendPrefix(element.type), element) + val result = redisTemplate.opsForSet().add(appendPrefix(element.subQueue), element) return result != null && result > 0 } /** - * Overriding to pass in the [queueType] into [appendPrefix]. + * Overriding to pass in the [subQueue] into [appendPrefix]. */ - override fun getNextQueueIndex(queueType: String): Optional + override fun getNextSubQueueIndex(subQueue: String): Optional { - val queueForType = getQueueForType(appendPrefix(queueType)) - return if (queueForType.isNotEmpty()) + val queue = getSubQueue(appendPrefix(subQueue)) + return if (queue.isNotEmpty()) { - Optional.ofNullable(queueForType.last().id?.plus(1) ?: 1) + Optional.ofNullable(queue.last().id?.plus(1) ?: 1) } else { @@ -148,35 +145,35 @@ class RedisMultiQueue(private val prefix: String = "", private val redisTemplate override fun removeInternal(element: QueueMessage): Boolean { - val result = redisTemplate.opsForSet().remove(appendPrefix(element.type), element) + val result = redisTemplate.opsForSet().remove(appendPrefix(element.subQueue), element) return result != null && result > 0 } - override fun clearForTypeInternal(queueType: String): Int + override fun clearSubQueueInternal(subQueue: String): Int { var amountRemoved = 0 - val queueForType = getQueueForType(queueType) - if (queueForType.isNotEmpty()) + val queue = getSubQueue(subQueue) + if (queue.isNotEmpty()) { - amountRemoved = queueForType.size - redisTemplate.delete(appendPrefix(queueType)) - LOG.debug("Cleared existing queue for type [{}]. Removed [{}] message entries.", queueType, amountRemoved) + amountRemoved = queue.size + redisTemplate.delete(appendPrefix(subQueue)) + LOG.debug("Cleared existing sub-queue [{}]. Removed [{}] message entries.", subQueue, amountRemoved) } else { - LOG.debug("Attempting to clear non-existent queue for type [{}]. No messages cleared.", queueType) + LOG.debug("Attempting to clear non-existent sub-queue [{}]. No messages cleared.", subQueue) } return amountRemoved } - override fun isEmptyForType(queueType: String): Boolean + override fun isEmptySubQueue(subQueue: String): Boolean { - return getQueueForType(queueType).isEmpty() + return getSubQueue(subQueue).isEmpty() } - override fun pollInternal(queueType: String): Optional + override fun pollInternal(subQueue: String): Optional { - val queue = getQueueForType(queueType) + val queue = getSubQueue(subQueue) if (queue.isNotEmpty()) { return Optional.of(queue.iterator().next()) @@ -203,7 +200,7 @@ class RedisMultiQueue(private val prefix: String = "", private val redisTemplate val sizeOfQueue = redisTemplate.opsForSet().size(key) if (sizeOfQueue != null && sizeOfQueue > 0) { - LOG.trace("Queue type [{}] is not empty and will be returned in keys() call.", key) + LOG.trace("Sub-queue [{}] is not empty and will be returned in keys() call.", key) retainedKeys.add(key) } } @@ -216,15 +213,15 @@ class RedisMultiQueue(private val prefix: String = "", private val redisTemplate { for (key in keys()) { - val queue = getQueueForType(key) + val queue = getSubQueue(key) val anyMatchTheUUID = queue.stream().anyMatch{ message -> uuid == message.uuid } if (anyMatchTheUUID) { - LOG.debug("Found queue type [{}] for UUID: [{}].", key, uuid) + LOG.debug("Found sub-queue [{}] for message UUID: [{}].", key, uuid) return Optional.of(key) } } - LOG.debug("No queue type exists for UUID: [{}].", uuid) + LOG.debug("No sub-queue contains message with UUID: [{}].", uuid) return Optional.empty() } @@ -234,7 +231,7 @@ class RedisMultiQueue(private val prefix: String = "", private val redisTemplate */ override fun persistMessageInternal(message: QueueMessage) { - val queue = getQueueForType(message.type) + val queue = getSubQueue(message.subQueue) val matchingMessage = queue.stream().filter{ element -> element.uuid == message.uuid }.findFirst() if (matchingMessage.isPresent) { diff --git a/src/main/kotlin/au/kilemon/messagequeue/queue/exception/DuplicateMessageException.kt b/src/main/kotlin/au/kilemon/messagequeue/queue/exception/DuplicateMessageException.kt index 338567b..4541f2e 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/queue/exception/DuplicateMessageException.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/queue/exception/DuplicateMessageException.kt @@ -5,4 +5,4 @@ package au.kilemon.messagequeue.queue.exception * * @author github.com/Kilemonn */ -class DuplicateMessageException(uuid: String, queueType: String) : Exception("Duplicate message with UUID [$uuid] exists in queue with type [$queueType].") +class DuplicateMessageException(uuid: String, subQueue: String) : Exception("Duplicate message with UUID [$uuid] exists in sub-queue [$subQueue].") diff --git a/src/main/kotlin/au/kilemon/messagequeue/queue/inmemory/InMemoryMultiQueue.kt b/src/main/kotlin/au/kilemon/messagequeue/queue/inmemory/InMemoryMultiQueue.kt index 95b15c6..9226b73 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/queue/inmemory/InMemoryMultiQueue.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/queue/inmemory/InMemoryMultiQueue.kt @@ -9,7 +9,6 @@ import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.atomic.AtomicLong -import java.util.stream.Collectors import kotlin.collections.HashMap import kotlin.jvm.Throws @@ -24,7 +23,7 @@ open class InMemoryMultiQueue : MultiQueue(), HasLogger override val LOG: Logger = this.initialiseLogger() /** - * An internal [Map] that holds known [UUID]s (as a [String]) and their related `queueType` to quickly find entries within the [MultiQueue]. + * An internal [Map] that holds known [UUID]s (as a [String]) and their related `sub-queue` to quickly find entries within the [MultiQueue]. */ private val uuidMap: ConcurrentHashMap = ConcurrentHashMap() @@ -36,34 +35,34 @@ open class InMemoryMultiQueue : MultiQueue(), HasLogger private val maxQueueIndex: HashMap = HashMap() /** - * This index is special compared to the other types it will be incremented once retrieved. So we could be skipping - * indexes, but it should be fine since it's only used for message ordering. + * This index is special compared to the other [au.kilemon.messagequeue.settings.StorageMedium] it will be incremented once retrieved. + * So we could be skipping indexes, but it should be fine since it's only used for message ordering. */ - override fun getNextQueueIndex(queueType: String): Optional + override fun getNextSubQueueIndex(subQueue: String): Optional { - var index = maxQueueIndex[queueType] + var index = maxQueueIndex[subQueue] if (index == null) { index = AtomicLong(1) - maxQueueIndex[queueType] = index + maxQueueIndex[subQueue] = index } return Optional.of(index.getAndIncrement()) } - override fun getQueueForTypeInternal(queueType: String): Queue + override fun getSubQueueInternal(subQueue: String): Queue { - var queueForType: Queue? = messageQueue[queueType] - if (queueForType == null) + var queue: Queue? = messageQueue[subQueue] + if (queue == null) { - queueForType = ConcurrentLinkedQueue() - LOG.debug("Initialising new queue for type [{}].", queueType) - messageQueue[queueType] = queueForType + queue = ConcurrentLinkedQueue() + LOG.debug("Initialising new sub-queue [{}].", subQueue) + messageQueue[subQueue] = queue } else { - LOG.debug("Found existing queue for type [{}] with size [{}].", queueType, queueForType.size) + LOG.debug("Found existing sub-queue [{}] with size [{}].", subQueue, queue.size) } - return queueForType + return queue } override fun performHealthCheckInternal() @@ -73,31 +72,31 @@ open class InMemoryMultiQueue : MultiQueue(), HasLogger override fun getMessageByUUID(uuid: String): Optional { - val queueType = containsUUID(uuid) - if (queueType.isPresent) + val subQueue = containsUUID(uuid) + if (subQueue.isPresent) { - val queueForType: Queue = getQueueForType(queueType.get()) - return queueForType.stream().filter { message -> message.uuid == uuid }.findFirst() + val queue: Queue = getSubQueue(subQueue.get()) + return queue.stream().filter { message -> message.uuid == uuid }.findFirst() } return Optional.empty() } - override fun clearForTypeInternal(queueType: String): Int + override fun clearSubQueueInternal(subQueue: String): Int { var amountRemoved = 0 - val queueForType: Queue? = messageQueue[queueType] - maxQueueIndex.remove(queueType) - if (queueForType != null) + val queue: Queue? = messageQueue[subQueue] + maxQueueIndex.remove(subQueue) + if (queue != null) { - amountRemoved = queueForType.size - queueForType.forEach { message -> uuidMap.remove(message.uuid) } - queueForType.clear() - messageQueue.remove(queueType) - LOG.debug("Cleared existing queue for type [{}]. Removed [{}] message entries.", queueType, amountRemoved) + amountRemoved = queue.size + queue.forEach { message -> uuidMap.remove(message.uuid) } + queue.clear() + messageQueue.remove(subQueue) + LOG.debug("Cleared existing sub-queue [{}]. Removed [{}] message entries.", subQueue, amountRemoved) } else { - LOG.debug("Attempting to clear non-existent queue for type [{}]. No messages cleared.", queueType) + LOG.debug("Attempting to clear non-existent sub-queue [{}]. No messages cleared.", subQueue) } return amountRemoved } @@ -114,7 +113,7 @@ open class InMemoryMultiQueue : MultiQueue(), HasLogger val wasAdded = super.add(element) if (wasAdded) { - uuidMap[element.uuid] = element.type + uuidMap[element.uuid] = element.subQueue } return wasAdded } @@ -124,8 +123,8 @@ open class InMemoryMultiQueue : MultiQueue(), HasLogger */ override fun addInternal(element: QueueMessage): Boolean { - val queueForType: Queue = getQueueForType(element.type) - return queueForType.add(element) + val queue: Queue = getSubQueue(element.subQueue) + return queue.add(element) } override fun remove(element: QueueMessage): Boolean @@ -143,14 +142,14 @@ open class InMemoryMultiQueue : MultiQueue(), HasLogger */ override fun removeInternal(element: QueueMessage): Boolean { - val queueForType: Queue = getQueueForType(element.type) - return queueForType.remove(element) + val queue: Queue = getSubQueue(element.subQueue) + return queue.remove(element) } - override fun isEmptyForType(queueType: String): Boolean + override fun isEmptySubQueue(subQueue: String): Boolean { - val queueForType: Queue = getQueueForType(queueType) - return queueForType.isEmpty() + val queue: Queue = getSubQueue(subQueue) + return queue.isEmpty() } override fun keysInternal(includeEmpty: Boolean): HashSet @@ -165,10 +164,10 @@ open class InMemoryMultiQueue : MultiQueue(), HasLogger val keys = HashSet() for (key: String in messageQueue.keys) { - val queueForType = getQueueForType(key) - if (queueForType.isNotEmpty()) + val queue = getSubQueue(key) + if (queue.isNotEmpty()) { - LOG.trace("Queue type [{}] is not empty and will be returned in keys() call.", queueForType) + LOG.trace("Sub-queue [{}] is not empty and will be returned in keys() call.", queue) keys.add(key) } } @@ -179,24 +178,24 @@ open class InMemoryMultiQueue : MultiQueue(), HasLogger override fun containsUUID(uuid: String): Optional { - val queueTypeForUUID: String? = uuidMap[uuid] - if (queueTypeForUUID.isNullOrBlank()) + val subQueueID: String? = uuidMap[uuid] + if (subQueueID.isNullOrBlank()) { - LOG.debug("No queue type exists for UUID: [{}].", uuid) + LOG.debug("No sub-queue exists for UUID: [{}].", uuid) } else { - LOG.debug("Found queue type [{}] for UUID: [{}].", queueTypeForUUID, uuid) + LOG.debug("Found sub-queue [{}] for UUID: [{}].", subQueueID, uuid) } - return Optional.ofNullable(queueTypeForUUID) + return Optional.ofNullable(subQueueID) } /** * Update the [uuidMap] and remove the entry if it is returned (removed). */ - override fun pollForType(queueType: String): Optional + override fun pollSubQueue(subQueue: String): Optional { - val message = super.pollForType(queueType) + val message = super.pollSubQueue(subQueue) if (message.isPresent) { uuidMap.remove(message.get().uuid) @@ -205,12 +204,12 @@ open class InMemoryMultiQueue : MultiQueue(), HasLogger return message } - override fun pollInternal(queueType: String): Optional + override fun pollInternal(subQueue: String): Optional { - val queueForType: Queue = getQueueForType(queueType) - return if (queueForType.isNotEmpty()) + val queue: Queue = getSubQueue(subQueue) + return if (queue.isNotEmpty()) { - Optional.of(queueForType.iterator().next()) + Optional.of(queue.iterator().next()) } else { diff --git a/src/main/kotlin/au/kilemon/messagequeue/queue/nosql/mongo/MongoMultiQueue.kt b/src/main/kotlin/au/kilemon/messagequeue/queue/nosql/mongo/MongoMultiQueue.kt index 1a5bf8b..1353f67 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/queue/nosql/mongo/MongoMultiQueue.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/queue/nosql/mongo/MongoMultiQueue.kt @@ -11,7 +11,6 @@ import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Lazy import java.util.* import java.util.concurrent.ConcurrentLinkedQueue -import java.util.concurrent.atomic.AtomicLong /** * A NoSql mongo backed [MultiQueue]. All operations are performed directly on the database it is the complete source of truth. @@ -48,15 +47,15 @@ class MongoMultiQueue : MultiQueue(), HasLogger /** * Overriding to use more direct optimised queries. */ - override fun getAssignedMessagesForType(queueType: String, assignedTo: String?): Queue + override fun getAssignedMessagesInSubQueue(subQueue: String, assignedTo: String?): Queue { val entries = if (assignedTo == null) { - queueMessageRepository.findByTypeAndAssignedToIsNotNullOrderByIdAsc(queueType) + queueMessageRepository.findBySubQueueAndAssignedToIsNotNullOrderByIdAsc(subQueue) } else { - queueMessageRepository.findByTypeAndAssignedToOrderByIdAsc(queueType, assignedTo) + queueMessageRepository.findBySubQueueAndAssignedToOrderByIdAsc(subQueue, assignedTo) } return ConcurrentLinkedQueue(entries.map { entry -> QueueMessage(entry) }) @@ -65,15 +64,15 @@ class MongoMultiQueue : MultiQueue(), HasLogger /** * Overriding since we can filter via the DB query. */ - override fun getUnassignedMessagesForType(queueType: String): Queue + override fun getUnassignedMessagesInSubQueue(subQueue: String): Queue { - val entries = queueMessageRepository.findByTypeAndAssignedToIsNullOrderByIdAsc(queueType) + val entries = queueMessageRepository.findBySubQueueAndAssignedToIsNullOrderByIdAsc(subQueue) return ConcurrentLinkedQueue(entries.map { entry -> QueueMessage(entry) }) } - override fun getQueueForTypeInternal(queueType: String): Queue + override fun getSubQueueInternal(subQueue: String): Queue { - val entries = queueMessageRepository.findByTypeOrderByIdAsc(queueType) + val entries = queueMessageRepository.findBySubQueueOrderByIdAsc(subQueue) return ConcurrentLinkedQueue(entries.map { entry -> QueueMessage(entry) }) } @@ -95,21 +94,21 @@ class MongoMultiQueue : MultiQueue(), HasLogger } } - override fun clearForTypeInternal(queueType: String): Int + override fun clearSubQueueInternal(subQueue: String): Int { - val amountCleared = queueMessageRepository.deleteByType(queueType) - LOG.debug("Cleared existing queue for type [{}]. Removed [{}] message entries.", queueType, amountCleared) + val amountCleared = queueMessageRepository.deleteBySubQueue(subQueue) + LOG.debug("Cleared existing queue for sub-queue [{}]. Removed [{}] message entries.", subQueue, amountCleared) return amountCleared } - override fun isEmptyForType(queueType: String): Boolean + override fun isEmptySubQueue(subQueue: String): Boolean { - return queueMessageRepository.findByTypeOrderByIdAsc(queueType).isEmpty() + return queueMessageRepository.findBySubQueueOrderByIdAsc(subQueue).isEmpty() } - override fun pollInternal(queueType: String): Optional + override fun pollInternal(subQueue: String): Optional { - val messages = queueMessageRepository.findByTypeOrderByIdAsc(queueType) + val messages = queueMessageRepository.findBySubQueueOrderByIdAsc(subQueue) return if (messages.isNotEmpty()) { return Optional.of(QueueMessage(messages[0])) @@ -125,7 +124,7 @@ class MongoMultiQueue : MultiQueue(), HasLogger */ override fun keysInternal(includeEmpty: Boolean): HashSet { - val keySet = HashSet(queueMessageRepository.getDistinctTypes()) + val keySet = HashSet(queueMessageRepository.getDistinctSubQueues()) LOG.debug("Total amount of queue keys [{}].", keySet.size) return keySet } @@ -136,12 +135,12 @@ class MongoMultiQueue : MultiQueue(), HasLogger return if (optionalMessage.isPresent) { val message = optionalMessage.get() - LOG.debug("Found queue type [{}] for UUID: [{}].", message.type, uuid) - Optional.of(message.type) + LOG.debug("Found sub-queue [{}] for UUID: [{}].", message.subQueue, uuid) + Optional.of(message.subQueue) } else { - LOG.debug("No queue type exists for UUID: [{}].", uuid) + LOG.debug("No sub-queue exists for UUID: [{}].", uuid) Optional.empty() } } @@ -163,7 +162,7 @@ class MongoMultiQueue : MultiQueue(), HasLogger * Overriding to use the constant [INDEX_ID] for all look-ups since the ID is shared and needs to be assigned to * the [QueueMessageDocument] before it is created. */ - override fun getNextQueueIndex(queueType: String): Optional + override fun getNextSubQueueIndex(subQueue: String): Optional { val largestIdMessage = queueMessageRepository.findTopByOrderByIdDesc() return if (largestIdMessage.isPresent) diff --git a/src/main/kotlin/au/kilemon/messagequeue/queue/nosql/mongo/repository/MongoQueueMessageRepository.kt b/src/main/kotlin/au/kilemon/messagequeue/queue/nosql/mongo/repository/MongoQueueMessageRepository.kt index 8d5e674..b8f3a74 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/queue/nosql/mongo/repository/MongoQueueMessageRepository.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/queue/nosql/mongo/repository/MongoQueueMessageRepository.kt @@ -16,20 +16,20 @@ import java.util.* interface MongoQueueMessageRepository: MongoRepository { /** - * Get a distinct [List] of [String] [QueueMessageDocument.type] that currently exist. + * Get a distinct [List] of [String] [QueueMessageDocument.subQueue] that currently exist. * - * @return a [List] of all the existing [QueueMessageDocument.type] as [String]s + * @return a [List] of all the existing [QueueMessageDocument.subQueue] as [String]s */ - @Aggregation(pipeline = [ "{ '\$group': { '_id' : '\$type' } }" ]) - fun getDistinctTypes(): List + @Aggregation(pipeline = [ "{ '\$group': { '_id' : '\$subQueue' } }" ]) + fun getDistinctSubQueues(): List /** - * Get a list of [QueueMessageDocument] which have [QueueMessageDocument.type] matching the provided [type]. + * Get a list of [QueueMessageDocument] which have [QueueMessageDocument.subQueue] matching the provided [subQueue]. * - * @param type the type to match [QueueMessageDocument.type] with - * @return a [List] of [QueueMessageDocument] who have a matching [QueueMessageDocument.type] with the provided [type] + * @param subQueue the type to match [QueueMessageDocument.subQueue] with + * @return a [List] of [QueueMessageDocument] who have a matching [QueueMessageDocument.subQueue] with the provided [subQueue] */ - fun findByTypeOrderByIdAsc(type: String): List + fun findBySubQueueOrderByIdAsc(subQueue: String): List /** * Find and return a [QueueMessageDocument] that matches the provided [uuid]. @@ -40,13 +40,13 @@ interface MongoQueueMessageRepository: MongoRepository /** - * Delete all [QueueMessageDocument] that have a [QueueMessageDocument.type] that matches the provided [type]. + * Delete all [QueueMessageDocument] that have a [QueueMessageDocument.subQueue] that matches the provided [subQueue]. * - * @param type messages that are assigned this queue type will be removed + * @param subQueue messages that are assigned this sub-queue will be removed * @return the [Int] number of deleted entries */ @Modifying - fun deleteByType(type: String): Int + fun deleteBySubQueue(subQueue: String): Int /** * Delete a [QueueMessageDocument] by `uuid`. @@ -65,30 +65,30 @@ interface MongoQueueMessageRepository: MongoRepository /** - * Find the entity with the matching [QueueMessageDocument.type] and that has a non-null [QueueMessageDocument.assignedTo]. Sorted by ID ascending. + * Find the entity with the matching [QueueMessageDocument.subQueue] and that has a non-null [QueueMessageDocument.assignedTo]. Sorted by ID ascending. * - * @param type the type to match [QueueMessageDocument.type] with - * @return a [List] of [QueueMessageDocument] who have a matching [QueueMessageDocument.type] with the provided [type] and non-null [QueueMessageDocument.assignedTo] + * @param subQueue the type to match [QueueMessageDocument.subQueue] with + * @return a [List] of [QueueMessageDocument] who have a matching [QueueMessageDocument.subQueue] with the provided [subQueue] and non-null [QueueMessageDocument.assignedTo] */ @Transactional - fun findByTypeAndAssignedToIsNotNullOrderByIdAsc(type: String): List + fun findBySubQueueAndAssignedToIsNotNullOrderByIdAsc(subQueue: String): List /** - * Find the entity with the matching [QueueMessageDocument.type] and [QueueMessageDocument.assignedTo]. Sorted by ID ascending. + * Find the entity with the matching [QueueMessageDocument.subQueue] and [QueueMessageDocument.assignedTo]. Sorted by ID ascending. * - * @param type the type to match [QueueMessageDocument.type] with + * @param subQueue the type to match [QueueMessageDocument.subQueue] with * @param assignedTo the identifier to match [QueueMessageDocument.assignedTo] with - * @return a [List] of [QueueMessageDocument] who have a matching [QueueMessageDocument.type] and [QueueMessageDocument.assignedTo] + * @return a [List] of [QueueMessageDocument] who have a matching [QueueMessageDocument.subQueue] and [QueueMessageDocument.assignedTo] */ @Transactional - fun findByTypeAndAssignedToOrderByIdAsc(type: String, assignedTo: String): List + fun findBySubQueueAndAssignedToOrderByIdAsc(subQueue: String, assignedTo: String): List /** - * Find the entity with the matching [QueueMessageDocument.type] and that has [QueueMessageDocument.assignedTo] set to `null`. Sorted by ID ascending. + * Find the entity with the matching [QueueMessageDocument.subQueue] and that has [QueueMessageDocument.assignedTo] set to `null`. Sorted by ID ascending. * - * @param type the type to match [QueueMessageDocument.type] with - * @return a [List] of [QueueMessageDocument] who have a matching [QueueMessageDocument.type] with the provided [type] and `null` [QueueMessageDocument.assignedTo] + * @param subQueue the type to match [QueueMessageDocument.subQueue] with + * @return a [List] of [QueueMessageDocument] who have a matching [QueueMessageDocument.subQueue] with the provided [subQueue] and `null` [QueueMessageDocument.assignedTo] */ @Transactional - fun findByTypeAndAssignedToIsNullOrderByIdAsc(type: String): List + fun findBySubQueueAndAssignedToIsNullOrderByIdAsc(subQueue: String): List } diff --git a/src/main/kotlin/au/kilemon/messagequeue/queue/sql/SqlMultiQueue.kt b/src/main/kotlin/au/kilemon/messagequeue/queue/sql/SqlMultiQueue.kt index 364df17..1764b05 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/queue/sql/SqlMultiQueue.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/queue/sql/SqlMultiQueue.kt @@ -25,24 +25,24 @@ class SqlMultiQueue : MultiQueue(), HasLogger @Autowired private lateinit var queueMessageRepository: SqlQueueMessageRepository - override fun getQueueForTypeInternal(queueType: String): Queue + override fun getSubQueueInternal(subQueue: String): Queue { - val entries = queueMessageRepository.findByTypeOrderByIdAsc(queueType) + val entries = queueMessageRepository.findBySubQueueOrderByIdAsc(subQueue) return ConcurrentLinkedQueue(entries.map { entry -> entry.resolvePayloadObject() }) } /** * Overriding since we can filter via the DB query. */ - override fun getAssignedMessagesForType(queueType: String, assignedTo: String?): Queue + override fun getAssignedMessagesInSubQueue(subQueue: String, assignedTo: String?): Queue { val entries = if (assignedTo == null) { - queueMessageRepository.findByTypeAndAssignedToIsNotNullOrderByIdAsc(queueType) + queueMessageRepository.findBySubQueueAndAssignedToIsNotNullOrderByIdAsc(subQueue) } else { - queueMessageRepository.findByTypeAndAssignedToOrderByIdAsc(queueType, assignedTo) + queueMessageRepository.findBySubQueueAndAssignedToOrderByIdAsc(subQueue, assignedTo) } return ConcurrentLinkedQueue(entries.map { entry -> entry.resolvePayloadObject() }) @@ -51,9 +51,9 @@ class SqlMultiQueue : MultiQueue(), HasLogger /** * Overriding since we can filter via the DB query. */ - override fun getUnassignedMessagesForType(queueType: String): Queue + override fun getUnassignedMessagesInSubQueue(subQueue: String): Queue { - val entries = queueMessageRepository.findByTypeAndAssignedToIsNullOrderByIdAsc(queueType) + val entries = queueMessageRepository.findBySubQueueAndAssignedToIsNullOrderByIdAsc(subQueue) return ConcurrentLinkedQueue(entries.map { entry -> entry.resolvePayloadObject() }) } @@ -75,21 +75,21 @@ class SqlMultiQueue : MultiQueue(), HasLogger } } - override fun clearForTypeInternal(queueType: String): Int + override fun clearSubQueueInternal(subQueue: String): Int { - val amountCleared = queueMessageRepository.deleteByType(queueType) - LOG.debug("Cleared existing queue for type [{}]. Removed [{}] message entries.", queueType, amountCleared) + val amountCleared = queueMessageRepository.deleteBySubQueue(subQueue) + LOG.debug("Cleared existing sub-queue [{}]. Removed [{}] message entries.", subQueue, amountCleared) return amountCleared } - override fun isEmptyForType(queueType: String): Boolean + override fun isEmptySubQueue(subQueue: String): Boolean { - return queueMessageRepository.findByTypeOrderByIdAsc(queueType).isEmpty() + return queueMessageRepository.findBySubQueueOrderByIdAsc(subQueue).isEmpty() } - override fun pollInternal(queueType: String): Optional + override fun pollInternal(subQueue: String): Optional { - val messages = queueMessageRepository.findByTypeOrderByIdAsc(queueType) + val messages = queueMessageRepository.findBySubQueueOrderByIdAsc(subQueue) return if (messages.isNotEmpty()) { return Optional.of(messages[0].resolvePayloadObject()) @@ -105,7 +105,7 @@ class SqlMultiQueue : MultiQueue(), HasLogger */ override fun keysInternal(includeEmpty: Boolean): HashSet { - val keySet = HashSet(queueMessageRepository.findDistinctType()) + val keySet = HashSet(queueMessageRepository.findDistinctSubQueue()) LOG.debug("Total amount of queue keys [{}].", keySet.size) return keySet } @@ -116,12 +116,12 @@ class SqlMultiQueue : MultiQueue(), HasLogger return if (optionalMessage.isPresent) { val message = optionalMessage.get() - LOG.debug("Found queue type [{}] for UUID: [{}].", message.type, uuid) - Optional.of(message.type) + LOG.debug("Found sub-queue [{}] for message with UUID: [{}].", message.subQueue, uuid) + Optional.of(message.subQueue) } else { - LOG.debug("No queue type exists for UUID: [{}].", uuid) + LOG.debug("No sub-queue found for message with UUID: [{}].", uuid) Optional.empty() } } @@ -159,7 +159,7 @@ class SqlMultiQueue : MultiQueue(), HasLogger * Overriding to return [Optional.EMPTY] so that the [MultiQueue.add] does set an `id` into the [QueueMessage] * even if the id is `null`. */ - override fun getNextQueueIndex(queueType: String): Optional + override fun getNextSubQueueIndex(subQueue: String): Optional { return Optional.empty() } diff --git a/src/main/kotlin/au/kilemon/messagequeue/queue/sql/repository/SqlQueueMessageRepository.kt b/src/main/kotlin/au/kilemon/messagequeue/queue/sql/repository/SqlQueueMessageRepository.kt index 295c9c6..12afb42 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/queue/sql/repository/SqlQueueMessageRepository.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/queue/sql/repository/SqlQueueMessageRepository.kt @@ -20,61 +20,61 @@ import java.util.* interface SqlQueueMessageRepository: JpaRepository { /** - * Delete a [QueueMessage] by the provided [QueueMessage.type] [String]. + * Delete a [QueueMessage] by the provided [QueueMessage.subQueue] [String]. * - * @param type the [QueueMessage.type] to remove entries by + * @param subQueue the [QueueMessage.subQueue] to remove entries by * @return the number of deleted entities */ @Modifying @Transactional - @Query("DELETE FROM QueueMessage WHERE type = ?1") - fun deleteByType(type: String): Int + @Query("DELETE FROM QueueMessage WHERE subQueue = ?1") + fun deleteBySubQueue(subQueue: String): Int /** - * Get a distinct [List] of [String] [QueueMessage.type] that currently exist. + * Get a distinct [List] of [String] [QueueMessage.subQueue] that currently exist. * - * @return a [List] of all the existing [QueueMessage.type] as [String]s + * @return a [List] of all the existing [QueueMessage.subQueue] as [String]s */ @Transactional - @Query("SELECT DISTINCT type FROM QueueMessage") - fun findDistinctType(): List + @Query("SELECT DISTINCT subQueue FROM QueueMessage") + fun findDistinctSubQueue(): List /** - * Get a list of [QueueMessage] which have [QueueMessage.type] matching the provided [type]. + * Get a list of [QueueMessage] which have [QueueMessage.subQueue] matching the provided [subQueue]. * - * @param type the type to match [QueueMessage.type] with - * @return a [List] of [QueueMessage] who have a matching [QueueMessage.type] with the provided [type] + * @param subQueue to match [QueueMessage.subQueue] with + * @return a [List] of [QueueMessage] who have a matching [QueueMessage.subQueue] with the provided [subQueue] */ @Transactional - fun findByTypeOrderByIdAsc(type: String): List + fun findBySubQueueOrderByIdAsc(subQueue: String): List /** - * Find the entity with the matching [QueueMessage.type] and that has a non-null [QueueMessage.assignedTo]. Sorted by ID ascending. + * Find the entity with the matching [QueueMessage.subQueue] and that has a non-null [QueueMessage.assignedTo]. Sorted by ID ascending. * - * @param type the type to match [QueueMessage.type] with - * @return a [List] of [QueueMessage] who have a matching [QueueMessage.type] with the provided [type] and non-null [QueueMessage.assignedTo] + * @param subQueue to match [QueueMessage.subQueue] with + * @return a [List] of [QueueMessage] who have a matching [QueueMessage.subQueue] with the provided [subQueue] and non-null [QueueMessage.assignedTo] */ @Transactional - fun findByTypeAndAssignedToIsNotNullOrderByIdAsc(type: String): List + fun findBySubQueueAndAssignedToIsNotNullOrderByIdAsc(subQueue: String): List /** - * Find the entity with the matching [QueueMessage.type] and that has [QueueMessage.assignedTo] set to `null`. Sorted by ID ascending. + * Find the entity with the matching [QueueMessage.subQueue] and that has [QueueMessage.assignedTo] set to `null`. Sorted by ID ascending. * - * @param type the type to match [QueueMessage.type] with - * @return a [List] of [QueueMessage] who have a matching [QueueMessage.type] with the provided [type] and `null` [QueueMessage.assignedTo] + * @param subQueue the type to match [QueueMessage.subQueue] with + * @return a [List] of [QueueMessage] who have a matching [QueueMessage.subQueue] with the provided [subQueue] and `null` [QueueMessage.assignedTo] */ @Transactional - fun findByTypeAndAssignedToIsNullOrderByIdAsc(type: String): List + fun findBySubQueueAndAssignedToIsNullOrderByIdAsc(subQueue: String): List /** - * Find the entity with the matching [QueueMessage.type] and [QueueMessage.assignedTo]. Sorted by ID ascending. + * Find the entity with the matching [QueueMessage.subQueue] and [QueueMessage.assignedTo]. Sorted by ID ascending. * - * @param type the type to match [QueueMessage.type] with + * @param subQueue the type to match [QueueMessage.subQueue] with * @param assignedTo the identifier to match [QueueMessage.assignedTo] with - * @return a [List] of [QueueMessage] who have a matching [QueueMessage.type] and [QueueMessage.assignedTo] + * @return a [List] of [QueueMessage] who have a matching [QueueMessage.subQueue] and [QueueMessage.assignedTo] */ @Transactional - fun findByTypeAndAssignedToOrderByIdAsc(type: String, assignedTo: String): List + fun findBySubQueueAndAssignedToOrderByIdAsc(subQueue: String, assignedTo: String): List /** * Find the entity which has a [QueueMessage.uuid] matching the provided [uuid]. diff --git a/src/main/kotlin/au/kilemon/messagequeue/rest/controller/AuthController.kt b/src/main/kotlin/au/kilemon/messagequeue/rest/controller/AuthController.kt index 1f640a7..c05a3fc 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/rest/controller/AuthController.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/rest/controller/AuthController.kt @@ -13,7 +13,6 @@ import io.swagger.v3.oas.annotations.media.Content import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.responses.ApiResponses import io.swagger.v3.oas.annotations.tags.Tag -import lombok.Generated import org.slf4j.Logger import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus @@ -60,7 +59,7 @@ open class AuthController : HasLogger { if (multiQueueAuthenticator.isInNoneMode()) { - LOG.trace("Returning no restricted identifiers since the authentication type is set to [{}].", multiQueueAuthenticator.getAuthenticationType()) + LOG.trace("Returning no restricted identifiers since the restriction mode is set to [{}].", multiQueueAuthenticator.getRestrictionMode()) return ResponseEntity.noContent().build() } @@ -68,7 +67,7 @@ open class AuthController : HasLogger } @Operation(summary = "Create restriction on sub-queue.", description = "Create restriction a specific sub-queue to require authentication for future interactions and retrieve a token used to interact with this sub-queue.") - @PostMapping("/{${RestParameters.QUEUE_TYPE}}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @PostMapping("/{${RestParameters.SUB_QUEUE}}", produces = [MediaType.APPLICATION_JSON_VALUE]) @ApiResponses( ApiResponse(responseCode = "201", description = "Successfully registered the sub-queue identifier and returns an appropriate token for future access to the sub-queue."), ApiResponse(responseCode = "204", description = "The MultiQueue is in a no-auth mode and tokens cannot be generated.", content = [Content()]), // Add empty Content() to remove duplicate responses in swagger docsApiResponse(responseCode = "204", description = "No queue messages match the provided UUID.", content = [Content()]) @@ -76,46 +75,46 @@ open class AuthController : HasLogger ApiResponse(responseCode = "500", description = "There was an error generating the auth token for the sub-queue.", content = [Content()]) ) fun restrictSubQueue(@Parameter(`in` = ParameterIn.PATH, required = true, description = "The sub-queue that you wish to restrict to allow further access only by callers that posses the returned token.") - @PathVariable(required = true, name = RestParameters.QUEUE_TYPE) queueType: String, - /*@Parameter(`in` = ParameterIn.QUERY, required = false, description = "The generated token's expiry in minutes.") - @RequestParam(required = false, name = RestParameters.EXPIRY) expiry: Long?*/): ResponseEntity + @PathVariable(required = true, name = RestParameters.SUB_QUEUE) subQueue: String, + /*@Parameter(`in` = ParameterIn.QUERY, required = false, description = "The generated token's expiry in minutes.") + @RequestParam(required = false, name = RestParameters.EXPIRY) expiry: Long?*/): ResponseEntity { if (multiQueueAuthenticator.isInNoneMode()) { - LOG.trace("Requested token for sub-queue [{}] is not provided as queue is in mode [{}].", queueType, - multiQueueAuthenticator.getAuthenticationType()) + LOG.trace("Requested token for sub-queue [{}] is not provided as queue is in mode [{}].", subQueue, + multiQueueAuthenticator.getRestrictionMode()) return ResponseEntity.noContent().build() } - if (multiQueueAuthenticator.isRestricted(queueType)) + if (multiQueueAuthenticator.isRestricted(subQueue)) { return ResponseEntity.status(HttpStatus.CONFLICT).build() } else { // Generating the token first, so we don't need to roll back restriction add later if there is a problem - val token = jwtTokenProvider.createTokenForSubQueue(queueType, null) + val token = jwtTokenProvider.createTokenForSubQueue(subQueue, null) if (token.isEmpty) { - LOG.error("Failed to generated token for sub-queue [{}].", queueType) + LOG.error("Failed to generated token for sub-queue [{}].", subQueue) return ResponseEntity.internalServerError().build() } - return if (!multiQueueAuthenticator.addRestrictedEntry(queueType)) + return if (!multiQueueAuthenticator.addRestrictedEntry(subQueue)) { - LOG.error("Failed to add restriction for sub-queue [{}].", queueType) + LOG.error("Failed to add restriction for sub-queue [{}].", subQueue) ResponseEntity.internalServerError().build() } else { - LOG.info("Successfully generated token for sub-queue [{}].", queueType) - ResponseEntity.status(HttpStatus.CREATED).body(AuthResponse(token.get(), queueType)) + LOG.info("Successfully generated token for sub-queue [{}].", subQueue) + ResponseEntity.status(HttpStatus.CREATED).body(AuthResponse(token.get(), subQueue)) } } } @Operation(summary = "Remove restriction from sub-queue.", description = "Remove restriction from sub-queue so it can be accessed without restriction.") - @DeleteMapping("/{${RestParameters.QUEUE_TYPE}}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @DeleteMapping("/{${RestParameters.SUB_QUEUE}}", produces = [MediaType.APPLICATION_JSON_VALUE]) @ApiResponses( ApiResponse(responseCode = "200", description = "Successfully removed restriction for the sub-queue identifier."), ApiResponse(responseCode = "202", description = "The MultiQueue is in a no-auth mode and sub-queue restrictions are disabled.", content = [Content()]), // Add empty Content() to remove duplicate responses in swagger docsApiResponse(responseCode = "204", description = "No queue messages match the provided UUID.", content = [Content()]) @@ -123,49 +122,51 @@ open class AuthController : HasLogger ApiResponse(responseCode = "403", description = "Invalid token provided to remove restriction from requested sub-queue.", content = [Content()]), ApiResponse(responseCode = "500", description = "There was an error releasing restriction from the sub-queue.", content = [Content()]) ) - fun removeRestrictionFromSubQueue(@Parameter(`in` = ParameterIn.PATH, required = true, description = "The sub-queue identifier to remove restriction for.") @PathVariable(required = true, name = RestParameters.QUEUE_TYPE) queueType: String, - @Parameter(`in` = ParameterIn.QUERY, required = false, description = "If restriction is removed successfully indicate whether the sub-queue should be cleared now that it is accessible without a token.") @RequestParam(required = false, name = RestParameters.CLEAR_QUEUE) clearQueue: Boolean?): ResponseEntity + fun removeRestrictionFromSubQueue(@Parameter(`in` = ParameterIn.PATH, required = true, description = "The sub-queue identifier to remove restriction for.") + @PathVariable(required = true, name = RestParameters.SUB_QUEUE) subQueue: String, + @Parameter(`in` = ParameterIn.QUERY, required = false, description = "If restriction is removed successfully indicate whether the sub-queue should be cleared now that it is accessible without a token.") + @RequestParam(required = false, name = RestParameters.CLEAR_QUEUE) clearQueue: Boolean?): ResponseEntity { if (multiQueueAuthenticator.isInNoneMode()) { - LOG.trace("Requested to release authentication for sub-queue [{}] but queue is in mode [{}].", queueType, - multiQueueAuthenticator.getAuthenticationType()) + LOG.trace("Requested to release authentication for sub-queue [{}] but queue is in mode [{}].", subQueue, + multiQueueAuthenticator.getRestrictionMode()) return ResponseEntity.accepted().build() } val authedToken = JwtAuthenticationFilter.getSubQueue() - if (authedToken == queueType) + if (authedToken == subQueue) { - if (multiQueueAuthenticator.isRestricted(queueType)) + if (multiQueueAuthenticator.isRestricted(subQueue)) { - return if (multiQueueAuthenticator.removeRestriction(queueType)) + return if (multiQueueAuthenticator.removeRestriction(subQueue)) { if (clearQueue == true) { - LOG.info("Restriction removed and clearing sub-queue [{}].", queueType) - multiQueue.clearForType(queueType) + LOG.info("Restriction removed and clearing sub-queue [{}].", subQueue) + multiQueue.clearSubQueue(subQueue) } else { - LOG.info("Removed restriction from sub-queue [{}] without clearing stored messages.", queueType) + LOG.info("Removed restriction from sub-queue [{}] without clearing stored messages.", subQueue) } ResponseEntity.ok().build() } else { - LOG.error("Failed to remove restriction for sub-queue [{}].", queueType) + LOG.error("Failed to remove restriction for sub-queue [{}].", subQueue) ResponseEntity.internalServerError().build() } } else { - LOG.info("Cannot remove restriction from a sub-queue [{}] that is not restricted.", queueType) + LOG.info("Cannot remove restriction from a sub-queue [{}] that is not restricted.", subQueue) return ResponseEntity.noContent().build() } } else { - LOG.error("Failed to release authentication for sub-queue [{}] since provided token [{}] is not for the requested sub-queue.", queueType, authedToken) + LOG.error("Failed to release authentication for sub-queue [{}] since provided token [{}] is not for the requested sub-queue.", subQueue, authedToken) return ResponseEntity.status(HttpStatus.FORBIDDEN).build() } } diff --git a/src/main/kotlin/au/kilemon/messagequeue/rest/controller/MessageQueueController.kt b/src/main/kotlin/au/kilemon/messagequeue/rest/controller/MessageQueueController.kt index 6261d37..b276398 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/rest/controller/MessageQueueController.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/rest/controller/MessageQueueController.kt @@ -64,7 +64,7 @@ open class MessageQueueController : HasLogger const val ENDPOINT_ENTRY: String = "/entry" /** - * The resource path used to view messages that are within the same `sub queue`. + * The resource path used to view messages that are within the same `sub-queue`. */ const val ENDPOINT_TYPE: String = "/type" @@ -117,7 +117,7 @@ open class MessageQueueController : HasLogger @Operation(summary = "Retrieve queue information for the whole multi queue.", description = "Retrieve information about the whole queue, specifically information on the queue entries.") @GetMapping(ENDPOINT_TYPE, produces = [MediaType.APPLICATION_JSON_VALUE]) @ApiResponse(responseCode = "200", description = "Successfully returns the information payload.") - fun getAllQueueTypeInfo(): ResponseEntity + fun getAllQueueInfo(): ResponseEntity { val size = messageQueue.size LOG.debug("Returning total multi-queue size [{}].", size) @@ -125,20 +125,20 @@ open class MessageQueueController : HasLogger } /** - * Retrieve information about a specific queue within [MultiQueue], based on the provided `queueType`. Specifically data related information. + * Retrieve information about a specific queue within [MultiQueue], based on the provided `sub-queue`. Specifically data related information. */ @Hidden - @Operation(summary = "Retrieve queue information for a specific sub queue.", description = "Retrieve information about the specified queueType within the queue, specifically information on the queue entries.") - @GetMapping("$ENDPOINT_TYPE/{${RestParameters.QUEUE_TYPE}}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @Operation(summary = "Retrieve queue information for a specific sub-queue.", description = "Retrieve information about the specified sub-queue, specifically information on the queue entries.") + @GetMapping("$ENDPOINT_TYPE/{${RestParameters.SUB_QUEUE}}", produces = [MediaType.APPLICATION_JSON_VALUE]) @ApiResponse(responseCode = "200", description = "Successfully returns the information payload.") - fun getQueueTypeInfo(@Parameter(`in` = ParameterIn.PATH, required = true, description = "The queueType to retrieve information about.") - @PathVariable(name = RestParameters.QUEUE_TYPE) queueType: String): ResponseEntity + fun getSubQueueInfo(@Parameter(`in` = ParameterIn.PATH, required = true, description = "The sub-queue to retrieve information about.") + @PathVariable(name = RestParameters.SUB_QUEUE) subQueue: String): ResponseEntity { - authenticator.canAccessSubQueue(queueType) + authenticator.canAccessSubQueue(subQueue) - val queueForType = messageQueue.getQueueForType(queueType) - LOG.debug("Returning size [{}] for queue with type [{}].", queueForType.size, queueType) - return ResponseEntity.ok(queueForType.size.toString()) + val queue = messageQueue.getSubQueue(subQueue) + LOG.debug("Returning size [{}] for sub-queue [{}].", queue.size, subQueue) + return ResponseEntity.ok(queue.size.toString()) } /** @@ -174,7 +174,7 @@ open class MessageQueueController : HasLogger * @param uuid the [UUID] of the message to retrieve * @return [MessageResponse] containing the found [QueueMessage] otherwise a [HttpStatus.NO_CONTENT] exception will be thrown */ - @Operation(summary = "Retrieve a queue message by UUID.", description = "Retrieve a queue message regardless of its sub queue, directly by UUID.") + @Operation(summary = "Retrieve a queue message by UUID.", description = "Retrieve a queue message regardless of its sub-queue, directly by UUID.") @GetMapping("$ENDPOINT_ENTRY/{${RestParameters.UUID}}", produces = [MediaType.APPLICATION_JSON_VALUE]) @ApiResponses( ApiResponse(responseCode = "200", description = "Successfully returns the queue message matching the provided UUID."), @@ -186,8 +186,8 @@ open class MessageQueueController : HasLogger if (entry.isPresent) { val foundEntry = entry.get() - authenticator.canAccessSubQueue(foundEntry.type) - LOG.debug("Found message with UUID [{}] in queue with type [{}].", foundEntry.uuid, foundEntry.type) + authenticator.canAccessSubQueue(foundEntry.subQueue) + LOG.debug("Found message with UUID [{}] in sub-queue [{}].", foundEntry.uuid, foundEntry.subQueue) return ResponseEntity.ok(MessageResponse(foundEntry)) } @@ -216,7 +216,7 @@ open class MessageQueueController : HasLogger { try { - authenticator.canAccessSubQueue(queueMessage.type) + authenticator.canAccessSubQueue(queueMessage.subQueue) if (queueMessage.assignedTo != null && queueMessage.assignedTo!!.isBlank()) { @@ -226,31 +226,31 @@ open class MessageQueueController : HasLogger val wasAdded = messageQueue.add(queueMessage) if (wasAdded) { - LOG.debug("Added new message with UUID [{}] to queue with type [{}}.", queueMessage.uuid, queueMessage.type) + LOG.debug("Added new message with UUID [{}] to sub-queue [{}}.", queueMessage.uuid, queueMessage.subQueue) return ResponseEntity.status(HttpStatus.CREATED).body(MessageResponse(queueMessage)) } else { - LOG.error("Failed to add entry with UUID [{}] to queue with type [{}]. AND the message does not already exist. This could be a memory limitation or an issue with the underlying collection.", queueMessage.uuid, queueMessage.type) - throw ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to add entry with UUID: [${queueMessage.uuid}] to queue with type [${queueMessage.type}]") + LOG.error("Failed to add entry with UUID [{}] to sub-queue [{}]. AND the message does not already exist. This could be a memory limitation or an issue with the underlying collection.", queueMessage.uuid, queueMessage.subQueue) + throw ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to add entry with UUID: [${queueMessage.uuid}] to sub-queue [${queueMessage.subQueue}]") } } catch (ex: DuplicateMessageException) { - val queueType = messageQueue.containsUUID(queueMessage.uuid).get() - val errorMessage = "Failed to add entry with UUID [${queueMessage.uuid}], an entry with the same UUID already exists in queue with type [$queueType]." + val subQueue = messageQueue.containsUUID(queueMessage.uuid).get() + val errorMessage = "Failed to add entry with UUID [${queueMessage.uuid}], an entry with the same UUID already exists in sub-queue [$subQueue]." LOG.error(errorMessage) throw ResponseStatusException(HttpStatus.CONFLICT, errorMessage, ex) } } /** - * A [GetMapping] which returns a list of all the `QueueTypes` defined in the [MultiQueue]. + * A [GetMapping] which returns a list of all the `sub-queue` IDs defined in the [MultiQueue]. * * @param includeEmpty to include `keys` which one had elements stored against them but don't at the moment. Default is `true`. - * @return a [Set] of [String] `queueType`s + * @return a [Set] of [String] `sub-queue`s */ - @Operation(summary = "Retrieve a list of all keys.", description = "Retrieve a list of all sub queue key values in the multi queue.") + @Operation(summary = "Retrieve a list of all keys.", description = "Retrieve a list of all sub-queue key values in the multi queue.") @GetMapping(ENDPOINT_KEYS, produces = [MediaType.APPLICATION_JSON_VALUE]) @ApiResponse(responseCode = "200", description = "Successfully returns the list of keys.") fun getKeys(@Parameter(`in` = ParameterIn.QUERY, required = false, description = "Indicates whether to include keys that currently have zero entries (but have had entries previously). Is true by default.") @@ -264,20 +264,20 @@ open class MessageQueueController : HasLogger return ResponseEntity.ok(keys) } - @Operation(summary = "Delete a keys or all keys, in turn clearing that sub queue.", description = "Delete the sub queue that matches the provided key. If no key is provided, all sub queues will be cleared.") + @Operation(summary = "Delete a keys or all keys, in turn clearing that sub-queue.", description = "Delete the sub-queue that matches the provided key. If no key is provided, all sub-queues will be cleared.") @DeleteMapping(ENDPOINT_KEYS, produces = [MediaType.APPLICATION_JSON_VALUE]) @ApiResponses( - ApiResponse(responseCode = "204", description = "Successfully cleared the sub queue(s) with the provided key, or all sub queues if the key is null."), + ApiResponse(responseCode = "204", description = "Successfully cleared the sub-queue(s) with the provided key, or all sub-queues if the key is null."), ApiResponse(responseCode = "206", description = "Successfully cleared the sub-queues that are unrestricted. Restricted sub-queues needs to be created with a valid token.") ) - fun deleteKeys(@Parameter(`in` = ParameterIn.QUERY, required = false, description = "The queue type to clear the sub queue of. If it is not provided, all sub queues will be cleared.") - @RequestParam(required = false, name = RestParameters.QUEUE_TYPE) queueType: String?): ResponseEntity + fun deleteKeys(@Parameter(`in` = ParameterIn.QUERY, required = false, description = "The sub-queue to clear. If it is not provided, all sub-queues will be cleared.") + @RequestParam(required = false, name = RestParameters.SUB_QUEUE) subQueue: String?): ResponseEntity { - if (queueType != null) + if (subQueue != null) { - authenticator.canAccessSubQueue(queueType) - messageQueue.clearForType(queueType) - LOG.info("Cleared queue with key [{}]", queueType) + authenticator.canAccessSubQueue(subQueue) + messageQueue.clearSubQueue(subQueue) + LOG.info("Cleared queue with key [{}]", subQueue) return ResponseEntity.noContent().build() } else @@ -290,7 +290,7 @@ open class MessageQueueController : HasLogger { if (authenticator.canAccessSubQueue(key, false)) { - messageQueue.clearForType(key) + messageQueue.clearSubQueue(key) clearedKeys.add(key) } else @@ -318,34 +318,36 @@ open class MessageQueueController : HasLogger * A [GetMapping] endpoint which retrieves all the stored [QueueMessage]s that are currently available in the [MultiQueue]. * * @param detailed *true* if you require detailed information about each message and their payload/owner, otherwise **false** which displayed only limited information about each message - * @param queueType the `type` to include, if provided only messages in this `queueType` will be retrieved. - * @return a [Map] where the `key` is the `queueType` and the `value` is a comma separated list of all the [QueueMessage.removePayload] + * @param subQueue the `sub-queue` to include, if provided only messages in this `sub-queue` will be retrieved. + * @return a [Map] where the `key` is the `sub-queue` and the `value` is a comma separated list of all the [QueueMessage.removePayload] */ - @Operation(summary = "Retrieve a limited or full version of the held messages.", description = "Retrieve queue message summaries for the held messages. This can be limited to a specific sub queue type and complete message detail to be included in the response if requested.") + @Operation(summary = "Retrieve a limited or full version of the held messages.", description = "Retrieve queue message summaries for the held messages. This can be limited to a specific sub-queue and complete message detail to be included in the response if requested.") @GetMapping(ENDPOINT_ALL, produces = [MediaType.APPLICATION_JSON_VALUE]) - @ApiResponse(responseCode = "200", description = "Successfully returns the list of summary entries for either the whole multi-queue or the sub queue.") - fun getAll(@Parameter(`in` = ParameterIn.QUERY, required = false, description = "Indicates whether the response messages should contain all message details including the underlying payload. By default details are hidden.") @RequestParam(required = false, name = RestParameters.DETAILED) detailed: Boolean = false, - @Parameter(`in` = ParameterIn.QUERY, required = false, description = "The sub queue type to search, if not provide all messages in the whole multi-queue will be returned.") @RequestParam(required = false, name = RestParameters.QUEUE_TYPE) queueType: String?): ResponseEntity>> + @ApiResponse(responseCode = "200", description = "Successfully returns the list of summary entries for either the whole multi-queue or the sub-queue.") + fun getAll(@Parameter(`in` = ParameterIn.QUERY, required = false, description = "Indicates whether the response messages should contain all message details including the underlying payload. By default details are hidden.") + @RequestParam(required = false, name = RestParameters.DETAILED) detailed: Boolean = false, + @Parameter(`in` = ParameterIn.QUERY, required = false, description = "The sub-queue to search, if not provide all messages in the whole multi-queue will be returned.") + @RequestParam(required = false, name = RestParameters.SUB_QUEUE) subQueue: String?): ResponseEntity>> { val responseMap = HashMap>() - if ( !queueType.isNullOrBlank()) + if ( !subQueue.isNullOrBlank()) { - LOG.debug("Retrieving all entry details from queue with type [{}].", queueType) - authenticator.canAccessSubQueue(queueType) - val queueForType: Queue = messageQueue.getQueueForType(queueType) - val queueDetails = queueForType.stream().map { message -> message.removePayload(detailed) }.collect(Collectors.toList()) - responseMap[queueType] = queueDetails + LOG.debug("Retrieving all entry details from sub-queue [{}].", subQueue) + authenticator.canAccessSubQueue(subQueue) + val queue: Queue = messageQueue.getSubQueue(subQueue) + val queueDetails = queue.stream().map { message -> message.removePayload(detailed) }.collect(Collectors.toList()) + responseMap[subQueue] = queueDetails } else { - LOG.debug("Retrieving all entry details from all queue types.") + LOG.debug("Retrieving all entry details from all sub-queues.") for (key: String in messageQueue.keys(false)) { if (authenticator.canAccessSubQueue(key, false)) { // No need to empty check since we passed `false` to `keys()` above - val queueForType: Queue = messageQueue.getQueueForType(key) - val queueDetails = queueForType.stream().map { message -> message.removePayload(detailed) }.collect(Collectors.toList()) + val queue: Queue = messageQueue.getSubQueue(key) + val queueDetails = queue.stream().map { message -> message.removePayload(detailed) }.collect(Collectors.toList()) responseMap[key] = queueDetails } } @@ -357,20 +359,22 @@ open class MessageQueueController : HasLogger * Retrieve all owned [QueueMessage] based on the provided user identifier. * * @param assignedTo the identifier used to indicate the owner of the [QueueMessage]s to return - * @param queueType the `queueType` to search for the related [QueueMessage] owned by [assignedTo] - * @return a [List] of [QueueMessage] based on messages that are `assigned` to the [assignedTo] in the `queue` mapped to [queueType] + * @param subQueue the `sub-queue` to search for the related [QueueMessage] owned by [assignedTo] + * @return a [List] of [QueueMessage] based on messages that are `assigned` to the [assignedTo] in the `queue` mapped to [subQueue] */ - @Operation(summary = "Retrieve all owned queue messages based on the provided user identifier.", description = "Retrieve all owned messages for the provided assignee identifier for the provided sub queue type.") + @Operation(summary = "Retrieve all owned queue messages based on the provided user identifier.", description = "Retrieve all owned messages for the provided assignee identifier for the provided sub-queue.") @GetMapping(ENDPOINT_OWNED, produces = [MediaType.APPLICATION_JSON_VALUE]) - @ApiResponse(responseCode = "200", description = "Successfully returns the list of owned queue messages in the sub queue for the provided assignee identifier.") - fun getOwned(@Parameter(`in` = ParameterIn.QUERY, required = true, description = "The identifier that must match the message's `assigned` property in order to be returned.") @RequestParam(required = true, name = RestParameters.ASSIGNED_TO) assignedTo: String, - @Parameter(`in` = ParameterIn.QUERY, required = true, description = "The sub queue to search for the assigned messages.") @RequestParam(required = true, name = RestParameters.QUEUE_TYPE) queueType: String): ResponseEntity> + @ApiResponse(responseCode = "200", description = "Successfully returns the list of owned queue messages in the sub-queue for the provided assignee identifier.") + fun getOwned(@Parameter(`in` = ParameterIn.QUERY, required = true, description = "The identifier that must match the message's `assigned` property in order to be returned.") + @RequestParam(required = true, name = RestParameters.ASSIGNED_TO) assignedTo: String, + @Parameter(`in` = ParameterIn.QUERY, required = true, description = "The sub-queue to search for the assigned messages.") + @RequestParam(required = true, name = RestParameters.SUB_QUEUE) subQueue: String): ResponseEntity> { - authenticator.canAccessSubQueue(queueType) + authenticator.canAccessSubQueue(subQueue) - val assignedMessages: Queue = messageQueue.getAssignedMessagesForType(queueType, assignedTo) + val assignedMessages: Queue = messageQueue.getAssignedMessagesInSubQueue(subQueue, assignedTo) val ownedMessages = assignedMessages.stream().map { message -> MessageResponse(message) }.collect(Collectors.toList()) - LOG.debug("Found [{}] owned entries within queue with type [{}] for user with identifier [{}].", ownedMessages.size, queueType, assignedTo) + LOG.debug("Found [{}] owned entries within sub-queue [{}] for user with identifier [{}].", ownedMessages.size, subQueue, assignedTo) return ResponseEntity.ok(ownedMessages) } @@ -400,19 +404,19 @@ open class MessageQueueController : HasLogger if (message.isPresent) { val messageToAssign = message.get() - authenticator.canAccessSubQueue(messageToAssign.type) + authenticator.canAccessSubQueue(messageToAssign.subQueue) if (!messageToAssign.assignedTo.isNullOrBlank()) { if (messageToAssign.assignedTo == assignedTo) { // The message is already in this state, returning 202 to tell the client that it is accepted but no action was done - LOG.debug("Message with uuid [{}] in queue with type [{}] is already assigned to the identifier [{}].", messageToAssign.uuid, messageToAssign.type, assignedTo) + LOG.debug("Message with uuid [{}] in sub-queue [{}] is already assigned to the identifier [{}].", messageToAssign.uuid, messageToAssign.subQueue, assignedTo) return ResponseEntity.accepted().body(MessageResponse(messageToAssign)) } else { - LOG.error("Message with uuid [{}] in queue with type [{}] is already assigned to the identifier [{}]. Attempting to assign to identifier [{}].", messageToAssign.uuid, messageToAssign.type, messageToAssign.assignedTo, assignedTo) - throw ResponseStatusException(HttpStatus.CONFLICT, "The message with UUID: [$uuid] and [${messageToAssign.type}] is already assigned to the identifier [${messageToAssign.assignedTo}].") + LOG.error("Message with uuid [{}] in sub-queue [{}] is already assigned to the identifier [{}]. Attempting to assign to identifier [{}].", messageToAssign.uuid, messageToAssign.subQueue, messageToAssign.assignedTo, assignedTo) + throw ResponseStatusException(HttpStatus.CONFLICT, "The message with UUID: [$uuid] and [${messageToAssign.subQueue}] is already assigned to the identifier [${messageToAssign.assignedTo}].") } } @@ -428,35 +432,37 @@ open class MessageQueueController : HasLogger } /** - * Retrieve the next `non-assigned` message in the [MultiQueue] for the provided [queueType] and assign it to the provided identifier [assignedTo]. + * Retrieve the next `non-assigned` message in the [MultiQueue] for the provided [subQueue] and assign it to the provided identifier [assignedTo]. * - * @param queueType the sub queue that the next [QueueMessage] should be from + * @param subQueue the sub-queue that the next [QueueMessage] should be from * @param assignedTo the identifier that the next [QueueMessage] should be `assigned` to before being returned - * @return the next [QueueMessage] that is not `assigned` in the provided [queueType]. If none exist then [HttpStatus.NO_CONTENT] will be returned indicating that the queue is either empty or has no available [QueueMessage]s to assign. + * @return the next [QueueMessage] that is not `assigned` in the provided [subQueue]. If none exist then [HttpStatus.NO_CONTENT] will be returned indicating that the queue is either empty or has no available [QueueMessage]s to assign. */ - @Operation(summary = "Retrieve the next available unassigned message in the queue.", description = "Retrieve the next available message in the queue for the provided sub queue identifier that is not assigned. The message will be assigned to the provided identifier then returned.") + @Operation(summary = "Retrieve the next available unassigned message in the queue.", description = "Retrieve the next available message in the queue for the provided sub-queue identifier that is not assigned. The message will be assigned to the provided identifier then returned.") @PutMapping(ENDPOINT_NEXT, produces = [MediaType.APPLICATION_JSON_VALUE]) @ApiResponses( ApiResponse(responseCode = "200", description = "Successfully returns the next message in queue after assigning it to the provided `assignedTo` identifier."), ApiResponse(responseCode = "204", description = "No messages are available.", content = [Content()]) ) - fun getNext(@Parameter(`in` = ParameterIn.QUERY, required = true, description = "The sub queue identifier to query the next available message from.") @RequestParam(required = true, name = RestParameters.QUEUE_TYPE) queueType: String, - @Parameter(`in` = ParameterIn.QUERY, required = true, description = "The identifier to assign the next available message to if one exists.") @RequestParam(required = true, name = RestParameters.ASSIGNED_TO) assignedTo: String): ResponseEntity + fun getNext(@Parameter(`in` = ParameterIn.QUERY, required = true, description = "The sub-queue identifier to query the next available message from.") + @RequestParam(required = true, name = RestParameters.SUB_QUEUE) subQueue: String, + @Parameter(`in` = ParameterIn.QUERY, required = true, description = "The identifier to assign the next available message to if one exists.") + @RequestParam(required = true, name = RestParameters.ASSIGNED_TO) assignedTo: String): ResponseEntity { - authenticator.canAccessSubQueue(queueType) + authenticator.canAccessSubQueue(subQueue) - val queueForType: Queue = messageQueue.getUnassignedMessagesForType(queueType) - return if (queueForType.iterator().hasNext()) + val queue: Queue = messageQueue.getUnassignedMessagesInSubQueue(subQueue) + return if (queue.iterator().hasNext()) { - val nextUnassignedMessage = queueForType.iterator().next() - LOG.debug("Retrieving and assigning next message for queue type [{}] with UUID [{}] to identifier [{}].", queueType, nextUnassignedMessage.uuid, assignedTo) + val nextUnassignedMessage = queue.iterator().next() + LOG.debug("Retrieving and assigning next message for sub-queue [{}] with UUID [{}] to identifier [{}].", subQueue, nextUnassignedMessage.uuid, assignedTo) nextUnassignedMessage.assignedTo = assignedTo messageQueue.persistMessage(nextUnassignedMessage) ResponseEntity.ok(MessageResponse(nextUnassignedMessage)) } else { - LOG.debug("No unassigned entries in queue with type [{}].", queueType) + LOG.debug("No unassigned entries in sub-queue [{}].", subQueue) ResponseEntity.noContent().build() } } @@ -487,7 +493,7 @@ open class MessageQueueController : HasLogger if (message.isPresent) { val messageToRelease = message.get() - authenticator.canAccessSubQueue(messageToRelease.type) + authenticator.canAccessSubQueue(messageToRelease.subQueue) if (messageToRelease.assignedTo == null) { @@ -498,7 +504,7 @@ open class MessageQueueController : HasLogger if (!assignedTo.isNullOrBlank() && messageToRelease.assignedTo != assignedTo) { - val errorMessage = "The message with UUID: [$uuid] and [${messageToRelease.type}] cannot be released because it is already assigned to identifier [${messageToRelease.assignedTo}] and the provided identifier was [$assignedTo]." + val errorMessage = "The message with UUID: [$uuid] and [${messageToRelease.subQueue}] cannot be released because it is already assigned to identifier [${messageToRelease.assignedTo}] and the provided identifier was [$assignedTo]." LOG.error(errorMessage) throw ResponseStatusException(HttpStatus.CONFLICT, errorMessage) } @@ -508,7 +514,7 @@ open class MessageQueueController : HasLogger return ResponseEntity.ok(MessageResponse(messageToRelease)) } - // No entries match the provided UUID (and queue type) + // No entries match the provided UUID (and sub-queue) LOG.debug("Could not find message to release with UUID [{}].", uuid) return ResponseEntity.noContent().build() } @@ -539,10 +545,10 @@ open class MessageQueueController : HasLogger if (message.isPresent) { val messageToRemove = message.get() - authenticator.canAccessSubQueue(messageToRemove.type) + authenticator.canAccessSubQueue(messageToRemove.subQueue) if ( !assignedTo.isNullOrBlank() && messageToRemove.assignedTo != assignedTo) { - val errorMessage = "Unable to remove message with UUID [$uuid] in Queue [${messageToRemove.type}] because the provided assignee identifier: [$assignedTo] does not match the message's assignee identifier: [${messageToRemove.assignedTo}]" + val errorMessage = "Unable to remove message with UUID [$uuid] in Queue [${messageToRemove.subQueue}] because the provided assignee identifier: [$assignedTo] does not match the message's assignee identifier: [${messageToRemove.assignedTo}]" LOG.error(errorMessage) throw ResponseStatusException(HttpStatus.FORBIDDEN, errorMessage) } @@ -564,14 +570,15 @@ open class MessageQueueController : HasLogger * "identifier2": ["queue-A", "queue-B", "queue-Z"] * } * ``` - * @param queueType the sub-queue identifier that you are interested in. If not provided, all sub-queues will be iterated through. + * @param subQueue the sub-queue identifier that you are interested in. If not provided, all sub-queues will be iterated through. * @return a [Map] of assignee identifiers mapped to a [Set] of the sub-queue identifiers that they have any assigned messages in. */ @Operation(summary = "Retrieve all unique owner identifiers for either a specified sub-queue or all sub-queues.", description = "Retrieve all owner identifier mapped to a list of the sub-queue identifiers that they are assigned any messages in.") @GetMapping(ENDPOINT_OWNERS, produces = [MediaType.APPLICATION_JSON_VALUE]) @ApiResponse(responseCode = "200", description = "Successfully returns the map of owner identifiers mapped to all the sub-queues that they have one or more assigned messages in.") - fun getOwners(@Parameter(`in` = ParameterIn.QUERY, required = false, description = "The sub queue to search for the owner identifiers.") @RequestParam(required = false, name = RestParameters.QUEUE_TYPE) queueType: String?): ResponseEntity>> + fun getOwners(@Parameter(`in` = ParameterIn.QUERY, required = false, description = "The sub-queue to search for the owner identifiers.") + @RequestParam(required = false, name = RestParameters.SUB_QUEUE) subQueue: String?): ResponseEntity>> { - return ResponseEntity.ok(messageQueue.getOwnersAndKeysMap(queueType)) + return ResponseEntity.ok(messageQueue.getOwnersAndKeysMap(subQueue)) } } diff --git a/src/main/kotlin/au/kilemon/messagequeue/rest/controller/RestParameters.kt b/src/main/kotlin/au/kilemon/messagequeue/rest/controller/RestParameters.kt index 033209e..6d1e5cb 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/rest/controller/RestParameters.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/rest/controller/RestParameters.kt @@ -12,7 +12,7 @@ object RestParameters { const val ASSIGNED_TO = "assignedTo" - const val QUEUE_TYPE = "queueType" + const val SUB_QUEUE = "subQueue" const val DETAILED = "detailed" diff --git a/src/main/kotlin/au/kilemon/messagequeue/rest/response/MessageResponse.kt b/src/main/kotlin/au/kilemon/messagequeue/rest/response/MessageResponse.kt index a89ad9b..6a53b13 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/rest/response/MessageResponse.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/rest/response/MessageResponse.kt @@ -6,9 +6,9 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder import org.slf4j.MDC /** - * A response object which wraps the [QueueMessage], and exposes the `type` [String]. + * A response object which wraps the [QueueMessage], and exposes the `sub-queue` [String]. * * @author github.com/Kilemonn */ -@JsonPropertyOrder("correlationId", "queueType", "message") -data class MessageResponse(val message: QueueMessage, val queueType: String = message.type, val correlationId: String? = MDC.get(CorrelationIdFilter.CORRELATION_ID)) +@JsonPropertyOrder("correlationId", "subQueue", "message") +data class MessageResponse(val message: QueueMessage, val subQueue: String = message.subQueue, val correlationId: String? = MDC.get(CorrelationIdFilter.CORRELATION_ID)) diff --git a/src/main/kotlin/au/kilemon/messagequeue/settings/MessageQueueSettings.kt b/src/main/kotlin/au/kilemon/messagequeue/settings/MessageQueueSettings.kt index 55591ff..f56d154 100644 --- a/src/main/kotlin/au/kilemon/messagequeue/settings/MessageQueueSettings.kt +++ b/src/main/kotlin/au/kilemon/messagequeue/settings/MessageQueueSettings.kt @@ -10,7 +10,8 @@ import org.springframework.stereotype.Component * An object that holds application level properties and is set initially on application start up. * This will control things such as: * - Credentials to external data storage - * - The type of `MultiQueue` being used + * - The storage medium of `MultiQueue` being used + * - The restriction mode being used * - Other utility configuration for the application to use. * * When `SQL` is used, the following property must be provided: @@ -67,7 +68,7 @@ class MessageQueueSettings const val SQL_SCHEMA_DEFAULT: String = "public" /** - * Start authenticated sub queue properties. + * Start authenticated sub-queue properties. */ /** * Indicates what authentication mode the `MultiQueue` should be in. @@ -93,7 +94,7 @@ class MessageQueueSettings @Value("\${$STORAGE_MEDIUM:$STORAGE_MEDIUM_DEFAULT}") @get:Generated @set:Generated - lateinit var multiQueueType: String + lateinit var storageMedium: String /** * `Optional` uses the [RESTRICTION_MODE] environment variable to determine whether specific sub-queues @@ -105,7 +106,7 @@ class MessageQueueSettings @Value("\${$RESTRICTION_MODE:$RESTRICTION_MODE_DEFAULT}") @get:Generated @set:Generated - lateinit var multiQueueAuthentication: String + lateinit var restrictionMode: String /** diff --git a/src/test/kotlin/au/kilemon/messagequeue/authentication/authenticator/MultiQueueAuthenticatorTest.kt b/src/test/kotlin/au/kilemon/messagequeue/authentication/authenticator/MultiQueueAuthenticatorTest.kt index d401b8b..437cdc4 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/authentication/authenticator/MultiQueueAuthenticatorTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/authentication/authenticator/MultiQueueAuthenticatorTest.kt @@ -25,12 +25,12 @@ abstract class MultiQueueAuthenticatorTest /** * Ensure [MultiQueueAuthenticator.addRestrictedEntry] always returns and does not add an entry if the - * [MultiQueueAuthenticator.getAuthenticationType] is [RestrictionMode.NONE]. + * [MultiQueueAuthenticator.getRestrictionMode] is [RestrictionMode.NONE]. */ @Test fun testAddRestrictedEntry_WithNoneMode() { - Assertions.assertEquals(RestrictionMode.NONE, multiQueueAuthenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, multiQueueAuthenticator.getRestrictionMode()) val subQueue = "testAddRestrictedEntry_WithNoneMode" Assertions.assertFalse(multiQueueAuthenticator.isRestricted(subQueue)) Assertions.assertFalse(multiQueueAuthenticator.addRestrictedEntry(subQueue)) @@ -38,15 +38,15 @@ abstract class MultiQueueAuthenticatorTest } /** - * Ensure [MultiQueueAuthenticator.addRestrictedEntry] will add the request sub queue identifier when the - * [MultiQueueAuthenticator.getAuthenticationType] is NOT [RestrictionMode.NONE]. - * Also tests [MultiQueueAuthenticator.isRestricted] can determine the sub queue is restricted after its been added. + * Ensure [MultiQueueAuthenticator.addRestrictedEntry] will add the request sub-queue identifier when the + * [MultiQueueAuthenticator.getRestrictionMode] is NOT [RestrictionMode.NONE]. + * Also tests [MultiQueueAuthenticator.isRestricted] can determine the sub-queue is restricted after its been added. */ @Test fun testAddRestrictedEntry_WithARestrictedNoneMode() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getRestrictionMode()) val subQueue = "testAddRestrictedEntry_WithARestrictedNoneMode" Assertions.assertFalse(multiQueueAuthenticator.isRestricted(subQueue)) @@ -56,33 +56,33 @@ abstract class MultiQueueAuthenticatorTest /** * Ensure that [MultiQueueAuthenticator.removeRestriction] will not be able to remove a restriction if the - * [MultiQueueAuthenticator.getAuthenticationType] is set to [RestrictionMode.NONE]. + * [MultiQueueAuthenticator.getRestrictionMode] is set to [RestrictionMode.NONE]. */ @Test fun testRemoveRestriction_WithNoneMode() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getRestrictionMode()) val subQueue = "testRemoveRestriction_WithNoneMode" Assertions.assertFalse(multiQueueAuthenticator.isRestricted(subQueue)) Assertions.assertTrue(multiQueueAuthenticator.addRestrictedEntry(subQueue)) Assertions.assertTrue(multiQueueAuthenticator.isRestricted(subQueue)) - Mockito.doReturn(RestrictionMode.NONE).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.NONE, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.NONE).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.NONE, multiQueueAuthenticator.getRestrictionMode()) Assertions.assertFalse(multiQueueAuthenticator.removeRestriction(subQueue)) } /** - * Ensure that [MultiQueueAuthenticator.addRestrictedEntry] returns `false` when an existing sub queue identifier + * Ensure that [MultiQueueAuthenticator.addRestrictedEntry] returns `false` when an existing sub-queue identifier * is attempting to be added. */ @Test fun testRemoveRestriction_AddExistingSubQueueIdentifier() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getRestrictionMode()) val subQueue = "testRemoveRestriction_AddExistingSubQueueIdentifier" Assertions.assertFalse(multiQueueAuthenticator.isRestricted(subQueue)) @@ -95,13 +95,13 @@ abstract class MultiQueueAuthenticatorTest /** * Ensure that [MultiQueueAuthenticator.removeRestriction] will not be able to remove a restriction if the - * [MultiQueueAuthenticator.getAuthenticationType] is set to [RestrictionMode.NONE]. + * [MultiQueueAuthenticator.getRestrictionMode] is set to [RestrictionMode.NONE]. */ @Test fun testRemoveRestriction_WithARestrictedNoneMode() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getRestrictionMode()) val subQueue = "testRemoveRestriction_WithARestrictedNoneMode" Assertions.assertFalse(multiQueueAuthenticator.isRestricted(subQueue)) @@ -113,14 +113,14 @@ abstract class MultiQueueAuthenticatorTest } /** - * Ensure that [MultiQueueAuthenticator.removeRestriction] returns `false` when you attempt to remove a sub queue + * Ensure that [MultiQueueAuthenticator.removeRestriction] returns `false` when you attempt to remove a sub-queue * identifier that does not exist. */ @Test fun testRemoveRestriction_DoesNotExist() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getRestrictionMode()) val subQueue = "testRemoveRestriction_DoesNotExist" Assertions.assertFalse(multiQueueAuthenticator.isRestricted(subQueue)) Assertions.assertFalse(multiQueueAuthenticator.removeRestriction(subQueue)) @@ -133,7 +133,7 @@ abstract class MultiQueueAuthenticatorTest @Test fun testCanAccessSubQueue_WithNoneMode() { - Assertions.assertEquals(RestrictionMode.NONE, multiQueueAuthenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, multiQueueAuthenticator.getRestrictionMode()) val subQueue = "testCanAccessSubQueue_WithNoneMode" Assertions.assertTrue(multiQueueAuthenticator.canAccessSubQueue(subQueue)) } @@ -145,8 +145,8 @@ abstract class MultiQueueAuthenticatorTest @Test fun testCanAccessSubQueue_WithHybridMode_isNotRestricted() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getRestrictionMode()) val subQueue = "testCanAccessSubQueue_WithHybridMode_isNotRestricted" Assertions.assertFalse(multiQueueAuthenticator.isRestricted(subQueue)) @@ -162,8 +162,8 @@ abstract class MultiQueueAuthenticatorTest @Test fun testCanAccessSubQueue_WithHybridMode_isRestricted_matchesStoredSubQueue() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getRestrictionMode()) val subQueue = "testCanAccessSubQueue_WithHybridMode_isRestricted_matchesStoredSubQueue" Assertions.assertTrue(multiQueueAuthenticator.addRestrictedEntry(subQueue)) @@ -188,8 +188,8 @@ abstract class MultiQueueAuthenticatorTest @Test fun testCanAccessSubQueue_WithHybridMode_isRestricted_doesNotMatchStoredSubQueue() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getRestrictionMode()) val subQueue = "testCanAccessSubQueue_WithHybridMode_isRestricted_doesNotMatchStoredSubQueue" Assertions.assertTrue(multiQueueAuthenticator.addRestrictedEntry(subQueue)) @@ -216,8 +216,8 @@ abstract class MultiQueueAuthenticatorTest @Test fun testCanAccessSubQueue_WithRestrictedMode_isNotRestricted() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getRestrictionMode()) val subQueue = "testCanAccessSubQueue_WithRestrictedMode_isNotRestricted" Assertions.assertFalse(multiQueueAuthenticator.isRestricted(subQueue)) @@ -235,8 +235,8 @@ abstract class MultiQueueAuthenticatorTest @Test fun testCanAccessSubQueue_WithRestrictedMode_isRestricted_matchesStoredSubQueue() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getRestrictionMode()) val subQueue = "testCanAccessSubQueue_WithRestrictedMode_isRestricted_matchesStoredSubQueue" Assertions.assertTrue(multiQueueAuthenticator.addRestrictedEntry(subQueue)) @@ -262,8 +262,8 @@ abstract class MultiQueueAuthenticatorTest @Test fun testCanAccessSubQueue_WithRestrictedMode_isRestricted_doesNotMatchStoredSubQueue() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getRestrictionMode()) val subQueue = "testCanAccessSubQueue_WithRestrictedMode_isRestricted_doesNotMatchStoredSubQueue" Assertions.assertTrue(multiQueueAuthenticator.addRestrictedEntry(subQueue)) @@ -289,8 +289,8 @@ abstract class MultiQueueAuthenticatorTest @Test fun testClearRestrictedSubQueues() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getRestrictionMode()) val subQueues = listOf("testClearRestrictedSubQueues1", "testClearRestrictedSubQueues2", "testClearRestrictedSubQueues3", "testClearRestrictedSubQueues4", "testClearRestrictedSubQueues5", "testClearRestrictedSubQueues6") @@ -310,8 +310,8 @@ abstract class MultiQueueAuthenticatorTest @Test fun testGetRestrictedSubQueueIdentifiers() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getRestrictionMode()) val subQueues = listOf("testGetRestrictedSubQueueIdentifiers1", "testGetRestrictedSubQueueIdentifiers2", "testGetRestrictedSubQueueIdentifiers3", "testGetRestrictedSubQueueIdentifiers4", diff --git a/src/test/kotlin/au/kilemon/messagequeue/authentication/authenticator/inmemory/InMemoryAuthenticatorTest.kt b/src/test/kotlin/au/kilemon/messagequeue/authentication/authenticator/inmemory/InMemoryAuthenticatorTest.kt index 3610fe6..218534c 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/authentication/authenticator/inmemory/InMemoryAuthenticatorTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/authentication/authenticator/inmemory/InMemoryAuthenticatorTest.kt @@ -40,13 +40,13 @@ class InMemoryAuthenticatorTest: MultiQueueAuthenticatorTest() fun testIsInNoneMode() { val authenticator = Mockito.spy(MultiQueueAuthenticator::class.java) - Mockito.doReturn(RestrictionMode.NONE).`when`(authenticator).getAuthenticationType() + Mockito.doReturn(RestrictionMode.NONE).`when`(authenticator).getRestrictionMode() Assertions.assertTrue(authenticator.isInNoneMode()) - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() Assertions.assertFalse(authenticator.isInNoneMode()) - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(authenticator).getAuthenticationType() + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(authenticator).getRestrictionMode() Assertions.assertFalse(authenticator.isInNoneMode()) } @@ -58,13 +58,13 @@ class InMemoryAuthenticatorTest: MultiQueueAuthenticatorTest() fun testIsInHybridMode() { val authenticator = Mockito.spy(MultiQueueAuthenticator::class.java) - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() Assertions.assertTrue(authenticator.isInHybridMode()) - Mockito.doReturn(RestrictionMode.NONE).`when`(authenticator).getAuthenticationType() + Mockito.doReturn(RestrictionMode.NONE).`when`(authenticator).getRestrictionMode() Assertions.assertFalse(authenticator.isInHybridMode()) - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(authenticator).getAuthenticationType() + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(authenticator).getRestrictionMode() Assertions.assertFalse(authenticator.isInHybridMode()) } @@ -76,13 +76,13 @@ class InMemoryAuthenticatorTest: MultiQueueAuthenticatorTest() fun testIsInRestrictedMode() { val authenticator = Mockito.spy(MultiQueueAuthenticator::class.java) - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(authenticator).getAuthenticationType() + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(authenticator).getRestrictionMode() Assertions.assertTrue(authenticator.isInRestrictedMode()) - Mockito.doReturn(RestrictionMode.NONE).`when`(authenticator).getAuthenticationType() + Mockito.doReturn(RestrictionMode.NONE).`when`(authenticator).getRestrictionMode() Assertions.assertFalse(authenticator.isInRestrictedMode()) - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() Assertions.assertFalse(authenticator.isInRestrictedMode()) } } diff --git a/src/test/kotlin/au/kilemon/messagequeue/authentication/exception/MultiQueueAuthorisationExceptionTest.kt b/src/test/kotlin/au/kilemon/messagequeue/authentication/exception/MultiQueueAuthorisationExceptionTest.kt index e418347..2fb693d 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/authentication/exception/MultiQueueAuthorisationExceptionTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/authentication/exception/MultiQueueAuthorisationExceptionTest.kt @@ -18,7 +18,7 @@ class MultiQueueAuthorisationExceptionTest @Test fun testTypeOfException() { - val e = MultiQueueAuthorisationException("Sub queue", RestrictionMode.NONE) + val e = MultiQueueAuthorisationException("sub-queue", RestrictionMode.NONE) Assertions.assertTrue(Exception::class.isInstance(e)) Assertions.assertFalse(RuntimeException::class.isInstance(e)) } diff --git a/src/test/kotlin/au/kilemon/messagequeue/message/QueueMessageTest.kt b/src/test/kotlin/au/kilemon/messagequeue/message/QueueMessageTest.kt index 58396a9..1b41d37 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/message/QueueMessageTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/message/QueueMessageTest.kt @@ -33,18 +33,18 @@ class QueueMessageTest /** * Ensure that two [QueueMessage]s are not equal if one has `null` [QueueMessage.payload] and [QueueMessage.payloadBytes], but the same - * [QueueMessage.uuid] and [QueueMessage.type]. + * [QueueMessage.uuid] and [QueueMessage.subQueue]. */ @Test fun testEquals_withOneMessageHavingNullPayloadAndBytes() { val uuid = UUID.randomUUID().toString() - val type = "type" + val subQueue = "testEquals_withOneMessageHavingNullPayloadAndBytes" val message1 = QueueMessage() message1.payload = null message1.uuid = uuid - message1.type = type - val message2 = QueueMessage(payload = "stuff", type = type) + message1.subQueue = subQueue + val message2 = QueueMessage(payload = "stuff", subQueue = subQueue) message2.uuid = uuid Assertions.assertNull(message1.payload) @@ -56,17 +56,17 @@ class QueueMessageTest /** * Ensure that two [QueueMessage] are equal if they both have `null` [QueueMessage.payload] but `equal` [QueueMessage.payloadBytes], and the same - * [QueueMessage.uuid] and [QueueMessage.type]. + * [QueueMessage.uuid] and [QueueMessage.subQueue]. */ @Test fun testEquals_withEqualPayloadBytes() { val uuid = UUID.randomUUID().toString() - val type = "type" - val message1 = QueueMessage(payload = "stuff", type = type) + val subQueue = "testEquals_withEqualPayloadBytes" + val message1 = QueueMessage(payload = "stuff", subQueue = subQueue) message1.payload = null message1.uuid = uuid - val message2 = QueueMessage(payload = "stuff", type = type) + val message2 = QueueMessage(payload = "stuff", subQueue = subQueue) message2.payload = null message2.uuid = uuid @@ -76,19 +76,19 @@ class QueueMessageTest /** * Ensure that two [QueueMessage] are equal if they both have `null` [QueueMessage.payloadBytes] but `equal` [QueueMessage.payload], and the same - * [QueueMessage.uuid] and [QueueMessage.type]. + * [QueueMessage.uuid] and [QueueMessage.subQueue]. */ @Test fun testEquals_withEqualPayloads() { val uuid = UUID.randomUUID().toString() - val type = "type" + val subQueue = "testEquals_withEqualPayloads" val message1 = QueueMessage() message1.uuid = uuid - message1.type = type + message1.subQueue = subQueue val message2 = QueueMessage() message2.uuid = uuid - message2.type = type + message2.subQueue = subQueue // Set the payload into both objects to ensure this is considered in the equals check too val obj = 1287354 @@ -103,16 +103,16 @@ class QueueMessageTest /** * Ensure that two [QueueMessage] are equal if they both have `equal` [QueueMessage.payloadBytes] and [QueueMessage.payload], and the same - * [QueueMessage.uuid] and [QueueMessage.type]. + * [QueueMessage.uuid] and [QueueMessage.subQueue]. */ @Test fun testEquals_withEqualPayloadsAndBytes() { val uuid = UUID.randomUUID().toString() - val type = "type" - val message1 = QueueMessage(payload = "stuff", type = type) + val subQueue = "testEquals_withEqualPayloadsAndBytes" + val message1 = QueueMessage(payload = "stuff", subQueue = subQueue) message1.uuid = uuid - val message2 = QueueMessage(payload = "stuff", type = type) + val message2 = QueueMessage(payload = "stuff", subQueue = subQueue) message2.uuid = uuid Assertions.assertEquals(message1.payload, message2.payload) @@ -121,15 +121,15 @@ class QueueMessageTest } /** - * Ensure that [QueueMessage.equals] returns `false` when all properties are equal except [QueueMessage.type]. + * Ensure that [QueueMessage.equals] returns `false` when all properties are equal except [QueueMessage.subQueue]. */ @Test - fun testEquals_nonEqualType() + fun testEquals_nonEqualSubQueue() { val uuid = UUID.randomUUID().toString() - val message1 = QueueMessage(payload = "stuff", type = "type1") + val message1 = QueueMessage(payload = "stuff", subQueue = "type1") message1.uuid = uuid - val message2 = QueueMessage(payload = "stuff", type = "type2") + val message2 = QueueMessage(payload = "stuff", subQueue = "type2") message2.uuid = uuid Assertions.assertEquals(message1.payload, message2.payload) @@ -143,7 +143,7 @@ class QueueMessageTest @Test fun testEquals_withNull() { - val message = QueueMessage(payload = "data", type = "testEquals_withNull") + val message = QueueMessage(payload = "data", subQueue = "testEquals_withNull") Assertions.assertNotEquals(message, null) } @@ -153,7 +153,7 @@ class QueueMessageTest @Test fun testEquals_withNonQueueMessageObject() { - val message = QueueMessage(payload = "data", type = "testEquals_withNonQueueMessageObject") + val message = QueueMessage(payload = "data", subQueue = "testEquals_withNonQueueMessageObject") val obj = Any() Assertions.assertTrue(obj !is QueueMessage) Assertions.assertNotEquals(message, obj) @@ -167,7 +167,7 @@ class QueueMessageTest fun testResolvePayload_payloadNotNullBytesNull() { val payload = "testResolvePayload_payloadNotNullBytesNull" - val message = QueueMessage(null, type = "test") + val message = QueueMessage(null, subQueue = "test") Assertions.assertNull(message.payloadBytes) message.payload = payload message.resolvePayloadObject() @@ -183,7 +183,7 @@ class QueueMessageTest { val payload1 = "testResolvePayload_payloadNotNullBytesNotNull" val payload2 = "payload-bytes" - val message = QueueMessage(payload1, type = "test") + val message = QueueMessage(payload1, subQueue = "test") message.payloadBytes = SerializationUtils.serialize(payload2) message.resolvePayloadObject() Assertions.assertEquals(payload1, message.payload) @@ -197,7 +197,7 @@ class QueueMessageTest @Test fun testResolvePayload_payloadNullBytesNull() { - val message = QueueMessage(null, type = "test") + val message = QueueMessage(null, subQueue = "test") Assertions.assertNull(message.payload) Assertions.assertNull(message.payloadBytes) @@ -215,7 +215,7 @@ class QueueMessageTest fun testResolvePayload_payloadNullBytesNotNull() { val payload = "testResolvePayload_payloadNullBytesNotNull" - val message = QueueMessage(null, type = "test") + val message = QueueMessage(null, subQueue = "test") message.payloadBytes = SerializationUtils.serialize(payload) // At this point the payload property will quest payloadBytes, we need to overwrite diff --git a/src/test/kotlin/au/kilemon/messagequeue/queue/MultiQueueTest.kt b/src/test/kotlin/au/kilemon/messagequeue/queue/MultiQueueTest.kt index 7b32b5a..9812ba0 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/queue/MultiQueueTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/queue/MultiQueueTest.kt @@ -68,24 +68,24 @@ abstract class MultiQueueTest /** * Ensure that when a new entry is added, that the [MultiQueue] is no longer empty and reports the correct size. * - * @param data the incoming [Serializable] data to store in the [MultiQueue] to test that we can cater for multiple types + * @param data the incoming [Serializable] data to store in the [MultiQueue] to test that we can cater for multiple [QueueMessage.subQueue] */ @ParameterizedTest @MethodSource("parameters_testAdd") fun testAdd(data: Serializable) { Assertions.assertTrue(multiQueue.isEmpty()) - val message = QueueMessage(data, "type") + val message = QueueMessage(data, "testAdd") Assertions.assertTrue(multiQueue.add(message)) Assertions.assertFalse(multiQueue.isEmpty()) Assertions.assertEquals(1, multiQueue.size) // Getting the element two ways, via the queue for type and via poll to ensure both ways resolve the object payload properly - val queue = multiQueue.getQueueForType(message.type) + val queue = multiQueue.getSubQueue(message.subQueue) Assertions.assertEquals(1, queue.size) val storedElement = queue.elementAt(0) - val retrievedMessage = multiQueue.pollForType(message.type) + val retrievedMessage = multiQueue.pollSubQueue(message.subQueue) Assertions.assertTrue(multiQueue.isEmpty()) Assertions.assertEquals(0, multiQueue.size) @@ -112,37 +112,37 @@ abstract class MultiQueueTest } /*** - * Test [MultiQueue.add] to ensure that [DuplicateMessageException] is thrown if a [QueueMessage] already exists with the same `UUID` even if it is assigned to a different `queue type`. + * Test [MultiQueue.add] to ensure that [DuplicateMessageException] is thrown if a [QueueMessage] already exists with the same `UUID` even if it is assigned to a different `sub-queue`. */ @Test - fun testAdd_entryAlreadyExistsInDifferentQueueType() + fun testAdd_entryAlreadyExistsInDifferentSubQueue() { Assertions.assertTrue(multiQueue.isEmpty()) - val message = QueueMessage("test", "type") + val message = QueueMessage("test", "testAdd_entryAlreadyExistsInDifferentSubQueue") Assertions.assertTrue(multiQueue.add(message)) - val differentType = "different-type" - val differentTypeMessage = QueueMessage(message.payload, differentType) - differentTypeMessage.uuid = message.uuid + val differentSubQueue = "testAdd_entryAlreadyExistsInDifferentSubQueue2" + val differentMessage = QueueMessage(message.payload, differentSubQueue) + differentMessage.uuid = message.uuid - Assertions.assertEquals(message.payload, differentTypeMessage.payload) - Assertions.assertEquals(message.uuid, differentTypeMessage.uuid) - Assertions.assertNotEquals(message.type, differentTypeMessage.type) + Assertions.assertEquals(message.payload, differentMessage.payload) + Assertions.assertEquals(message.uuid, differentMessage.uuid) + Assertions.assertNotEquals(message.subQueue, differentMessage.subQueue) Assertions.assertThrows(DuplicateMessageException::class.java) { - multiQueue.add(differentTypeMessage) + multiQueue.add(differentMessage) } } /*** - * Test [MultiQueue.add] to ensure that [DuplicateMessageException] is thrown if a [QueueMessage] already exists with the same `UUID` even if it is assigned to the same `queue type`. + * Test [MultiQueue.add] to ensure that [DuplicateMessageException] is thrown if a [QueueMessage] already exists with the same `UUID` even if it is assigned to the same `sub-queue`. */ @Test fun testAdd_sameEntryAlreadyExists() { Assertions.assertTrue(multiQueue.isEmpty()) - val message = QueueMessage("test", "type") + val message = QueueMessage("test", "testAdd_sameEntryAlreadyExists") Assertions.assertTrue(multiQueue.add(message)) Assertions.assertThrows(DuplicateMessageException::class.java) @@ -159,7 +159,7 @@ abstract class MultiQueueTest { Assertions.assertTrue(multiQueue.isEmpty()) - val message = QueueMessage("A test value", "type") + val message = QueueMessage("A test value", "testRemove") Assertions.assertTrue(multiQueue.add(message)) Assertions.assertFalse(multiQueue.isEmpty()) @@ -177,7 +177,7 @@ abstract class MultiQueueTest fun testRemove_whenEntryDoesntExist() { Assertions.assertTrue(multiQueue.isEmpty()) - val messageThatDoesntExist = QueueMessage(Payload("some Other data", 23, false, PayloadEnum.A), "type") + val messageThatDoesntExist = QueueMessage(Payload("some Other data", 23, false, PayloadEnum.A), "testRemove_whenEntryDoesntExist") Assertions.assertFalse(multiQueue.remove(messageThatDoesntExist)) Assertions.assertTrue(multiQueue.isEmpty()) @@ -190,9 +190,9 @@ abstract class MultiQueueTest fun testContains_whenEntryDoesntExist() { Assertions.assertTrue(multiQueue.isEmpty()) - val type = "type" + val subQueue = "testContains_whenEntryDoesntExist" val otherData = Payload("some Other data", 65, true, PayloadEnum.B) - val messageThatDoesntExist = QueueMessage(otherData, type) + val messageThatDoesntExist = QueueMessage(otherData, subQueue) Assertions.assertFalse(multiQueue.contains(messageThatDoesntExist)) } @@ -203,7 +203,7 @@ abstract class MultiQueueTest fun testContains_whenEntryExists() { Assertions.assertTrue(multiQueue.isEmpty()) - val message = QueueMessage(0x52347, "type") + val message = QueueMessage(0x52347, "testContains_whenEntryExists") Assertions.assertTrue(multiQueue.add(message)) Assertions.assertFalse(multiQueue.isEmpty()) @@ -221,7 +221,7 @@ abstract class MultiQueueTest fun testContains_whenMetadataPropertiesAreSet() { Assertions.assertTrue(multiQueue.isEmpty()) - val message = QueueMessage(0x5234, "type") + val message = QueueMessage(0x5234, "testContains_whenMetadataPropertiesAreSet") Assertions.assertTrue(multiQueue.add(message)) Assertions.assertFalse(multiQueue.isEmpty()) @@ -248,94 +248,94 @@ abstract class MultiQueueTest @Test fun testGetNextQueueIndex_doesNotIncrement() { - val queueType = "testGetNextQueueIndex_doesNotIncrement" + val subQueue = "testGetNextQueueIndex_doesNotIncrement" if (multiQueue is SqlMultiQueue) { - Assertions.assertTrue(multiQueue.getNextQueueIndex(queueType).isEmpty) + Assertions.assertTrue(multiQueue.getNextSubQueueIndex(subQueue).isEmpty) } else if (multiQueue is InMemoryMultiQueue) { - Assertions.assertEquals(1, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(2, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(3, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(4, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(5, multiQueue.getNextQueueIndex(queueType).get()) - - multiQueue.clearForType(queueType) - Assertions.assertEquals(1, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(2, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(3, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(4, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(5, multiQueue.getNextQueueIndex(queueType).get()) + Assertions.assertEquals(1, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(2, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(3, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(4, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(5, multiQueue.getNextSubQueueIndex(subQueue).get()) + + multiQueue.clearSubQueue(subQueue) + Assertions.assertEquals(1, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(2, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(3, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(4, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(5, multiQueue.getNextSubQueueIndex(subQueue).get()) multiQueue.clear() - Assertions.assertEquals(1, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(2, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(3, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(4, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(5, multiQueue.getNextQueueIndex(queueType).get()) + Assertions.assertEquals(1, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(2, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(3, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(4, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(5, multiQueue.getNextSubQueueIndex(subQueue).get()) } else { - Assertions.assertTrue(multiQueue.getNextQueueIndex(queueType).isPresent) - Assertions.assertEquals(1, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(1, multiQueue.getNextQueueIndex(queueType).get()) - Assertions.assertEquals(1, multiQueue.getNextQueueIndex(queueType).get()) + Assertions.assertTrue(multiQueue.getNextSubQueueIndex(subQueue).isPresent) + Assertions.assertEquals(1, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(1, multiQueue.getNextSubQueueIndex(subQueue).get()) + Assertions.assertEquals(1, multiQueue.getNextSubQueueIndex(subQueue).get()) } } /** - * Ensure that [MultiQueue.getNextQueueIndex] starts at `1` and increments properly as called once entries are added. + * Ensure that [MultiQueue.getNextSubQueueIndex] starts at `1` and increments properly as called once entries are added. */ @Test fun testGetNextQueueIndex_withMessages() { Assertions.assertTrue(multiQueue.isEmpty()) - val queueType1 = "testGetNextQueueIndex_reInitialise1" - val queueType2 = "testGetNextQueueIndex_reInitialise2" + val subQueue1 = "testGetNextQueueIndex_reInitialise1" + val subQueue2 = "testGetNextQueueIndex_reInitialise2" - val list1 = listOf(QueueMessage(81273648, queueType1), QueueMessage("test test test", queueType1), QueueMessage(false, queueType1)) - val list2 = listOf(QueueMessage("test", queueType2), QueueMessage(123, queueType2)) + val list1 = listOf(QueueMessage(81273648, subQueue1), QueueMessage("test test test", subQueue1), QueueMessage(false, subQueue1)) + val list2 = listOf(QueueMessage("test", subQueue2), QueueMessage(123, subQueue2)) Assertions.assertTrue(multiQueue.addAll(list1)) Assertions.assertTrue(multiQueue.addAll(list2)) if (multiQueue is SqlMultiQueue) { - Assertions.assertTrue(multiQueue.getNextQueueIndex(queueType1).isEmpty) - Assertions.assertTrue(multiQueue.getNextQueueIndex(queueType2).isEmpty) + Assertions.assertTrue(multiQueue.getNextSubQueueIndex(subQueue1).isEmpty) + Assertions.assertTrue(multiQueue.getNextSubQueueIndex(subQueue2).isEmpty) } else if (multiQueue is InMemoryMultiQueue) { - Assertions.assertEquals((list1.size + 1).toLong(), multiQueue.getNextQueueIndex(queueType1).get()) - Assertions.assertEquals((list2.size + 1).toLong(), multiQueue.getNextQueueIndex(queueType2).get()) + Assertions.assertEquals((list1.size + 1).toLong(), multiQueue.getNextSubQueueIndex(subQueue1).get()) + Assertions.assertEquals((list2.size + 1).toLong(), multiQueue.getNextSubQueueIndex(subQueue2).get()) } else if (multiQueue is MongoMultiQueue) { - Assertions.assertEquals((list1.size + list2.size + 1).toLong(), multiQueue.getNextQueueIndex(queueType1).get()) - Assertions.assertEquals((list1.size + list2.size + 1).toLong(), multiQueue.getNextQueueIndex(queueType2).get()) + Assertions.assertEquals((list1.size + list2.size + 1).toLong(), multiQueue.getNextSubQueueIndex(subQueue1).get()) + Assertions.assertEquals((list1.size + list2.size + 1).toLong(), multiQueue.getNextSubQueueIndex(subQueue2).get()) } else { - Assertions.assertEquals((list1.size + 1).toLong(), multiQueue.getNextQueueIndex(queueType1).get()) - Assertions.assertEquals((list2.size + 1).toLong(), multiQueue.getNextQueueIndex(queueType2).get()) + Assertions.assertEquals((list1.size + 1).toLong(), multiQueue.getNextSubQueueIndex(subQueue1).get()) + Assertions.assertEquals((list2.size + 1).toLong(), multiQueue.getNextSubQueueIndex(subQueue2).get()) } } /** - * Ensure [MultiQueue.getQueueForType] returns the list of [QueueMessage]s always ordered by their [QueueMessage.id]. + * Ensure [MultiQueue.getSubQueue] returns the list of [QueueMessage]s always ordered by their [QueueMessage.id]. * * This also ensures they are assigned the `id` in the order they are enqueued. */ @Test - fun testGetQueueForType_ordered() + fun testGetqueue_ordered() { Assertions.assertTrue(multiQueue.isEmpty()) - val queueType = "testGetQueueForType_ordered" + val subQueue = "testGetqueue_ordered" - val list = listOf(QueueMessage(81248, queueType), QueueMessage("test data", queueType), QueueMessage(false, queueType)) + val list = listOf(QueueMessage(81248, subQueue), QueueMessage("test data", subQueue), QueueMessage(false, subQueue)) Assertions.assertTrue(multiQueue.addAll(list)) - val queue = multiQueue.getQueueForType(queueType) + val queue = multiQueue.getSubQueue(subQueue) Assertions.assertEquals(list.size, queue.size) var previousIndex: Long? = null list.zip(queue).forEach { pair -> @@ -353,22 +353,22 @@ abstract class MultiQueueTest } /** - * Ensure [MultiQueue.getQueueForType] returns the list of [QueueMessage]s always ordered by their [QueueMessage.id]. + * Ensure [MultiQueue.getSubQueue] returns the list of [QueueMessage]s always ordered by their [QueueMessage.id]. * Even when messages are changed and re-enqueued we need to make sure the returned message order is retained. */ @Test - fun testGetQueueForType_reordered() + fun testGetqueue_reordered() { Assertions.assertTrue(multiQueue.isEmpty()) - val queueType = "testGetQueueForType_reordered" + val subQueue = "testGetqueue_reordered" - val list = listOf(QueueMessage(81248, queueType), QueueMessage("test data", queueType), QueueMessage(false, queueType)) + val list = listOf(QueueMessage(81248, subQueue), QueueMessage("test data", subQueue), QueueMessage(false, subQueue)) Assertions.assertTrue(multiQueue.addAll(list)) // Force an object change, which for some mechanisms would re-enqueue it at the end // We will re-retrieve the queue and ensure they are in order to test that the ordering is correct // even after the object is changed - var queue = multiQueue.getQueueForType(queueType) + var queue = multiQueue.getSubQueue(subQueue) Assertions.assertEquals(list.size, queue.size) val firstMessage = queue.first() Assertions.assertEquals(list[0].uuid, firstMessage.uuid) @@ -376,7 +376,7 @@ abstract class MultiQueueTest firstMessage.payload = newData multiQueue.persistMessage(firstMessage) - queue = multiQueue.getQueueForType(queueType) + queue = multiQueue.getSubQueue(subQueue) var previousIndex: Long? = null list.zip(queue).forEach { pair -> Assertions.assertEquals(pair.first.uuid, pair.second.uuid) @@ -394,16 +394,16 @@ abstract class MultiQueueTest } /** - * Ensure that calls to [MultiQueue.getQueueForType] with a [MultiQueueAuthenticator.getReservedSubQueues] as an + * Ensure that calls to [MultiQueue.getSubQueue] with a [MultiQueueAuthenticator.getReservedSubQueues] as an * argument will throw [IllegalSubQueueIdentifierException]. */ @Test - fun testGetQueueForType_reservedSubQueue() + fun testGetqueue_reservedSubQueue() { - doWithAuthType(RestrictionMode.HYBRID) { + doWithRestrictedMode(RestrictionMode.HYBRID) { authenticator.getReservedSubQueues().forEach { reservedSubQueueIdentifier -> Assertions.assertThrows(IllegalSubQueueIdentifierException::class.java) { - multiQueue.getQueueForType(reservedSubQueueIdentifier) + multiQueue.getSubQueue(reservedSubQueueIdentifier) } } } @@ -416,7 +416,7 @@ abstract class MultiQueueTest fun testAddAll_containsAll_removeAll() { Assertions.assertTrue(multiQueue.isEmpty()) - val list = listOf(QueueMessage(81273648, "type"), QueueMessage("test test test", "type")) + val list = listOf(QueueMessage(81273648, "testAddAll_containsAll_removeAll"), QueueMessage("test test test", "testAddAll_containsAll_removeAll")) Assertions.assertTrue(multiQueue.addAll(list)) Assertions.assertFalse(multiQueue.isEmpty()) Assertions.assertEquals(2, multiQueue.size) @@ -436,7 +436,7 @@ abstract class MultiQueueTest @Test fun testAddAll_throwsDuplicateException() { - val list = listOf(QueueMessage(81273648, "type"), QueueMessage("test test test", "type")) + val list = listOf(QueueMessage(81273648, "testAddAll_throwsDuplicateException"), QueueMessage("test test test", "testAddAll_throwsDuplicateException")) Assertions.assertTrue(multiQueue.add(list[1])) Assertions.assertFalse(multiQueue.addAll(list)) Assertions.assertEquals(list.size, multiQueue.size) @@ -447,15 +447,15 @@ abstract class MultiQueueTest * Otherwise, if it does exist make sure that the correct entry is returned and that it is removed. */ @Test - fun testPollForType() + fun testPollForSubQueue() { Assertions.assertTrue(multiQueue.isEmpty()) - val message = QueueMessage(Payload("poll for type", 89, true, PayloadEnum.B), "poll-type") + val message = QueueMessage(Payload("poll for type", 89, true, PayloadEnum.B), "testPollForSubQueue") - Assertions.assertFalse(multiQueue.pollForType(message.type).isPresent) + Assertions.assertFalse(multiQueue.pollSubQueue(message.subQueue).isPresent) Assertions.assertTrue(multiQueue.add(message)) Assertions.assertFalse(multiQueue.isEmpty()) - val polledMessage = multiQueue.pollForType(message.type).get() + val polledMessage = multiQueue.pollSubQueue(message.subQueue).get() Assertions.assertEquals(message, polledMessage) Assertions.assertTrue(multiQueue.isEmpty()) } @@ -465,68 +465,68 @@ abstract class MultiQueueTest * Otherwise, if it does exist make sure that the correct entry is returned. */ @Test - fun testPeekForType() + fun testPeekForSubQueue() { Assertions.assertTrue(multiQueue.isEmpty()) - val message = QueueMessage(Payload("peek for type", 1121, false, PayloadEnum.C), "peek-type") + val message = QueueMessage(Payload("peek for type", 1121, false, PayloadEnum.C), "testPeekForSubQueue") - Assertions.assertFalse(multiQueue.peekForType(message.type).isPresent) + Assertions.assertFalse(multiQueue.peekSubQueue(message.subQueue).isPresent) Assertions.assertTrue(multiQueue.add(message)) Assertions.assertFalse(multiQueue.isEmpty()) - val peekedMessage = multiQueue.peekForType(message.type).get() + val peekedMessage = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertEquals(message, peekedMessage) Assertions.assertFalse(multiQueue.isEmpty()) } /** - * Ensure that [MultiQueue.isEmptyForType] operates as expected when entries exist and don't exist for a specific type. + * Ensure that [MultiQueue.isEmptySubQueue] operates as expected when entries exist and don't exist for a specific sub-queue. */ @Test - fun testIsEmptyForType() + fun testIsEmptyForSubQueue() { Assertions.assertTrue(multiQueue.isEmpty()) - val type = "type" + val subQueue = "testIsEmptyForSubQueue" val data = "test data" - val message = QueueMessage(data, type) + val message = QueueMessage(data, subQueue) Assertions.assertTrue(multiQueue.add(message)) Assertions.assertFalse(multiQueue.isEmpty()) - Assertions.assertFalse(multiQueue.isEmptyForType(type)) - Assertions.assertTrue(multiQueue.isEmptyForType("another-type")) + Assertions.assertFalse(multiQueue.isEmptySubQueue(subQueue)) + Assertions.assertTrue(multiQueue.isEmptySubQueue("testIsEmptyForSubQueue-another")) } /** - * Ensure that only the specific entries are removed when [MultiQueue.clearForTypeInternal] is called. + * Ensure that only the specific entries are removed when [MultiQueue.clearSubQueueInternal] is called. */ @Test - fun testClearForType() + fun testClearForSubQueue() { Assertions.assertTrue(multiQueue.isEmpty()) - val type = "clear-for-type" - val list = listOf(QueueMessage(81273648, type), QueueMessage("test test test", type)) + val subQueue = "testClearForSubQueue" + val list = listOf(QueueMessage(81273648, subQueue), QueueMessage("test test test", subQueue)) Assertions.assertTrue(multiQueue.addAll(list)) - val singleEntryType = "single-entry-type" - val message = QueueMessage("test message", singleEntryType) + val singleEntrySubQueue = "testClearForSubQueue2" + val message = QueueMessage("test message", singleEntrySubQueue) Assertions.assertTrue(multiQueue.add(message)) Assertions.assertEquals(3, multiQueue.size) - multiQueue.clearForTypeInternal(type) + multiQueue.clearSubQueueInternal(subQueue) Assertions.assertEquals(1, multiQueue.size) - multiQueue.clearForTypeInternal(singleEntryType) + multiQueue.clearSubQueueInternal(singleEntrySubQueue) Assertions.assertTrue(multiQueue.isEmpty()) } /** - * Ensure that no change is made when the specific type has no entries. + * Ensure that no change is made when the specific sub-queue has no entries. */ @Test - fun testClearForType_DoesNotExist() + fun testClearSubQueue_DoesNotExist() { Assertions.assertTrue(multiQueue.isEmpty()) - val type = "clear-for-type-does-not-exist" - multiQueue.clearForTypeInternal(type) + val subQueue = "testClearSubQueue_DoesNotExist" + multiQueue.clearSubQueueInternal(subQueue) Assertions.assertTrue(multiQueue.isEmpty()) } @@ -537,11 +537,11 @@ abstract class MultiQueueTest fun testRetainAll() { Assertions.assertTrue(multiQueue.isEmpty()) - val type = "type1" - val type2 = "type2" + val subQueue = "testRetainAll1" + val subQueue2 = "testRetainAll2" val data = Payload("some payload", 1, true, PayloadEnum.A) val data2 = Payload("some more data", 2, false, PayloadEnum.B) - val list = listOf(QueueMessage(data, type), QueueMessage(data, type2), QueueMessage(data2, type), QueueMessage(data2, type2)) + val list = listOf(QueueMessage(data, subQueue), QueueMessage(data, subQueue2), QueueMessage(data2, subQueue), QueueMessage(data2, subQueue2)) Assertions.assertTrue(multiQueue.addAll(list)) Assertions.assertEquals(4, multiQueue.size) @@ -550,9 +550,9 @@ abstract class MultiQueueTest toRetain.addAll(list.subList(0, 2)) Assertions.assertEquals(2, toRetain.size) // No elements of this type to cover all branches of code - val type3 = "type3" - val type3Message = QueueMessage(Payload("type3 data", 3, false, PayloadEnum.C), type3) - toRetain.add(type3Message) + val subQueue3 = "testRetainAll3" + val message3 = QueueMessage(Payload("data 3", 3, false, PayloadEnum.C), subQueue3) + toRetain.add(message3) Assertions.assertEquals(3, toRetain.size) Assertions.assertTrue(multiQueue.retainAll(toRetain)) @@ -574,14 +574,14 @@ abstract class MultiQueueTest fun testPersistMessage() { Assertions.assertTrue(multiQueue.isEmpty()) - val type = "test-persist" + val subQueue = "testPersistMessage" val data = Payload("some payload", 1, true, PayloadEnum.A) val data2 = Payload("some more data", 2, false, PayloadEnum.B) - val message = QueueMessage(data, type) + val message = QueueMessage(data, subQueue) Assertions.assertTrue(multiQueue.add(message)) - val persistedMessage = multiQueue.peekForType(message.type) + val persistedMessage = multiQueue.peekSubQueue(message.subQueue) Assertions.assertTrue(persistedMessage.isPresent) val messageToUpdate = persistedMessage.get() Assertions.assertEquals(message, messageToUpdate) @@ -601,7 +601,7 @@ abstract class MultiQueueTest multiQueue.persistMessage(messageToUpdate) - val reRetrievedMessage = multiQueue.peekForType(message.type) + val reRetrievedMessage = multiQueue.peekSubQueue(message.subQueue) Assertions.assertTrue(reRetrievedMessage.isPresent) Assertions.assertEquals(messageToUpdate, reRetrievedMessage.get()) } @@ -613,7 +613,7 @@ abstract class MultiQueueTest @Test fun testPersistMessage_messageHasNullID() { - val message = QueueMessage("payload", "type") + val message = QueueMessage("payload", "testPersistMessage_messageHasNullID") Assertions.assertNull(message.id) if (multiQueue !is InMemoryMultiQueue) @@ -626,16 +626,16 @@ abstract class MultiQueueTest } /** - * Test [MultiQueue.getAssignedMessagesForType] returns only messages with a non-null [QueueMessage.assignedTo] property. + * Test [MultiQueue.getAssignedMessagesInSubQueue] returns only messages with a non-null [QueueMessage.assignedTo] property. */ @Test - fun testGetAssignedMessagesForType_noAssignedTo() + fun testGetAssignedMessagesForSubQueue_noAssignedTo() { Assertions.assertTrue(multiQueue.isEmpty()) - val type = "test-assigned-messages-for-type" - val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), type) - val message2 = QueueMessage(Payload("some more data", 2, false, PayloadEnum.B), type) - val message3 = QueueMessage(Payload("some more data data", 3, false, PayloadEnum.C), type) + val subQueue = "testGetAssignedMessagesForSubQueue_noAssignedTo" + val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), subQueue) + val message2 = QueueMessage(Payload("some more data", 2, false, PayloadEnum.B), subQueue) + val message3 = QueueMessage(Payload("some more data data", 3, false, PayloadEnum.C), subQueue) // Assign message 1 val assignedTo = "me" @@ -651,11 +651,11 @@ abstract class MultiQueueTest multiQueue.persistMessage(message2) // Ensure all messages are in the queue - val messagesInSubQueue = multiQueue.getQueueForType(type) + val messagesInSubQueue = multiQueue.getSubQueue(subQueue) Assertions.assertEquals(3, messagesInSubQueue.size) // Check only messages 1 and 2 are returned in the assigned queue - val assignedMessages = multiQueue.getAssignedMessagesForType(type, null) + val assignedMessages = multiQueue.getAssignedMessagesInSubQueue(subQueue, null) Assertions.assertEquals(2, assignedMessages.size) val list = ArrayList() @@ -666,17 +666,18 @@ abstract class MultiQueueTest } /** - * Test [MultiQueue.getAssignedMessagesForType] returns only messages with the matching [QueueMessage.assignedTo] property. + * Test [MultiQueue.getAssignedMessagesInSubQueue] returns only messages with the matching [QueueMessage.assignedTo] property. */ @Test - fun testGetAssignedMessagesForType_withAssignedTo() + fun testGetAssignedMessagesForSubQueue_withAssignedTo() { Assertions.assertTrue(multiQueue.isEmpty()) - val type = "test-assigned-messages-for-type" - val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), type) - val message2 = QueueMessage(Payload("some more data", 2, false, PayloadEnum.B), type) - val message3 = QueueMessage(Payload("some more data data", 3, false, PayloadEnum.C), type) - val message4 = QueueMessage(Payload("some more data data data", 4, false, PayloadEnum.A), type) + Assertions.assertTrue(multiQueue.isEmpty()) + val subQueue = "testGetAssignedMessagesForSubQueue_withAssignedTo" + val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), subQueue) + val message2 = QueueMessage(Payload("some more data", 2, false, PayloadEnum.B), subQueue) + val message3 = QueueMessage(Payload("some more data data", 3, false, PayloadEnum.C), subQueue) + val message4 = QueueMessage(Payload("some more data data data", 4, false, PayloadEnum.A), subQueue) // Assign message 1, 2 and 3 val assignedTo = "me" @@ -695,11 +696,11 @@ abstract class MultiQueueTest multiQueue.persistMessage(message2) // Ensure all messages are in the queue - val messagesInSubQueue = multiQueue.getQueueForType(type) + val messagesInSubQueue = multiQueue.getSubQueue(subQueue) Assertions.assertEquals(4, messagesInSubQueue.size) // Check only messages 1 and 2 are assigned to 'assignedTo' - val assignedMessages = multiQueue.getAssignedMessagesForType(type, assignedTo) + val assignedMessages = multiQueue.getAssignedMessagesInSubQueue(subQueue, assignedTo) Assertions.assertEquals(2, assignedMessages.size) val list = ArrayList() @@ -711,17 +712,17 @@ abstract class MultiQueueTest } /** - * Test [MultiQueue.getUnassignedMessagesForType] returns only messages with a `null` [QueueMessage.assignedTo] property. + * Test [MultiQueue.getUnassignedMessagesInSubQueue] returns only messages with a `null` [QueueMessage.assignedTo] property. */ @Test - fun testGetUnassignedMessagesForType() + fun testGetUnassignedMessagesForSubQueue() { Assertions.assertTrue(multiQueue.isEmpty()) - val type = "test-unassigned-messages-for-type" - val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), type) - val message2 = QueueMessage(Payload("some more data", 2, false, PayloadEnum.B), type) - val message3 = QueueMessage(Payload("some more data data", 3, false, PayloadEnum.C), type) - val message4 = QueueMessage(Payload("some more data data data", 4, true, PayloadEnum.A), type) + val subQueue = "testGetUnassignedMessagesForSubQueue" + val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), subQueue) + val message2 = QueueMessage(Payload("some more data", 2, false, PayloadEnum.B), subQueue) + val message3 = QueueMessage(Payload("some more data data", 3, false, PayloadEnum.C), subQueue) + val message4 = QueueMessage(Payload("some more data data data", 4, true, PayloadEnum.A), subQueue) val assignedTo = "you" message.assignedTo = assignedTo @@ -739,11 +740,11 @@ abstract class MultiQueueTest multiQueue.persistMessage(message3) // Ensure all messages are in the queue - val messagesInSubQueue = multiQueue.getQueueForType(type) + val messagesInSubQueue = multiQueue.getSubQueue(subQueue) Assertions.assertEquals(4, messagesInSubQueue.size) // Check only messages 3 and 4 are returned in the unassigned queue - val assignedMessages = multiQueue.getUnassignedMessagesForType(type) + val assignedMessages = multiQueue.getUnassignedMessagesInSubQueue(subQueue) Assertions.assertEquals(2, assignedMessages.size) val list = ArrayList() @@ -755,21 +756,21 @@ abstract class MultiQueueTest } /** - * Test [MultiQueue.getOwnersAndKeysMapForType] to ensure that the provided map is populated properly with the correct entries + * Test [MultiQueue.getOwnersAndKeysMapForSubQueue] to ensure that the provided map is populated properly with the correct entries * for the current [MultiQueue] state. */ @Test - fun testGetOwnersAndKeysMapForType() + fun testGetOwnersAndKeysMapForSubQueue() { val responseMap = HashMap>() Assertions.assertTrue(multiQueue.isEmpty()) - val type = "test-get-owners-and-keys-map-for-type" - val type2 = "test-get-owners-and-keys-map-for-type2" - val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), type) - val message2 = QueueMessage(Payload("some more data", 2, false, PayloadEnum.B), type) - val message3 = QueueMessage(Payload("some more data data", 3, false, PayloadEnum.C), type2) - val message4 = QueueMessage(Payload("some more data data data", 4, true, PayloadEnum.A), type) + val subQueue = "test-get-owners-and-keys-map-for-subqueue" + val subQueue2 = "test-get-owners-and-keys-map-for-subqueue2" + val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), subQueue) + val message2 = QueueMessage(Payload("some more data", 2, false, PayloadEnum.B), subQueue) + val message3 = QueueMessage(Payload("some more data data", 3, false, PayloadEnum.C), subQueue2) + val message4 = QueueMessage(Payload("some more data data data", 4, true, PayloadEnum.A), subQueue) val assignedTo = "assigned1" val assignedTo2 = "assigned2" @@ -783,7 +784,7 @@ abstract class MultiQueueTest Assertions.assertTrue(multiQueue.add(message3)) Assertions.assertTrue(multiQueue.add(message4)) - multiQueue.getOwnersAndKeysMapForType(type, responseMap) + multiQueue.getOwnersAndKeysMapForSubQueue(subQueue, responseMap) Assertions.assertEquals(2, responseMap.keys.size) val listOfKeys = ArrayList() @@ -792,13 +793,13 @@ abstract class MultiQueueTest Assertions.assertTrue(listOfKeys.contains(assignedTo)) Assertions.assertTrue(listOfKeys.contains(assignedTo2)) - val typesForAssignedTo = responseMap[assignedTo] - Assertions.assertEquals(1, typesForAssignedTo!!.size) - Assertions.assertEquals(type, typesForAssignedTo.iterator().next()) + val subQueuesForAssignedTo = responseMap[assignedTo] + Assertions.assertEquals(1, subQueuesForAssignedTo!!.size) + Assertions.assertEquals(subQueue, subQueuesForAssignedTo.iterator().next()) - val typesForAssignedTo2 = responseMap[assignedTo2] - Assertions.assertEquals(1, typesForAssignedTo2!!.size) - Assertions.assertEquals(type, typesForAssignedTo2.iterator().next()) + val subQueuesForAssignedTo2 = responseMap[assignedTo2] + Assertions.assertEquals(1, subQueuesForAssignedTo2!!.size) + Assertions.assertEquals(subQueue, subQueuesForAssignedTo2.iterator().next()) } /** @@ -806,15 +807,15 @@ abstract class MultiQueueTest * for the current [MultiQueue] state. */ @Test - fun testGetOwnersAndKeysMap_withQueueType() + fun testGetOwnersAndKeysMap_inSubQueue() { Assertions.assertTrue(multiQueue.isEmpty()) - val type = "test-get-owners-and-keys-map" - val type2 = "test-get-owners-and-keys-map2" - val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), type) - val message2 = QueueMessage(Payload("some more data", 2, false, PayloadEnum.B), type) - val message3 = QueueMessage(Payload("some more data data", 3, false, PayloadEnum.C), type2) - val message4 = QueueMessage(Payload("some more data data data", 4, true, PayloadEnum.A), type) + val subQueue = "testGetOwnersAndKeysMap_inSubQueue" + val subQueue2 = "testGetOwnersAndKeysMap_inSubQueue2" + val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), subQueue) + val message2 = QueueMessage(Payload("some more data", 2, false, PayloadEnum.B), subQueue) + val message3 = QueueMessage(Payload("some more data data", 3, false, PayloadEnum.C), subQueue2) + val message4 = QueueMessage(Payload("some more data data data", 4, true, PayloadEnum.A), subQueue) val assignedTo = "assigned1" val assignedTo2 = "assigned2" @@ -828,7 +829,7 @@ abstract class MultiQueueTest Assertions.assertTrue(multiQueue.add(message3)) Assertions.assertTrue(multiQueue.add(message4)) - val responseMap = multiQueue.getOwnersAndKeysMap(type) + val responseMap = multiQueue.getOwnersAndKeysMap(subQueue) Assertions.assertEquals(2, responseMap.keys.size) val listOfKeys = responseMap.keys.toList() @@ -836,13 +837,13 @@ abstract class MultiQueueTest Assertions.assertTrue(listOfKeys.contains(assignedTo)) Assertions.assertTrue(listOfKeys.contains(assignedTo2)) - val typesForAssignedTo = responseMap[assignedTo] - Assertions.assertEquals(1, typesForAssignedTo!!.size) - Assertions.assertEquals(type, typesForAssignedTo.iterator().next()) + val subQueuesForAssignedTo = responseMap[assignedTo] + Assertions.assertEquals(1, subQueuesForAssignedTo!!.size) + Assertions.assertEquals(subQueue, subQueuesForAssignedTo.iterator().next()) - val typesForAssignedTo2 = responseMap[assignedTo2] - Assertions.assertEquals(1, typesForAssignedTo2!!.size) - Assertions.assertEquals(type, typesForAssignedTo2.iterator().next()) + val subQueuesForAssignedTo2 = responseMap[assignedTo2] + Assertions.assertEquals(1, subQueuesForAssignedTo2!!.size) + Assertions.assertEquals(subQueue, subQueuesForAssignedTo2.iterator().next()) } /** @@ -850,19 +851,19 @@ abstract class MultiQueueTest * for the current [MultiQueue] state. */ @Test - fun testGetOwnersAndKeysMap_withoutQueueType() + fun testGetOwnersAndKeysMap_notInSubQueue() { Assertions.assertTrue(multiQueue.isEmpty()) - val type = "test-get-owners-and-keys-map" - val type2 = "test-get-owners-and-keys-map2" - val type3 = "test-get-owners-and-keys-map3" - val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), type) - val message2 = QueueMessage(Payload("some more data", 2, false, PayloadEnum.B), type) - val message3 = QueueMessage(Payload("some more data data", 3, false, PayloadEnum.C), type2) - val message4 = QueueMessage(Payload("some more data data data", 4, true, PayloadEnum.A), type) - val message5 = QueueMessage(Payload("just data", 5, true, PayloadEnum.C), type3) - val message6 = QueueMessage(Payload("just more data", 6, false, PayloadEnum.B), type2) - val message7 = QueueMessage(Payload("just more and more data", 7, false, PayloadEnum.A), type) + val subQueue = "test-get-owners-and-keys-map" + val subQueue2 = "test-get-owners-and-keys-map2" + val subQueue3 = "test-get-owners-and-keys-map3" + val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), subQueue) + val message2 = QueueMessage(Payload("some more data", 2, false, PayloadEnum.B), subQueue) + val message3 = QueueMessage(Payload("some more data data", 3, false, PayloadEnum.C), subQueue2) + val message4 = QueueMessage(Payload("some more data data data", 4, true, PayloadEnum.A), subQueue) + val message5 = QueueMessage(Payload("just data", 5, true, PayloadEnum.C), subQueue3) + val message6 = QueueMessage(Payload("just more data", 6, false, PayloadEnum.B), subQueue2) + val message7 = QueueMessage(Payload("just more and more data", 7, false, PayloadEnum.A), subQueue) val assignedTo = "assigned1" val assignedTo2 = "assigned2" @@ -892,19 +893,19 @@ abstract class MultiQueueTest Assertions.assertTrue(listOfKeys.contains(assignedTo2)) Assertions.assertTrue(listOfKeys.contains(assignedTo3)) - val typesForAssignedTo = responseMap[assignedTo]!!.toList() - Assertions.assertEquals(1, typesForAssignedTo.size) - Assertions.assertTrue(typesForAssignedTo.contains(type)) + val subQueuesForAssignedTo = responseMap[assignedTo]!!.toList() + Assertions.assertEquals(1, subQueuesForAssignedTo.size) + Assertions.assertTrue(subQueuesForAssignedTo.contains(subQueue)) - val typesForAssignedTo2 = responseMap[assignedTo2]!!.toList() - Assertions.assertEquals(2, typesForAssignedTo2.size) - Assertions.assertTrue(typesForAssignedTo2.contains(type)) - Assertions.assertTrue(typesForAssignedTo2.contains(type2)) + val subQueuesForAssignedTo2 = responseMap[assignedTo2]!!.toList() + Assertions.assertEquals(2, subQueuesForAssignedTo2.size) + Assertions.assertTrue(subQueuesForAssignedTo2.contains(subQueue)) + Assertions.assertTrue(subQueuesForAssignedTo2.contains(subQueue2)) - val typesForAssignedTo3 = responseMap[assignedTo3]!!.toList() - Assertions.assertEquals(2, typesForAssignedTo3.size) - Assertions.assertTrue(typesForAssignedTo3.contains(type2)) - Assertions.assertTrue(typesForAssignedTo3.contains(type3)) + val subQueuesForAssignedTo3 = responseMap[assignedTo3]!!.toList() + Assertions.assertEquals(2, subQueuesForAssignedTo3.size) + Assertions.assertTrue(subQueuesForAssignedTo3.contains(subQueue2)) + Assertions.assertTrue(subQueuesForAssignedTo3.contains(subQueue3)) } /** @@ -913,8 +914,8 @@ abstract class MultiQueueTest @Test fun testGetMessageByUUID_matchingMessage() { - val type = "testGetMessageByUUID_matchingMessage" - val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), type) + val subQueue = "testGetMessageByUUID_matchingMessage" + val message = QueueMessage(Payload("some payload", 1, true, PayloadEnum.A), subQueue) Assertions.assertTrue(multiQueue.add(message)) val retrievedMessage = multiQueue.getMessageByUUID(message.uuid) @@ -944,12 +945,12 @@ abstract class MultiQueueTest } /** - * Ensure that we cannot add a new [QueueMessage] with [QueueMessage.type] set to any of the [MultiQueueAuthenticator.getReservedSubQueues] entries. + * Ensure that we cannot add a new [QueueMessage] with [QueueMessage.subQueue] set to any of the [MultiQueueAuthenticator.getReservedSubQueues] entries. */ @Test fun testAddReservedSubQueue() { - doWithAuthType(RestrictionMode.RESTRICTED) { + doWithRestrictedMode(RestrictionMode.RESTRICTED) { authenticator.getReservedSubQueues().forEach { reservedSubQueueIdentifier -> val message = QueueMessage("Data", reservedSubQueueIdentifier) Assertions.assertThrows(IllegalSubQueueIdentifierException::class.java) { @@ -966,7 +967,7 @@ abstract class MultiQueueTest @Test fun testKeysWithReservedSubQueueUsage() { - doWithAuthType(RestrictionMode.HYBRID) { + doWithRestrictedMode(RestrictionMode.HYBRID) { var keys = multiQueue.keys() authenticator.getReservedSubQueues().forEach { reservedSubQueueIdentifier -> Assertions.assertFalse(keys.contains(reservedSubQueueIdentifier)) @@ -986,17 +987,17 @@ abstract class MultiQueueTest } /** - * Perform the provided [function] with the [RestrictionMode] set to [authenticationType]. + * Perform the provided [function] with the [RestrictionMode] set to [restrictionMode]. * Once completed the [RestrictionMode] will be set back to its initial value. * - * @param authenticationType the [RestrictionMode] to be set while the [function] is being called + * @param restrictionMode the [RestrictionMode] to be set while the [function] is being called * @param function the function to call with the provided [RestrictionMode] being active * @return `T` the result of the [function] */ - private fun doWithAuthType(authenticationType: RestrictionMode, function: Supplier): T + private fun doWithRestrictedMode(restrictionMode: RestrictionMode, function: Supplier): T { - val previousAuthType = authenticator.getAuthenticationType() - authenticator.setAuthenticationType(authenticationType) + val previousRestrictedMode = authenticator.getRestrictionMode() + authenticator.setRestrictionMode(restrictionMode) try { @@ -1004,7 +1005,7 @@ abstract class MultiQueueTest } finally { - authenticator.setAuthenticationType(previousAuthType) + authenticator.setRestrictionMode(previousRestrictedMode) } } @@ -1024,7 +1025,7 @@ abstract class MultiQueueTest { Assertions.assertThrows(UnsupportedOperationException::class.java) { - multiQueue.offer(QueueMessage(Payload("test data", 13, false, PayloadEnum.C), "test type")) + multiQueue.offer(QueueMessage(Payload("test data", 13, false, PayloadEnum.C), "test sub-queue")) } }, { diff --git a/src/test/kotlin/au/kilemon/messagequeue/queue/cache/redis/RedisStandAloneMultiQueueTest.kt b/src/test/kotlin/au/kilemon/messagequeue/queue/cache/redis/RedisStandAloneMultiQueueTest.kt index d19a5e2..c00c9f6 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/queue/cache/redis/RedisStandAloneMultiQueueTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/queue/cache/redis/RedisStandAloneMultiQueueTest.kt @@ -111,22 +111,22 @@ class RedisStandAloneMultiQueueTest: MultiQueueTest() val prefix = redisMultiQueue.getPrefix() - val type = "removePrefix" - val type2 = "removePrefix2" - Assertions.assertTrue(redisMultiQueue.add(QueueMessage("data", type))) - Assertions.assertTrue(redisMultiQueue.add(QueueMessage("data2", type2))) + val subQueue = "removePrefix" + val subQueue2 = "removePrefix2" + Assertions.assertTrue(redisMultiQueue.add(QueueMessage("data", subQueue))) + Assertions.assertTrue(redisMultiQueue.add(QueueMessage("data2", subQueue2))) val keys = redisMultiQueue.keys() - Assertions.assertTrue(keys.contains("$prefix$type")) - Assertions.assertTrue(keys.contains("$prefix$type2")) + Assertions.assertTrue(keys.contains("$prefix$subQueue")) + Assertions.assertTrue(keys.contains("$prefix$subQueue2")) keys.forEach { key -> Assertions.assertTrue(key.startsWith(prefix)) } val removedPrefix = redisMultiQueue.removePrefix(keys) - Assertions.assertFalse(removedPrefix.contains("$prefix$type")) - Assertions.assertFalse(removedPrefix.contains("$prefix$type2")) + Assertions.assertFalse(removedPrefix.contains("$prefix$subQueue")) + Assertions.assertFalse(removedPrefix.contains("$prefix$subQueue2")) removedPrefix.forEach { key -> Assertions.assertFalse(key.startsWith(prefix)) } - Assertions.assertTrue(removedPrefix.contains(type)) - Assertions.assertTrue(removedPrefix.contains(type2)) + Assertions.assertTrue(removedPrefix.contains(subQueue)) + Assertions.assertTrue(removedPrefix.contains(subQueue2)) } } diff --git a/src/test/kotlin/au/kilemon/messagequeue/queue/inmemory/InMemoryMockMultiQueueTest.kt b/src/test/kotlin/au/kilemon/messagequeue/queue/inmemory/InMemoryMockMultiQueueTest.kt index bc4e64a..da7f0cc 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/queue/inmemory/InMemoryMockMultiQueueTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/queue/inmemory/InMemoryMockMultiQueueTest.kt @@ -39,7 +39,7 @@ class InMemoryMockMultiQueueTest @Test fun testPerformAdd_returnsFalse() { - val message = QueueMessage(null, "type") + val message = QueueMessage(null, "testPerformAdd_returnsFalse") Mockito.`when`(multiQueue.addInternal(message)).thenReturn(false) Mockito.`when`(multiQueue.containsUUID(message.uuid)).thenReturn(Optional.empty()) Assertions.assertFalse(multiQueue.add(message)) @@ -67,7 +67,7 @@ class InMemoryMockMultiQueueTest @Test fun testRetainAll_removeFails() { - val message = QueueMessage("payload", "type-string") + val message = QueueMessage("payload", "testRetainAll_removeFails") Mockito.`when`(multiQueue.remove(message)).thenReturn(false) Assertions.assertTrue(multiQueue.add(message)) diff --git a/src/test/kotlin/au/kilemon/messagequeue/queue/nosql/mongo/MongoMultiQueueTest.kt b/src/test/kotlin/au/kilemon/messagequeue/queue/nosql/mongo/MongoMultiQueueTest.kt index b10391a..775645b 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/queue/nosql/mongo/MongoMultiQueueTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/queue/nosql/mongo/MongoMultiQueueTest.kt @@ -95,8 +95,6 @@ class MongoMultiQueueTest: MultiQueueTest() /** * Check the container is running before each test as it's required for the methods to access the [MongoMultiQueue]. - * - * We will call [MongoMultiQueue.initialiseQueueIndex] here because we pass in the [MessageQueueSettings.MULTI_QUEUE_LAZY_INITIALISE] in the [DataMongoTest] annotation. */ @BeforeEach fun beforeEach() diff --git a/src/test/kotlin/au/kilemon/messagequeue/rest/controller/AuthControllerTest.kt b/src/test/kotlin/au/kilemon/messagequeue/rest/controller/AuthControllerTest.kt index fd7c828..e4b8505 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/rest/controller/AuthControllerTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/rest/controller/AuthControllerTest.kt @@ -87,49 +87,49 @@ class AuthControllerTest @Test fun testRestrictSubQueue_inNoneMode() { - val queueType = "testRestrictSubQueue_inNoneMode" - Assertions.assertEquals(RestrictionMode.NONE, multiQueueAuthenticator.getAuthenticationType()) + val subQueue = "testRestrictSubQueue_inNoneMode" + Assertions.assertEquals(RestrictionMode.NONE, multiQueueAuthenticator.getRestrictionMode()) mockMvc.perform( - MockMvcRequestBuilders.post("${AuthController.AUTH_PATH}/${queueType}") + MockMvcRequestBuilders.post("${AuthController.AUTH_PATH}/${subQueue}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isNoContent) } /** * Ensure [AuthController.restrictSubQueue] returns [org.springframework.http.HttpStatus.CONFLICT] when the - * requested queue type requested is already restricted. + * requested sub-queue requested is already restricted. */ @Test fun testRestrictSubQueue_alreadyRestricted() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getRestrictionMode()) - val queueType = "testRestrictSubQueue_alreadyRestricted" - Assertions.assertTrue(multiQueueAuthenticator.addRestrictedEntry(queueType)) - Assertions.assertTrue(multiQueueAuthenticator.isRestricted(queueType)) + val subQueue = "testRestrictSubQueue_alreadyRestricted" + Assertions.assertTrue(multiQueueAuthenticator.addRestrictedEntry(subQueue)) + Assertions.assertTrue(multiQueueAuthenticator.isRestricted(subQueue)) mockMvc.perform( - MockMvcRequestBuilders.post("${AuthController.AUTH_PATH}/${queueType}") + MockMvcRequestBuilders.post("${AuthController.AUTH_PATH}/${subQueue}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isConflict) } /** * Ensure [AuthController.restrictSubQueue] returns [org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR] - * when the requested queue type fails to be restricted. + * when the requested sub-queue fails to be restricted. */ @Test fun testRestrictSubQueue_wasNotAdded() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getRestrictionMode()) - val queueType = "testRestrictSubQueue_wasNotAdded" - Mockito.doReturn(false).`when`(multiQueueAuthenticator).addRestrictedEntry(queueType) + val subQueue = "testRestrictSubQueue_wasNotAdded" + Mockito.doReturn(false).`when`(multiQueueAuthenticator).addRestrictedEntry(subQueue) mockMvc.perform( - MockMvcRequestBuilders.post("${AuthController.AUTH_PATH}/${queueType}") + MockMvcRequestBuilders.post("${AuthController.AUTH_PATH}/${subQueue}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isInternalServerError) } @@ -141,32 +141,32 @@ class AuthControllerTest @Test fun testRestrictSubQueue_tokenGenerationFailure() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getRestrictionMode()) - val queueType = "testRestrictSubQueue_tokenGenerationFailure" - Mockito.doReturn(Optional.empty()).`when`(jwtTokenProvider).createTokenForSubQueue(queueType) + val subQueue = "testRestrictSubQueue_tokenGenerationFailure" + Mockito.doReturn(Optional.empty()).`when`(jwtTokenProvider).createTokenForSubQueue(subQueue) mockMvc.perform( - MockMvcRequestBuilders.post("${AuthController.AUTH_PATH}/${queueType}") + MockMvcRequestBuilders.post("${AuthController.AUTH_PATH}/${subQueue}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isInternalServerError) } /** * Ensure [AuthController.restrictSubQueue] returns [org.springframework.http.HttpStatus.OK] and a valid - * [AuthResponse] when the requested queue type is restricted successfully. + * [AuthResponse] when the requested sub-queue is restricted successfully. */ @Test fun testRestrictSubQueue_tokenGenerated() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getRestrictionMode()) - val queueType = "testRestrictSubQueue_tokenGenerated" + val subQueue = "testRestrictSubQueue_tokenGenerated" val mvcResult: MvcResult = mockMvc.perform( - MockMvcRequestBuilders.post("${AuthController.AUTH_PATH}/${queueType}") + MockMvcRequestBuilders.post("${AuthController.AUTH_PATH}/${subQueue}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isCreated) .andReturn() @@ -174,7 +174,7 @@ class AuthControllerTest val authResponse = gson.fromJson(mvcResult.response.contentAsString, AuthResponse::class.java) Assertions.assertNotNull(authResponse.token) Assertions.assertNotNull(authResponse.correlationId) - Assertions.assertEquals(queueType, authResponse.subQueue) + Assertions.assertEquals(subQueue, authResponse.subQueue) } /** @@ -185,13 +185,13 @@ class AuthControllerTest @Test fun testRestrictSubQueue_inRestrictedMode() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getRestrictionMode()) - val queueType = "testRestrictSubQueue_inRestrictedMode" + val subQueue = "testRestrictSubQueue_inRestrictedMode" val mvcResult: MvcResult = mockMvc.perform( - MockMvcRequestBuilders.post("${AuthController.AUTH_PATH}/${queueType}") + MockMvcRequestBuilders.post("${AuthController.AUTH_PATH}/${subQueue}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isCreated) .andReturn() @@ -199,7 +199,7 @@ class AuthControllerTest val authResponse = gson.fromJson(mvcResult.response.contentAsString, AuthResponse::class.java) Assertions.assertNotNull(authResponse.token) Assertions.assertNotNull(authResponse.correlationId) - Assertions.assertEquals(queueType, authResponse.subQueue) + Assertions.assertEquals(subQueue, authResponse.subQueue) } /** @@ -209,11 +209,11 @@ class AuthControllerTest @Test fun testRemoveRestrictionFromSubQueue_inNoneMode() { - val queueType = "testRemoveRestrictionFromSubQueue_inNoneMode" + val subQueue = "testRemoveRestrictionFromSubQueue_inNoneMode" - Assertions.assertEquals(RestrictionMode.NONE, multiQueueAuthenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, multiQueueAuthenticator.getRestrictionMode()) mockMvc.perform( - MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${queueType}") + MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${subQueue}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isAccepted) } @@ -225,16 +225,16 @@ class AuthControllerTest @Test fun testRemoveRestrictionFromSubQueue_invalidToken() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getRestrictionMode()) - val queueType = "testRemoveRestrictionFromSubQueue_invalidToken" - val invalidQueueType = "invalidQueueType" - val token = jwtTokenProvider.createTokenForSubQueue(queueType) + val subQueue = "testRemoveRestrictionFromSubQueue_invalidToken" + val invalidsubQueue = "invalidsubQueue" + val token = jwtTokenProvider.createTokenForSubQueue(subQueue) Assertions.assertTrue(token.isPresent) mockMvc.perform( - MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${invalidQueueType}") + MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${invalidsubQueue}") .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${token.get()}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isForbidden) @@ -248,13 +248,13 @@ class AuthControllerTest @Test fun testRemoveRestrictionFromSubQueue_withoutAuthToken() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, multiQueueAuthenticator.getRestrictionMode()) - val queueType = "testRemoveRestrictionFromSubQueue_withoutAuthToken" + val subQueue = "testRemoveRestrictionFromSubQueue_withoutAuthToken" mockMvc.perform( - MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${queueType}") + MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${subQueue}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isUnauthorized) } @@ -266,17 +266,17 @@ class AuthControllerTest @Test fun testRemoveRestrictionFromSubQueue_validTokenButNotRestricted() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getRestrictionMode()) - val queueType = "testRemoveRestrictionFromSubQueue_validToken" - val token = jwtTokenProvider.createTokenForSubQueue(queueType) + val subQueue = "testRemoveRestrictionFromSubQueue_validToken" + val token = jwtTokenProvider.createTokenForSubQueue(subQueue) Assertions.assertTrue(token.isPresent) - Assertions.assertFalse(multiQueueAuthenticator.isRestricted(queueType)) + Assertions.assertFalse(multiQueueAuthenticator.isRestricted(subQueue)) mockMvc.perform( - MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${queueType}") + MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${subQueue}") .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${token.get()}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isNoContent) @@ -290,20 +290,20 @@ class AuthControllerTest @Test fun testRemoveRestrictionFromSubQueue_failedToRemoveRestriction() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getRestrictionMode()) - val queueType = "testRemoveRestrictionFromSubQueue_failedToRemoveRestriction" - val token = jwtTokenProvider.createTokenForSubQueue(queueType) + val subQueue = "testRemoveRestrictionFromSubQueue_failedToRemoveRestriction" + val token = jwtTokenProvider.createTokenForSubQueue(subQueue) Assertions.assertTrue(token.isPresent) - Assertions.assertTrue(multiQueueAuthenticator.addRestrictedEntry(queueType)) - Assertions.assertTrue(multiQueueAuthenticator.isRestricted(queueType)) + Assertions.assertTrue(multiQueueAuthenticator.addRestrictedEntry(subQueue)) + Assertions.assertTrue(multiQueueAuthenticator.isRestricted(subQueue)) - Mockito.doReturn(false).`when`(multiQueueAuthenticator).removeRestriction(queueType) + Mockito.doReturn(false).`when`(multiQueueAuthenticator).removeRestriction(subQueue) mockMvc.perform( - MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${queueType}") + MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${subQueue}") .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${token.get()}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isInternalServerError) @@ -317,30 +317,30 @@ class AuthControllerTest @Test fun testRemoveRestrictionFromSubQueue_removeButDontClearQueue() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getRestrictionMode()) - val queueType = "testRemoveRestrictionFromSubQueue_removeButDontClearQueue" - val token = jwtTokenProvider.createTokenForSubQueue(queueType) + val subQueue = "testRemoveRestrictionFromSubQueue_removeButDontClearQueue" + val token = jwtTokenProvider.createTokenForSubQueue(subQueue) Assertions.assertTrue(token.isPresent) - Assertions.assertTrue(multiQueueAuthenticator.addRestrictedEntry(queueType)) - Assertions.assertTrue(multiQueueAuthenticator.isRestricted(queueType)) + Assertions.assertTrue(multiQueueAuthenticator.addRestrictedEntry(subQueue)) + Assertions.assertTrue(multiQueueAuthenticator.isRestricted(subQueue)) multiQueue.clear() try { - Assertions.assertTrue(multiQueue.add(QueueMessage("a payload", queueType))) + Assertions.assertTrue(multiQueue.add(QueueMessage("a payload", subQueue))) Assertions.assertEquals(1, multiQueue.size) mockMvc.perform( - MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${queueType}") + MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${subQueue}") .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${token.get()}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk) Assertions.assertEquals(1, multiQueue.size) - Assertions.assertFalse(multiQueueAuthenticator.isRestricted(queueType)) + Assertions.assertFalse(multiQueueAuthenticator.isRestricted(subQueue)) } finally { @@ -356,30 +356,30 @@ class AuthControllerTest @Test fun testRemoveRestrictionFromSubQueue_removeAndClearQueue() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getRestrictionMode()) - val queueType = "testRemoveRestrictionFromSubQueue_removeAndClearQueue" - val token = jwtTokenProvider.createTokenForSubQueue(queueType) + val subQueue = "testRemoveRestrictionFromSubQueue_removeAndClearQueue" + val token = jwtTokenProvider.createTokenForSubQueue(subQueue) Assertions.assertTrue(token.isPresent) - Assertions.assertTrue(multiQueueAuthenticator.addRestrictedEntry(queueType)) - Assertions.assertTrue(multiQueueAuthenticator.isRestricted(queueType)) + Assertions.assertTrue(multiQueueAuthenticator.addRestrictedEntry(subQueue)) + Assertions.assertTrue(multiQueueAuthenticator.isRestricted(subQueue)) multiQueue.clear() try { - Assertions.assertTrue(multiQueue.add(QueueMessage("a payload", queueType))) + Assertions.assertTrue(multiQueue.add(QueueMessage("a payload", subQueue))) Assertions.assertEquals(1, multiQueue.size) mockMvc.perform( - MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${queueType}?${RestParameters.CLEAR_QUEUE}=true") + MockMvcRequestBuilders.delete("${AuthController.AUTH_PATH}/${subQueue}?${RestParameters.CLEAR_QUEUE}=true") .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${token.get()}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk) Assertions.assertEquals(0, multiQueue.size) - Assertions.assertFalse(multiQueueAuthenticator.isRestricted(queueType)) + Assertions.assertFalse(multiQueueAuthenticator.isRestricted(subQueue)) } finally { @@ -394,8 +394,8 @@ class AuthControllerTest @Test fun testGetRestrictedSubQueueIdentifiers_inNoneMode() { - Mockito.doReturn(RestrictionMode.NONE).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.NONE, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.NONE).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.NONE, multiQueueAuthenticator.getRestrictionMode()) mockMvc.perform(MockMvcRequestBuilders.get(AuthController.AUTH_PATH) .contentType(MediaType.APPLICATION_JSON_VALUE)) @@ -410,8 +410,8 @@ class AuthControllerTest @Test fun testGetRestrictedSubQueueIdentifiers_notInNoneMode() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, multiQueueAuthenticator.getRestrictionMode()) val restrictedIdentifiers = setOf("testGetRestrictedSubQueueIdentifiers_inNoneMode1", "testGetRestrictedSubQueueIdentifiers_inNoneMode2", "testGetRestrictedSubQueueIdentifiers_inNoneMode3", "testGetRestrictedSubQueueIdentifiers_inNoneMode4", "testGetRestrictedSubQueueIdentifiers_inNoneMode5") diff --git a/src/test/kotlin/au/kilemon/messagequeue/rest/controller/MessageQueueControllerTest.kt b/src/test/kotlin/au/kilemon/messagequeue/rest/controller/MessageQueueControllerTest.kt index 5bbb6d5..b6f2aed 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/rest/controller/MessageQueueControllerTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/rest/controller/MessageQueueControllerTest.kt @@ -90,53 +90,53 @@ class MessageQueueControllerTest } /** - * Test [MessageQueueController.getQueueTypeInfo] to ensure the correct information is returned for the specified - * `queueType`. + * Test [MessageQueueController.getSubQueueInfo] to ensure the correct information is returned for the specified + * `sub-queue`. */ @Test - fun testGetQueueTypeInfo() + fun testGetSubQueueInfo() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) - val queueType = "testGetQueueTypeInfo" - Assertions.assertEquals(0, multiQueue.getQueueForType(queueType).size) - mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_TYPE + "/" + queueType) + val subQueue = "testGetSubQueueInfo" + Assertions.assertEquals(0, multiQueue.getSubQueue(subQueue).size) + mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_TYPE + "/" + subQueue) .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.content().json("0")) - val message = createQueueMessage(type = queueType) + val message = createQueueMessage(subQueue = subQueue) Assertions.assertTrue(multiQueue.add(message)) - Assertions.assertEquals(1, multiQueue.getQueueForType(queueType).size) + Assertions.assertEquals(1, multiQueue.getSubQueue(subQueue).size) - mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_TYPE + "/" + queueType) + mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_TYPE + "/" + subQueue) .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.content().json("1")) } /** - * Test [MessageQueueController.getAllQueueTypeInfo] to ensure that information for all `queue type`s is returned - * when no `queue type` is specified. + * Test [MessageQueueController.getAllQueueInfo] to ensure that information for all `sub-queue`s is returned + * when no `sub-queue` is specified. */ @Test - fun testGetAllQueueTypeInfo() + fun testGetAllSubQueueInfo() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_TYPE) .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.content().json("0")) - val message = createQueueMessage(type = "testGetAllQueueTypeInfo_type1") - val message2 = createQueueMessage(type = "testGetAllQueueTypeInfo_type2") + val message = createQueueMessage(subQueue = "testGetAllSubQueueInfo1") + val message2 = createQueueMessage(subQueue = "testGetAllSubQueueInfo2") Assertions.assertTrue(multiQueue.add(message)) Assertions.assertTrue(multiQueue.add(message2)) - Assertions.assertEquals(1, multiQueue.getQueueForType(message.type).size) - Assertions.assertEquals(1, multiQueue.getQueueForType(message2.type).size) + Assertions.assertEquals(1, multiQueue.getSubQueue(message.subQueue).size) + Assertions.assertEquals(1, multiQueue.getSubQueue(message2.subQueue).size) Assertions.assertEquals(2, multiQueue.size) mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_TYPE) @@ -152,9 +152,9 @@ class MessageQueueControllerTest @Test fun testGetEntry() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) - val message = createQueueMessage(type = "testGetEntry") + val message = createQueueMessage(subQueue = "testGetEntry") Assertions.assertTrue(multiQueue.add(message)) @@ -168,8 +168,8 @@ class MessageQueueControllerTest val deserialisedPayload = gson.fromJson(gson.toJson(messageResponse.message.payload), Payload::class.java) Assertions.assertEquals(message.payload, deserialisedPayload) Assertions.assertNull(messageResponse.message.assignedTo) - Assertions.assertEquals(message.type, messageResponse.message.type) - Assertions.assertEquals(message.type, messageResponse.queueType) + Assertions.assertEquals(message.subQueue, messageResponse.message.subQueue) + Assertions.assertEquals(message.subQueue, messageResponse.subQueue) Assertions.assertNotNull(messageResponse.message.uuid) } @@ -180,7 +180,7 @@ class MessageQueueControllerTest @Test fun testGetEntry_ResponseBody_NotExists() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val uuid = "invalid-not-found-uuid" mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY + "/" + uuid) @@ -195,17 +195,17 @@ class MessageQueueControllerTest @Test fun testGetEntry_usingHybridMode_withRestrictedSubQueue() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getRestrictionMode()) val entries = initialiseMapWithEntries() - val type1 = entries.second[0] + val subQueue1 = entries.second[0] val message1 = entries.first[0] - val type1Token = jwtTokenProvider.createTokenForSubQueue(type1) - Assertions.assertTrue(type1Token.isPresent) - Assertions.assertTrue(authenticator.addRestrictedEntry(type1)) - Assertions.assertTrue(authenticator.isRestricted(type1)) + val subQueue1Token = jwtTokenProvider.createTokenForSubQueue(subQueue1) + Assertions.assertTrue(subQueue1Token.isPresent) + Assertions.assertTrue(authenticator.addRestrictedEntry(subQueue1)) + Assertions.assertTrue(authenticator.isRestricted(subQueue1)) // Make sure we cannot access without a token mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY + "/" + message1.uuid) @@ -214,7 +214,7 @@ class MessageQueueControllerTest // Checking entry is retrieve with provided token val mvcResult: MvcResult = mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY + "/" + message1.uuid) - .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${type1Token.get()}") + .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${subQueue1Token.get()}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() @@ -224,17 +224,17 @@ class MessageQueueControllerTest val deserialisedPayload = gson.fromJson(gson.toJson(messageResponse.message.payload), Payload::class.java) Assertions.assertEquals(message1.payload, deserialisedPayload) Assertions.assertNull(messageResponse.message.assignedTo) - Assertions.assertEquals(message1.type, messageResponse.message.type) - Assertions.assertEquals(message1.type, messageResponse.queueType) + Assertions.assertEquals(message1.subQueue, messageResponse.message.subQueue) + Assertions.assertEquals(message1.subQueue, messageResponse.subQueue) Assertions.assertNotNull(messageResponse.message.uuid) - val type2 = entries.second[1] + val subQueue2 = entries.second[1] val message2 = entries.first[1] - Assertions.assertFalse(authenticator.isRestricted(type2)) + Assertions.assertFalse(authenticator.isRestricted(subQueue2)) // Check un-restricted entry is still accessible without a token val mvcResult2: MvcResult = mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY + "/" + message2.uuid) - .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${type1Token.get()}") + .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${subQueue1Token.get()}") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() @@ -244,8 +244,8 @@ class MessageQueueControllerTest val deserialisedPayload2 = gson.fromJson(gson.toJson(messageResponse2.message.payload), Payload::class.java) Assertions.assertEquals(message2.payload, deserialisedPayload2) Assertions.assertNull(messageResponse2.message.assignedTo) - Assertions.assertEquals(message2.type, messageResponse2.message.type) - Assertions.assertEquals(message2.type, messageResponse2.queueType) + Assertions.assertEquals(message2.subQueue, messageResponse2.message.subQueue) + Assertions.assertEquals(message2.subQueue, messageResponse2.subQueue) Assertions.assertNotNull(messageResponse2.message.uuid) } @@ -256,9 +256,9 @@ class MessageQueueControllerTest @Test fun testCreateQueueEntry_withProvidedDefaults() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) - val message = createQueueMessage(type = "testCreateQueueEntry_withProvidedDefaults", assignedTo = "user-1") + val message = createQueueMessage(subQueue = "testCreateQueueEntry_withProvidedDefaults", assignedTo = "user-1") val mvcResult: MvcResult = mockMvc.perform(post(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY) .contentType(MediaType.APPLICATION_JSON_VALUE) @@ -271,13 +271,13 @@ class MessageQueueControllerTest val deserialisedPayload = gson.fromJson(gson.toJson(messageResponse.message.payload), Payload::class.java) Assertions.assertEquals(message.payload, deserialisedPayload) Assertions.assertEquals(message.assignedTo, messageResponse.message.assignedTo) - Assertions.assertEquals(message.type, messageResponse.message.type) - Assertions.assertEquals(message.type, messageResponse.queueType) + Assertions.assertEquals(message.subQueue, messageResponse.message.subQueue) + Assertions.assertEquals(message.subQueue, messageResponse.subQueue) Assertions.assertEquals(message.uuid, messageResponse.message.uuid) - val createdMessage = multiQueue.peekForType(message.type).get() + val createdMessage = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertEquals(message.assignedTo, createdMessage.assignedTo) - Assertions.assertEquals(message.type, createdMessage.type) + Assertions.assertEquals(message.subQueue, createdMessage.subQueue) Assertions.assertEquals(message.uuid, createdMessage.uuid) } @@ -288,9 +288,9 @@ class MessageQueueControllerTest @Test fun testCreateQueueEntry_withOutDefaults() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) - val message = createQueueMessage(type = "testCreateQueueEntry_withOutDefaults") + val message = createQueueMessage(subQueue = "testCreateQueueEntry_withOutDefaults") val mvcResult: MvcResult = mockMvc.perform(post(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY) .contentType(MediaType.APPLICATION_JSON_VALUE) @@ -303,13 +303,13 @@ class MessageQueueControllerTest val deserialisedPayload = gson.fromJson(gson.toJson(messageResponse.message.payload), Payload::class.java) Assertions.assertEquals(message.payload, deserialisedPayload) Assertions.assertNull(messageResponse.message.assignedTo) - Assertions.assertEquals(message.type, messageResponse.message.type) - Assertions.assertEquals(message.type, messageResponse.queueType) + Assertions.assertEquals(message.subQueue, messageResponse.message.subQueue) + Assertions.assertEquals(message.subQueue, messageResponse.subQueue) Assertions.assertNotNull(messageResponse.message.uuid) - val createdMessage = multiQueue.peekForType(message.type).get() + val createdMessage = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertNull(createdMessage.assignedTo) - Assertions.assertEquals(message.type, createdMessage.type) + Assertions.assertEquals(message.subQueue, createdMessage.subQueue) Assertions.assertEquals(message.uuid, createdMessage.uuid) } @@ -320,9 +320,9 @@ class MessageQueueControllerTest @Test fun testCreateEntry_Conflict() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) - val message = createQueueMessage(type = "testCreateEntry_Conflict") + val message = createQueueMessage(subQueue = "testCreateEntry_Conflict") Assertions.assertTrue(multiQueue.add(message)) @@ -339,9 +339,9 @@ class MessageQueueControllerTest @Test fun testCreateQueueEntry_withBlankAssignedTo() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) - val message = createQueueMessage(type = "testCreateQueueEntry_withAssignedButNoAssignedTo") + val message = createQueueMessage(subQueue = "testCreateQueueEntry_withAssignedButNoAssignedTo") message.assignedTo = " " val mvcResult: MvcResult = mockMvc.perform(post(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY) @@ -361,15 +361,15 @@ class MessageQueueControllerTest @Test fun testCreateEntry_inHybridMode() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getRestrictionMode()) - val message = createQueueMessage(type = "testCreateEntry_inHybridMode") + val message = createQueueMessage(subQueue = "testCreateEntry_inHybridMode") - Assertions.assertTrue(authenticator.addRestrictedEntry(message.type)) - Assertions.assertTrue(authenticator.isRestricted(message.type)) + Assertions.assertTrue(authenticator.addRestrictedEntry(message.subQueue)) + Assertions.assertTrue(authenticator.isRestricted(message.subQueue)) - val token = jwtTokenProvider.createTokenForSubQueue(message.type) + val token = jwtTokenProvider.createTokenForSubQueue(message.subQueue) Assertions.assertTrue(token.isPresent) mockMvc.perform(post(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY) @@ -383,8 +383,8 @@ class MessageQueueControllerTest .content(gson.toJson(message))) .andExpect(MockMvcResultMatchers.status().isCreated) - val message2 = createQueueMessage(type = "testCreateEntry_inHybridMode2") - Assertions.assertFalse(authenticator.isRestricted(message2.type)) + val message2 = createQueueMessage(subQueue = "testCreateEntry_inHybridMode2") + Assertions.assertFalse(authenticator.isRestricted(message2.subQueue)) mockMvc.perform(post(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY) .contentType(MediaType.APPLICATION_JSON_VALUE) @@ -399,7 +399,7 @@ class MessageQueueControllerTest @Test fun testGetKeys() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val entries = initialiseMapWithEntries() @@ -411,12 +411,12 @@ class MessageQueueControllerTest val keys = gson.fromJson(mvcResult.response.contentAsString, List::class.java) Assertions.assertFalse(keys.isNullOrEmpty()) Assertions.assertEquals(entries.second.size, keys.size) - entries.second.forEach { type -> Assertions.assertTrue(keys.contains(type)) } + entries.second.forEach { subQueue -> Assertions.assertTrue(keys.contains(subQueue)) } val mapKeys = multiQueue.keys(true) Assertions.assertFalse(mapKeys.isEmpty()) Assertions.assertEquals(entries.second.size, mapKeys.size) - entries.second.forEach { type -> Assertions.assertTrue(mapKeys.contains(type)) } + entries.second.forEach { subQueue -> Assertions.assertTrue(mapKeys.contains(subQueue)) } } /** @@ -426,7 +426,7 @@ class MessageQueueControllerTest @Test fun testGetKeys_excludeEmpty() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val entries = initialiseMapWithEntries() Assertions.assertTrue(multiQueue.remove(entries.first[0])) @@ -441,27 +441,27 @@ class MessageQueueControllerTest val keys = gson.fromJson(mvcResult.response.contentAsString, List::class.java) Assertions.assertFalse(keys.isNullOrEmpty()) Assertions.assertEquals(2, keys.size) - entries.second.subList(2, 3).forEach { type -> Assertions.assertTrue(keys.contains(type)) } + entries.second.subList(2, 3).forEach { subQueue -> Assertions.assertTrue(keys.contains(subQueue)) } val mapKeys = multiQueue.keys(false) Assertions.assertFalse(mapKeys.isEmpty()) Assertions.assertEquals(2, mapKeys.size) - entries.second.subList(2, 3).forEach { type -> Assertions.assertTrue(mapKeys.contains(type)) } + entries.second.subList(2, 3).forEach { subQueue -> Assertions.assertTrue(mapKeys.contains(subQueue)) } } /** - * Test [MessageQueueController.getAll] to ensure that all entries are returned from all `queueTypes` when no - * explicit `queueType` is provided. + * Test [MessageQueueController.getAll] to ensure that all entries are returned from all `sub-queues` when no + * explicit `sub-queue` is provided. * This also checks the returned object has a `non-null` value in the payload since the `detailed` flag is set to * `true`. */ @Test fun testGetAll() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val entries = initialiseMapWithEntries() - val type = entries.first[0].type + val subQueue = entries.first[0].subQueue val detailed = true val mvcResult: MvcResult = mockMvc.perform(get("${MessageQueueController.MESSAGE_QUEUE_BASE_PATH}/${MessageQueueController.ENDPOINT_ALL}?${RestParameters.DETAILED}=$detailed") @@ -473,32 +473,32 @@ class MessageQueueControllerTest val keys = gson.fromJson>>(mvcResult.response.contentAsString, mapType) Assertions.assertNotNull(keys) Assertions.assertEquals(entries.second.size, keys.keys.size) - entries.second.forEach { typeString -> Assertions.assertTrue(keys.keys.contains(typeString)) } + entries.second.forEach { subQueueId -> Assertions.assertTrue(keys.keys.contains(subQueueId)) } keys.values.forEach { detailList -> Assertions.assertEquals(1, detailList.size) } - Assertions.assertEquals(entries.first[0].removePayload(detailed).uuid, keys[type]!![0].uuid) + Assertions.assertEquals(entries.first[0].removePayload(detailed).uuid, keys[subQueue]!![0].uuid) // Since we passed in true for the detailed flag, ensure the payload is equal - val payloadObject = gson.fromJson(keys[type]!![0].payload.toString(), Payload::class.java) + val payloadObject = gson.fromJson(keys[subQueue]!![0].payload.toString(), Payload::class.java) Assertions.assertEquals(entries.first[0].payload, payloadObject) - Assertions.assertEquals(entries.first[0].removePayload(detailed).assignedTo, keys[type]!![0].assignedTo) - Assertions.assertEquals(entries.first[0].removePayload(detailed).type, keys[type]!![0].type) + Assertions.assertEquals(entries.first[0].removePayload(detailed).assignedTo, keys[subQueue]!![0].assignedTo) + Assertions.assertEquals(entries.first[0].removePayload(detailed).subQueue, keys[subQueue]!![0].subQueue) } /** - * Test [MessageQueueController.getAll] to ensure that all entries are returned from the `queueType` when an - * explicit `queueType` is provided. + * Test [MessageQueueController.getAll] to ensure that all entries are returned from the `sub-queue` when an + * explicit `sub-queue` is provided. * This also checks the returned object has `null` in the payload since the `detailed` flag is not provided. */ @Test - fun testGetAll_SpecificQueueType() + fun testGetAll_SpecificSubQueue() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val entries = initialiseMapWithEntries() - val type = entries.first[0].type + val subQueue = entries.first[0].subQueue val mvcResult: MvcResult = mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ALL) .contentType(MediaType.APPLICATION_JSON_VALUE) - .param(RestParameters.QUEUE_TYPE, type)) + .param(RestParameters.SUB_QUEUE, subQueue)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() @@ -506,13 +506,13 @@ class MessageQueueControllerTest val keys = gson.fromJson>>(mvcResult.response.contentAsString, mapType) Assertions.assertNotNull(keys) Assertions.assertEquals(1, keys.keys.size) - Assertions.assertTrue(keys.keys.contains(type)) + Assertions.assertTrue(keys.keys.contains(subQueue)) keys.values.forEach { detailList -> Assertions.assertEquals(1, detailList.size) } - Assertions.assertEquals(entries.first[0].removePayload(false).uuid, keys[type]!![0].uuid) + Assertions.assertEquals(entries.first[0].removePayload(false).uuid, keys[subQueue]!![0].uuid) // Since we did not pass a detailed flag value, ensure the payload is a placeholder value Assertions.assertEquals("***", entries.first[0].removePayload(false).payload) - Assertions.assertEquals(entries.first[0].removePayload(false).assignedTo, keys[type]!![0].assignedTo) - Assertions.assertEquals(entries.first[0].removePayload(false).type, keys[type]!![0].type) + Assertions.assertEquals(entries.first[0].removePayload(false).assignedTo, keys[subQueue]!![0].assignedTo) + Assertions.assertEquals(entries.first[0].removePayload(false).subQueue, keys[subQueue]!![0].subQueue) } /** @@ -522,24 +522,24 @@ class MessageQueueControllerTest @Test fun testGetAll_inHybridMode() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getRestrictionMode()) - val queueType = "testGetAll_inHybridMode" - val messages = listOf(createQueueMessage(queueType), createQueueMessage(queueType)) + val subQueue = "testGetAll_inHybridMode" + val messages = listOf(createQueueMessage(subQueue), createQueueMessage(subQueue)) messages.forEach { message -> Assertions.assertTrue(multiQueue.add(message)) } - Assertions.assertTrue(authenticator.addRestrictedEntry(queueType)) - Assertions.assertTrue(authenticator.isRestricted(queueType)) + Assertions.assertTrue(authenticator.addRestrictedEntry(subQueue)) + Assertions.assertTrue(authenticator.isRestricted(subQueue)) - val token = jwtTokenProvider.createTokenForSubQueue(queueType) + val token = jwtTokenProvider.createTokenForSubQueue(subQueue) Assertions.assertTrue(token.isPresent) val entries = initialiseMapWithEntries() - entries.second.forEach { type -> Assertions.assertFalse(authenticator.isRestricted(type)) } + entries.second.forEach { subQueueId -> Assertions.assertFalse(authenticator.isRestricted(subQueueId)) } val detailed = true - // Ensure the message in the restricted queue type are not returned + // Ensure the message in the restricted sub-queue are not returned var mvcResult: MvcResult = mockMvc.perform(get("${MessageQueueController.MESSAGE_QUEUE_BASE_PATH}/${MessageQueueController.ENDPOINT_ALL}?${RestParameters.DETAILED}=$detailed") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk) @@ -550,8 +550,8 @@ class MessageQueueControllerTest Assertions.assertNotNull(keys) Assertions.assertEquals(entries.second.size, keys.keys.size) - Assertions.assertFalse(keys.keys.contains(queueType)) - Assertions.assertNull(keys[queueType]) + Assertions.assertFalse(keys.keys.contains(subQueue)) + Assertions.assertNull(keys[subQueue]) // After providing the token we should see the messages for the restricted queue mvcResult = mockMvc.perform(get("${MessageQueueController.MESSAGE_QUEUE_BASE_PATH}/${MessageQueueController.ENDPOINT_ALL}?${RestParameters.DETAILED}=$detailed") @@ -564,8 +564,8 @@ class MessageQueueControllerTest Assertions.assertNotNull(keys) Assertions.assertEquals(entries.second.size + 1, keys.keys.size) - Assertions.assertTrue(keys.keys.contains(queueType)) - Assertions.assertNotNull(keys[queueType]) + Assertions.assertTrue(keys.keys.contains(subQueue)) + Assertions.assertNotNull(keys[subQueue]) } /** @@ -573,30 +573,30 @@ class MessageQueueControllerTest * and all messages are requested for a restricted queue are not accessible unless a token is provided. */ @Test - fun testGetAll_SpecificQueueType_inHybridMode() + fun testGetAll_SpecificSubQueue_inHybridMode() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getRestrictionMode()) - val queueType = "testGetAll_SpecificQueueType_inHybridMode" - val messages = listOf(createQueueMessage(queueType), createQueueMessage(queueType)) + val subQueue = "testGetAll_SpecificSubQueue_inHybridMode" + val messages = listOf(createQueueMessage(subQueue), createQueueMessage(subQueue)) messages.forEach { message -> Assertions.assertTrue(multiQueue.add(message)) } - Assertions.assertTrue(authenticator.addRestrictedEntry(queueType)) - Assertions.assertTrue(authenticator.isRestricted(queueType)) + Assertions.assertTrue(authenticator.addRestrictedEntry(subQueue)) + Assertions.assertTrue(authenticator.isRestricted(subQueue)) mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ALL) .contentType(MediaType.APPLICATION_JSON_VALUE) - .param(RestParameters.QUEUE_TYPE, queueType)) + .param(RestParameters.SUB_QUEUE, subQueue)) .andExpect(MockMvcResultMatchers.status().isForbidden) - val token = jwtTokenProvider.createTokenForSubQueue(queueType) + val token = jwtTokenProvider.createTokenForSubQueue(subQueue) Assertions.assertTrue(token.isPresent) val mvcResult: MvcResult = mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ALL) .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${token.get()}") .contentType(MediaType.APPLICATION_JSON_VALUE) - .param(RestParameters.QUEUE_TYPE, queueType)) + .param(RestParameters.SUB_QUEUE, subQueue)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() @@ -605,9 +605,9 @@ class MessageQueueControllerTest Assertions.assertNotNull(keys) Assertions.assertEquals(1, keys.keys.size) - Assertions.assertTrue(keys.keys.contains(queueType)) - Assertions.assertNotNull(keys[queueType]) - Assertions.assertEquals(2, keys[queueType]!!.size) + Assertions.assertTrue(keys.keys.contains(subQueue)) + Assertions.assertNotNull(keys[subQueue]) + Assertions.assertEquals(2, keys[subQueue]!!.size) } /** @@ -617,7 +617,7 @@ class MessageQueueControllerTest @Test fun testGetOwned_NoneOwned() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val entries = initialiseMapWithEntries() val assignedTo = "my-assigned-to-identifier" @@ -625,7 +625,7 @@ class MessageQueueControllerTest val mvcResult: MvcResult = mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_OWNED) .contentType(MediaType.APPLICATION_JSON_VALUE) .param(RestParameters.ASSIGNED_TO, assignedTo) - .param(RestParameters.QUEUE_TYPE, entries.first[0].type)) + .param(RestParameters.SUB_QUEUE, entries.first[0].subQueue)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() @@ -641,12 +641,12 @@ class MessageQueueControllerTest @Test fun testGetOwned_SomeOwned() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "my-assigned-to-identifier" - val type = "testGetOwned_SomeOwned" - val message1 = createQueueMessage(assignedTo = assignedTo, type = type) - val message2 = createQueueMessage(assignedTo = assignedTo, type = type) + val subQueue = "testGetOwned_SomeOwned" + val message1 = createQueueMessage(assignedTo = assignedTo, subQueue = subQueue) + val message2 = createQueueMessage(assignedTo = assignedTo, subQueue = subQueue) Assertions.assertTrue(multiQueue.add(message1)) Assertions.assertTrue(multiQueue.add(message2)) @@ -654,7 +654,7 @@ class MessageQueueControllerTest val mvcResult: MvcResult = mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_OWNED) .contentType(MediaType.APPLICATION_JSON_VALUE) .param(RestParameters.ASSIGNED_TO, assignedTo) - .param(RestParameters.QUEUE_TYPE, type)) + .param(RestParameters.SUB_QUEUE, subQueue)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() @@ -663,8 +663,8 @@ class MessageQueueControllerTest Assertions.assertTrue(owned.isNotEmpty()) owned.forEach { message -> Assertions.assertTrue(message.message.uuid == message1.uuid || message.message.uuid == message2.uuid) - Assertions.assertEquals(type, message.queueType) - Assertions.assertEquals(type, message.message.type) + Assertions.assertEquals(subQueue, message.subQueue) + Assertions.assertEquals(subQueue, message.message.subQueue) Assertions.assertEquals(assignedTo, message.message.assignedTo) } } @@ -676,34 +676,34 @@ class MessageQueueControllerTest @Test fun testGetOwned_SomeOwned_inHybridMode() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getRestrictionMode()) val assignedTo = "my-assigned-to-identifier" - val type = "testGetOwned_SomeOwned_inHybridMode" - val message1 = createQueueMessage(assignedTo = assignedTo, type = type) - val message2 = createQueueMessage(assignedTo = assignedTo, type = type) + val subQueue = "testGetOwned_SomeOwned_inHybridMode" + val message1 = createQueueMessage(assignedTo = assignedTo, subQueue = subQueue) + val message2 = createQueueMessage(assignedTo = assignedTo, subQueue = subQueue) Assertions.assertTrue(multiQueue.add(message1)) Assertions.assertTrue(multiQueue.add(message2)) - Assertions.assertTrue(authenticator.addRestrictedEntry(type)) - Assertions.assertTrue(authenticator.isRestricted(type)) + Assertions.assertTrue(authenticator.addRestrictedEntry(subQueue)) + Assertions.assertTrue(authenticator.isRestricted(subQueue)) mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_OWNED) .contentType(MediaType.APPLICATION_JSON_VALUE) .param(RestParameters.ASSIGNED_TO, assignedTo) - .param(RestParameters.QUEUE_TYPE, type)) + .param(RestParameters.SUB_QUEUE, subQueue)) .andExpect(MockMvcResultMatchers.status().isForbidden) - val token = jwtTokenProvider.createTokenForSubQueue(type) + val token = jwtTokenProvider.createTokenForSubQueue(subQueue) Assertions.assertTrue(token.isPresent) val mvcResult: MvcResult = mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_OWNED) .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${token.get()}") .contentType(MediaType.APPLICATION_JSON_VALUE) .param(RestParameters.ASSIGNED_TO, assignedTo) - .param(RestParameters.QUEUE_TYPE, type)) + .param(RestParameters.SUB_QUEUE, subQueue)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() @@ -712,8 +712,8 @@ class MessageQueueControllerTest Assertions.assertTrue(owned.isNotEmpty()) owned.forEach { message -> Assertions.assertTrue(message.message.uuid == message1.uuid || message.message.uuid == message2.uuid) - Assertions.assertEquals(type, message.queueType) - Assertions.assertEquals(type, message.message.type) + Assertions.assertEquals(subQueue, message.subQueue) + Assertions.assertEquals(subQueue, message.message.subQueue) Assertions.assertEquals(assignedTo, message.message.assignedTo) } } @@ -725,7 +725,7 @@ class MessageQueueControllerTest @Test fun testAssignMessage_doesNotExist() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val uuid = UUID.randomUUID().toString() val assignedTo = "assigned" @@ -742,10 +742,10 @@ class MessageQueueControllerTest @Test fun testAssignMessage_messageIsAssigned() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "assigned" - val message = createQueueMessage(type = "testAssignMessage_messageIsAssigned") + val message = createQueueMessage(subQueue = "testAssignMessage_messageIsAssigned") Assertions.assertNull(message.assignedTo) Assertions.assertTrue(multiQueue.add(message)) @@ -759,7 +759,7 @@ class MessageQueueControllerTest Assertions.assertEquals(assignedTo, messageResponse.message.assignedTo) Assertions.assertEquals(message.uuid, messageResponse.message.uuid) - val assignedMessage = multiQueue.peekForType(message.type).get() + val assignedMessage = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertEquals(assignedTo, assignedMessage.assignedTo) Assertions.assertEquals(message.uuid, assignedMessage.uuid) } @@ -771,23 +771,23 @@ class MessageQueueControllerTest @Test fun testAssignMessage_messageIsAssigned_inHybridMode() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getRestrictionMode()) val assignedTo = "assigned" - val message = createQueueMessage(type = "testAssignMessage_messageIsAssigned_inHybridMode") + val message = createQueueMessage(subQueue = "testAssignMessage_messageIsAssigned_inHybridMode") Assertions.assertNull(message.assignedTo) Assertions.assertTrue(multiQueue.add(message)) - Assertions.assertTrue(authenticator.addRestrictedEntry(message.type)) - Assertions.assertTrue(authenticator.isRestricted(message.type)) + Assertions.assertTrue(authenticator.addRestrictedEntry(message.subQueue)) + Assertions.assertTrue(authenticator.isRestricted(message.subQueue)) mockMvc.perform(put(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + MessageQueueController.ENDPOINT_ENTRY + "/" + message.uuid + MessageQueueController.ENDPOINT_ASSIGN) .contentType(MediaType.APPLICATION_JSON_VALUE) .param(RestParameters.ASSIGNED_TO, assignedTo)) .andExpect(MockMvcResultMatchers.status().isForbidden) - val token = jwtTokenProvider.createTokenForSubQueue(message.type) + val token = jwtTokenProvider.createTokenForSubQueue(message.subQueue) Assertions.assertTrue(token.isPresent) val mvcResult: MvcResult = mockMvc.perform(put(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + MessageQueueController.ENDPOINT_ENTRY + "/" + message.uuid + MessageQueueController.ENDPOINT_ASSIGN) @@ -801,7 +801,7 @@ class MessageQueueControllerTest Assertions.assertEquals(assignedTo, messageResponse.message.assignedTo) Assertions.assertEquals(message.uuid, messageResponse.message.uuid) - val assignedMessage = multiQueue.peekForType(message.type).get() + val assignedMessage = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertEquals(assignedTo, assignedMessage.assignedTo) Assertions.assertEquals(message.uuid, assignedMessage.uuid) } @@ -814,10 +814,10 @@ class MessageQueueControllerTest @Test fun testAssignMessage_alreadyAssignedToSameID() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "assigned" - val message = createQueueMessage(type = "testAssignMessage_alreadyAssignedToSameID", assignedTo = assignedTo) + val message = createQueueMessage(subQueue = "testAssignMessage_alreadyAssignedToSameID", assignedTo = assignedTo) Assertions.assertEquals(assignedTo, message.assignedTo) Assertions.assertTrue(multiQueue.add(message)) @@ -832,7 +832,7 @@ class MessageQueueControllerTest Assertions.assertEquals(message.assignedTo, messageResponse.message.assignedTo) Assertions.assertEquals(message.uuid, messageResponse.message.uuid) - val assignedMessage = multiQueue.peekForType(message.type).get() + val assignedMessage = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertEquals(assignedTo, assignedMessage.assignedTo) Assertions.assertEquals(message.uuid, assignedMessage.uuid) } @@ -844,16 +844,16 @@ class MessageQueueControllerTest @Test fun testAssignMessage_alreadyAssignedToOtherID() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "assignee" - val message = createQueueMessage(type = "testAssignMessage_alreadyAssignedToOtherID", assignedTo = assignedTo) + val message = createQueueMessage(subQueue = "testAssignMessage_alreadyAssignedToOtherID", assignedTo = assignedTo) Assertions.assertEquals(assignedTo, message.assignedTo) Assertions.assertTrue(multiQueue.add(message)) // Check the message is set correctly - var assignedMessage = multiQueue.peekForType(message.type).get() + var assignedMessage = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertEquals(assignedTo, assignedMessage.assignedTo) Assertions.assertEquals(message.uuid, assignedMessage.uuid) @@ -864,29 +864,29 @@ class MessageQueueControllerTest .andExpect(MockMvcResultMatchers.status().isConflict) // Check the message is still assigned to the correct ID - assignedMessage = multiQueue.peekForType(message.type).get() + assignedMessage = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertEquals(assignedTo, assignedMessage.assignedTo) Assertions.assertEquals(message.uuid, assignedMessage.uuid) } /** * Test [MessageQueueController.getNext] to ensure [HttpStatus.NO_CONTENT] is returned when there are no - * [QueueMessage]s available for the provided `queueType`. + * [QueueMessage]s available for the provided `sub-queue`. */ @Test fun testGetNext_noNewMessages() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "assignee" - val type = "testGetNext_noNewMessages" + val subQueue = "testGetNext_noNewMessages" mockMvc.perform(put(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_NEXT) .contentType(MediaType.APPLICATION_JSON_VALUE) - .param(RestParameters.QUEUE_TYPE, type) + .param(RestParameters.SUB_QUEUE, subQueue) .param(RestParameters.ASSIGNED_TO, assignedTo)) .andExpect(MockMvcResultMatchers.status().isNoContent) - Assertions.assertTrue(multiQueue.getQueueForType(type).isEmpty()) + Assertions.assertTrue(multiQueue.getSubQueue(subQueue).isEmpty()) } /** @@ -896,21 +896,21 @@ class MessageQueueControllerTest @Test fun testGetNext_noNewUnAssignedMessages() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "assignee" - val type = "testGetNext_noNewUnAssignedMessages" - val message = createQueueMessage(type = type, assignedTo = assignedTo) - val message2 = createQueueMessage(type = type, assignedTo = assignedTo) + val subQueue = "testGetNext_noNewUnAssignedMessages" + val message = createQueueMessage(subQueue = subQueue, assignedTo = assignedTo) + val message2 = createQueueMessage(subQueue = subQueue, assignedTo = assignedTo) Assertions.assertTrue(multiQueue.add(message)) Assertions.assertTrue(multiQueue.add(message2)) - Assertions.assertFalse(multiQueue.getQueueForType(type).isEmpty()) + Assertions.assertFalse(multiQueue.getSubQueue(subQueue).isEmpty()) mockMvc.perform(put(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_NEXT) .contentType(MediaType.APPLICATION_JSON_VALUE) - .param(RestParameters.QUEUE_TYPE, type) + .param(RestParameters.SUB_QUEUE, subQueue) .param(RestParameters.ASSIGNED_TO, assignedTo)) .andExpect(MockMvcResultMatchers.status().isNoContent) } @@ -922,23 +922,23 @@ class MessageQueueControllerTest @Test fun testGetNext() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "assignee" - val type = "testGetNext" - val message = createQueueMessage(type = type, assignedTo = assignedTo) - val message2 = createQueueMessage(type = type) + val subQueue = "testGetNext" + val message = createQueueMessage(subQueue = subQueue, assignedTo = assignedTo) + val message2 = createQueueMessage(subQueue = subQueue) Assertions.assertTrue(multiQueue.add(message)) Assertions.assertTrue(multiQueue.add(message2)) - val storedMessage2 = multiQueue.getQueueForType(type).stream().filter{ m -> m.uuid == message2.uuid }.findFirst().get() + val storedMessage2 = multiQueue.getSubQueue(subQueue).stream().filter{ m -> m.uuid == message2.uuid }.findFirst().get() Assertions.assertNull(storedMessage2.assignedTo) Assertions.assertEquals(message2.uuid, storedMessage2.uuid) val mvcResult: MvcResult = mockMvc.perform(put(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_NEXT) .contentType(MediaType.APPLICATION_JSON_VALUE) - .param(RestParameters.QUEUE_TYPE, type) + .param(RestParameters.SUB_QUEUE, subQueue) .param(RestParameters.ASSIGNED_TO, assignedTo)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() @@ -947,7 +947,7 @@ class MessageQueueControllerTest Assertions.assertEquals(assignedTo, messageResponse.message.assignedTo) Assertions.assertEquals(message2.uuid, messageResponse.message.uuid) - val assignedMessage2 = multiQueue.getQueueForType(type).stream().filter{ m -> m.uuid == message2.uuid }.findFirst().get() + val assignedMessage2 = multiQueue.getSubQueue(subQueue).stream().filter{ m -> m.uuid == message2.uuid }.findFirst().get() Assertions.assertEquals(assignedTo, assignedMessage2.assignedTo) Assertions.assertEquals(message2.uuid, assignedMessage2.uuid) } @@ -959,37 +959,37 @@ class MessageQueueControllerTest @Test fun testGetNext_inHybridMode() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getRestrictionMode()) val assignedTo = "assignee" - val type = "testGetNext_inHybridMode" - val message = createQueueMessage(type = type, assignedTo = assignedTo) - val message2 = createQueueMessage(type = type) + val subQueue = "testGetNext_inHybridMode" + val message = createQueueMessage(subQueue = subQueue, assignedTo = assignedTo) + val message2 = createQueueMessage(subQueue = subQueue) Assertions.assertTrue(multiQueue.add(message)) Assertions.assertTrue(multiQueue.add(message2)) - Assertions.assertTrue(authenticator.addRestrictedEntry(type)) - Assertions.assertTrue(authenticator.isRestricted(type)) + Assertions.assertTrue(authenticator.addRestrictedEntry(subQueue)) + Assertions.assertTrue(authenticator.isRestricted(subQueue)) - val storedMessage2 = multiQueue.getQueueForType(type).stream().filter{ m -> m.uuid == message2.uuid }.findFirst().get() + val storedMessage2 = multiQueue.getSubQueue(subQueue).stream().filter{ m -> m.uuid == message2.uuid }.findFirst().get() Assertions.assertNull(storedMessage2.assignedTo) Assertions.assertEquals(message2.uuid, storedMessage2.uuid) mockMvc.perform(put(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_NEXT) .contentType(MediaType.APPLICATION_JSON_VALUE) - .param(RestParameters.QUEUE_TYPE, type) + .param(RestParameters.SUB_QUEUE, subQueue) .param(RestParameters.ASSIGNED_TO, assignedTo)) .andExpect(MockMvcResultMatchers.status().isForbidden) - val token = jwtTokenProvider.createTokenForSubQueue(type) + val token = jwtTokenProvider.createTokenForSubQueue(subQueue) Assertions.assertTrue(token.isPresent) val mvcResult: MvcResult = mockMvc.perform(put(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_NEXT) .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${token.get()}") .contentType(MediaType.APPLICATION_JSON_VALUE) - .param(RestParameters.QUEUE_TYPE, type) + .param(RestParameters.SUB_QUEUE, subQueue) .param(RestParameters.ASSIGNED_TO, assignedTo)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() @@ -998,7 +998,7 @@ class MessageQueueControllerTest Assertions.assertEquals(assignedTo, messageResponse.message.assignedTo) Assertions.assertEquals(message2.uuid, messageResponse.message.uuid) - val assignedMessage2 = multiQueue.getQueueForType(type).stream().filter{ m -> m.uuid == message2.uuid }.findFirst().get() + val assignedMessage2 = multiQueue.getSubQueue(subQueue).stream().filter{ m -> m.uuid == message2.uuid }.findFirst().get() Assertions.assertEquals(assignedTo, assignedMessage2.assignedTo) Assertions.assertEquals(message2.uuid, assignedMessage2.uuid) } @@ -1010,7 +1010,7 @@ class MessageQueueControllerTest @Test fun testReleaseMessage_doesNotExist() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val uuid = UUID.randomUUID().toString() mockMvc.perform(put(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + MessageQueueController.ENDPOINT_ENTRY + "/" + uuid + MessageQueueController.ENDPOINT_RELEASE) @@ -1025,10 +1025,10 @@ class MessageQueueControllerTest @Test fun testReleaseMessage_messageIsReleased() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "assignee" - val message = createQueueMessage(type = "testReleaseMessage_messageIsReleased", assignedTo = assignedTo) + val message = createQueueMessage(subQueue = "testReleaseMessage_messageIsReleased", assignedTo = assignedTo) Assertions.assertEquals(assignedTo, message.assignedTo) Assertions.assertTrue(multiQueue.add(message)) @@ -1043,7 +1043,7 @@ class MessageQueueControllerTest Assertions.assertNull(messageResponse.message.assignedTo) Assertions.assertEquals(message.uuid, messageResponse.message.uuid) - val updatedMessage = multiQueue.peekForType(message.type).get() + val updatedMessage = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertNull(updatedMessage.assignedTo) Assertions.assertEquals(message.uuid, updatedMessage.uuid) } @@ -1055,17 +1055,17 @@ class MessageQueueControllerTest @Test fun testReleaseMessage_messageIsReleased_inHybridMode() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getRestrictionMode()) val assignedTo = "assignee" - val message = createQueueMessage(type = "testReleaseMessage_messageIsReleased_inHybridMode", assignedTo = assignedTo) + val message = createQueueMessage(subQueue = "testReleaseMessage_messageIsReleased_inHybridMode", assignedTo = assignedTo) Assertions.assertEquals(assignedTo, message.assignedTo) Assertions.assertTrue(multiQueue.add(message)) - Assertions.assertTrue(authenticator.addRestrictedEntry(message.type)) - Assertions.assertTrue(authenticator.isRestricted(message.type)) + Assertions.assertTrue(authenticator.addRestrictedEntry(message.subQueue)) + Assertions.assertTrue(authenticator.isRestricted(message.subQueue)) mockMvc.perform(put(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + MessageQueueController.ENDPOINT_ENTRY + "/" + message.uuid + MessageQueueController.ENDPOINT_RELEASE) .contentType(MediaType.APPLICATION_JSON_VALUE) @@ -1073,7 +1073,7 @@ class MessageQueueControllerTest .andExpect(MockMvcResultMatchers.status().isForbidden) - val token = jwtTokenProvider.createTokenForSubQueue(message.type) + val token = jwtTokenProvider.createTokenForSubQueue(message.subQueue) Assertions.assertTrue(token.isPresent) val mvcResult: MvcResult = mockMvc.perform(put(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + MessageQueueController.ENDPOINT_ENTRY + "/" + message.uuid + MessageQueueController.ENDPOINT_RELEASE) @@ -1087,7 +1087,7 @@ class MessageQueueControllerTest Assertions.assertNull(messageResponse.message.assignedTo) Assertions.assertEquals(message.uuid, messageResponse.message.uuid) - val updatedMessage = multiQueue.peekForType(message.type).get() + val updatedMessage = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertNull(updatedMessage.assignedTo) Assertions.assertEquals(message.uuid, updatedMessage.uuid) } @@ -1099,10 +1099,10 @@ class MessageQueueControllerTest @Test fun testReleaseMessage_messageIsReleased_withoutAssignedToInQuery() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "assigned" - val message = createQueueMessage(type = "testReleaseMessage_messageIsReleased_withoutAssignedToInQuery", assignedTo = assignedTo) + val message = createQueueMessage(subQueue = "testReleaseMessage_messageIsReleased_withoutAssignedToInQuery", assignedTo = assignedTo) Assertions.assertEquals(assignedTo, message.assignedTo) Assertions.assertTrue(multiQueue.add(message)) @@ -1116,7 +1116,7 @@ class MessageQueueControllerTest Assertions.assertNull(messageResponse.message.assignedTo) Assertions.assertEquals(message.uuid, messageResponse.message.uuid) - val updatedMessage = multiQueue.peekForType(message.type).get() + val updatedMessage = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertNull(updatedMessage.assignedTo) Assertions.assertEquals(message.uuid, updatedMessage.uuid) } @@ -1128,9 +1128,9 @@ class MessageQueueControllerTest @Test fun testReleaseMessage_alreadyReleased() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) - val message = createQueueMessage(type = "testReleaseMessage_alreadyReleased") + val message = createQueueMessage(subQueue = "testReleaseMessage_alreadyReleased") Assertions.assertNull(message.assignedTo) Assertions.assertTrue(multiQueue.add(message)) @@ -1144,7 +1144,7 @@ class MessageQueueControllerTest Assertions.assertEquals(message.uuid, messageResponse.message.uuid) // Ensure the message is updated in the queue too - val updatedMessage = multiQueue.peekForType(message.type).get() + val updatedMessage = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertNull(updatedMessage.assignedTo) Assertions.assertEquals(message.uuid, updatedMessage.uuid) } @@ -1157,10 +1157,10 @@ class MessageQueueControllerTest @Test fun testReleaseMessage_cannotBeReleasedWithMisMatchingID() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "assigned" - val message = createQueueMessage(type = "testReleaseMessage_cannotBeReleasedWithMisMatchingID", assignedTo = assignedTo) + val message = createQueueMessage(subQueue = "testReleaseMessage_cannotBeReleasedWithMisMatchingID", assignedTo = assignedTo) Assertions.assertEquals(assignedTo, message.assignedTo) Assertions.assertTrue(multiQueue.add(message)) @@ -1171,7 +1171,7 @@ class MessageQueueControllerTest .param(RestParameters.ASSIGNED_TO, wrongAssignedTo)) .andExpect(MockMvcResultMatchers.status().isConflict) - val assignedEntry = multiQueue.peekForType(message.type).get() + val assignedEntry = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertEquals(assignedTo, assignedEntry.assignedTo) } @@ -1182,7 +1182,7 @@ class MessageQueueControllerTest @Test fun testRemoveMessage_notFound() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val uuid = UUID.randomUUID().toString() @@ -1198,9 +1198,9 @@ class MessageQueueControllerTest @Test fun testRemoveMessage_removeExistingEntry() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) - val message = createQueueMessage(type = "testRemoveMessage_removed") + val message = createQueueMessage(subQueue = "testRemoveMessage_removed") Assertions.assertTrue(multiQueue.add(message)) Assertions.assertTrue(multiQueue.containsUUID(message.uuid).isPresent) @@ -1209,7 +1209,7 @@ class MessageQueueControllerTest .andExpect(MockMvcResultMatchers.status().isOk) Assertions.assertFalse(multiQueue.containsUUID(message.uuid).isPresent) - Assertions.assertTrue(multiQueue.getQueueForType(message.type).isEmpty()) + Assertions.assertTrue(multiQueue.getSubQueue(message.subQueue).isEmpty()) } /** @@ -1219,21 +1219,21 @@ class MessageQueueControllerTest @Test fun testRemoveMessage_removeExistingEntry_inHybridMode() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getRestrictionMode()) - val message = createQueueMessage(type = "testRemoveMessage_removeExistingEntry_inHybridMode") + val message = createQueueMessage(subQueue = "testRemoveMessage_removeExistingEntry_inHybridMode") Assertions.assertTrue(multiQueue.add(message)) Assertions.assertTrue(multiQueue.containsUUID(message.uuid).isPresent) - Assertions.assertTrue(authenticator.addRestrictedEntry(message.type)) - Assertions.assertTrue(authenticator.isRestricted(message.type)) + Assertions.assertTrue(authenticator.addRestrictedEntry(message.subQueue)) + Assertions.assertTrue(authenticator.isRestricted(message.subQueue)) mockMvc.perform(delete(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY + "/" + message.uuid) .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isForbidden) - val token = jwtTokenProvider.createTokenForSubQueue(message.type) + val token = jwtTokenProvider.createTokenForSubQueue(message.subQueue) Assertions.assertTrue(token.isPresent) mockMvc.perform(delete(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY + "/" + message.uuid) @@ -1242,7 +1242,7 @@ class MessageQueueControllerTest .andExpect(MockMvcResultMatchers.status().isOk) Assertions.assertFalse(multiQueue.containsUUID(message.uuid).isPresent) - Assertions.assertTrue(multiQueue.getQueueForType(message.type).isEmpty()) + Assertions.assertTrue(multiQueue.getSubQueue(message.subQueue).isEmpty()) } /** @@ -1252,7 +1252,7 @@ class MessageQueueControllerTest @Test fun testRemoveMessage_doesNotExist() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val uuid = UUID.randomUUID().toString() Assertions.assertFalse(multiQueue.containsUUID(uuid).isPresent) @@ -1271,10 +1271,10 @@ class MessageQueueControllerTest @Test fun testRemoveMessage_assignedToAnotherID() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "assignee" - val message = createQueueMessage(type = "testRemoveMessage_assignedToAnotherID", assignedTo = assignedTo) + val message = createQueueMessage(subQueue = "testRemoveMessage_assignedToAnotherID", assignedTo = assignedTo) Assertions.assertTrue(multiQueue.add(message)) val wrongAssignedTo = "wrong-assignee" @@ -1283,27 +1283,27 @@ class MessageQueueControllerTest .param(RestParameters.ASSIGNED_TO, wrongAssignedTo)) .andExpect(MockMvcResultMatchers.status().isForbidden) - val assignedEntry = multiQueue.peekForType(message.type).get() + val assignedEntry = multiQueue.peekSubQueue(message.subQueue).get() Assertions.assertEquals(assignedTo, assignedEntry.assignedTo) } /** - * Test [MessageQueueController.getOwners] with a provided `queueType` parameter to ensure the appropriate map is + * Test [MessageQueueController.getOwners] with a provided `sub-queue` parameter to ensure the appropriate map is * provided in the response and [HttpStatus.OK] is returned. */ @Test - fun testGetOwners_withQueueType() + fun testGetOwners_inSubQueue() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "assignedTo" val assignedTo2 = "assignedTo2" - val type = "testGetOwners" + val subQueue = "testGetOwners" - val message = createQueueMessage(type = type, assignedTo = assignedTo) - val message2 = createQueueMessage(type = type, assignedTo = assignedTo2) - val message3 = createQueueMessage(type = type, assignedTo = assignedTo2) + val message = createQueueMessage(subQueue = subQueue, assignedTo = assignedTo) + val message2 = createQueueMessage(subQueue = subQueue, assignedTo = assignedTo2) + val message3 = createQueueMessage(subQueue = subQueue, assignedTo = assignedTo2) Assertions.assertTrue(multiQueue.add(message)) Assertions.assertTrue(multiQueue.add(message2)) @@ -1311,7 +1311,7 @@ class MessageQueueControllerTest val mvcResult = mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_OWNERS) .contentType(MediaType.APPLICATION_JSON_VALUE) - .param(RestParameters.QUEUE_TYPE, type)) + .param(RestParameters.SUB_QUEUE, subQueue)) .andExpect(MockMvcResultMatchers.status().isOk) .andReturn() @@ -1323,31 +1323,31 @@ class MessageQueueControllerTest val valuesInAssignedTo = owners[assignedTo] Assertions.assertTrue(valuesInAssignedTo is ArrayList<*>) - Assertions.assertTrue((valuesInAssignedTo as ArrayList<*>).contains(type)) + Assertions.assertTrue((valuesInAssignedTo as ArrayList<*>).contains(subQueue)) val valuesInAssignedTo2 = owners[assignedTo2] Assertions.assertTrue(valuesInAssignedTo2 is ArrayList<*>) - Assertions.assertTrue((valuesInAssignedTo2 as ArrayList<*>).contains(type)) + Assertions.assertTrue((valuesInAssignedTo2 as ArrayList<*>).contains(subQueue)) } /** - * Test [MessageQueueController.getOwners] without a provided `queueType` parameter to ensure the appropriate map + * Test [MessageQueueController.getOwners] without a provided `sub-queue` parameter to ensure the appropriate map * is provided in the response and [HttpStatus.OK] is returned. */ @Test - fun testGetOwners_withoutQueueType() + fun testGetOwners_notInSubQueue() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "assignedTo" val assignedTo2 = "assignedTo2" - val type = "testGetOwners" - val type2 = "testGetOwners2" + val subQueue = "testGetOwners" + val subQueue2 = "testGetOwners2" - val message = createQueueMessage(type = type, assignedTo = assignedTo) - val message2 = createQueueMessage(type = type2, assignedTo = assignedTo) - val message3 = createQueueMessage(type = type2, assignedTo = assignedTo2) + val message = createQueueMessage(subQueue = subQueue, assignedTo = assignedTo) + val message2 = createQueueMessage(subQueue = subQueue2, assignedTo = assignedTo) + val message3 = createQueueMessage(subQueue = subQueue2, assignedTo = assignedTo2) Assertions.assertTrue(multiQueue.add(message)) Assertions.assertTrue(multiQueue.add(message2)) @@ -1366,12 +1366,12 @@ class MessageQueueControllerTest val valuesInAssignedTo = owners[assignedTo] Assertions.assertTrue(valuesInAssignedTo is ArrayList<*>) - Assertions.assertTrue((valuesInAssignedTo as ArrayList<*>).contains(type)) - Assertions.assertTrue(valuesInAssignedTo.contains(type2)) + Assertions.assertTrue((valuesInAssignedTo as ArrayList<*>).contains(subQueue)) + Assertions.assertTrue(valuesInAssignedTo.contains(subQueue2)) val valuesInAssignedTo2 = owners[assignedTo2] Assertions.assertTrue(valuesInAssignedTo2 is ArrayList<*>) - Assertions.assertTrue((valuesInAssignedTo2 as ArrayList<*>).contains(type2)) + Assertions.assertTrue((valuesInAssignedTo2 as ArrayList<*>).contains(subQueue2)) } /** @@ -1381,7 +1381,7 @@ class MessageQueueControllerTest @Test fun testGetPerformHealthCheck() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_HEALTH_CHECK) .contentType(MediaType.APPLICATION_JSON_VALUE)) @@ -1396,9 +1396,9 @@ class MessageQueueControllerTest @Test fun testCorrelationId_randomIdOnSuccess() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) - val message = createQueueMessage(type = "testCorrelationId_providedId") + val message = createQueueMessage(subQueue = "testCorrelationId_providedId") val mvcResult: MvcResult = mockMvc.perform(post(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY) .contentType(MediaType.APPLICATION_JSON_VALUE) @@ -1418,9 +1418,9 @@ class MessageQueueControllerTest @Test fun testCorrelationId_providedId() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) - val message = createQueueMessage(type = "testCorrelationId_providedId") + val message = createQueueMessage(subQueue = "testCorrelationId_providedId") val correlationId = "my-correlation-id-123456" val mvcResult: MvcResult = mockMvc.perform(post(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY) @@ -1441,10 +1441,10 @@ class MessageQueueControllerTest @Test fun testCorrelationId_randomIdOnError() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val assignedTo = "assignee" - val message = createQueueMessage(type = "testCorrelationId_randomIdOnError", assignedTo = assignedTo) + val message = createQueueMessage(subQueue = "testCorrelationId_randomIdOnError", assignedTo = assignedTo) Assertions.assertTrue(multiQueue.add(message)) val wrongAssignedTo = "wrong-assignee" @@ -1464,12 +1464,12 @@ class MessageQueueControllerTest /** * Ensure that [MessageQueueController.deleteKeys] will only delete keys by the specified - * [RestParameters.QUEUE_TYPE] when it is provided and that other sub queues are not cleared. + * [RestParameters.SUB_QUEUE] when it is provided and that other sub-queues are not cleared. */ @Test fun testDeleteKeys_singleKey() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) val subQueue1 = "testDeleteKeys_singleKey1" var messages = listOf(createQueueMessage(subQueue1), createQueueMessage(subQueue1), createQueueMessage(subQueue1)) @@ -1488,7 +1488,7 @@ class MessageQueueControllerTest mockMvc.perform(delete(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_KEYS) .contentType(MediaType.APPLICATION_JSON_VALUE) - .param(RestParameters.QUEUE_TYPE, subQueue1)) + .param(RestParameters.SUB_QUEUE, subQueue1)) .andExpect(MockMvcResultMatchers.status().isNoContent) Assertions.assertEquals(2, multiQueue.size) @@ -1503,8 +1503,8 @@ class MessageQueueControllerTest @Test fun testDeleteKeys_singleKey_inHybridMode() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getRestrictionMode()) val subQueue1 = "testDeleteKeys_singleKey_inHybridMode1" var messages = listOf(createQueueMessage(subQueue1), createQueueMessage(subQueue1), createQueueMessage(subQueue1)) @@ -1526,7 +1526,7 @@ class MessageQueueControllerTest mockMvc.perform(delete(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_KEYS) .contentType(MediaType.APPLICATION_JSON_VALUE) - .param(RestParameters.QUEUE_TYPE, subQueue1)) + .param(RestParameters.SUB_QUEUE, subQueue1)) .andExpect(MockMvcResultMatchers.status().isNoContent) Assertions.assertEquals(2, multiQueue.size) @@ -1535,7 +1535,7 @@ class MessageQueueControllerTest mockMvc.perform(delete(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_KEYS) .contentType(MediaType.APPLICATION_JSON_VALUE) - .param(RestParameters.QUEUE_TYPE, subQueue2)) + .param(RestParameters.SUB_QUEUE, subQueue2)) .andExpect(MockMvcResultMatchers.status().isForbidden) val token = jwtTokenProvider.createTokenForSubQueue(subQueue2) @@ -1544,7 +1544,7 @@ class MessageQueueControllerTest mockMvc.perform(delete(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_KEYS) .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${token.get()}") .contentType(MediaType.APPLICATION_JSON_VALUE) - .param(RestParameters.QUEUE_TYPE, subQueue2)) + .param(RestParameters.SUB_QUEUE, subQueue2)) .andExpect(MockMvcResultMatchers.status().isNoContent) Assertions.assertEquals(0, multiQueue.size) @@ -1554,23 +1554,23 @@ class MessageQueueControllerTest /** * Ensure that [MessageQueueController.deleteKeys] will only delete all keys/queues when the provided - * [RestParameters.QUEUE_TYPE] is `null`. + * [RestParameters.SUB_QUEUE] is `null`. */ @Test fun testDeleteKeys_allKeys() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) - val (messages, types) = initialiseMapWithEntries() + val (messages, subQueues) = initialiseMapWithEntries() Assertions.assertEquals(messages.size, multiQueue.size) - types.forEach { type -> Assertions.assertTrue(multiQueue.keys().contains(type)) } + subQueues.forEach { subQueue -> Assertions.assertTrue(multiQueue.keys().contains(subQueue)) } mockMvc.perform(delete(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_KEYS) .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isNoContent) Assertions.assertTrue(multiQueue.isEmpty()) - types.forEach { type -> Assertions.assertFalse(multiQueue.keys().contains(type)) } + subQueues.forEach { subQueue -> Assertions.assertFalse(multiQueue.keys().contains(subQueue)) } } /** @@ -1580,25 +1580,25 @@ class MessageQueueControllerTest @Test fun testDeleteKeys_allKeys_inHybridMode() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.HYBRID).`when`(authenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.HYBRID, authenticator.getRestrictionMode()) - val (messages, types) = initialiseMapWithEntries() + val (messages, subQueues) = initialiseMapWithEntries() Assertions.assertEquals(messages.size, multiQueue.size) - types.forEach { type -> Assertions.assertTrue(multiQueue.keys().contains(type)) } + subQueues.forEach { subQueue -> Assertions.assertTrue(multiQueue.keys().contains(subQueue)) } - Assertions.assertTrue(authenticator.addRestrictedEntry(types[0])) - Assertions.assertTrue(authenticator.isRestricted(types[0])) + Assertions.assertTrue(authenticator.addRestrictedEntry(subQueues[0])) + Assertions.assertTrue(authenticator.isRestricted(subQueues[0])) mockMvc.perform(delete(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_KEYS) .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isPartialContent) Assertions.assertEquals(1, multiQueue.size) - Assertions.assertTrue(multiQueue.keys().contains(types[0])) - types.subList(1, types.size - 1).forEach { type -> Assertions.assertFalse(multiQueue.keys().contains(type)) } + Assertions.assertTrue(multiQueue.keys().contains(subQueues[0])) + subQueues.subList(1, subQueues.size - 1).forEach { subQueue -> Assertions.assertFalse(multiQueue.keys().contains(subQueue)) } - val token = jwtTokenProvider.createTokenForSubQueue(types[0]) + val token = jwtTokenProvider.createTokenForSubQueue(subQueues[0]) Assertions.assertTrue(token.isPresent) mockMvc.perform(delete(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_KEYS) @@ -1607,7 +1607,7 @@ class MessageQueueControllerTest .andExpect(MockMvcResultMatchers.status().isNoContent) Assertions.assertTrue(multiQueue.isEmpty()) - types.forEach { type -> Assertions.assertFalse(multiQueue.keys().contains(type)) } + subQueues.forEach { subQueue -> Assertions.assertFalse(multiQueue.keys().contains(subQueue)) } } /** @@ -1619,7 +1619,7 @@ class MessageQueueControllerTest @Test fun testGetPerformHealthCheck_failureResponse() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) Mockito.doThrow(RuntimeException("Failed to perform health check.")).`when`(multiQueue).performHealthCheckInternal() @@ -1637,9 +1637,9 @@ class MessageQueueControllerTest @Test fun testCreateMessage_addFails() { - Assertions.assertEquals(RestrictionMode.NONE, authenticator.getAuthenticationType()) + Assertions.assertEquals(RestrictionMode.NONE, authenticator.getRestrictionMode()) - val message = QueueMessage("payload", "type") + val message = QueueMessage("payload", "testCreateMessage_addFails") Mockito.doReturn(false).`when`(multiQueue).add(message) @@ -1656,8 +1656,8 @@ class MessageQueueControllerTest @Test fun testRestrictedModeMakesAllEndpointsInaccessibleWithoutAToken() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(authenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, authenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(authenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, authenticator.getRestrictionMode()) mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY + "/" + UUID.randomUUID().toString()) .contentType(MediaType.APPLICATION_JSON_VALUE)) @@ -1681,7 +1681,7 @@ class MessageQueueControllerTest .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isUnauthorized) - mockMvc.perform(put(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_NEXT + "?" + RestParameters.QUEUE_TYPE +"=someType&" + RestParameters.ASSIGNED_TO + "=me") + mockMvc.perform(put(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_NEXT + "?" + RestParameters.SUB_QUEUE +"=someType&" + RestParameters.ASSIGNED_TO + "=me") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isUnauthorized) @@ -1689,7 +1689,7 @@ class MessageQueueControllerTest .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isUnauthorized) - mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_OWNED + "?" + RestParameters.QUEUE_TYPE +"=someType&" + RestParameters.ASSIGNED_TO + "=me") + mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_OWNED + "?" + RestParameters.SUB_QUEUE +"=someType&" + RestParameters.ASSIGNED_TO + "=me") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isUnauthorized) } @@ -1701,11 +1701,11 @@ class MessageQueueControllerTest @Test fun testGetEntry_inRestrictedMode() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(authenticator).getAuthenticationType() - Assertions.assertEquals(RestrictionMode.RESTRICTED, authenticator.getAuthenticationType()) + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(authenticator).getRestrictionMode() + Assertions.assertEquals(RestrictionMode.RESTRICTED, authenticator.getRestrictionMode()) - val type = "testRestrictedMode_getByUUID" - val message = createQueueMessage(type) + val subQueue = "testGetEntry_inRestrictedMode" + val message = createQueueMessage(subQueue) Assertions.assertTrue(multiQueue.add(message)) @@ -1713,7 +1713,7 @@ class MessageQueueControllerTest .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isUnauthorized) - val token = jwtTokenProvider.createTokenForSubQueue(type) + val token = jwtTokenProvider.createTokenForSubQueue(subQueue) Assertions.assertTrue(token.isPresent) mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY + "/" + message.uuid) @@ -1721,8 +1721,8 @@ class MessageQueueControllerTest .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.status().isUnauthorized) - Assertions.assertTrue(authenticator.addRestrictedEntry(type)) - Assertions.assertTrue(authenticator.isRestricted(type)) + Assertions.assertTrue(authenticator.addRestrictedEntry(subQueue)) + Assertions.assertTrue(authenticator.isRestricted(subQueue)) mockMvc.perform(get(MessageQueueController.MESSAGE_QUEUE_BASE_PATH + "/" + MessageQueueController.ENDPOINT_ENTRY + "/" + message.uuid) .header(JwtAuthenticationFilter.AUTHORIZATION_HEADER, "${JwtAuthenticationFilter.BEARER_HEADER_VALUE}${token.get()}") @@ -1733,36 +1733,36 @@ class MessageQueueControllerTest /** * A helper method which creates `4` [QueueMessage] objects and inserts them into the [MultiQueue]. * - * @return a [Pair] containing the [List] of [QueueMessage] and their related matching [List] of [String] `queueTypes` in order. + * @return a [Pair] containing the [List] of [QueueMessage] and their related matching [List] of [String] `sub-queue` IDs in order. */ private fun initialiseMapWithEntries(): Pair, List> { - val types = listOf("type1", "type2", "type3", "type4") - val message = createQueueMessage(type = types[0]) - val message2 = createQueueMessage(type = types[1]) - val message3 = createQueueMessage(type = types[2], assignedTo = "assignee") - val message4 = createQueueMessage(type = types[3]) + val subQueues = listOf("type1", "type2", "type3", "type4") + val message = createQueueMessage(subQueue = subQueues[0]) + val message2 = createQueueMessage(subQueue = subQueues[1]) + val message3 = createQueueMessage(subQueue = subQueues[2], assignedTo = "assignee") + val message4 = createQueueMessage(subQueue = subQueues[3]) Assertions.assertTrue(multiQueue.add(message)) Assertions.assertTrue(multiQueue.add(message2)) Assertions.assertTrue(multiQueue.add(message3)) Assertions.assertTrue(multiQueue.add(message4)) - return Pair(listOf(message, message2, message3, message4), types) + return Pair(listOf(message, message2, message3, message4), subQueues) } /** * A helper method to create a [QueueMessage] that can be easily re-used between each test. * - * @param type the `queueType` to assign to the created [QueueMessage] + * @param subQueue the `subQueue` to set in to the created [QueueMessage] * @param assignedTo the [QueueMessage.assignedTo] value to set * @return a [QueueMessage] initialised with multiple parameters */ - private fun createQueueMessage(type: String, assignedTo: String? = null): QueueMessage + private fun createQueueMessage(subQueue: String, assignedTo: String? = null): QueueMessage { val uuid = UUID.randomUUID().toString() val payload = Payload("test", 12, true, PayloadEnum.C) - val message = QueueMessage(payload = payload, type = type) + val message = QueueMessage(payload = payload, subQueue = subQueue) message.uuid = UUID.fromString(uuid).toString() message.assignedTo = assignedTo diff --git a/src/test/kotlin/au/kilemon/messagequeue/rest/controller/SettingsControllerTest.kt b/src/test/kotlin/au/kilemon/messagequeue/rest/controller/SettingsControllerTest.kt index d49d120..8421e58 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/rest/controller/SettingsControllerTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/rest/controller/SettingsControllerTest.kt @@ -66,7 +66,7 @@ class SettingsControllerTest */ private fun testGetSettings_defaultValues(authenticationType: RestrictionMode) { - Assertions.assertEquals(authenticationType, multiQueueAuthenticator.getAuthenticationType()) + Assertions.assertEquals(authenticationType, multiQueueAuthenticator.getRestrictionMode()) val mvcResult: MvcResult = mockMvc.perform(MockMvcRequestBuilders.get(SettingsController.SETTINGS_PATH) .contentType(MediaType.APPLICATION_JSON_VALUE)) @@ -74,8 +74,8 @@ class SettingsControllerTest .andReturn() val settings = gson.fromJson(mvcResult.response.contentAsString, MessageQueueSettings::class.java) - Assertions.assertEquals(StorageMedium.IN_MEMORY.toString(), settings.multiQueueType) - Assertions.assertEquals(RestrictionMode.NONE.toString(), settings.multiQueueAuthentication) + Assertions.assertEquals(StorageMedium.IN_MEMORY.toString(), settings.storageMedium) + Assertions.assertEquals(RestrictionMode.NONE.toString(), settings.restrictionMode) Assertions.assertTrue(settings.redisPrefix.isEmpty()) Assertions.assertEquals(MessageQueueSettings.REDIS_ENDPOINT_DEFAULT, settings.redisEndpoint) @@ -99,7 +99,7 @@ class SettingsControllerTest @Test fun testGetSettings_noneMode() { - Mockito.doReturn(RestrictionMode.NONE).`when`(multiQueueAuthenticator).getAuthenticationType() + Mockito.doReturn(RestrictionMode.NONE).`when`(multiQueueAuthenticator).getRestrictionMode() testGetSettings_defaultValues(RestrictionMode.NONE) } @@ -110,7 +110,7 @@ class SettingsControllerTest @Test fun testGetSettings_hybridMode() { - Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getAuthenticationType() + Mockito.doReturn(RestrictionMode.HYBRID).`when`(multiQueueAuthenticator).getRestrictionMode() testGetSettings_defaultValues(RestrictionMode.HYBRID) } @@ -121,7 +121,7 @@ class SettingsControllerTest @Test fun testGetSettings_restrictedMode() { - Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getAuthenticationType() + Mockito.doReturn(RestrictionMode.RESTRICTED).`when`(multiQueueAuthenticator).getRestrictionMode() testGetSettings_defaultValues(RestrictionMode.RESTRICTED) } } diff --git a/src/test/kotlin/au/kilemon/messagequeue/rest/response/RestResponseExceptionHandlerTest.kt b/src/test/kotlin/au/kilemon/messagequeue/rest/response/RestResponseExceptionHandlerTest.kt index f7f6267..77f392d 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/rest/response/RestResponseExceptionHandlerTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/rest/response/RestResponseExceptionHandlerTest.kt @@ -104,13 +104,13 @@ class RestResponseExceptionHandlerTest { val correlationId = UUID.randomUUID().toString() MDC.put(CorrelationIdFilter.CORRELATION_ID, correlationId) - val type = "testHandleIllegalSubQueueIdentifierException" - val exception = IllegalSubQueueIdentifierException(type) + val subQueue = "testHandleIllegalSubQueueIdentifierException" + val exception = IllegalSubQueueIdentifierException(subQueue) val response = responseHandler.handleIllegalSubQueueIdentifierException(exception) Assertions.assertEquals(HttpStatus.BAD_REQUEST, response.statusCode) Assertions.assertNotNull(response.body) - Assertions.assertTrue(response.body!!.message!!.contains(type)) + Assertions.assertTrue(response.body!!.message!!.contains(subQueue)) Assertions.assertEquals(correlationId, response.body!!.correlationId) } } diff --git a/src/test/kotlin/au/kilemon/messagequeue/settings/MessageQueueSettingsDefaultTest.kt b/src/test/kotlin/au/kilemon/messagequeue/settings/MessageQueueSettingsDefaultTest.kt index 22cb8fa..9f1cc79 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/settings/MessageQueueSettingsDefaultTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/settings/MessageQueueSettingsDefaultTest.kt @@ -42,8 +42,8 @@ class MessageQueueSettingsDefaultTest fun testDefaults() { Assertions.assertNotNull(messageQueueSettings) - Assertions.assertEquals(MessageQueueSettings.STORAGE_MEDIUM_DEFAULT, messageQueueSettings.multiQueueType) - Assertions.assertEquals(MessageQueueSettings.RESTRICTION_MODE_DEFAULT, messageQueueSettings.multiQueueAuthentication) + Assertions.assertEquals(MessageQueueSettings.STORAGE_MEDIUM_DEFAULT, messageQueueSettings.storageMedium) + Assertions.assertEquals(MessageQueueSettings.RESTRICTION_MODE_DEFAULT, messageQueueSettings.restrictionMode) Assertions.assertEquals(MessageQueueSettings.REDIS_ENDPOINT_DEFAULT, messageQueueSettings.redisEndpoint) Assertions.assertEquals("", messageQueueSettings.redisPrefix) diff --git a/src/test/kotlin/au/kilemon/messagequeue/settings/MessageQueueSettingsTest.kt b/src/test/kotlin/au/kilemon/messagequeue/settings/MessageQueueSettingsTest.kt index 8f56377..e95c07a 100644 --- a/src/test/kotlin/au/kilemon/messagequeue/settings/MessageQueueSettingsTest.kt +++ b/src/test/kotlin/au/kilemon/messagequeue/settings/MessageQueueSettingsTest.kt @@ -50,7 +50,7 @@ class MessageQueueSettingsTest fun testValues() { Assertions.assertNotNull(messageQueueSettings) - Assertions.assertEquals("REDIS", messageQueueSettings.multiQueueType) + Assertions.assertEquals("REDIS", messageQueueSettings.storageMedium) Assertions.assertEquals("123.123.123.123", messageQueueSettings.redisEndpoint) Assertions.assertEquals("redis", messageQueueSettings.redisPrefix) Assertions.assertEquals("master", messageQueueSettings.redisMasterName)