You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pekko.apache.org by sa...@apache.org on 2024/07/02 20:59:28 UTC
(pekko-connectors) branch main updated: Adding Jakarta Messaging 3.0 support (#674)
This is an automated email from the ASF dual-hosted git repository.
samueler pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/pekko-connectors.git
The following commit(s) were added to refs/heads/main by this push:
new deccaf78e Adding Jakarta Messaging 3.0 support (#674)
deccaf78e is described below
commit deccaf78e4efecf8508f61931f4839e92192ea04
Author: Samuele Resca <sa...@gmail.com>
AuthorDate: Tue Jul 2 21:59:23 2024 +0100
Adding Jakarta Messaging 3.0 support (#674)
* Initializing jakarta JMS with jakarta.jms-api 3.0.0
* Fixing imports + Adding pinned deps to scala steward.
* Updating config definition.
* Common artemis version.
* Removing JMS 2.0 comment
---
.github/workflows/check-build-test.yml | 1 +
.scala-steward.conf | 2 +
build.sbt | 2 +
.../src/main/resources/reference.conf | 18 +-
.../connectors/jakartams/AcknowledgeMode.scala | 67 ++
.../jakartams/ConnectionRetrySettings.scala | 145 +++
.../stream/connectors/jakartams/Credentials.scala | 78 ++
.../stream/connectors/jakartams/Destinations.scala | 74 ++
.../stream/connectors/jakartams/Envelopes.scala | 38 +
.../stream/connectors/jakartams/Headers.scala | 161 +++
.../connectors/jakartams/JmsBrowseSettings.scala | 161 +++
.../connectors/jakartams/JmsConsumerSettings.scala | 255 ++++
.../connectors/jakartams/JmsExceptions.scala | 67 ++
.../stream/connectors/jakartams/JmsMessages.scala | 1023 ++++++++++++++++
.../connectors/jakartams/JmsProducerSettings.scala | 199 ++++
.../stream/connectors/jakartams/JmsSettings.scala | 31 +
.../connectors/jakartams/SendRetrySettings.scala | 131 +++
.../jakartams/impl/GraphStageCompanion.scala | 34 +
.../jakartams/impl/InternalConnectionState.scala | 44 +
.../jakartams/impl/JmsAckSourceStage.scala | 90 ++
.../connectors/jakartams/impl/JmsBrowseStage.scala | 77 ++
.../connectors/jakartams/impl/JmsConnector.scala | 424 +++++++
.../jakartams/impl/JmsConsumerStage.scala | 76 ++
.../jakartams/impl/JmsInternalMatValues.scala | 32 +
.../jakartams/impl/JmsMessageProducer.scala | 145 +++
.../jakartams/impl/JmsMessageReader.scala | 100 ++
.../jakartams/impl/JmsProducerStage.scala | 300 +++++
.../jakartams/impl/JmsTxSourceStage.scala | 98 ++
.../connectors/jakartams/impl/Sessions.scala | 137 +++
.../jakartams/impl/SoftReferenceCache.scala | 50 +
.../jakartams/impl/SourceStageLogic.scala | 166 +++
.../jakartams/javadsl/JmsConnectorState.java | 20 +
.../connectors/jakartams/javadsl/JmsConsumer.scala | 109 ++
.../jakartams/javadsl/JmsConsumerControl.java | 27 +
.../connectors/jakartams/javadsl/JmsProducer.scala | 123 ++
.../jakartams/javadsl/JmsProducerStatus.java | 26 +
.../jakartams/scaladsl/JmsConnectorState.scala | 66 ++
.../jakartams/scaladsl/JmsConsumer.scala | 132 +++
.../jakartams/scaladsl/JmsProducer.scala | 106 ++
.../connectors/jakartams/scaladsl/package.scala | 38 +
.../docs/javadsl/JmsBufferedAckConnectorsTest.java | 392 +++++++
.../test/java/docs/javadsl/JmsConnectorsTest.java | 930 +++++++++++++++
.../java/docs/javadsl/JmsIbmmqConnectorsTest.java | 223 ++++
.../test/java/docs/javadsl/JmsSettingsTest.java | 105 ++
.../java/docs/javadsl/JmsTxConnectorsTest.java | 394 +++++++
.../jakartams/javadsl/JmsAckConnectorsTest.java | 387 +++++++
jakartams/src/test/resources/application.conf | 7 +
jakartams/src/test/resources/logback-test.xml | 29 +
.../scaladsl/JmsBufferedAckConnectorsSpec.scala | 407 +++++++
.../scala/docs/scaladsl/JmsConnectorsSpec.scala | 1221 ++++++++++++++++++++
.../docs/scaladsl/JmsIbmmqConnectorsSpec.scala | 160 +++
.../test/scala/docs/scaladsl/JmsSettingsSpec.scala | 177 +++
.../scala/docs/scaladsl/JmsTxConnectorsSpec.scala | 695 +++++++++++
.../jakartams/EmbeddedActiveMQServer.scala | 34 +
.../jakartams/JmsConnectionStatusSpec.scala | 396 +++++++
.../jakartams/JmsProducerRetrySpec.scala | 245 ++++
.../connectors/jakartams/JmsSharedServerSpec.scala | 53 +
.../stream/connectors/jakartams/JmsSpec.scala | 93 ++
.../jakartams/impl/JmsMessageProducerSpec.scala | 159 +++
.../jakartams/impl/SoftReferenceCacheSpec.scala | 145 +++
.../scaladsl/CachedConnectionFactory.scala | 38 +
.../jakartams/scaladsl/JmsAckConnectorsSpec.scala | 444 +++++++
jms/src/main/resources/reference.conf | 2 +-
project/Dependencies.scala | 12 +
64 files changed, 11611 insertions(+), 10 deletions(-)
diff --git a/.github/workflows/check-build-test.yml b/.github/workflows/check-build-test.yml
index 36343198c..af6749a4d 100644
--- a/.github/workflows/check-build-test.yml
+++ b/.github/workflows/check-build-test.yml
@@ -108,6 +108,7 @@ jobs:
- { connector: influxdb, pre_cmd: 'docker-compose up -d influxdb' }
# ironmq disabled while we resolve https://github.com/apache/pekko-connectors/issues/697
# - { connector: ironmq, pre_cmd: 'docker-compose up -d ironauth ironmq' }
+ - { connector: jakartams, pre_cmd: 'docker-compose up -d ibmmq' }
- { connector: jms, pre_cmd: 'docker-compose up -d ibmmq' }
- { connector: json-streaming }
- { connector: kinesis }
diff --git a/.scala-steward.conf b/.scala-steward.conf
index 645760ec4..c64b50bb2 100644
--- a/.scala-steward.conf
+++ b/.scala-steward.conf
@@ -17,6 +17,8 @@ updates.pin = [
{ groupId = "org.mockito", version = "4." }
# activemq 5.17+ requires Java 11 (only used in tests)
{ groupId = "org.apache.activemq", version = "5.16." }
+ # jakarta 3.0+ requires Java 11
+ { groupId = "jakarta.jms", version="3.0."}
# wiremock 3.0+ requires Java 11 (only used in tests)
{ groupId = "com.github.tomakehurst", version = "2." }
# jetty 10.+ requires Java 11 (only used in tests - via wiremock)
diff --git a/build.sbt b/build.sbt
index 6e20858d7..e480559fc 100644
--- a/build.sbt
+++ b/build.sbt
@@ -290,6 +290,8 @@ lazy val ironmq = pekkoConnectorProject(
lazy val jms = pekkoConnectorProject("jms", "jms", Dependencies.Jms)
+lazy val jakartams = pekkoConnectorProject("jakartams", "jakartams", Dependencies.JakartaMs)
+
lazy val jsonStreaming = pekkoConnectorProject("json-streaming", "json.streaming", Dependencies.JsonStreaming)
lazy val kinesis = pekkoConnectorProject("kinesis", "aws.kinesis", Dependencies.Kinesis)
diff --git a/jms/src/main/resources/reference.conf b/jakartams/src/main/resources/reference.conf
similarity index 89%
copy from jms/src/main/resources/reference.conf
copy to jakartams/src/main/resources/reference.conf
index 39ba4d6fc..4243e1da4 100644
--- a/jms/src/main/resources/reference.conf
+++ b/jakartams/src/main/resources/reference.conf
@@ -2,7 +2,7 @@
# Settings for the Apache Pekko Connectors JMS connector
#
-pekko.connectors.jms {
+pekko.connectors.jakartams {
#connection-retry
# Connection Retry Settings
# these set the defaults for Consumer, Producer, and Browse settings
@@ -13,7 +13,7 @@ pekko.connectors.jms {
initial-retry = 100 millis
# Back-off factor for subsequent retries.
backoff-factor = 2
- # Back-off factor for subsequent retries.
+ # Maximum back-off time for subsequent retries.
max-backoff = 1 minute
# Maximum number of retries allowed.
# "infinite", or positive integer
@@ -27,7 +27,7 @@ pekko.connectors.jms {
# sets default values
consumer {
# Configure connection retrying by providing settings for ConnectionRetrySettings.
- connection-retry = ${pekko.connectors.jms.connection-retry}
+ connection-retry = ${pekko.connectors.jakartams.connection-retry}
# Credentials to connect to the JMS broker.
# credentials {
# username = "some text"
@@ -45,7 +45,7 @@ pekko.connectors.jms {
selector = "" # optional
# Set an explicit acknowledge mode.
# (Consumers have specific defaults.)
- # See eg. javax.jms.Session.AUTO_ACKNOWLEDGE
+ # See eg. jakarta.jms.Session.AUTO_ACKNOWLEDGE
# Allowed values: "off", "auto", "client", "duplicates-ok", "session", integer value
acknowledge-mode = off
# Timeout for acknowledge.
@@ -57,7 +57,7 @@ pekko.connectors.jms {
# Max interval before sending queued acknowledges back to the broker. (Used by AckSources.)
# max-ack-interval = 5 seconds
# Max number of acks queued by AckSource before they are sent to broker. (Unless MaxAckInterval is specified).
- max-pending-acks = ${pekko.connectors.jms.consumer.buffer-size}
+ max-pending-acks = ${pekko.connectors.jakartams.consumer.buffer-size}
# How long the stage should preserve connection status events for the first subscriber before discarding them
connection-status-subscription-timeout = 5 seconds
}
@@ -84,9 +84,9 @@ pekko.connectors.jms {
# sets default values
producer {
# Configure connection retrying by providing settings for ConnectionRetrySettings.
- connection-retry = ${pekko.connectors.jms.connection-retry}
+ connection-retry = ${pekko.connectors.jakartams.connection-retry}
# Configure re-sending by providing settings for SendRetrySettings.
- send-retry = ${pekko.connectors.jms.send-retry}
+ send-retry = ${pekko.connectors.jakartams.send-retry}
# Credentials to connect to the JMS broker.
# credentials {
# username = "some text"
@@ -113,7 +113,7 @@ pekko.connectors.jms {
# sets default values
browse {
# Configure connection retrying by providing settings for ConnectionRetrySettings.
- connection-retry = ${pekko.connectors.jms.connection-retry}
+ connection-retry = ${pekko.connectors.jakartams.connection-retry}
# Credentials to connect to the JMS broker.
# credentials {
# username = "some text"
@@ -126,7 +126,7 @@ pekko.connectors.jms {
# empty string for unset
selector = "" # optional
# Set an explicit acknowledge mode.
- # See eg. javax.jms.Session.AUTO_ACKNOWLEDGE
+ # See eg. jakarta.jms.Session.AUTO_ACKNOWLEDGE
# Allowed values: "auto", "client", "duplicates-ok", "session", integer value
acknowledge-mode = auto
}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/AcknowledgeMode.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/AcknowledgeMode.scala
new file mode 100644
index 000000000..e08490c2b
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/AcknowledgeMode.scala
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import jakarta.jms
+
+/**
+ * JMS acknowledge modes.
+ * See [[jakarta.jms.Connection#createSession-boolean-int-]]
+ */
+final class AcknowledgeMode(val mode: Int) {
+ override def equals(other: Any): Boolean = other match {
+ case that: AcknowledgeMode => this.mode == that.mode
+ case _ => false
+ }
+ override def hashCode: Int = mode
+ override def toString: String = s"AcknowledgeMode(${AcknowledgeMode.asString(this)})"
+}
+
+object AcknowledgeMode {
+ val AutoAcknowledge: AcknowledgeMode = new AcknowledgeMode(jms.Session.AUTO_ACKNOWLEDGE)
+ val ClientAcknowledge: AcknowledgeMode = new AcknowledgeMode(jms.Session.CLIENT_ACKNOWLEDGE)
+ val DupsOkAcknowledge: AcknowledgeMode = new AcknowledgeMode(jms.Session.DUPS_OK_ACKNOWLEDGE)
+ val SessionTransacted: AcknowledgeMode = new AcknowledgeMode(jms.Session.SESSION_TRANSACTED)
+
+ /**
+ * Interpret string to corresponding acknowledge mode.
+ */
+ def from(s: String): AcknowledgeMode = s match {
+ case "auto" => AutoAcknowledge
+ case "client" => ClientAcknowledge
+ case "duplicates-ok" => DupsOkAcknowledge
+ case "session" => SessionTransacted
+ case other =>
+ try {
+ val mode = other.toInt
+ new AcknowledgeMode(mode)
+ } catch {
+ case _: NumberFormatException =>
+ throw new IllegalArgumentException(
+ s"can't read AcknowledgeMode '$other', (known are auto, client, duplicates-ok, session, or an integer value)")
+ }
+ }
+
+ /**
+ * Convert to a string presentation.
+ */
+ def asString(mode: AcknowledgeMode): String = mode match {
+ case AutoAcknowledge => "auto"
+ case ClientAcknowledge => "client"
+ case DupsOkAcknowledge => "duplicates-ok"
+ case SessionTransacted => "session"
+ case other => other.mode.toString
+ }
+
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/ConnectionRetrySettings.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/ConnectionRetrySettings.scala
new file mode 100644
index 000000000..3a4c33589
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/ConnectionRetrySettings.scala
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import com.typesafe.config.Config
+import org.apache.pekko.actor.{ ActorSystem, ClassicActorSystemProvider }
+import org.apache.pekko.util.JavaDurationConverters._
+
+import scala.concurrent.duration._
+
+/**
+ * When a connection to a broker cannot be established and errors out, or is timing out being established or
+ * started, the connection can be retried.
+ * All JMS publishers, consumers, and browsers are configured with connection retry settings.
+ */
+final class ConnectionRetrySettings private (
+ val connectTimeout: scala.concurrent.duration.FiniteDuration,
+ val initialRetry: scala.concurrent.duration.FiniteDuration,
+ val backoffFactor: Double,
+ val maxBackoff: scala.concurrent.duration.FiniteDuration,
+ val maxRetries: Int) {
+
+ /** Time allowed to establish and start a connection. */
+ def withConnectTimeout(timeout: scala.concurrent.duration.FiniteDuration): ConnectionRetrySettings =
+ copy(connectTimeout = timeout)
+
+ /** Java API: Time allowed to establish and start a connection. */
+ def withConnectTimeout(timeout: java.time.Duration): ConnectionRetrySettings = copy(connectTimeout = timeout.asScala)
+
+ /** Wait time before retrying the first time. */
+ def withInitialRetry(timeout: scala.concurrent.duration.FiniteDuration): ConnectionRetrySettings =
+ copy(initialRetry = timeout)
+
+ /** Java API: Wait time before retrying the first time. */
+ def withInitialRetry(timeout: java.time.Duration): ConnectionRetrySettings = copy(initialRetry = timeout.asScala)
+
+ /** Back-off factor for subsequent retries. */
+ def withBackoffFactor(factor: Double): ConnectionRetrySettings = copy(backoffFactor = factor)
+
+ /** Maximum back-off time allowed, after which all retries will happen after this delay. */
+ def withMaxBackoff(backoffTime: scala.concurrent.duration.FiniteDuration): ConnectionRetrySettings =
+ copy(maxBackoff = backoffTime)
+
+ /** Java API: Maximum back-off time allowed, after which all retries will happen after this delay. */
+ def withMaxBackoff(backoffTime: java.time.Duration): ConnectionRetrySettings = copy(maxBackoff = backoffTime.asScala)
+
+ /** Maximum number of retries allowed. */
+ def withMaxRetries(value: Int): ConnectionRetrySettings = copy(maxRetries = value)
+
+ /** Do not limit the number of retries. */
+ def withInfiniteRetries(): ConnectionRetrySettings = withMaxRetries(ConnectionRetrySettings.infiniteRetries)
+
+ /** The wait time before the next attempt may be made. */
+ def waitTime(retryNumber: Int): FiniteDuration =
+ (initialRetry * Math.pow(retryNumber, backoffFactor)).asInstanceOf[FiniteDuration].min(maxBackoff)
+
+ private def copy(
+ connectTimeout: scala.concurrent.duration.FiniteDuration = connectTimeout,
+ initialRetry: scala.concurrent.duration.FiniteDuration = initialRetry,
+ backoffFactor: Double = backoffFactor,
+ maxBackoff: scala.concurrent.duration.FiniteDuration = maxBackoff,
+ maxRetries: Int = maxRetries): ConnectionRetrySettings = new ConnectionRetrySettings(
+ connectTimeout = connectTimeout,
+ initialRetry = initialRetry,
+ backoffFactor = backoffFactor,
+ maxBackoff = maxBackoff,
+ maxRetries = maxRetries)
+
+ override def toString: String =
+ "ConnectionRetrySettings(" +
+ s"connectTimeout=${connectTimeout.toCoarsest}," +
+ s"initialRetry=${initialRetry.toCoarsest}," +
+ s"backoffFactor=$backoffFactor," +
+ s"maxBackoff=${maxBackoff.toCoarsest}," +
+ s"maxRetries=${if (maxRetries == ConnectionRetrySettings.infiniteRetries) "infinite" else maxRetries}" +
+ ")"
+}
+
+object ConnectionRetrySettings {
+ val configPath = "pekko.connectors.jakartams.connection-retry"
+
+ val infiniteRetries: Int = -1
+
+ /**
+ * Reads from the given config.
+ */
+ def apply(c: Config): ConnectionRetrySettings = {
+ val connectTimeout = c.getDuration("connect-timeout").asScala
+ val initialRetry = c.getDuration("initial-retry").asScala
+ val backoffFactor = c.getDouble("backoff-factor")
+ val maxBackoff = c.getDuration("max-backoff").asScala
+ val maxRetries = if (c.getString("max-retries") == "infinite") infiniteRetries else c.getInt("max-retries")
+ new ConnectionRetrySettings(
+ connectTimeout,
+ initialRetry,
+ backoffFactor,
+ maxBackoff,
+ maxRetries)
+ }
+
+ /** Java API: Reads from the given config. */
+ def create(c: Config): ConnectionRetrySettings = apply(c)
+
+ /**
+ * Reads from the default config provided by the actor system at `pekko.connectors.jakartams.connection-retry`.
+ *
+ * @param actorSystem The actor system
+ */
+ def apply(actorSystem: ActorSystem): ConnectionRetrySettings =
+ apply(actorSystem.settings.config.getConfig(configPath))
+
+ /**
+ * Reads from the default config provided by the actor system at `pekko.connectors.jakartams.connection-retry`.
+ *
+ * @param actorSystem The actor system
+ */
+ def apply(actorSystem: ClassicActorSystemProvider): ConnectionRetrySettings =
+ apply(actorSystem.classicSystem.settings.config.getConfig(configPath))
+
+ /**
+ * Java API: Reads from the default config provided by the actor system at `pekko.connectors.jakartams.connection-retry`.
+ *
+ * @param actorSystem The actor system
+ */
+ def create(actorSystem: ActorSystem): ConnectionRetrySettings = apply(actorSystem)
+
+ /**
+ * Java API: Reads from the default config provided by the actor system at `pekko.connectors.jakartams.connection-retry`.
+ *
+ * @param actorSystem The actor system
+ */
+ def create(actorSystem: ClassicActorSystemProvider): ConnectionRetrySettings = apply(actorSystem)
+
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/Credentials.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/Credentials.scala
new file mode 100644
index 000000000..82e9e379a
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/Credentials.scala
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import com.typesafe.config.Config
+
+final class Credentials private (
+ val username: String,
+ val password: String) {
+
+ def withUsername(value: String): Credentials = copy(username = value)
+ def withPassword(value: String): Credentials = copy(password = value)
+
+ private def copy(
+ username: String = username,
+ password: String = password): Credentials = new Credentials(
+ username = username,
+ password = password)
+
+ override def toString =
+ "Credentials(" +
+ s"username=$username," +
+ s"password=${"*" * password.length}" +
+ ")"
+
+ override def equals(other: Any): Boolean = other match {
+ case that: Credentials =>
+ java.util.Objects.equals(this.username, that.username) &&
+ java.util.Objects.equals(this.password, that.password)
+ case _ => false
+ }
+
+ override def hashCode(): Int = java.util.Objects.hash(username, password)
+}
+
+object Credentials {
+
+ /**
+ * Reads from the given config.
+ */
+ def apply(c: Config): Credentials = {
+ val username = c.getString("username")
+ val password = c.getString("password")
+ new Credentials(
+ username,
+ password)
+ }
+
+ /**
+ * Java API: Reads from the given config.
+ */
+ def create(c: Config): Credentials = apply(c)
+
+ /** Scala API */
+ def apply(
+ username: String,
+ password: String): Credentials = new Credentials(
+ username,
+ password)
+
+ /** Java API */
+ def create(
+ username: String,
+ password: String): Credentials = new Credentials(
+ username,
+ password)
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/Destinations.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/Destinations.scala
new file mode 100644
index 000000000..6d9423d09
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/Destinations.scala
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import jakarta.jms
+import org.apache.pekko.util.FunctionConverters._
+
+/**
+ * A destination to send to/receive from.
+ */
+sealed abstract class Destination {
+ val name: String
+ val create: jms.Session => jms.Destination
+}
+
+object Destination {
+
+ /**
+ * Create a [[Destination]] from a [[jakarta.jms.Destination]]
+ */
+ def apply(destination: jms.Destination): Destination = destination match {
+ case queue: jms.Queue => Queue(queue.getQueueName)
+ case topic: jms.Topic => Topic(topic.getTopicName)
+ case _ => CustomDestination(destination.toString, _ => destination)
+ }
+
+ /**
+ * Java API: Create a [[Destination]] from a [[jakarta.jms.Destination]]
+ */
+ def createDestination(destination: jms.Destination): Destination = apply(destination)
+}
+
+/**
+ * Specify a topic as destination to send to/receive from.
+ */
+final case class Topic(override val name: String) extends Destination {
+ override val create: jms.Session => jms.Destination = session => session.createTopic(name)
+}
+
+/**
+ * Specify a durable topic destination to send to/receive from.
+ */
+final case class DurableTopic(name: String, subscriberName: String) extends Destination {
+ override val create: jms.Session => jms.Destination = session => session.createTopic(name)
+}
+
+/**
+ * Specify a queue as destination to send to/receive from.
+ */
+final case class Queue(override val name: String) extends Destination {
+ override val create: jms.Session => jms.Destination = session => session.createQueue(name)
+}
+
+/**
+ * Destination factory to create specific destinations to send to/receive from.
+ */
+final case class CustomDestination(override val name: String, override val create: jms.Session => jms.Destination)
+ extends Destination {
+
+ /** Java API */
+ def this(name: String, create: java.util.function.Function[jms.Session, jms.Destination]) =
+ this(name, create.asScala)
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/Envelopes.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/Envelopes.scala
new file mode 100644
index 000000000..367b19037
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/Envelopes.scala
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import jakarta.jms
+import org.apache.pekko.stream.connectors.jakartams.impl.{ JmsAckSession, JmsSession }
+
+import java.util.concurrent.atomic.AtomicBoolean
+import scala.concurrent.{ Future, Promise }
+
+case class AckEnvelope private[jakartams] (message: jms.Message, private val jmsSession: JmsAckSession) {
+
+ val processed = new AtomicBoolean(false)
+
+ def acknowledge(): Unit = if (processed.compareAndSet(false, true)) jmsSession.ack(message)
+}
+
+case class TxEnvelope private[jakartams] (message: jms.Message, private val jmsSession: JmsSession) {
+
+ private[this] val commitPromise = Promise[() => Unit]()
+
+ private[jakartams] val commitFuture: Future[() => Unit] = commitPromise.future
+
+ def commit(): Unit = commitPromise.success(jmsSession.session.commit _)
+
+ def rollback(): Unit = commitPromise.success(jmsSession.session.rollback _)
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/Headers.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/Headers.scala
new file mode 100644
index 000000000..2e66e78c0
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/Headers.scala
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import java.util.concurrent.TimeUnit
+import scala.concurrent.duration.Duration
+
+sealed trait JmsHeader {
+
+ /**
+ * Indicates if this header must be set during the send() operation according to the JMS specification or as attribute of the jms message before.
+ */
+ def usedDuringSend: Boolean
+}
+
+final case class JmsCorrelationId(jmsCorrelationId: String) extends JmsHeader {
+ override val usedDuringSend = false
+}
+
+object JmsCorrelationId {
+
+ /**
+ * Java API: create [[JmsCorrelationId]]
+ */
+ def create(correlationId: String) = JmsCorrelationId(correlationId)
+}
+
+final case class JmsReplyTo(jmsDestination: Destination) extends JmsHeader {
+ override val usedDuringSend = false
+}
+
+object JmsReplyTo {
+
+ /**
+ * Reply to a queue with given name.
+ */
+ def queue(name: String) = JmsReplyTo(Queue(name))
+
+ /**
+ * Reply to a topic with given name.
+ */
+ def topic(name: String) = JmsReplyTo(Topic(name))
+}
+
+final case class JmsType(jmsType: String) extends JmsHeader {
+ override val usedDuringSend = false
+}
+
+object JmsType {
+
+ /**
+ * Java API: create [[JmsType]]
+ */
+ def create(jmsType: String) = JmsType(jmsType)
+}
+
+final case class JmsTimeToLive(timeInMillis: Long) extends JmsHeader {
+ override val usedDuringSend = true
+}
+
+object JmsTimeToLive {
+
+ /**
+ * Scala API: create [[JmsTimeToLive]]
+ */
+ def apply(timeToLive: Duration): JmsTimeToLive = JmsTimeToLive(timeToLive.toMillis)
+
+ /**
+ * Java API: create [[JmsTimeToLive]]
+ */
+ def create(timeToLive: Long, unit: TimeUnit) = JmsTimeToLive(unit.toMillis(timeToLive))
+}
+
+/**
+ * Priority of a message can be between 0 (lowest) and 9 (highest). The default priority is 4.
+ */
+final case class JmsPriority(priority: Int) extends JmsHeader {
+ override val usedDuringSend = true
+}
+
+object JmsPriority {
+
+ /**
+ * Java API: create [[JmsPriority]]
+ */
+ def create(priority: Int) = JmsPriority(priority)
+}
+
+/**
+ * Delivery mode can be [[jakarta.jms.DeliveryMode.NON_PERSISTENT]] or [[jakarta.jms.DeliveryMode.PERSISTENT]]
+ */
+final case class JmsDeliveryMode(deliveryMode: Int) extends JmsHeader {
+ override val usedDuringSend = true
+}
+
+object JmsDeliveryMode {
+
+ /**
+ * Java API: create [[JmsDeliveryMode]]
+ */
+ def create(deliveryMode: Int) = JmsDeliveryMode(deliveryMode)
+}
+
+final case class JmsMessageId(jmsMessageId: String) extends JmsHeader {
+ override val usedDuringSend: Boolean = false
+}
+
+object JmsMessageId {
+
+ /**
+ * Java API: create [[JmsMessageId]]
+ */
+ def create(messageId: String) = JmsMessageId(messageId)
+}
+
+final case class JmsTimestamp(jmsTimestamp: Long) extends JmsHeader {
+ override val usedDuringSend: Boolean = false
+}
+
+object JmsTimestamp {
+
+ /**
+ * Java API: create [[JmsTimestamp]]
+ */
+ def create(timestamp: Long) = JmsTimestamp(timestamp)
+}
+
+final case class JmsRedelivered(jmsRedelivered: Boolean) extends JmsHeader {
+ override val usedDuringSend: Boolean = false
+}
+
+object JmsRedelivered {
+
+ /**
+ * Java API: create [[JmsRedelivered]]
+ */
+ def create(redelivered: Boolean) = JmsRedelivered(redelivered)
+}
+
+final case class JmsExpiration(jmsExpiration: Long) extends JmsHeader {
+ override val usedDuringSend: Boolean = false
+}
+
+object JmsExpiration {
+
+ /**
+ * Java API: create [[JmsExpiration]]
+ */
+ def create(expiration: Long) = JmsExpiration(expiration)
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsBrowseSettings.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsBrowseSettings.scala
new file mode 100644
index 000000000..5b5a256fe
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsBrowseSettings.scala
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import com.typesafe.config.{ Config, ConfigValueType }
+import org.apache.pekko
+import pekko.actor.{ ActorSystem, ClassicActorSystemProvider }
+
+/**
+ * Settings for [[pekko.stream.connectors.jakartams.scaladsl.JmsConsumer.browse]] and [[pekko.stream.connectors.jakartams.javadsl.JmsConsumer.browse]].
+ */
+final class JmsBrowseSettings private (
+ val connectionFactory: jakarta.jms.ConnectionFactory,
+ val connectionRetrySettings: ConnectionRetrySettings,
+ val destination: Option[Destination],
+ val credentials: Option[Credentials],
+ val selector: Option[String],
+ val acknowledgeMode: AcknowledgeMode) {
+
+ /** Factory to use for creating JMS connections. */
+ def withConnectionFactory(value: jakarta.jms.ConnectionFactory): JmsBrowseSettings = copy(connectionFactory = value)
+
+ /** Configure connection retrying. */
+ def withConnectionRetrySettings(value: ConnectionRetrySettings): JmsBrowseSettings =
+ copy(connectionRetrySettings = value)
+
+ /** Set a queue name to browse from. */
+ def withQueue(name: String): JmsBrowseSettings = copy(destination = Some(Queue(name)))
+
+ /** Set a JMS to subscribe to. Allows for custom handling with [[pekko.stream.connectors.jakartams.CustomDestination CustomDestination]]. */
+ def withDestination(value: Destination): JmsBrowseSettings = copy(destination = Option(value))
+
+ /** Set JMS broker credentials. */
+ def withCredentials(value: Credentials): JmsBrowseSettings = copy(credentials = Option(value))
+
+ /**
+ * JMS selector expression.
+ *
+ * @see https://docs.oracle.com/cd/E19798-01/821-1841/bncer/index.html
+ */
+ def withSelector(value: String): JmsBrowseSettings = copy(selector = Option(value))
+
+ /** Set an explicit acknowledge mode. (Consumers have specific defaults.) */
+ def withAcknowledgeMode(value: AcknowledgeMode): JmsBrowseSettings = copy(acknowledgeMode = value)
+
+ private def copy(
+ connectionFactory: jakarta.jms.ConnectionFactory = connectionFactory,
+ connectionRetrySettings: ConnectionRetrySettings = connectionRetrySettings,
+ destination: Option[Destination] = destination,
+ credentials: Option[Credentials] = credentials,
+ selector: Option[String] = selector,
+ acknowledgeMode: AcknowledgeMode = acknowledgeMode): JmsBrowseSettings = new JmsBrowseSettings(
+ connectionFactory = connectionFactory,
+ connectionRetrySettings = connectionRetrySettings,
+ destination = destination,
+ credentials = credentials,
+ selector = selector,
+ acknowledgeMode = acknowledgeMode)
+
+ override def toString =
+ "JmsBrowseSettings(" +
+ s"connectionFactory=$connectionFactory," +
+ s"connectionRetrySettings=$connectionRetrySettings," +
+ s"destination=$destination," +
+ s"credentials=$credentials," +
+ s"selector=$selector," +
+ s"acknowledgeMode=${AcknowledgeMode.asString(acknowledgeMode)}" +
+ ")"
+}
+
+object JmsBrowseSettings {
+
+ val configPath = "pekko.connectors.jakartams.browse"
+
+ /**
+ * Reads from the given config.
+ *
+ * @param c Config instance read configuration from
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def apply(c: Config, connectionFactory: jakarta.jms.ConnectionFactory): JmsBrowseSettings = {
+ def getOption[A](path: String, read: Config => A): Option[A] =
+ if (c.hasPath(path) && (c.getValue(path).valueType() != ConfigValueType.STRING || c.getString(path) != "off"))
+ Some(read(c))
+ else None
+ def getStringOption(path: String): Option[String] =
+ if (c.hasPath(path) && c.getString(path).nonEmpty) Some(c.getString(path)) else None
+
+ val connectionRetrySettings = ConnectionRetrySettings(c.getConfig("connection-retry"))
+ val destination = None
+ val credentials = getOption("credentials", c => Credentials(c.getConfig("credentials")))
+ val selector = getStringOption("selector")
+ val acknowledgeMode = AcknowledgeMode.from(c.getString("acknowledge-mode"))
+ new JmsBrowseSettings(
+ connectionFactory,
+ connectionRetrySettings,
+ destination,
+ credentials,
+ selector,
+ acknowledgeMode)
+ }
+
+ /**
+ * Java API: Reads from the given config.
+ *
+ * @param c Config instance read configuration from
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def create(c: Config, connectionFactory: jakarta.jms.ConnectionFactory): JmsBrowseSettings =
+ apply(c, connectionFactory)
+
+ /**
+ * Reads from the default config provided by the actor system at `pekko.connectors.jakartams.browse`.
+ *
+ * @param actorSystem The actor system
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def apply(actorSystem: ActorSystem, connectionFactory: jakarta.jms.ConnectionFactory): JmsBrowseSettings =
+ apply(actorSystem.settings.config.getConfig(configPath), connectionFactory)
+
+ /**
+ * Reads from the default config provided by the actor system at `pekko.connectors.jakartams.browse`.
+ *
+ * @param actorSystem The actor system
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def apply(actorSystem: ClassicActorSystemProvider,
+ connectionFactory: jakarta.jms.ConnectionFactory): JmsBrowseSettings =
+ apply(actorSystem.classicSystem, connectionFactory)
+
+ /**
+ * Java API: Reads from the default config provided by the actor system at `pekko.connectors.jakartams.browse`.
+ *
+ * @param actorSystem The actor system
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def create(actorSystem: ActorSystem, connectionFactory: jakarta.jms.ConnectionFactory): JmsBrowseSettings =
+ apply(actorSystem, connectionFactory)
+
+ /**
+ * Java API: Reads from the default config provided by the actor system at `pekko.connectors.jakartams.browse`.
+ *
+ * @param actorSystem The actor system
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def create(actorSystem: ClassicActorSystemProvider,
+ connectionFactory: jakarta.jms.ConnectionFactory): JmsBrowseSettings =
+ apply(actorSystem.classicSystem, connectionFactory)
+
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsConsumerSettings.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsConsumerSettings.scala
new file mode 100644
index 000000000..71759af00
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsConsumerSettings.scala
@@ -0,0 +1,255 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import com.typesafe.config.{ Config, ConfigValueType }
+import org.apache.pekko
+import pekko.actor.{ ActorSystem, ClassicActorSystemProvider }
+import pekko.util.JavaDurationConverters._
+
+import scala.concurrent.duration.FiniteDuration
+
+/**
+ * Settings for [[pekko.stream.connectors.jakartams.scaladsl.JmsConsumer]] and [[pekko.stream.connectors.jakartams.javadsl.JmsConsumer]].
+ */
+final class JmsConsumerSettings private (
+ val connectionFactory: jakarta.jms.ConnectionFactory,
+ val connectionRetrySettings: ConnectionRetrySettings,
+ val destination: Option[Destination],
+ val credentials: Option[Credentials],
+ val sessionCount: Int,
+ val bufferSize: Int,
+ val selector: Option[String],
+ val acknowledgeMode: Option[AcknowledgeMode],
+ val ackTimeout: scala.concurrent.duration.Duration,
+ val maxAckInterval: Option[scala.concurrent.duration.FiniteDuration],
+ val maxPendingAcks: Int,
+ val failStreamOnAckTimeout: Boolean,
+ val connectionStatusSubscriptionTimeout: scala.concurrent.duration.FiniteDuration)
+ extends pekko.stream.connectors.jakartams.JmsSettings {
+
+ /** Factory to use for creating JMS connections. */
+ def withConnectionFactory(value: jakarta.jms.ConnectionFactory): JmsConsumerSettings = copy(connectionFactory = value)
+
+ /** Configure connection retrying. */
+ def withConnectionRetrySettings(value: ConnectionRetrySettings): JmsConsumerSettings =
+ copy(connectionRetrySettings = value)
+
+ /** Set a queue name to read from. */
+ def withQueue(name: String): JmsConsumerSettings = copy(destination = Some(Queue(name)))
+
+ /** Set a topic name to listen to. */
+ def withTopic(name: String): JmsConsumerSettings = copy(destination = Some(Topic(name)))
+
+ /** Set a durable topic name to listen to, with a unique subscriber name. */
+ def withDurableTopic(name: String, subscriberName: String): JmsConsumerSettings =
+ copy(destination = Some(DurableTopic(name, subscriberName)))
+
+ /** Set a JMS to subscribe to. Allows for custom handling with [[pekko.stream.connectors.jakartams.CustomDestination CustomDestination]]. */
+ def withDestination(value: Destination): JmsConsumerSettings = copy(destination = Option(value))
+
+ /** Set JMS broker credentials. */
+ def withCredentials(value: Credentials): JmsConsumerSettings = copy(credentials = Option(value))
+
+ /**
+ * Number of parallel sessions to use for receiving JMS messages.
+ */
+ def withSessionCount(value: Int): JmsConsumerSettings = copy(sessionCount = value)
+
+ /** Buffer size for maximum number for messages read from JMS when there is no demand. */
+ def withBufferSize(value: Int): JmsConsumerSettings = copy(bufferSize = value)
+
+ /**
+ * JMS selector expression.
+ *
+ * @see https://docs.oracle.com/cd/E19798-01/821-1841/bncer/index.html
+ */
+ def withSelector(value: String): JmsConsumerSettings = copy(selector = Option(value))
+
+ /** Set an explicit acknowledge mode. (Consumers have specific defaults.) */
+ def withAcknowledgeMode(value: AcknowledgeMode): JmsConsumerSettings = copy(acknowledgeMode = Option(value))
+
+ /** Timeout for acknowledge. (Used by TX consumers.) */
+ def withAckTimeout(value: scala.concurrent.duration.Duration): JmsConsumerSettings = copy(ackTimeout = value)
+
+ /** Java API: Timeout for acknowledge. (Used by TX consumers.) */
+ def withAckTimeout(value: java.time.Duration): JmsConsumerSettings = copy(ackTimeout = value.asScala)
+
+ /** Max interval before sending queued acknowledges back to the broker. (Used by AckSources.) */
+ def withMaxAckInterval(value: scala.concurrent.duration.FiniteDuration): JmsConsumerSettings =
+ copy(maxAckInterval = Option(value))
+
+ /** Java API: Max interval before sending queued acknowledges back to the broker. (Used by AckSources.) */
+ def withMaxAckInterval(value: java.time.Duration): JmsConsumerSettings =
+ copy(maxAckInterval = Option(value.asScala))
+
+ /** Max number of acks queued by AckSource before they are sent to broker. (Unless MaxAckInterval is specified) */
+ def withMaxPendingAcks(value: Int): JmsConsumerSettings = copy(maxPendingAcks = value)
+
+ /**
+ * For use with transactions, if true the stream fails if Pekko Connectors rolls back the transaction when `ackTimeout` is hit.
+ */
+ def withFailStreamOnAckTimeout(value: Boolean): JmsConsumerSettings =
+ if (failStreamOnAckTimeout == value) this else copy(failStreamOnAckTimeout = value)
+
+ /** Timeout for connection status subscriber */
+ def withConnectionStatusSubscriptionTimeout(value: FiniteDuration): JmsConsumerSettings =
+ copy(connectionStatusSubscriptionTimeout = value)
+
+ /** Java API: Timeout for connection status subscriber */
+ def withConnectionStatusSubscriptionTimeout(value: java.time.Duration): JmsConsumerSettings =
+ copy(connectionStatusSubscriptionTimeout = value.asScala)
+
+ private def copy(
+ connectionFactory: jakarta.jms.ConnectionFactory = connectionFactory,
+ connectionRetrySettings: ConnectionRetrySettings = connectionRetrySettings,
+ destination: Option[Destination] = destination,
+ credentials: Option[Credentials] = credentials,
+ sessionCount: Int = sessionCount,
+ bufferSize: Int = bufferSize,
+ selector: Option[String] = selector,
+ acknowledgeMode: Option[AcknowledgeMode] = acknowledgeMode,
+ ackTimeout: scala.concurrent.duration.Duration = ackTimeout,
+ maxAckInterval: Option[scala.concurrent.duration.FiniteDuration] = maxAckInterval,
+ maxPendingAcks: Int = maxPendingAcks,
+ failStreamOnAckTimeout: Boolean = failStreamOnAckTimeout,
+ connectionStatusSubscriptionTimeout: scala.concurrent.duration.FiniteDuration =
+ connectionStatusSubscriptionTimeout): JmsConsumerSettings = new JmsConsumerSettings(
+ connectionFactory = connectionFactory,
+ connectionRetrySettings = connectionRetrySettings,
+ destination = destination,
+ credentials = credentials,
+ sessionCount = sessionCount,
+ bufferSize = bufferSize,
+ selector = selector,
+ acknowledgeMode = acknowledgeMode,
+ ackTimeout = ackTimeout,
+ maxAckInterval = maxAckInterval,
+ maxPendingAcks = maxPendingAcks,
+ failStreamOnAckTimeout = failStreamOnAckTimeout,
+ connectionStatusSubscriptionTimeout = connectionStatusSubscriptionTimeout)
+
+ override def toString =
+ "JmsConsumerSettings(" +
+ s"connectionFactory=$connectionFactory," +
+ s"connectionRetrySettings=$connectionRetrySettings," +
+ s"destination=$destination," +
+ s"credentials=$credentials," +
+ s"sessionCount=$sessionCount," +
+ s"bufferSize=$bufferSize," +
+ s"selector=$selector," +
+ s"acknowledgeMode=${acknowledgeMode.map(m => AcknowledgeMode.asString(m))}," +
+ s"ackTimeout=${ackTimeout.toCoarsest}," +
+ s"maxAckInterval=${maxAckInterval.map(_.toCoarsest)}," +
+ s"maxPendingAcks=$maxPendingAcks," +
+ s"failStreamOnAckTimeout=$failStreamOnAckTimeout," +
+ s"connectionStatusSubscriptionTimeout=${connectionStatusSubscriptionTimeout.toCoarsest}" +
+ ")"
+}
+
+object JmsConsumerSettings {
+
+ val configPath = "pekko.connectors.jakartams.consumer"
+
+ /**
+ * Reads from the given config.
+ *
+ * @param c Config instance read configuration from
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def apply(c: Config, connectionFactory: jakarta.jms.ConnectionFactory): JmsConsumerSettings = {
+ def getOption[A](path: String, read: Config => A): Option[A] =
+ if (c.hasPath(path) && (c.getValue(path).valueType() != ConfigValueType.STRING || c.getString(path) != "off"))
+ Some(read(c))
+ else None
+
+ def getStringOption(path: String): Option[String] =
+ if (c.hasPath(path) && c.getString(path).nonEmpty) Some(c.getString(path)) else None
+
+ val connectionRetrySettings = ConnectionRetrySettings(c.getConfig("connection-retry"))
+ val destination = None
+ val credentials = getOption("credentials", c => Credentials(c.getConfig("credentials")))
+ val sessionCount = c.getInt("session-count")
+ val bufferSize = c.getInt("buffer-size")
+ val selector = getStringOption("selector")
+ val acknowledgeMode = getOption("acknowledge-mode", c => AcknowledgeMode.from(c.getString("acknowledge-mode")))
+ val ackTimeout = c.getDuration("ack-timeout").asScala
+ val maxAckIntervalDuration = getOption("max-ack-interval", config => config.getDuration("max-ack-interval").asScala)
+ val maxAckInterval = maxAckIntervalDuration.map(duration => FiniteDuration(duration.length, duration.unit))
+ val maxPendingAcks = c.getInt("max-pending-acks")
+ val failStreamOnAckTimeout = c.getBoolean("fail-stream-on-ack-timeout")
+ val connectionStatusSubscriptionTimeout = c.getDuration("connection-status-subscription-timeout").asScala
+ new JmsConsumerSettings(
+ connectionFactory,
+ connectionRetrySettings,
+ destination,
+ credentials,
+ sessionCount,
+ bufferSize,
+ selector,
+ acknowledgeMode,
+ ackTimeout,
+ maxAckInterval,
+ maxPendingAcks,
+ failStreamOnAckTimeout,
+ connectionStatusSubscriptionTimeout)
+ }
+
+ /**
+ * Reads from the default config provided by the actor system at `pekko.connectors.jakartams.consumer`.
+ *
+ * @param actorSystem The actor system
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def apply(actorSystem: ActorSystem, connectionFactory: jakarta.jms.ConnectionFactory): JmsConsumerSettings =
+ apply(actorSystem.settings.config.getConfig(configPath), connectionFactory)
+
+ /**
+ * Reads from the default config provided by the actor system at `pekko.connectors.jakartams.consumer`.
+ *
+ * @param actorSystem The actor system
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def apply(actorSystem: ClassicActorSystemProvider,
+ connectionFactory: jakarta.jms.ConnectionFactory): JmsConsumerSettings =
+ apply(actorSystem.classicSystem, connectionFactory)
+
+ /**
+ * Java API: Reads from the given config.
+ *
+ * @param c Config instance read configuration from
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def create(c: Config, connectionFactory: jakarta.jms.ConnectionFactory): JmsConsumerSettings =
+ apply(c, connectionFactory)
+
+ /**
+ * Java API: Reads from the default config provided by the actor system at `pekko.connectors.jakartams.consumer`.
+ *
+ * @param actorSystem The actor system
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def create(actorSystem: ActorSystem, connectionFactory: jakarta.jms.ConnectionFactory): JmsConsumerSettings =
+ apply(actorSystem, connectionFactory)
+
+ /**
+ * Java API: Reads from the default config provided by the actor system at `pekko.connectors.jakartams.consumer`.
+ *
+ * @param actorSystem The actor system
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def create(actorSystem: ClassicActorSystemProvider,
+ connectionFactory: jakarta.jms.ConnectionFactory): JmsConsumerSettings =
+ apply(actorSystem.classicSystem, connectionFactory)
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsExceptions.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsExceptions.scala
new file mode 100644
index 000000000..bc8ce15b9
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsExceptions.scala
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import jakarta.jms
+
+import scala.concurrent.TimeoutException
+import scala.concurrent.duration.Duration
+import scala.util.control.NoStackTrace
+
+/**
+ * Marker trait indicating that the exception thrown is persistent. The operation will always fail when retried.
+ */
+trait NonRetriableJmsException extends Exception
+
+case class UnsupportedMessagePropertyType(propertyName: String, propertyValue: Any, message: JmsEnvelope[_])
+ extends Exception(
+ s"Jms property '$propertyName' has unknown type '${propertyValue.getClass.getName}'. " +
+ "Only primitive types and String are supported as property values.")
+ with NonRetriableJmsException
+
+@deprecated("Not used anywhere", "Alpakka 3.0.4")
+case class NullMessageProperty(propertyName: String, message: JmsEnvelope[_])
+ extends Exception(
+ s"null value was given for Jms property '$propertyName'.")
+ with NonRetriableJmsException
+
+case class UnsupportedMapMessageEntryType(entryName: String, entryValue: Any, message: JmsMapMessagePassThrough[_])
+ extends Exception(
+ s"Jms MapMessage entry '$entryName' has unknown type '${entryValue.getClass.getName}'. " +
+ "Only primitive types, String, and Byte array are supported as entry values.")
+ with NonRetriableJmsException
+
+@deprecated("Not used anywhere", "Alpakka 3.0.4")
+case class NullMapMessageEntry(entryName: String, message: JmsMapMessagePassThrough[_])
+ extends Exception(
+ s"null value was given for Jms MapMessage entry '$entryName'.")
+ with NonRetriableJmsException
+
+case class UnsupportedMessageType(message: jms.Message)
+ extends Exception(
+ s"Can't convert a ${message.getClass.getName} to a JmsMessage")
+ with NonRetriableJmsException
+
+case class ConnectionRetryException(message: String, cause: Throwable) extends Exception(message, cause)
+
+case object RetrySkippedOnMissingConnection
+ extends Exception("JmsProducer is not connected, send attempt skipped")
+ with NoStackTrace
+
+case object JmsNotConnected extends Exception("JmsConnector is not connected") with NoStackTrace
+
+case class JmsConnectTimedOut(message: String) extends TimeoutException(message)
+
+final class JmsTxAckTimeout(ackTimeout: Duration)
+ extends TimeoutException(s"The TxEnvelope didn't get committed or rolled back within ack-timeout ($ackTimeout)")
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsMessages.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsMessages.scala
new file mode 100644
index 000000000..3913a5855
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsMessages.scala
@@ -0,0 +1,1023 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import jakarta.jms
+import org.apache.pekko
+import org.apache.pekko.NotUsed
+import org.apache.pekko.stream.connectors.jakartams.impl.JmsMessageReader._
+import org.apache.pekko.util.ByteString
+import org.apache.pekko.util.OptionConverters._
+import org.apache.pekko.util.ccompat.JavaConverters._
+
+/**
+ * Base interface for messages handled by JmsProducers. Sub-classes support pass-through or use [[pekko.NotUsed]] as type for pass-through.
+ *
+ * @tparam PassThrough the type of data passed through the `flexiFlow`
+ */
+sealed trait JmsEnvelope[+PassThrough] {
+ def headers: Set[JmsHeader]
+
+ /**
+ * Java API.
+ */
+ def getHeaders: java.util.Collection[JmsHeader] = headers.asJavaCollection
+
+ def properties: Map[String, Any]
+
+ /**
+ * Java API.
+ */
+ def getProperties: java.util.Map[String, Any] = properties.asJava
+
+ def destination: Option[Destination]
+
+ /**
+ * Java API.
+ */
+ def getDestination: java.util.Optional[Destination] = destination.toJava
+
+ def passThrough: PassThrough
+
+ /**
+ * Java API
+ */
+ def getPassThrough: PassThrough = passThrough
+}
+
+/**
+ * A stream element that does not produce a JMS message, but merely passes data through a `flexiFlow`.
+ *
+ * @param passThrough the data to pass through
+ * @tparam PassThrough the type of data passed through the `flexiFlow`
+ */
+final class JmsPassThrough[+PassThrough](val passThrough: PassThrough) extends JmsEnvelope[PassThrough] {
+ val properties: Map[String, Any] = Map.empty
+ val headers: Set[JmsHeader] = Set.empty
+ val destination: Option[Destination] = None
+}
+
+/**
+ * A stream element that does not produce a JMS message, but merely passes data through a `flexiFlow`.
+ */
+object JmsPassThrough {
+ def apply[PassThrough](passThrough: PassThrough): JmsEnvelope[PassThrough] =
+ new JmsPassThrough[PassThrough](passThrough)
+ def create[PassThrough](passThrough: PassThrough): JmsEnvelope[PassThrough] =
+ new JmsPassThrough[PassThrough](passThrough)
+}
+
+/**
+ * Marker trait for stream elements that contain pass-through data with properties.
+ */
+sealed trait JmsEnvelopeWithProperties[+PassThrough] extends JmsEnvelope[PassThrough] {
+ def withProperty(name: String, value: Any): JmsEnvelopeWithProperties[PassThrough]
+
+ def withProperties(props: Map[String, Any]): JmsEnvelopeWithProperties[PassThrough]
+
+ /**
+ * Java API.
+ */
+ def withProperties(properties: java.util.Map[String, Object]): JmsEnvelopeWithProperties[PassThrough]
+}
+
+/**
+ * Marker trait for stream elements that do not contain pass-through data.
+ */
+sealed trait JmsMessage extends JmsEnvelope[NotUsed] with JmsEnvelopeWithProperties[NotUsed] {
+
+ def withHeader(jmsHeader: JmsHeader): JmsMessage
+
+ def withHeaders(newHeaders: Set[JmsHeader]): JmsMessage
+
+ def withoutDestination: JmsMessage
+
+ def withProperty(name: String, value: Any): JmsMessage
+
+ def withProperties(props: Map[String, Any]): JmsMessage
+
+ /**
+ * Java API.
+ */
+ def withProperties(properties: java.util.Map[String, Object]): JmsMessage
+}
+
+object JmsMessage {
+
+ /**
+ * Convert a [[jakarta.jms.Message]] to a [[JmsEnvelope]] with pass-through
+ */
+ def apply[PassThrough](message: jms.Message, passThrough: PassThrough): JmsEnvelope[PassThrough] = message match {
+ case v: jms.BytesMessage => JmsByteMessage(v, passThrough)
+ case v: jms.MapMessage => JmsMapMessage(v, passThrough)
+ case v: jms.TextMessage => JmsTextMessage(v, passThrough)
+ case v: jms.ObjectMessage => JmsObjectMessage(v, passThrough)
+ case _ => throw UnsupportedMessageType(message)
+ }
+
+ /**
+ * Convert a [[jakarta.jms.Message]] to a [[JmsMessage]]
+ */
+ def apply(message: jms.Message): JmsMessage = message match {
+ case v: jms.BytesMessage => JmsByteMessage(v)
+ case v: jms.MapMessage => JmsMapMessage(v)
+ case v: jms.TextMessage => JmsTextMessage(v)
+ case v: jms.ObjectMessage => JmsObjectMessage(v)
+ case _ => throw UnsupportedMessageType(message)
+ }
+
+ /**
+ * Java API: Convert a [[jakarta.jms.Message]] to a [[JmsEnvelope]] with pass-through
+ */
+ def create[PassThrough](message: jms.Message, passThrough: PassThrough): JmsEnvelope[PassThrough] =
+ apply(message, passThrough)
+
+ /**
+ * Java API: Convert a [[jakarta.jms.Message]] to a [[JmsMessage]]
+ */
+ def create(message: jms.Message): JmsMessage = apply(message)
+}
+
+// Scala 2.11 compatibility adapter for the Java API
+object JmsMessageFactory {
+
+ /**
+ * Java API: Convert a [[jakarta.jms.Message]] to a [[JmsEnvelope]] with pass-through
+ */
+ def create[PassThrough](message: jms.Message, passThrough: PassThrough): JmsEnvelope[PassThrough] =
+ JmsMessage.apply(message, passThrough)
+
+ /**
+ * Java API: Convert a [[jakarta.jms.Message]] to a [[JmsMessage]]
+ */
+ def create(message: jms.Message): JmsMessage = JmsMessage.apply(message)
+}
+
+/**
+ * Produces byte arrays to JMS, supports pass-through data.
+ *
+ * @tparam PassThrough the type of data passed through the `flexiFlow`
+ */
+sealed class JmsByteMessagePassThrough[+PassThrough] protected[jakartams] (val bytes: Array[Byte],
+ val headers: Set[JmsHeader] = Set.empty,
+ val properties: Map[String, Any] = Map.empty,
+ val destination: Option[Destination] = None,
+ val passThrough: PassThrough)
+ extends JmsEnvelope[PassThrough]
+ with JmsEnvelopeWithProperties[PassThrough] {
+
+ /**
+ * Add a Jms header e.g. JMSType
+ */
+ def withHeader(jmsHeader: JmsHeader): JmsByteMessagePassThrough[PassThrough] = copy(headers = headers + jmsHeader)
+
+ /**
+ * Add a property
+ */
+ def withProperty(name: String, value: Any): JmsByteMessagePassThrough[PassThrough] =
+ copy(properties = properties + (name -> value))
+
+ def withProperties(props: Map[String, Any]): JmsByteMessagePassThrough[PassThrough] =
+ copy(properties = properties ++ props)
+
+ /**
+ * Java API.
+ */
+ def withProperties(map: java.util.Map[String, Object]): JmsByteMessagePassThrough[PassThrough] =
+ copy(properties = properties ++ map.asScala)
+
+ def toQueue(name: String): JmsByteMessagePassThrough[PassThrough] = to(Queue(name))
+
+ def toTopic(name: String): JmsByteMessagePassThrough[PassThrough] = to(Topic(name))
+
+ def to(destination: Destination): JmsByteMessagePassThrough[PassThrough] = copy(destination = Some(destination))
+
+ def withoutDestination: JmsByteMessagePassThrough[PassThrough] = copy(destination = None)
+
+ def withPassThrough[PassThrough2](passThrough: PassThrough2): JmsByteMessagePassThrough[PassThrough2] =
+ new JmsByteMessagePassThrough(
+ bytes,
+ headers,
+ properties,
+ destination,
+ passThrough)
+
+ private def copy(bytes: Array[Byte] = bytes,
+ headers: Set[JmsHeader] = headers,
+ properties: Map[String, Any] = properties,
+ destination: Option[Destination] = destination): JmsByteMessagePassThrough[PassThrough] =
+ new JmsByteMessagePassThrough[PassThrough](
+ bytes,
+ headers,
+ properties,
+ destination,
+ passThrough)
+}
+
+/**
+ * Produces byte arrays to JMS.
+ */
+final class JmsByteMessage private (bytes: Array[Byte],
+ headers: Set[JmsHeader] = Set.empty,
+ properties: Map[String, Any] = Map.empty,
+ destination: Option[Destination] = None)
+ extends JmsByteMessagePassThrough[NotUsed](bytes, headers, properties, destination, NotUsed)
+ with JmsMessage {
+
+ /**
+ * Add a Jms header e.g. JMSType
+ */
+ override def withHeader(jmsHeader: JmsHeader): JmsByteMessage = copy(headers = headers + jmsHeader)
+
+ override def withHeaders(newHeaders: Set[JmsHeader]): JmsByteMessage = copy(headers = headers ++ newHeaders)
+
+ /**
+ * Add a property
+ */
+ override def withProperty(name: String, value: Any): JmsByteMessage =
+ copy(properties = properties + (name -> value))
+
+ override def withProperties(props: Map[String, Any]): JmsByteMessage =
+ copy(properties = properties ++ props)
+
+ /**
+ * Java API.
+ */
+ override def withProperties(map: java.util.Map[String, Object]): JmsByteMessage =
+ copy(properties = properties ++ map.asScala)
+
+ override def toQueue(name: String): JmsByteMessage = to(Queue(name))
+
+ override def toTopic(name: String): JmsByteMessage = to(Topic(name))
+
+ override def to(destination: Destination): JmsByteMessage = copy(destination = Some(destination))
+
+ override def withoutDestination: JmsByteMessage = copy(destination = None)
+
+ private def copy(bytes: Array[Byte] = bytes,
+ headers: Set[JmsHeader] = headers,
+ properties: Map[String, Any] = properties,
+ destination: Option[Destination] = destination): JmsByteMessage =
+ new JmsByteMessage(
+ bytes,
+ headers,
+ properties,
+ destination)
+
+}
+
+/**
+ * Produces byte arrays to JMS.
+ */
+object JmsByteMessage {
+
+ /**
+ * create a byte message with pass-through
+ */
+ def apply[PassThrough](bytes: Array[Byte], passThrough: PassThrough): JmsByteMessagePassThrough[PassThrough] =
+ new JmsByteMessagePassThrough[PassThrough](bytes = bytes, passThrough = passThrough)
+
+ /**
+ * create a byte message
+ */
+ def apply(bytes: Array[Byte]) = new JmsByteMessage(bytes = bytes)
+
+ /**
+ * Java API: create a byte message with pass-through
+ */
+ def create[PassThrough](bytes: Array[Byte], passThrough: PassThrough): JmsByteMessagePassThrough[PassThrough] =
+ new JmsByteMessagePassThrough[PassThrough](bytes = bytes, passThrough = passThrough)
+
+ /**
+ * Java API: create [[JmsByteMessage]]
+ */
+ def create(bytes: Array[Byte]) = new JmsByteMessage(bytes = bytes)
+
+ /**
+ * Create a byte message from a [[jakarta.jms.BytesMessage]] with pass-through
+ */
+ def apply[PassThrough](message: jms.BytesMessage, passThrough: PassThrough): JmsByteMessagePassThrough[PassThrough] =
+ new JmsByteMessagePassThrough[PassThrough](readArray(message),
+ readHeaders(message),
+ readProperties(message),
+ Option(message.getJMSDestination).map(Destination(_)),
+ passThrough)
+
+ /**
+ * Create a byte message from a [[jakarta.jms.BytesMessage]]
+ */
+ def apply(message: jms.BytesMessage): JmsByteMessage =
+ new JmsByteMessage(readArray(message),
+ readHeaders(message),
+ readProperties(message),
+ Option(message.getJMSDestination).map(Destination(_)))
+
+ /**
+ * Java API: Create a byte message from a [[jakarta.jms.BytesMessage]] with pass-through
+ */
+ def create[PassThrough](message: jms.BytesMessage, passThrough: PassThrough): JmsByteMessagePassThrough[PassThrough] =
+ apply(message, passThrough)
+
+ /**
+ * Java API: Create a byte message from a [[jakarta.jms.BytesMessage]]
+ */
+ def create(message: jms.BytesMessage): JmsByteMessage = apply(message)
+}
+
+/**
+ * Produces byte array messages to JMS from the incoming `ByteString`, supports pass-through data.
+ *
+ * @tparam PassThrough the type of data passed through the `flexiFlow`
+ */
+sealed class JmsByteStringMessagePassThrough[+PassThrough] protected[jakartams] (val bytes: ByteString,
+ val headers: Set[JmsHeader] = Set.empty,
+ val properties: Map[String, Any] = Map.empty,
+ val destination: Option[Destination] = None,
+ val passThrough: PassThrough)
+ extends JmsEnvelope[PassThrough]
+ with JmsEnvelopeWithProperties[PassThrough] {
+
+ /**
+ * Add a Jms header e.g. JMSType
+ */
+ def withHeader(jmsHeader: JmsHeader): JmsByteStringMessagePassThrough[PassThrough] =
+ copy(headers = headers + jmsHeader)
+
+ /**
+ * Add a property
+ */
+ def withProperty(name: String, value: Any): JmsByteStringMessagePassThrough[PassThrough] =
+ copy(properties = properties + (name -> value))
+
+ def withProperties(props: Map[String, Any]): JmsByteStringMessagePassThrough[PassThrough] =
+ copy(properties = properties ++ props)
+
+ /**
+ * Java API
+ */
+ def withProperties(props: java.util.Map[String, Object]): JmsByteStringMessagePassThrough[PassThrough] =
+ copy(properties = properties ++ props.asScala)
+
+ def toQueue(name: String): JmsByteStringMessagePassThrough[PassThrough] = to(Queue(name))
+
+ def toTopic(name: String): JmsByteStringMessagePassThrough[PassThrough] = to(Topic(name))
+
+ def to(destination: Destination): JmsByteStringMessagePassThrough[PassThrough] = copy(destination = Some(destination))
+
+ def withoutDestination: JmsByteStringMessagePassThrough[PassThrough] = copy(destination = None)
+
+ def withPassThrough[PassThrough2](passThrough: PassThrough2): JmsByteStringMessagePassThrough[PassThrough2] =
+ new JmsByteStringMessagePassThrough(
+ bytes,
+ headers,
+ properties,
+ destination,
+ passThrough)
+
+ private def copy(bytes: ByteString = bytes,
+ headers: Set[JmsHeader] = headers,
+ properties: Map[String, Any] = properties,
+ destination: Option[Destination] = destination): JmsByteStringMessagePassThrough[PassThrough] =
+ new JmsByteStringMessagePassThrough(
+ bytes,
+ headers,
+ properties,
+ destination,
+ passThrough)
+
+}
+
+/**
+ * Produces byte array messages to JMS from the incoming `ByteString`.
+ */
+final class JmsByteStringMessage private (bytes: ByteString,
+ headers: Set[JmsHeader] = Set.empty,
+ properties: Map[String, Any] = Map.empty,
+ destination: Option[Destination] = None)
+ extends JmsByteStringMessagePassThrough[NotUsed](bytes, headers, properties, destination, NotUsed)
+ with JmsMessage {
+
+ /**
+ * Add a Jms header e.g. JMSType
+ */
+ override def withHeader(jmsHeader: JmsHeader): JmsByteStringMessage = copy(headers = headers + jmsHeader)
+
+ override def withHeaders(newHeaders: Set[JmsHeader]): JmsByteStringMessage = copy(headers = headers ++ newHeaders)
+
+ /**
+ * Add a property
+ */
+ override def withProperty(name: String, value: Any): JmsByteStringMessage =
+ copy(properties = properties + (name -> value))
+
+ override def withProperties(props: Map[String, Any]): JmsByteStringMessage =
+ copy(properties = properties ++ props)
+
+ /**
+ * Java API.
+ */
+ override def withProperties(map: java.util.Map[String, Object]): JmsByteStringMessage =
+ copy(properties = properties ++ map.asScala)
+
+ override def toQueue(name: String): JmsByteStringMessage = to(Queue(name))
+
+ override def toTopic(name: String): JmsByteStringMessage = to(Topic(name))
+
+ override def to(destination: Destination): JmsByteStringMessage = copy(destination = Some(destination))
+
+ override def withoutDestination: JmsByteStringMessage = copy(destination = None)
+
+ private def copy(bytes: ByteString = bytes,
+ headers: Set[JmsHeader] = headers,
+ properties: Map[String, Any] = properties,
+ destination: Option[Destination] = destination): JmsByteStringMessage =
+ new JmsByteStringMessage(
+ bytes,
+ headers,
+ properties,
+ destination)
+
+}
+
+/**
+ * Produces byte array messages to JMS from the incoming `ByteString`.
+ */
+object JmsByteStringMessage {
+
+ /**
+ * Create a byte message from a ByteString with a pass-through attached
+ */
+ def apply[PassThrough](byteString: ByteString,
+ passThrough: PassThrough): JmsByteStringMessagePassThrough[PassThrough] =
+ new JmsByteStringMessagePassThrough[PassThrough](byteString, passThrough = passThrough)
+
+ /**
+ * Create a byte message from a ByteString
+ */
+ def apply(byteString: ByteString) = new JmsByteStringMessage(byteString)
+
+ /**
+ * Java API: Create a byte message from a ByteString with a pass-through attached
+ */
+ def create[PassThrough](byteString: ByteString,
+ passThrough: PassThrough): JmsByteStringMessagePassThrough[PassThrough] =
+ new JmsByteStringMessagePassThrough[PassThrough](byteString, passThrough = passThrough)
+
+ /**
+ * Java API: Create a byte message from a ByteString
+ */
+ def create(byteString: ByteString) = apply(byteString)
+
+ /**
+ * Create a byte message from a [[jakarta.jms.BytesMessage]] with pass-through
+ */
+ def apply[PassThrough](message: jms.BytesMessage,
+ passThrough: PassThrough): JmsByteStringMessagePassThrough[PassThrough] =
+ new JmsByteStringMessagePassThrough[PassThrough](readBytes(message),
+ readHeaders(message),
+ readProperties(message),
+ Option(message.getJMSDestination).map(Destination(_)),
+ passThrough)
+
+ /**
+ * Create a byte message from a [[jakarta.jms.BytesMessage]]
+ */
+ def apply(message: jms.BytesMessage): JmsByteStringMessage =
+ new JmsByteStringMessage(readBytes(message),
+ readHeaders(message),
+ readProperties(message),
+ Option(message.getJMSDestination).map(Destination(_)))
+
+ /**
+ * Java API: Create a byte message from a [[jakarta.jms.BytesMessage]] with pass-through
+ */
+ def create[PassThrough](message: jms.BytesMessage,
+ passThrough: PassThrough): JmsByteStringMessagePassThrough[PassThrough] =
+ apply(message, passThrough)
+
+ /**
+ * Java API: Create a byte message from a [[jakarta.jms.BytesMessage]]
+ */
+ def create(message: jms.BytesMessage): JmsByteStringMessage = apply(message)
+
+}
+
+/**
+ * Produces map messages to JMS, supports pass-through data.
+ *
+ * @tparam PassThrough the type of data passed through the `flexiFlow`
+ */
+sealed class JmsMapMessagePassThrough[+PassThrough] protected[jakartams] (val body: Map[String, Any],
+ val headers: Set[JmsHeader] = Set.empty,
+ val properties: Map[String, Any] = Map.empty,
+ val destination: Option[Destination] = None,
+ val passThrough: PassThrough)
+ extends JmsEnvelope[PassThrough]
+ with JmsEnvelopeWithProperties[PassThrough] {
+
+ /**
+ * Add a Jms header e.g. JMSType
+ */
+ def withHeader(jmsHeader: JmsHeader): JmsMapMessagePassThrough[PassThrough] = copy(headers = headers + jmsHeader)
+
+ /**
+ * Add a property
+ */
+ def withProperty(name: String, value: Any): JmsMapMessagePassThrough[PassThrough] =
+ copy(properties = properties + (name -> value))
+
+ def withProperties(props: Map[String, Any]): JmsMapMessagePassThrough[PassThrough] =
+ copy(properties = properties ++ props)
+
+ def withProperties(props: java.util.Map[String, Object]): JmsMapMessagePassThrough[PassThrough] =
+ copy(properties = properties ++ props.asScala)
+
+ def toQueue(name: String): JmsMapMessagePassThrough[PassThrough] = to(Queue(name))
+
+ def toTopic(name: String): JmsMapMessagePassThrough[PassThrough] = to(Topic(name))
+
+ def to(destination: Destination): JmsMapMessagePassThrough[PassThrough] = copy(destination = Some(destination))
+
+ def withoutDestination: JmsMapMessagePassThrough[PassThrough] = copy(destination = None)
+
+ def withPassThrough[PassThrough2](passThrough: PassThrough2): JmsMapMessagePassThrough[PassThrough2] =
+ new JmsMapMessagePassThrough(
+ body,
+ headers,
+ properties,
+ destination,
+ passThrough)
+
+ private def copy(body: Map[String, Any] = body,
+ headers: Set[JmsHeader] = headers,
+ properties: Map[String, Any] = properties,
+ destination: Option[Destination] = destination): JmsMapMessagePassThrough[PassThrough] =
+ new JmsMapMessagePassThrough(
+ body,
+ headers,
+ properties,
+ destination,
+ passThrough)
+
+}
+
+/**
+ * Produces map messages to JMS.
+ */
+final class JmsMapMessage(body: Map[String, Any],
+ headers: Set[JmsHeader] = Set.empty,
+ properties: Map[String, Any] = Map.empty,
+ destination: Option[Destination] = None)
+ extends JmsMapMessagePassThrough[NotUsed](body, headers, properties, destination, NotUsed)
+ with JmsMessage {
+
+ /**
+ * Add a Jms header e.g. JMSType
+ */
+ override def withHeader(jmsHeader: JmsHeader): JmsMapMessage = copy(headers = headers + jmsHeader)
+
+ override def withHeaders(newHeaders: Set[JmsHeader]): JmsMapMessage = copy(headers = headers ++ newHeaders)
+
+ /**
+ * Add a property
+ */
+ override def withProperty(name: String, value: Any): JmsMapMessage =
+ copy(properties = properties + (name -> value))
+
+ override def withProperties(props: Map[String, Any]): JmsMapMessage =
+ copy(properties = properties ++ props)
+
+ /**
+ * Java API.
+ */
+ override def withProperties(map: java.util.Map[String, Object]): JmsMapMessage =
+ copy(properties = properties ++ map.asScala)
+
+ override def toQueue(name: String): JmsMapMessage = to(Queue(name))
+
+ override def toTopic(name: String): JmsMapMessage = to(Topic(name))
+
+ override def to(destination: Destination): JmsMapMessage = copy(destination = Some(destination))
+
+ override def withoutDestination: JmsMapMessage = copy(destination = None)
+
+ private def copy(body: Map[String, Any] = body,
+ headers: Set[JmsHeader] = headers,
+ properties: Map[String, Any] = properties,
+ destination: Option[Destination] = destination): JmsMapMessage =
+ new JmsMapMessage(
+ body,
+ headers,
+ properties,
+ destination)
+
+}
+
+/**
+ * Produces map messages to JMS.
+ */
+object JmsMapMessage {
+
+ /**
+ * create a map message with a pass-through attached
+ */
+ def apply[PassThrough](map: Map[String, Any], passThrough: PassThrough): JmsMapMessagePassThrough[PassThrough] =
+ new JmsMapMessagePassThrough[PassThrough](body = map, passThrough = passThrough)
+
+ /**
+ * create a map message
+ */
+ def apply(map: Map[String, Any]) = new JmsMapMessage(body = map)
+
+ /**
+ * Java API: create a map message with a pass-through attached
+ */
+ def create[PassThrough](map: java.util.Map[String, Any],
+ passThrough: PassThrough): JmsMapMessagePassThrough[PassThrough] =
+ new JmsMapMessagePassThrough[PassThrough](body = map.asScala.toMap, passThrough = passThrough)
+
+ /**
+ * Java API: create map message
+ */
+ def create(map: java.util.Map[String, Any]) = new JmsMapMessage(body = map.asScala.toMap)
+
+ /**
+ * Create a map message from a [[jakarta.jms.MapMessage]] with pass-through
+ */
+ def apply[PassThrough](message: jms.MapMessage, passThrough: PassThrough): JmsMapMessagePassThrough[PassThrough] =
+ new JmsMapMessagePassThrough[PassThrough](readMap(message),
+ readHeaders(message),
+ readProperties(message),
+ Option(message.getJMSDestination).map(Destination(_)),
+ passThrough)
+
+ /**
+ * Create a map message from a [[jakarta.jms.MapMessage]]
+ */
+ def apply(message: jms.MapMessage): JmsMapMessage =
+ new JmsMapMessage(readMap(message),
+ readHeaders(message),
+ readProperties(message),
+ Option(message.getJMSDestination).map(Destination(_)))
+
+ /**
+ * Java API: Create a map message from a [[jakarta.jms.MapMessage]] with pass-through
+ */
+ def create[PassThrough](message: jms.MapMessage, passThrough: PassThrough): JmsMapMessagePassThrough[PassThrough] =
+ apply(message, passThrough)
+
+ /**
+ * Java API: Create a map message from a [[jakarta.jms.MapMessage]]
+ */
+ def create(message: jms.MapMessage): JmsMapMessage = apply(message)
+}
+
+/**
+ * Produces text messages to JMS, supports pass-through data.
+ *
+ * @tparam PassThrough the type of data passed through the `flexiFlow`
+ */
+sealed class JmsTextMessagePassThrough[+PassThrough] protected[jakartams] (val body: String,
+ val headers: Set[JmsHeader] = Set.empty,
+ val properties: Map[String, Any] = Map.empty,
+ val destination: Option[Destination] = None,
+ val passThrough: PassThrough)
+ extends JmsEnvelope[PassThrough]
+ with JmsEnvelopeWithProperties[PassThrough] {
+
+ /**
+ * Add a Jms header e.g. JMSType
+ */
+ def withHeader(jmsHeader: JmsHeader): JmsTextMessagePassThrough[PassThrough] = copy(headers = headers + jmsHeader)
+
+ /**
+ * Add a property
+ */
+ def withProperty(name: String, value: Any): JmsTextMessagePassThrough[PassThrough] =
+ copy(properties = properties + (name -> value))
+
+ def withProperties(props: Map[String, Any]): JmsTextMessagePassThrough[PassThrough] =
+ copy(properties = properties ++ props)
+
+ /**
+ * Java API
+ */
+ def withProperties(props: java.util.Map[String, Object]): JmsTextMessagePassThrough[PassThrough] =
+ copy(properties = properties ++ props.asScala)
+
+ def toQueue(name: String): JmsTextMessagePassThrough[PassThrough] = to(Queue(name))
+
+ def toTopic(name: String): JmsTextMessagePassThrough[PassThrough] = to(Topic(name))
+
+ def to(destination: Destination): JmsTextMessagePassThrough[PassThrough] = copy(destination = Some(destination))
+
+ def withoutDestination: JmsTextMessagePassThrough[PassThrough] = copy(destination = None)
+
+ def withPassThrough[PassThrough2](passThrough: PassThrough2): JmsTextMessagePassThrough[PassThrough2] =
+ new JmsTextMessagePassThrough(
+ body,
+ headers,
+ properties,
+ destination,
+ passThrough)
+
+ private def copy(body: String = body,
+ headers: Set[JmsHeader] = headers,
+ properties: Map[String, Any] = properties,
+ destination: Option[Destination] = destination): JmsTextMessagePassThrough[PassThrough] =
+ new JmsTextMessagePassThrough[PassThrough](
+ body,
+ headers,
+ properties,
+ destination,
+ passThrough)
+
+}
+
+/**
+ * Produces text messages to JMS.
+ */
+final class JmsTextMessage private (body: String,
+ headers: Set[JmsHeader] = Set.empty,
+ properties: Map[String, Any] = Map.empty,
+ destination: Option[Destination] = None)
+ extends JmsTextMessagePassThrough[NotUsed](body, headers, properties, destination, NotUsed)
+ with JmsMessage {
+
+ /**
+ * Add a Jms header e.g. JMSType
+ */
+ override def withHeader(jmsHeader: JmsHeader): JmsTextMessage = copy(headers = headers + jmsHeader)
+
+ override def withHeaders(newHeaders: Set[JmsHeader]): JmsTextMessage = copy(headers = headers ++ newHeaders)
+
+ /**
+ * Add a property
+ */
+ override def withProperty(name: String, value: Any): JmsTextMessage = copy(properties = properties + (name -> value))
+
+ override def withProperties(props: Map[String, Any]): JmsTextMessage =
+ copy(properties = properties ++ props)
+
+ /**
+ * Java API.
+ */
+ override def withProperties(map: java.util.Map[String, Object]): JmsTextMessage =
+ copy(properties = properties ++ map.asScala)
+
+ override def toQueue(name: String): JmsTextMessage = to(Queue(name))
+
+ override def toTopic(name: String): JmsTextMessage = to(Topic(name))
+
+ override def to(destination: Destination): JmsTextMessage = copy(destination = Some(destination))
+
+ override def withoutDestination: JmsTextMessage = copy(destination = None)
+
+ private def copy(body: String = body,
+ headers: Set[JmsHeader] = headers,
+ properties: Map[String, Any] = properties,
+ destination: Option[Destination] = destination): JmsTextMessage = new JmsTextMessage(
+ body,
+ headers,
+ properties,
+ destination)
+
+}
+
+/**
+ * Produces text messages to JMS.
+ */
+object JmsTextMessage {
+
+ /**
+ * Create a text message with a pass-through attached
+ */
+ def apply[PassThrough](body: String, passThrough: PassThrough): JmsTextMessagePassThrough[PassThrough] =
+ new JmsTextMessagePassThrough(body = body, passThrough = passThrough)
+
+ /**
+ * Create a text message
+ */
+ def apply(body: String): JmsTextMessage = new JmsTextMessage(body = body)
+
+ /**
+ * Java API: Create a text message with a pass-through attached
+ */
+ def create[PassThrough](body: String, passThrough: PassThrough): JmsTextMessagePassThrough[PassThrough] =
+ new JmsTextMessagePassThrough(body = body, passThrough = passThrough)
+
+ /**
+ * Java API: create a text message
+ */
+ def create(body: String): JmsTextMessage = new JmsTextMessage(body = body)
+
+ /**
+ * Create a text message from a [[jakarta.jms.TextMessage]] with pass-through
+ */
+ def apply[PassThrough](message: jms.TextMessage, passThrough: PassThrough): JmsTextMessagePassThrough[PassThrough] =
+ new JmsTextMessagePassThrough[PassThrough](message.getText,
+ readHeaders(message),
+ readProperties(message),
+ Option(message.getJMSDestination).map(Destination(_)),
+ passThrough)
+
+ /**
+ * Create a text message from a [[jakarta.jms.TextMessage]]
+ */
+ def apply(message: jms.TextMessage): JmsTextMessage =
+ new JmsTextMessage(message.getText,
+ readHeaders(message),
+ readProperties(message),
+ Option(message.getJMSDestination).map(Destination(_)))
+
+ /**
+ * Java API: Create a text message from a [[jakarta.jms.TextMessage]] with pass-through
+ */
+ def create[PassThrough](message: jms.TextMessage, passThrough: PassThrough): JmsTextMessagePassThrough[PassThrough] =
+ apply(message, passThrough)
+
+ /**
+ * Java API: Create a text message from a [[jakarta.jms.TextMessage]]
+ */
+ def create(message: jms.TextMessage): JmsTextMessage = apply(message)
+}
+
+/**
+ * Produces object messages to JMS, supports pass-through data.
+ *
+ * @tparam PassThrough the type of data passed through the `flexiFlow`
+ */
+sealed class JmsObjectMessagePassThrough[+PassThrough] protected[jakartams] (val serializable: java.io.Serializable,
+ val headers: Set[JmsHeader] = Set.empty,
+ val properties: Map[String, Any] = Map.empty,
+ val destination: Option[Destination] = None,
+ val passThrough: PassThrough)
+ extends JmsEnvelope[PassThrough] {
+
+ /**
+ * Add a Jms header e.g. JMSType
+ */
+ def withHeader(jmsHeader: JmsHeader): JmsObjectMessagePassThrough[PassThrough] = copy(headers = headers + jmsHeader)
+
+ /**
+ * Add a property
+ */
+ def withProperty(name: String, value: Any): JmsObjectMessagePassThrough[PassThrough] =
+ copy(properties = properties + (name -> value))
+
+ def withProperties(props: Map[String, Any]): JmsObjectMessagePassThrough[PassThrough] =
+ copy(properties = properties ++ props)
+
+ def toQueue(name: String): JmsObjectMessagePassThrough[PassThrough] = to(Queue(name))
+
+ def toTopic(name: String): JmsObjectMessagePassThrough[PassThrough] = to(Topic(name))
+
+ def to(destination: Destination): JmsObjectMessagePassThrough[PassThrough] = copy(destination = Some(destination))
+
+ def withoutDestination: JmsObjectMessagePassThrough[PassThrough] = copy(destination = None)
+
+ def withPassThrough[PassThrough2](passThrough: PassThrough2): JmsObjectMessagePassThrough[PassThrough2] =
+ new JmsObjectMessagePassThrough(
+ serializable,
+ headers,
+ properties,
+ destination,
+ passThrough)
+
+ private def copy(serializable: java.io.Serializable = serializable,
+ headers: Set[JmsHeader] = headers,
+ properties: Map[String, Any] = properties,
+ destination: Option[Destination] = destination): JmsObjectMessagePassThrough[PassThrough] =
+ new JmsObjectMessagePassThrough(
+ serializable,
+ headers,
+ properties,
+ destination,
+ passThrough)
+
+}
+
+/**
+ * Produces object messages to JMS.
+ */
+final class JmsObjectMessage private (serializable: java.io.Serializable,
+ headers: Set[JmsHeader] = Set.empty,
+ properties: Map[String, Any] = Map.empty,
+ destination: Option[Destination] = None)
+ extends JmsObjectMessagePassThrough[NotUsed](serializable, headers, properties, destination, NotUsed)
+ with JmsMessage {
+
+ /**
+ * Add a Jms header e.g. JMSType
+ */
+ override def withHeader(jmsHeader: JmsHeader): JmsObjectMessage = copy(headers = headers + jmsHeader)
+
+ override def withHeaders(newHeaders: Set[JmsHeader]): JmsObjectMessage = copy(headers = headers ++ newHeaders)
+
+ /**
+ * Add a property
+ */
+ override def withProperty(name: String, value: Any): JmsObjectMessage =
+ copy(properties = properties + (name -> value))
+
+ override def withProperties(props: Map[String, Any]): JmsObjectMessage =
+ copy(properties = properties ++ props)
+
+ /**
+ * Java API.
+ */
+ override def withProperties(map: java.util.Map[String, Object]): JmsObjectMessage =
+ copy(properties = properties ++ map.asScala)
+
+ override def toQueue(name: String): JmsObjectMessage = to(Queue(name))
+
+ override def toTopic(name: String): JmsObjectMessage = to(Topic(name))
+
+ override def to(destination: Destination): JmsObjectMessage = copy(destination = Some(destination))
+
+ override def withoutDestination: JmsObjectMessage = copy(destination = None)
+
+ private def copy(serializable: java.io.Serializable = serializable,
+ headers: Set[JmsHeader] = headers,
+ properties: Map[String, Any] = properties,
+ destination: Option[Destination] = destination): JmsObjectMessage =
+ new JmsObjectMessage(
+ serializable,
+ headers,
+ properties,
+ destination)
+
+}
+
+/**
+ * Produces object messages to JMS.
+ */
+object JmsObjectMessage {
+
+ /**
+ * create an object message with a pass-through attached
+ */
+ def apply[PassThrough](serializable: java.io.Serializable,
+ passThrough: PassThrough): JmsObjectMessagePassThrough[PassThrough] =
+ new JmsObjectMessagePassThrough[PassThrough](serializable, passThrough = passThrough)
+
+ /**
+ * create an object message
+ */
+ def apply(serializable: java.io.Serializable) = new JmsObjectMessage(serializable)
+
+ /**
+ * Java API: create an object message with a pass-through attached
+ */
+ def create[PassThrough](serializable: java.io.Serializable,
+ passThrough: PassThrough): JmsObjectMessagePassThrough[PassThrough] =
+ new JmsObjectMessagePassThrough[PassThrough](serializable, passThrough = passThrough)
+
+ /**
+ * Java API: create an object message
+ */
+ def create(serializable: Serializable) = new JmsObjectMessage(serializable)
+
+ /**
+ * Create an object message with pass-through
+ */
+ def apply[PassThrough](message: jms.ObjectMessage,
+ passThrough: PassThrough): JmsObjectMessagePassThrough[PassThrough] =
+ new JmsObjectMessagePassThrough[PassThrough](message.getObject,
+ readHeaders(message),
+ readProperties(message),
+ Option(message.getJMSDestination).map(Destination(_)),
+ passThrough)
+
+ /**
+ * Create an object message
+ */
+ def apply(message: jms.ObjectMessage): JmsObjectMessage =
+ new JmsObjectMessage(message.getObject,
+ readHeaders(message),
+ readProperties(message),
+ Option(message.getJMSDestination).map(Destination(_)))
+
+ /**
+ * Java API: Create an object message with pass-through
+ */
+ def create[PassThrough](message: jms.ObjectMessage,
+ passThrough: PassThrough): JmsObjectMessagePassThrough[PassThrough] =
+ apply(message, passThrough)
+
+ /**
+ * Java API: Create an object message
+ */
+ def create(message: jms.ObjectMessage): JmsObjectMessage = apply(message)
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsProducerSettings.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsProducerSettings.scala
new file mode 100644
index 000000000..be0ed9764
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsProducerSettings.scala
@@ -0,0 +1,199 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import com.typesafe.config.{ Config, ConfigValueType }
+import org.apache.pekko
+import pekko.actor.{ ActorSystem, ClassicActorSystemProvider }
+import pekko.util.JavaDurationConverters._
+
+import scala.concurrent.duration.FiniteDuration
+
+/**
+ * Settings for [[pekko.stream.connectors.jakartams.scaladsl.JmsProducer]] and [[pekko.stream.connectors.jakartams.javadsl.JmsProducer]].
+ */
+final class JmsProducerSettings private (
+ val connectionFactory: jakarta.jms.ConnectionFactory,
+ val connectionRetrySettings: ConnectionRetrySettings,
+ val sendRetrySettings: SendRetrySettings,
+ val destination: Option[Destination],
+ val credentials: Option[Credentials],
+ val sessionCount: Int,
+ val timeToLive: Option[scala.concurrent.duration.Duration],
+ val connectionStatusSubscriptionTimeout: scala.concurrent.duration.FiniteDuration)
+ extends pekko.stream.connectors.jakartams.JmsSettings {
+
+ /** Factory to use for creating JMS connections. */
+ def withConnectionFactory(value: jakarta.jms.ConnectionFactory): JmsProducerSettings = copy(connectionFactory = value)
+
+ /** Configure connection retrying. */
+ def withConnectionRetrySettings(value: ConnectionRetrySettings): JmsProducerSettings =
+ copy(connectionRetrySettings = value)
+
+ /** Configure re-sending. */
+ def withSendRetrySettings(value: SendRetrySettings): JmsProducerSettings = copy(sendRetrySettings = value)
+
+ /** Set a queue name as JMS destination. */
+ def withQueue(name: String): JmsProducerSettings = copy(destination = Some(Queue(name)))
+
+ /** Set a topic name as JMS destination. */
+ def withTopic(name: String): JmsProducerSettings = copy(destination = Some(Topic(name)))
+
+ /** Set a JMS destination. Allows for custom handling with [[pekko.stream.connectors.jakartams.CustomDestination CustomDestination]]. */
+ def withDestination(value: Destination): JmsProducerSettings = copy(destination = Option(value))
+
+ /** Set JMS broker credentials. */
+ def withCredentials(value: Credentials): JmsProducerSettings = copy(credentials = Option(value))
+
+ /**
+ * Number of parallel sessions to use for sending JMS messages.
+ * Increasing the number of parallel sessions increases throughput at the cost of message ordering.
+ * While the messages may arrive out of order on the JMS broker, the producer flow outputs messages
+ * in the order they are received.
+ */
+ def withSessionCount(value: Int): JmsProducerSettings = copy(sessionCount = value)
+
+ /**
+ * Time messages should be kept on the JMS broker. This setting can be overridden on
+ * individual messages. If not set, messages will never expire.
+ */
+ def withTimeToLive(value: scala.concurrent.duration.Duration): JmsProducerSettings = copy(timeToLive = Option(value))
+
+ /**
+ * Java API: Time messages should be kept on the JMS broker. This setting can be overridden on
+ * individual messages. If not set, messages will never expire.
+ */
+ def withTimeToLive(value: java.time.Duration): JmsProducerSettings = copy(timeToLive = Option(value).map(_.asScala))
+
+ /** Timeout for connection status subscriber */
+ def withConnectionStatusSubscriptionTimeout(value: FiniteDuration): JmsProducerSettings =
+ copy(connectionStatusSubscriptionTimeout = value)
+
+ /** Java API: Timeout for connection status subscriber */
+ def withConnectionStatusSubscriptionTimeout(value: java.time.Duration): JmsProducerSettings =
+ copy(connectionStatusSubscriptionTimeout = value.asScala)
+
+ private def copy(
+ connectionFactory: jakarta.jms.ConnectionFactory = connectionFactory,
+ connectionRetrySettings: ConnectionRetrySettings = connectionRetrySettings,
+ sendRetrySettings: SendRetrySettings = sendRetrySettings,
+ destination: Option[Destination] = destination,
+ credentials: Option[Credentials] = credentials,
+ sessionCount: Int = sessionCount,
+ timeToLive: Option[scala.concurrent.duration.Duration] = timeToLive,
+ connectionStatusSubscriptionTimeout: scala.concurrent.duration.FiniteDuration =
+ connectionStatusSubscriptionTimeout): JmsProducerSettings = new JmsProducerSettings(
+ connectionFactory = connectionFactory,
+ connectionRetrySettings = connectionRetrySettings,
+ sendRetrySettings = sendRetrySettings,
+ destination = destination,
+ credentials = credentials,
+ sessionCount = sessionCount,
+ timeToLive = timeToLive,
+ connectionStatusSubscriptionTimeout = connectionStatusSubscriptionTimeout)
+
+ override def toString =
+ "JmsProducerSettings(" +
+ s"connectionFactory=$connectionFactory," +
+ s"connectionRetrySettings=$connectionRetrySettings," +
+ s"sendRetrySettings=$sendRetrySettings," +
+ s"destination=$destination," +
+ s"credentials=$credentials," +
+ s"sessionCount=$sessionCount," +
+ s"timeToLive=${timeToLive.map(_.toCoarsest)}," +
+ s"connectionStatusSubscriptionTimeout=${connectionStatusSubscriptionTimeout.toCoarsest}" +
+ ")"
+}
+
+object JmsProducerSettings {
+
+ val configPath = "pekko.connectors.jakartams.producer"
+
+ /**
+ * Reads from the given config.
+ *
+ * @param c Config instance read configuration from
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def apply(c: Config, connectionFactory: jakarta.jms.ConnectionFactory): JmsProducerSettings = {
+ def getOption[A](path: String, read: Config => A): Option[A] =
+ if (c.hasPath(path) && (c.getValue(path).valueType() != ConfigValueType.STRING || c.getString(path) != "off"))
+ Some(read(c))
+ else None
+
+ val connectionRetrySettings = ConnectionRetrySettings(c.getConfig("connection-retry"))
+ val sendRetrySettings = SendRetrySettings(c.getConfig("send-retry"))
+ val credentials = getOption("credentials", c => Credentials(c.getConfig("credentials")))
+ val sessionCount = c.getInt("session-count")
+ val timeToLive = getOption("time-to-live", _.getDuration("time-to-live").asScala)
+ val connectionStatusSubscriptionTimeout = c.getDuration("connection-status-subscription-timeout").asScala
+ new JmsProducerSettings(
+ connectionFactory,
+ connectionRetrySettings,
+ sendRetrySettings,
+ destination = None,
+ credentials,
+ sessionCount,
+ timeToLive,
+ connectionStatusSubscriptionTimeout)
+ }
+
+ /**
+ * Reads from the default config provided by the actor system at `pekko.connectors.jakartams.producer`.
+ *
+ * @param actorSystem The actor system
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def apply(actorSystem: ActorSystem, connectionFactory: jakarta.jms.ConnectionFactory): JmsProducerSettings =
+ apply(actorSystem.settings.config.getConfig(configPath), connectionFactory)
+
+ /**
+ * Reads from the default config provided by the actor system at `pekko.connectors.jakartams.producer`.
+ *
+ * @param actorSystem The actor system
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def apply(actorSystem: ClassicActorSystemProvider,
+ connectionFactory: jakarta.jms.ConnectionFactory): JmsProducerSettings =
+ apply(actorSystem.classicSystem, connectionFactory)
+
+ /**
+ * Java API: Reads from the given config.
+ *
+ * @param c Config instance read configuration from
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def create(c: Config, connectionFactory: jakarta.jms.ConnectionFactory): JmsProducerSettings =
+ apply(c, connectionFactory)
+
+ /**
+ * Java API: Reads from the default config provided by the actor system at `pekko.connectors.jakartams.producer`.
+ *
+ * @param actorSystem The actor system
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def create(actorSystem: ActorSystem, connectionFactory: jakarta.jms.ConnectionFactory): JmsProducerSettings =
+ apply(actorSystem, connectionFactory)
+
+ /**
+ * Java API: Reads from the default config provided by the actor system at `pekko.connectors.jakartams.producer`.
+ *
+ * @param actorSystem The actor system
+ * @param connectionFactory Factory to use for creating JMS connections.
+ */
+ def create(actorSystem: ClassicActorSystemProvider,
+ connectionFactory: jakarta.jms.ConnectionFactory): JmsProducerSettings =
+ apply(actorSystem.classicSystem, connectionFactory)
+
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsSettings.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsSettings.scala
new file mode 100644
index 000000000..7ddadc8c9
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/JmsSettings.scala
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import jakarta.jms
+import org.apache.pekko.annotation.DoNotInherit
+
+/**
+ * Shared settings for all JMS stages.
+ * Used for internal standardization, and not meant to be used by user code.
+ */
+@DoNotInherit
+trait JmsSettings {
+ def connectionFactory: jms.ConnectionFactory
+ def connectionRetrySettings: ConnectionRetrySettings
+ def destination: Option[Destination]
+ def credentials: Option[Credentials]
+ def sessionCount: Int
+ def connectionStatusSubscriptionTimeout: scala.concurrent.duration.FiniteDuration
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/SendRetrySettings.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/SendRetrySettings.scala
new file mode 100644
index 000000000..e09c25eaf
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/SendRetrySettings.scala
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import com.typesafe.config.Config
+import org.apache.pekko
+import pekko.actor.{ ActorSystem, ClassicActorSystemProvider }
+import pekko.util.JavaDurationConverters._
+
+import scala.concurrent.duration._
+
+/**
+ * When a connection to a broker starts failing, sending JMS messages will also fail.
+ * Those failed messages can be retried at the cost of potentially duplicating the failed messages.
+ */
+final class SendRetrySettings private (val initialRetry: scala.concurrent.duration.FiniteDuration,
+ val backoffFactor: Double,
+ val maxBackoff: scala.concurrent.duration.FiniteDuration,
+ val maxRetries: Int) {
+
+ /** Wait time before retrying the first time. */
+ def withInitialRetry(value: scala.concurrent.duration.FiniteDuration): SendRetrySettings = copy(initialRetry = value)
+
+ /** Java API: Wait time before retrying the first time. */
+ def withInitialRetry(value: java.time.Duration): SendRetrySettings = copy(initialRetry = value.asScala)
+
+ /** Back-off factor for subsequent retries */
+ def withBackoffFactor(value: Double): SendRetrySettings = copy(backoffFactor = value)
+
+ /** Maximum back-off time allowed, after which all retries will happen after this delay. */
+ def withMaxBackoff(value: scala.concurrent.duration.FiniteDuration): SendRetrySettings = copy(maxBackoff = value)
+
+ /** Java API: Maximum back-off time allowed, after which all retries will happen after this delay. */
+ def withMaxBackoff(value: java.time.Duration): SendRetrySettings = copy(maxBackoff = value.asScala)
+
+ /** Maximum number of retries allowed. */
+ def withMaxRetries(value: Int): SendRetrySettings = copy(maxRetries = value)
+
+ /** Do not limit the number of retries. */
+ def withInfiniteRetries(): SendRetrySettings = withMaxRetries(SendRetrySettings.infiniteRetries)
+
+ /** The wait time before the next attempt may be made. */
+ def waitTime(retryNumber: Int): FiniteDuration =
+ (initialRetry * Math.pow(retryNumber, backoffFactor)).asInstanceOf[FiniteDuration].min(maxBackoff)
+
+ private def copy(
+ initialRetry: scala.concurrent.duration.FiniteDuration = initialRetry,
+ backoffFactor: Double = backoffFactor,
+ maxBackoff: scala.concurrent.duration.FiniteDuration = maxBackoff,
+ maxRetries: Int = maxRetries): SendRetrySettings = new SendRetrySettings(
+ initialRetry = initialRetry,
+ backoffFactor = backoffFactor,
+ maxBackoff = maxBackoff,
+ maxRetries = maxRetries)
+
+ override def toString: String =
+ "SendRetrySettings(" +
+ s"initialRetry=${initialRetry.toCoarsest}," +
+ s"backoffFactor=$backoffFactor," +
+ s"maxBackoff=${maxBackoff.toCoarsest}," +
+ s"maxRetries=${if (maxRetries == SendRetrySettings.infiniteRetries) "infinite" else maxRetries}" +
+ ")"
+}
+
+object SendRetrySettings {
+ val configPath = "pekko.connectors.jakartams.send-retry"
+
+ val infiniteRetries: Int = -1
+
+ /**
+ * Reads from the given config.
+ */
+ def apply(c: Config): SendRetrySettings = {
+ val initialRetry = c.getDuration("initial-retry").asScala
+ val backoffFactor = c.getDouble("backoff-factor")
+ val maxBackoff = c.getDuration("max-backoff").asScala
+ val maxRetries = if (c.getString("max-retries") == "infinite") infiniteRetries else c.getInt("max-retries")
+ new SendRetrySettings(
+ initialRetry,
+ backoffFactor,
+ maxBackoff,
+ maxRetries)
+ }
+
+ /**
+ * Java API: Reads from given config.
+ */
+ def create(c: Config): SendRetrySettings = apply(c)
+
+ /**
+ * Reads from the default config provided by the actor system at `pekko.connectors.jakartams.send-retry`.
+ *
+ * @param actorSystem The actor system
+ */
+ def apply(actorSystem: ActorSystem): SendRetrySettings =
+ apply(actorSystem.settings.config.getConfig(configPath))
+
+ /**
+ * Reads from the default config provided by the actor system at `pekko.connectors.jakartams.send-retry`.
+ *
+ * @param actorSystem The actor system
+ */
+ def apply(actorSystem: ClassicActorSystemProvider): SendRetrySettings =
+ apply(actorSystem.classicSystem)
+
+ /**
+ * Java API: Reads from the default config provided by the actor system at `pekko.connectors.jakartams.send-retry`.
+ *
+ * @param actorSystem The actor system
+ */
+ def create(actorSystem: ActorSystem): SendRetrySettings = apply(actorSystem)
+
+ /**
+ * Java API: Reads from the default config provided by the actor system at `pekko.connectors.jakartams.send-retry`.
+ *
+ * @param actorSystem The actor system
+ */
+ def create(actorSystem: ClassicActorSystemProvider): SendRetrySettings = apply(actorSystem.classicSystem)
+
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/GraphStageCompanion.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/GraphStageCompanion.scala
new file mode 100644
index 000000000..8f455658c
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/GraphStageCompanion.scala
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import org.apache.pekko
+import pekko.annotation.InternalApi
+import pekko.stream.Materializer
+import pekko.stream.connectors.jakartams.Destination
+
+import scala.concurrent.duration.FiniteDuration
+
+/**
+ * Exposes some protected methods from [[pekko.stream.stage.GraphStage]]
+ * that are not accessible when using Scala3 compiler.
+ */
+@InternalApi
+private[impl] trait GraphStageCompanion {
+ def graphStageMaterializer: Materializer
+
+ def graphStageDestination: Destination
+
+ def scheduleOnceOnGraphStage(timerKey: Any, delay: FiniteDuration): Unit
+
+ def isTimerActiveOnGraphStage(timerKey: Any): Boolean
+
+ def cancelTimerOnGraphStage(timerKey: Any): Unit
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/InternalConnectionState.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/InternalConnectionState.scala
new file mode 100644
index 000000000..a9267e2c1
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/InternalConnectionState.scala
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import jakarta.jms
+import org.apache.pekko
+import pekko.Done
+import pekko.annotation.InternalApi
+
+import scala.concurrent.Future
+import scala.util.Try
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[jakartams] trait InternalConnectionState
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[jakartams] object InternalConnectionState {
+ case object JmsConnectorDisconnected extends InternalConnectionState
+ case class JmsConnectorInitializing(connection: Future[jms.Connection],
+ attempt: Int,
+ backoffMaxed: Boolean,
+ sessions: Int)
+ extends InternalConnectionState
+ case class JmsConnectorConnected(connection: jms.Connection) extends InternalConnectionState
+ case class JmsConnectorStopping(completion: Try[Done]) extends InternalConnectionState
+ case class JmsConnectorStopped(completion: Try[Done]) extends InternalConnectionState
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsAckSourceStage.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsAckSourceStage.scala
new file mode 100644
index 000000000..28fbb32e2
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsAckSourceStage.scala
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import jakarta.jms
+import org.apache.pekko
+import pekko.annotation.InternalApi
+import pekko.stream.connectors.jakartams._
+import pekko.stream.connectors.jakartams.impl.JmsConnector.FlushAcknowledgementsTimerKey
+import pekko.stream.stage.{ GraphStageLogic, GraphStageWithMaterializedValue }
+import pekko.stream.{ Attributes, Outlet, SourceShape }
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[jakartams] final class JmsAckSourceStage(settings: JmsConsumerSettings, destination: Destination)
+ extends GraphStageWithMaterializedValue[SourceShape[AckEnvelope], JmsConsumerMatValue] {
+
+ private val out = Outlet[AckEnvelope]("JmsSource.out")
+
+ override def shape: SourceShape[AckEnvelope] = SourceShape[AckEnvelope](out)
+
+ override def createLogicAndMaterializedValue(
+ inheritedAttributes: Attributes): (GraphStageLogic, JmsConsumerMatValue) = {
+ val logic = new JmsAckSourceStageLogic(inheritedAttributes)
+ (logic, logic.consumerControl)
+ }
+
+ override protected def initialAttributes: Attributes = Attributes.name("JmsAckConsumer")
+
+ private final class JmsAckSourceStageLogic(inheritedAttributes: Attributes)
+ extends SourceStageLogic[AckEnvelope](shape, out, settings, destination, inheritedAttributes) {
+ private val maxPendingAcks = settings.maxPendingAcks
+ private val maxAckInterval = settings.maxAckInterval
+
+ protected def createSession(connection: jms.Connection,
+ createDestination: jms.Session => jakarta.jms.Destination): JmsAckSession = {
+ val session =
+ connection.createSession(false, settings.acknowledgeMode.getOrElse(AcknowledgeMode.ClientAcknowledge).mode)
+ new JmsAckSession(connection, session, createDestination(session), graphStageDestination, maxPendingAcks)
+ }
+
+ protected def pushMessage(msg: AckEnvelope): Unit = push(out, msg)
+
+ override protected def onSessionOpened(jmsSession: JmsConsumerSession): Unit =
+ jmsSession match {
+ case session: JmsAckSession =>
+ maxAckInterval.foreach { timeout =>
+ scheduleWithFixedDelay(FlushAcknowledgementsTimerKey(session), timeout, timeout)
+ }
+ session
+ .createConsumer(settings.selector)
+ .map { consumer =>
+ consumer.setMessageListener((message: jms.Message) => {
+ if (session.isListenerRunning)
+ try {
+ handleMessage.invoke(AckEnvelope(message, session))
+ session.pendingAck += 1
+ if (session.maxPendingAcksReached) {
+ session.ackBackpressure()
+ }
+ session.drainAcks()
+ } catch {
+ case e: jms.JMSException =>
+ handleError.invoke(e)
+ }
+ })
+ }
+ .onComplete(sessionOpenedCB.invoke)
+
+ case _ =>
+ throw new IllegalArgumentException(
+ "Session must be of type JMSAckSession, it is a " +
+ jmsSession.getClass.getName)
+ }
+ }
+
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsBrowseStage.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsBrowseStage.scala
new file mode 100644
index 000000000..346f10fdf
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsBrowseStage.scala
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import jakarta.jms
+import org.apache.pekko
+import org.apache.pekko.annotation.InternalApi
+import org.apache.pekko.stream.connectors.jakartams.{ Destination, JmsBrowseSettings }
+import org.apache.pekko.stream.stage.{ GraphStage, GraphStageLogic, OutHandler }
+import org.apache.pekko.stream.{ ActorAttributes, Attributes, Outlet, SourceShape }
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[jakartams] final class JmsBrowseStage(settings: JmsBrowseSettings, queue: Destination)
+ extends GraphStage[SourceShape[jms.Message]] {
+ private val out = Outlet[jms.Message]("JmsBrowseStage.out")
+ val shape = SourceShape(out)
+
+ override protected def initialAttributes: Attributes =
+ super.initialAttributes and Attributes.name("JmsBrowse") and ActorAttributes.IODispatcher
+
+ override def createLogic(inheritedAttributes: Attributes): GraphStageLogic =
+ new GraphStageLogic(shape) with OutHandler {
+ setHandler(out, this)
+
+ var connection: jms.Connection = _
+ var session: jms.Session = _
+ var browser: jms.QueueBrowser = _
+ var messages: java.util.Enumeration[jms.Message] = _
+
+ override def preStart(): Unit = {
+ val ackMode = settings.acknowledgeMode.mode
+ connection = settings.connectionFactory.createConnection()
+ connection.start()
+
+ session = connection.createSession(false, ackMode)
+ browser = session.createBrowser(session.createQueue(queue.name), settings.selector.orNull)
+ messages = browser.getEnumeration.asInstanceOf[java.util.Enumeration[jms.Message]]
+ }
+
+ override def postStop(): Unit = {
+ messages = null
+ if (browser ne null) {
+ browser.close()
+ browser = null
+ }
+ if (session ne null) {
+ session.close()
+ session = null
+ }
+ if (connection ne null) {
+ connection.close()
+ connection = null
+ }
+ }
+
+ def onPull(): Unit =
+ if (messages.hasMoreElements) {
+ push(out, messages.nextElement())
+ } else {
+ complete(out)
+ }
+ }
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsConnector.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsConnector.scala
new file mode 100644
index 000000000..965d4b991
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsConnector.scala
@@ -0,0 +1,424 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import jakarta.jms
+import org.apache.pekko
+import org.apache.pekko.actor.ActorSystem
+import org.apache.pekko.annotation.InternalApi
+import org.apache.pekko.dispatch.ExecutionContexts
+import org.apache.pekko.pattern.after
+import org.apache.pekko.stream.connectors.jakartams._
+import org.apache.pekko.stream.connectors.jakartams.impl.InternalConnectionState._
+import org.apache.pekko.stream.scaladsl.{ BroadcastHub, Keep, Sink, Source, SourceQueueWithComplete }
+import org.apache.pekko.stream.stage.{ AsyncCallback, StageLogging, TimerGraphStageLogic }
+import org.apache.pekko.stream.{ ActorAttributes, Attributes, OverflowStrategy }
+import org.apache.pekko.{ Done, NotUsed }
+
+import java.util.concurrent.atomic.AtomicReference
+import scala.concurrent.{ ExecutionContext, Future, Promise }
+import scala.util.control.NonFatal
+import scala.util.{ Failure, Success, Try }
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[jakartams] trait JmsConnector[S <: JmsSession] {
+ this: TimerGraphStageLogic with GraphStageCompanion with StageLogging =>
+
+ import JmsConnector._
+
+ implicit protected var ec: ExecutionContext = _
+
+ private var jmsSessions = Seq.empty[S]
+
+ protected def destination: Destination
+
+ protected def jmsSettings: JmsSettings
+
+ protected def onSessionOpened(jmsSession: S): Unit = {}
+
+ protected val fail: AsyncCallback[Throwable] = getAsyncCallback[Throwable](publishAndFailStage)
+
+ private val connectionFailedCB = getAsyncCallback[Throwable](connectionFailed)
+
+ private var connectionStateQueue: SourceQueueWithComplete[InternalConnectionState] = _
+
+ private val connectionStateSourcePromise = Promise[Source[InternalConnectionState, NotUsed]]()
+
+ protected val connectionStateSource: Future[Source[InternalConnectionState, NotUsed]] =
+ connectionStateSourcePromise.future
+
+ private var connectionState: InternalConnectionState = JmsConnectorDisconnected
+
+ override def preStart(): Unit = {
+ // keep two elements since the time between initializing and connected can be very short.
+ // always drops the old state, and keeps the most current (two) state(s) in the queue.
+ val (queue, source) =
+ Source
+ .queue[InternalConnectionState](2, OverflowStrategy.dropHead)
+ .toMat(BroadcastHub.sink(1))(Keep.both)
+ .run()(graphStageMaterializer)
+ connectionStateQueue = queue
+ connectionStateSourcePromise.complete(Success(source))
+
+ // add subscription to purge queued connection status events after the configured timeout.
+ scheduleOnceOnGraphStage(ConnectionStatusTimeout, jmsSettings.connectionStatusSubscriptionTimeout)
+ }
+
+ protected def finishStop(): Unit = {
+ val update: InternalConnectionState => InternalConnectionState = {
+ case JmsConnectorStopping(completion) => JmsConnectorStopped(completion)
+ case stopped: JmsConnectorStopped => stopped
+ case current =>
+ JmsConnectorStopped(
+ Failure(new IllegalStateException(s"Completing stage stop in unexpected state ${current.getClass}")))
+ }
+
+ closeSessions()
+ val previous = updateStateWith(update)
+ closeConnectionAsync(connection(previous))
+ if (isTimerActiveOnGraphStage("connection-status-timeout")) drainConnectionState()
+ connectionStateQueue.complete()
+ }
+
+ protected def publishAndFailStage(ex: Throwable): Unit = {
+ val previous = updateState(JmsConnectorStopping(Failure(ex)))
+ closeConnectionAsync(connection(previous))
+ failStage(ex)
+ }
+
+ protected def updateState(next: InternalConnectionState): InternalConnectionState = {
+ val update: InternalConnectionState => InternalConnectionState = {
+ case current: JmsConnectorStopping => current
+ case current: JmsConnectorStopped => current
+ case _ => next
+ }
+ updateStateWith(update)
+ }
+
+ private def updateStateWith(f: InternalConnectionState => InternalConnectionState): InternalConnectionState = {
+ val last = connectionState
+ connectionState = f(last)
+
+ // use type-based comparison to publish JmsConnectorInitializing only once.
+ if (last.getClass != connectionState.getClass) {
+ if (log.isDebugEnabled)
+ log.debug("updateStateWith {} -> {}", last.getClass.getSimpleName, connectionState.getClass.getSimpleName)
+ connectionStateQueue.offer(connectionState)
+ }
+
+ last
+ }
+
+ protected def connectionFailed(ex: Throwable): Unit = ex match {
+ case ex: jms.JMSSecurityException =>
+ log.error(
+ ex,
+ "{} initializing connection failed, security settings are not properly configured for destination[{}]",
+ attributes.nameLifted.mkString,
+ destination.name)
+ publishAndFailStage(ex)
+
+ case _: jms.JMSException | _: JmsConnectTimedOut => handleRetriableException(ex)
+
+ case _ =>
+ connectionState match {
+ case _: JmsConnectorStopping | _: JmsConnectorStopped => logStoppingException(ex)
+ case _ =>
+ log.error(ex, "{} connection failed for destination[{}]", attributes.nameLifted.mkString, destination.name)
+ publishAndFailStage(ex)
+ }
+ }
+
+ private def handleRetriableException(ex: Throwable): Unit = {
+ closeSessions()
+ connectionState match {
+ case JmsConnectorInitializing(_, attempt, backoffMaxed, _) =>
+ maybeReconnect(ex, attempt, backoffMaxed)
+ case JmsConnectorConnected(_) | JmsConnectorDisconnected =>
+ maybeReconnect(ex, 0, backoffMaxed = false)
+ case _: JmsConnectorStopping | _: JmsConnectorStopped => logStoppingException(ex)
+ case other =>
+ log.warning("received [{}] in connectionState={}", ex, connectionState)
+ }
+ }
+
+ private def logStoppingException(ex: Throwable): Unit =
+ log.info("{} caught exception {} while stopping stage: {}",
+ attributes.nameLifted.mkString,
+ ex.getClass.getSimpleName,
+ ex.getMessage)
+
+ private val onSession: AsyncCallback[S] = getAsyncCallback[S] { session =>
+ jmsSessions :+= session
+ onSessionOpened(session)
+ }
+
+ protected val sessionOpened: Try[Unit] => Unit = {
+ case Success(_) =>
+ connectionState match {
+ case init @ JmsConnectorInitializing(c, _, _, sessions) =>
+ if (sessions + 1 == jmsSettings.sessionCount) {
+ c.foreach { c =>
+ updateState(JmsConnectorConnected(c))
+ log.info("{} connected", attributes.nameLifted.mkString)
+ }
+ } else {
+ updateState(init.copy(sessions = sessions + 1))
+ }
+ case s => ()
+ }
+
+ case Failure(ex: jms.JMSException) =>
+ updateState(JmsConnectorDisconnected) match {
+ case JmsConnectorInitializing(c, attempt, backoffMaxed, _) =>
+ closeConnectionAsync(c)
+ maybeReconnect(ex, attempt, backoffMaxed)
+ case _ => ()
+ }
+
+ case Failure(ex) =>
+ log.error(ex,
+ "{} initializing connection failed for destination[{}]",
+ attributes.nameLifted.mkString,
+ destination.name)
+ publishAndFailStage(ex)
+ }
+
+ protected val sessionOpenedCB: AsyncCallback[Try[Unit]] = getAsyncCallback[Try[Unit]](sessionOpened)
+
+ private def maybeReconnect(ex: Throwable, attempt: Int, backoffMaxed: Boolean): Unit = {
+ val retrySettings = jmsSettings.connectionRetrySettings
+ import retrySettings._
+ val nextAttempt = attempt + 1
+ if (maxRetries >= 0 && nextAttempt > maxRetries) {
+ val exception =
+ if (maxRetries == 0) ex
+ else ConnectionRetryException(s"Could not establish connection after $maxRetries retries.", ex)
+ log.error(exception,
+ "{} initializing connection failed for destination[{}]",
+ attributes.nameLifted.mkString,
+ destination.name)
+ publishAndFailStage(exception)
+ } else {
+ val status = updateState(JmsConnectorDisconnected)
+ closeConnectionAsync(connection(status))
+ val delay = if (backoffMaxed) maxBackoff else waitTime(nextAttempt)
+ val backoffNowMaxed = backoffMaxed || delay == maxBackoff
+ scheduleOnceOnGraphStage(AttemptConnect(nextAttempt, backoffNowMaxed), delay)
+ }
+ }
+
+ override def onTimer(timerKey: Any): Unit = timerKey match {
+ case FlushAcknowledgementsTimerKey(session) =>
+ session.drainAcks()
+ case AttemptConnect(attempt, backoffMaxed) =>
+ log.info("{} retries connecting, attempt {}", attributes.nameLifted.mkString, attempt)
+ initSessionAsync(attempt, backoffMaxed)
+ case ConnectionStatusTimeout => drainConnectionState()
+ case _ => ()
+ }
+
+ private def drainConnectionState(): Unit =
+ Source.future(connectionStateSource).flatMapConcat(identity).runWith(Sink.ignore)(graphStageMaterializer)
+
+ protected def executionContext(attributes: Attributes): ExecutionContext = {
+ val dispatcherId = (attributes.get[ActorAttributes.Dispatcher](ActorAttributes.IODispatcher) match {
+ case ActorAttributes.Dispatcher("") =>
+ ActorAttributes.IODispatcher
+ case d => d
+ }) match {
+ case d @ ActorAttributes.IODispatcher =>
+ // this one is not a dispatcher id, but is a config path pointing to the dispatcher id
+ graphStageMaterializer.system.settings.config.getString(d.dispatcher)
+ case d => d.dispatcher
+ }
+
+ graphStageMaterializer.system.dispatchers.lookup(dispatcherId)
+ }
+
+ protected def createSession(connection: jms.Connection, createDestination: jms.Session => jms.Destination): S
+
+ protected def initSessionAsync(attempt: Int = 0, backoffMaxed: Boolean = false): Unit = {
+ val allSessions = openSessions(attempt, backoffMaxed)
+ allSessions.failed.foreach(connectionFailedCB.invoke)(ExecutionContexts.parasitic)
+ // wait for all sessions to successfully initialize before invoking the onSession callback.
+ // reduces flakiness (start, consume, then crash) at the cost of increased latency of startup.
+ allSessions.foreach(_.foreach(onSession.invoke))
+ }
+
+ protected def closeConnection(connection: jms.Connection): Unit = {
+ try {
+ // deregister exception listener to clear reference from JMS client to the Pekko stage
+ connection.setExceptionListener(null)
+ } catch {
+ case _: jms.JMSException => // ignore
+ }
+ try {
+ connection.close()
+ log.debug("JMS connection {} closed", connection)
+ } catch {
+ case NonFatal(e) => log.warning("Error closing JMS connection {}: {}", connection, e)
+ }
+ }
+
+ protected def closeConnectionAsync(eventualConnection: Future[jms.Connection]): Future[Done] =
+ eventualConnection.map(closeConnection).map(_ => Done)
+
+ protected def closeSessions(): Unit = {
+ jmsSessions.foreach(s => closeSession(s))
+ jmsSessions = Seq.empty
+ }
+
+ protected def closeSessionsAsync(): Future[Unit] = {
+ val closing = Future
+ .sequence {
+ jmsSessions.map(s => Future(closeSession(s)))
+ }
+ .map(_ => ())
+ jmsSessions = Seq.empty
+ closing
+ }
+
+ private def closeSession(s: S): Unit = {
+ try {
+ cancelAckTimers(s)
+ s.closeSession()
+ } catch {
+ case e: Throwable => log.error(e, "Error closing jms session")
+ }
+ }
+
+ protected def abortSessionsAsync(): Future[Unit] = {
+ val aborting = Future
+ .sequence {
+ jmsSessions.map { s =>
+ Future {
+ try {
+ cancelAckTimers(s)
+ s.abortSession()
+ } catch {
+ case e: Throwable => log.error(e, "Error aborting jms session")
+ }
+ }
+ }
+ }
+ .map(_ => ())
+ jmsSessions = Seq.empty
+ aborting
+ }
+
+ private def cancelAckTimers(s: JmsSession): Unit = s match {
+ case session: JmsAckSession =>
+ cancelTimerOnGraphStage(FlushAcknowledgementsTimerKey(session))
+ case _ => ()
+ }
+
+ def startConnection: Boolean
+
+ private def openSessions(attempt: Int, backoffMaxed: Boolean): Future[Seq[S]] = {
+ val eventualConnection = openConnection(attempt, backoffMaxed)
+ eventualConnection.flatMap { connection =>
+ val sessionFutures =
+ for (_ <- 0 until jmsSettings.sessionCount)
+ yield Future(createSession(connection, destination.create))
+ Future.sequence(sessionFutures)
+ }(ExecutionContexts.parasitic)
+ }
+
+ private def openConnection(attempt: Int, backoffMaxed: Boolean): Future[jms.Connection] = {
+ implicit val system: ActorSystem = graphStageMaterializer.system
+ val jmsConnection = openConnectionAttempt(startConnection)
+ updateState(JmsConnectorInitializing(jmsConnection, attempt, backoffMaxed, 0))
+ jmsConnection.map { connection =>
+ connection.setExceptionListener(new jms.ExceptionListener {
+ override def onException(ex: jms.JMSException): Unit = {
+ closeConnection(connection)
+ connectionFailedCB.invoke(ex)
+ }
+ })
+ connection
+ }
+ }
+
+ private def openConnectionAttempt(startConnection: Boolean)(implicit system: ActorSystem): Future[jms.Connection] = {
+ val factory = jmsSettings.connectionFactory
+ val connectionRef = new AtomicReference[Option[jms.Connection]](None)
+
+ // status is also the decision point between the two futures below which one will win.
+ val status = new AtomicReference[ConnectionAttemptStatus](Connecting)
+
+ val connectionFuture = Future {
+ val connection = jmsSettings.credentials match {
+ case Some(c: Credentials) => factory.createConnection(c.username, c.password)
+ case _ => factory.createConnection()
+ }
+ if (status.get == Connecting) { // `TimedOut` can be set at any point. So we have to check whether to continue.
+ connectionRef.set(Some(connection))
+ if (startConnection) connection.start()
+ }
+ // ... and close if the connection is not to be used, don't return the connection
+ if (!status.compareAndSet(Connecting, Connected)) {
+ connectionRef.get.foreach(closeConnection)
+ connectionRef.set(None)
+ throw JmsConnectTimedOut("Received timed out signal trying to establish connection")
+ } else connection
+ }
+
+ val connectTimeout = jmsSettings.connectionRetrySettings.connectTimeout
+ val timeoutFuture = after(connectTimeout, system.scheduler) {
+ // Even if the timer goes off, the connection may already be good. We use the
+ // status field and an atomic compareAndSet to see whether we should indeed time out, or just return
+ // the connection. In this case it does not matter which future returns. Both will have the right answer.
+ if (status.compareAndSet(Connecting, TimedOut)) {
+ connectionRef.get.foreach(closeConnection)
+ connectionRef.set(None)
+ Future.failed(
+ JmsConnectTimedOut(
+ s"Timed out after $connectTimeout trying to establish connection. " +
+ "Please see ConnectionRetrySettings.connectTimeout"))
+ } else
+ connectionRef.get match {
+ case Some(connection) => Future.successful(connection)
+ case None => Future.failed(new IllegalStateException("BUG: Connection reference not set when connected"))
+ }
+ }
+
+ Future.firstCompletedOf(Iterator(connectionFuture, timeoutFuture))(ExecutionContexts.parasitic)
+ }
+}
+
+/**
+ * Internal API.
+ */
+@InternalApi
+object JmsConnector {
+
+ sealed trait ConnectionAttemptStatus
+ case object Connecting extends ConnectionAttemptStatus
+ case object Connected extends ConnectionAttemptStatus
+ case object TimedOut extends ConnectionAttemptStatus
+
+ final case class AttemptConnect(attempt: Int, backoffMaxed: Boolean)
+ final case class FlushAcknowledgementsTimerKey(jmsSession: JmsAckSession)
+ case object ConnectionStatusTimeout
+
+ def connection: InternalConnectionState => Future[jms.Connection] = {
+ case InternalConnectionState.JmsConnectorInitializing(c, _, _, _) => c
+ case InternalConnectionState.JmsConnectorConnected(c) => Future.successful(c)
+ case _ => Future.failed(JmsNotConnected)
+ }
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsConsumerStage.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsConsumerStage.scala
new file mode 100644
index 000000000..c228a64e4
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsConsumerStage.scala
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import jakarta.jms
+import org.apache.pekko
+import org.apache.pekko.annotation.InternalApi
+import org.apache.pekko.stream._
+import org.apache.pekko.stream.connectors.jakartams._
+import org.apache.pekko.stream.stage._
+
+import java.util.concurrent.Semaphore
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[jakartams] final class JmsConsumerStage(settings: JmsConsumerSettings, destination: Destination)
+ extends GraphStageWithMaterializedValue[SourceShape[jms.Message], JmsConsumerMatValue] {
+
+ private val out = Outlet[jms.Message]("JmsConsumer.out")
+
+ override protected def initialAttributes: Attributes = Attributes.name("JmsConsumer")
+
+ override def shape: SourceShape[jms.Message] = SourceShape[jms.Message](out)
+
+ override def createLogicAndMaterializedValue(
+ inheritedAttributes: Attributes): (GraphStageLogic, JmsConsumerMatValue) = {
+ val logic = new JmsConsumerStageLogic(inheritedAttributes)
+ (logic, logic.consumerControl)
+ }
+
+ private final class JmsConsumerStageLogic(inheritedAttributes: Attributes)
+ extends SourceStageLogic[jms.Message](shape, out, settings, destination, inheritedAttributes) {
+
+ private val bufferSize = (settings.bufferSize + 1) * settings.sessionCount
+
+ private val backpressure = new Semaphore(bufferSize)
+
+ protected def createSession(connection: jms.Connection,
+ createDestination: jms.Session => jakarta.jms.Destination): JmsConsumerSession = {
+ val session =
+ connection.createSession(false, settings.acknowledgeMode.getOrElse(AcknowledgeMode.AutoAcknowledge).mode)
+ new JmsConsumerSession(connection, session, createDestination(session), graphStageDestination)
+ }
+
+ protected def pushMessage(msg: jms.Message): Unit = {
+ push(out, msg)
+ backpressure.release()
+ }
+
+ override protected def onSessionOpened(jmsSession: JmsConsumerSession): Unit =
+ jmsSession
+ .createConsumer(settings.selector)
+ .map { consumer =>
+ consumer.setMessageListener(new jms.MessageListener {
+ def onMessage(message: jms.Message): Unit = {
+ backpressure.acquire()
+ handleMessage.invoke(message)
+ }
+ })
+ }
+ .onComplete(sessionOpenedCB.invoke)
+ }
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsInternalMatValues.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsInternalMatValues.scala
new file mode 100644
index 000000000..a9667d0ca
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsInternalMatValues.scala
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import org.apache.pekko
+import org.apache.pekko.NotUsed
+import org.apache.pekko.annotation.InternalApi
+import org.apache.pekko.stream.KillSwitch
+import org.apache.pekko.stream.scaladsl.Source
+
+/**
+ * Internal API.
+ */
+@InternalApi private[jakartams] trait JmsProducerMatValue {
+ def connected: Source[InternalConnectionState, NotUsed]
+}
+
+/**
+ * Internal API.
+ */
+@InternalApi private[jakartams] trait JmsConsumerMatValue extends KillSwitch with JmsProducerMatValue
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsMessageProducer.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsMessageProducer.scala
new file mode 100644
index 000000000..f95b434ce
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsMessageProducer.scala
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import jakarta.jms
+import org.apache.pekko
+import org.apache.pekko.annotation.InternalApi
+import org.apache.pekko.stream.connectors.jakartams._
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private class JmsMessageProducer(jmsProducer: jms.MessageProducer, jmsSession: JmsProducerSession, val epoch: Int) {
+
+ private val defaultDestination = jmsSession.jmsDestination
+
+ private val destinationCache = new SoftReferenceCache[Destination, jms.Destination]()
+
+ def send(elem: JmsEnvelope[_]): Unit = {
+ val message: jms.Message = createMessage(elem)
+ populateMessageProperties(message, elem)
+
+ val (sendHeaders, headersBeforeSend: Set[JmsHeader]) = elem.headers.partition(_.usedDuringSend)
+ populateMessageHeader(message, headersBeforeSend)
+
+ val deliveryMode = sendHeaders
+ .collectFirst { case x: JmsDeliveryMode => x.deliveryMode }
+ .getOrElse(jmsProducer.getDeliveryMode)
+
+ val priority = sendHeaders
+ .collectFirst { case x: JmsPriority => x.priority }
+ .getOrElse(jmsProducer.getPriority)
+
+ val timeToLive = sendHeaders
+ .collectFirst { case x: JmsTimeToLive => x.timeInMillis }
+ .getOrElse(jmsProducer.getTimeToLive)
+
+ val destination = elem.destination match {
+ case Some(messageDestination) => lookup(messageDestination)
+ case None => defaultDestination
+ }
+ jmsProducer.send(destination, message, deliveryMode, priority, timeToLive)
+ }
+
+ private def lookup(dest: Destination) = destinationCache.lookup(dest, dest.create(jmsSession.session))
+
+ private[jakartams] def createMessage(element: JmsEnvelope[_]): jms.Message =
+ element match {
+
+ case textMessage: JmsTextMessagePassThrough[_] => jmsSession.session.createTextMessage(textMessage.body)
+
+ case byteMessage: JmsByteMessagePassThrough[_] =>
+ val newMessage = jmsSession.session.createBytesMessage()
+ newMessage.writeBytes(byteMessage.bytes)
+ newMessage
+
+ case byteStringMessage: JmsByteStringMessagePassThrough[_] =>
+ val newMessage = jmsSession.session.createBytesMessage()
+ newMessage.writeBytes(byteStringMessage.bytes.toArray)
+ newMessage
+
+ case mapMessage: JmsMapMessagePassThrough[_] =>
+ val newMessage = jmsSession.session.createMapMessage()
+ populateMapMessage(newMessage, mapMessage)
+ newMessage
+
+ case objectMessage: JmsObjectMessagePassThrough[_] =>
+ jmsSession.session.createObjectMessage(objectMessage.serializable)
+
+ case pt: JmsPassThrough[_] => throw new IllegalArgumentException("can't create message for JmsPassThrough")
+
+ }
+
+ private[jakartams] def populateMessageProperties(message: jakarta.jms.Message, jmsMessage: JmsEnvelope[_]): Unit =
+ jmsMessage.properties.foreach {
+ case (key, v) =>
+ v match {
+ case v: String => message.setStringProperty(key, v)
+ case v: Int => message.setIntProperty(key, v)
+ case v: Boolean => message.setBooleanProperty(key, v)
+ case v: Byte => message.setByteProperty(key, v)
+ case v: Short => message.setShortProperty(key, v)
+ case v: Float => message.setFloatProperty(key, v)
+ case v: Long => message.setLongProperty(key, v)
+ case v: Double => message.setDoubleProperty(key, v)
+ case v: Array[Byte] => message.setObjectProperty(key, v)
+ case null => message.setObjectProperty(key, null)
+ case _ => throw UnsupportedMessagePropertyType(key, v, jmsMessage)
+ }
+ }
+
+ private def populateMapMessage(message: jakarta.jms.MapMessage, jmsMessage: JmsMapMessagePassThrough[_]): Unit =
+ jmsMessage.body.foreach {
+ case (key, v) =>
+ v match {
+ case v: String => message.setString(key, v)
+ case v: Int => message.setInt(key, v)
+ case v: Boolean => message.setBoolean(key, v)
+ case v: Byte => message.setByte(key, v)
+ case v: Short => message.setShort(key, v)
+ case v: Float => message.setFloat(key, v)
+ case v: Long => message.setLong(key, v)
+ case v: Double => message.setDouble(key, v)
+ case v: Array[Byte] => message.setBytes(key, v)
+ case null => message.setObject(key, v)
+ case _ => throw UnsupportedMapMessageEntryType(key, v, jmsMessage)
+ }
+ }
+
+ private def populateMessageHeader(message: jakarta.jms.Message, headers: Set[JmsHeader]): Unit =
+ headers.foreach {
+ case JmsType(jmsType) => message.setJMSType(jmsType)
+ case JmsReplyTo(destination) => message.setJMSReplyTo(destination.create(jmsSession.session))
+ case JmsCorrelationId(jmsCorrelationId) => message.setJMSCorrelationID(jmsCorrelationId)
+ case JmsExpiration(jmsExpiration) => message.setJMSExpiration(jmsExpiration)
+ case JmsDeliveryMode(_) | JmsPriority(_) | JmsTimeToLive(_) | JmsTimestamp(_) | JmsRedelivered(_) |
+ JmsMessageId(_) => // see #send(JmsMessage)
+ }
+}
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[impl] object JmsMessageProducer {
+ def apply(jmsSession: JmsProducerSession, settings: JmsProducerSettings, epoch: Int): JmsMessageProducer = {
+ val producer = jmsSession.session.createProducer(null)
+ if (settings.timeToLive.nonEmpty) {
+ producer.setTimeToLive(settings.timeToLive.get.toMillis)
+ }
+ new JmsMessageProducer(producer, jmsSession, epoch)
+ }
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsMessageReader.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsMessageReader.scala
new file mode 100644
index 000000000..54077e7bf
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsMessageReader.scala
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import jakarta.jms
+import org.apache.pekko
+import org.apache.pekko.annotation.InternalApi
+import org.apache.pekko.stream.connectors.jakartams._
+import org.apache.pekko.util.ByteString
+import org.apache.pekko.util.ccompat.JavaConverters._
+
+import scala.annotation.tailrec
+
+@InternalApi
+private[jakartams] object JmsMessageReader {
+
+ /**
+ * Read a [[pekko.util.ByteString]] from a [[jakarta.jms.BytesMessage]]
+ */
+ def readBytes(message: jms.BytesMessage, bufferSize: Int = 4096): ByteString = {
+ if (message.getBodyLength > Int.MaxValue)
+ sys.error(s"Message too large, unable to read ${message.getBodyLength} bytes of data")
+
+ val buff = new Array[Byte](Math.min(message.getBodyLength, bufferSize).toInt)
+
+ @tailrec def read(data: ByteString): ByteString =
+ if (message.getBodyLength == data.length)
+ data
+ else {
+ val len = message.readBytes(buff)
+ val d = buff.take(len)
+ read(data ++ ByteString(d))
+ }
+ read(ByteString.empty)
+ }
+
+ /**
+ * Read a byte array from a [[jakarta.jms.BytesMessage]]
+ */
+ def readArray(message: jms.BytesMessage, bufferSize: Int = 4096): Array[Byte] =
+ readBytes(message, bufferSize).toArray
+
+ private def createMap(keys: java.util.Enumeration[_], accessor: String => AnyRef) =
+ keys
+ .asInstanceOf[java.util.Enumeration[String]]
+ .asScala
+ .map { key =>
+ key -> (accessor(key) match {
+ case v: java.lang.Boolean => v.booleanValue()
+ case v: java.lang.Byte => v.byteValue()
+ case v: java.lang.Short => v.shortValue()
+ case v: java.lang.Integer => v.intValue()
+ case v: java.lang.Long => v.longValue()
+ case v: java.lang.Float => v.floatValue()
+ case v: java.lang.Double => v.doubleValue()
+ case other => other
+ })
+ }
+ .toMap
+
+ /**
+ * Read a Scala Map from a [[jakarta.jms.MapMessage]]
+ */
+ def readMap(message: jms.MapMessage): Map[String, Any] =
+ createMap(message.getMapNames, message.getObject)
+
+ /**
+ * Extract a properties map from a [[jakarta.jms.Message]]
+ */
+ def readProperties(message: jms.Message): Map[String, Any] =
+ createMap(message.getPropertyNames, message.getObjectProperty)
+
+ /**
+ * Extract [[JmsHeader]]s from a [[jakarta.jms.Message]]
+ */
+ def readHeaders(message: jms.Message): Set[JmsHeader] = {
+ def messageId = Option(message.getJMSMessageID).map(JmsMessageId(_))
+ def timestamp = Some(JmsTimestamp(message.getJMSTimestamp))
+ def correlationId = Option(message.getJMSCorrelationID).map(JmsCorrelationId(_))
+ def replyTo = Option(message.getJMSReplyTo).map(Destination(_)).map(JmsReplyTo(_))
+ def deliveryMode = Some(JmsDeliveryMode(message.getJMSDeliveryMode))
+ def redelivered = Some(JmsRedelivered(message.getJMSRedelivered))
+ def jmsType = Option(message.getJMSType).map(JmsType(_))
+ def expiration = Some(JmsExpiration(message.getJMSExpiration))
+ def priority = Some(JmsPriority(message.getJMSPriority))
+
+ Set(messageId, timestamp, correlationId, replyTo, deliveryMode, redelivered, jmsType, expiration, priority).flatten
+ }
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsProducerStage.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsProducerStage.scala
new file mode 100644
index 000000000..e62198e35
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsProducerStage.scala
@@ -0,0 +1,300 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import jakarta.jms
+import org.apache.pekko
+import org.apache.pekko.annotation.InternalApi
+import org.apache.pekko.stream.ActorAttributes.SupervisionStrategy
+import org.apache.pekko.stream._
+import org.apache.pekko.stream.connectors.jakartams._
+import org.apache.pekko.stream.impl.Buffer
+import org.apache.pekko.stream.scaladsl.Source
+import org.apache.pekko.stream.stage._
+import org.apache.pekko.util.OptionVal
+import org.apache.pekko.{ Done, NotUsed }
+
+import scala.concurrent.Future
+import scala.concurrent.duration.FiniteDuration
+import scala.util.control.NoStackTrace
+import scala.util.{ Failure, Success, Try }
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private trait JmsProducerConnector extends JmsConnector[JmsProducerSession] {
+ this: TimerGraphStageLogic with GraphStageCompanion with StageLogging =>
+
+ protected final def createSession(connection: jms.Connection,
+ createDestination: jms.Session => jms.Destination): JmsProducerSession = {
+ val session = connection.createSession(false, AcknowledgeMode.AutoAcknowledge.mode)
+ new JmsProducerSession(connection, session, createDestination(session))
+ }
+
+ override val startConnection = false
+
+ val status: JmsProducerMatValue = new JmsProducerMatValue {
+ override def connected: Source[InternalConnectionState, NotUsed] =
+ Source.future(connectionStateSource).flatMapConcat(identity)
+ }
+}
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[jakartams] final class JmsProducerStage[E <: JmsEnvelope[PassThrough], PassThrough](
+ settings: JmsProducerSettings,
+ destination: Destination)
+ extends GraphStageWithMaterializedValue[FlowShape[E, E], JmsProducerMatValue] { stage =>
+ import JmsProducerStage._
+
+ private val in = Inlet[E]("JmsProducer.in")
+ private val out = Outlet[E]("JmsProducer.out")
+
+ override def shape: FlowShape[E, E] = FlowShape.of(in, out)
+
+ override protected def initialAttributes: Attributes =
+ super.initialAttributes and Attributes.name("JmsProducer") and ActorAttributes.IODispatcher
+
+ override def createLogicAndMaterializedValue(
+ inheritedAttributes: Attributes): (GraphStageLogic, JmsProducerMatValue) = {
+ val logic: TimerGraphStageLogic with JmsProducerConnector = producerLogic(inheritedAttributes)
+ (logic, logic.status)
+ }
+
+ private def producerLogic(inheritedAttributes: Attributes) =
+ new TimerGraphStageLogic(shape) with JmsProducerConnector with GraphStageCompanion with StageLogging {
+
+ final override def graphStageMaterializer: Materializer = materializer
+
+ final override def graphStageDestination: Destination = destination
+
+ final override def scheduleOnceOnGraphStage(timerKey: Any, delay: FiniteDuration): Unit =
+ scheduleOnce(timerKey, delay)
+
+ final override def isTimerActiveOnGraphStage(timerKey: Any): Boolean = isTimerActive(timerKey)
+
+ final override def cancelTimerOnGraphStage(timerKey: Any): Unit = cancelTimer(timerKey)
+
+ /*
+ * NOTE: the following code is heavily inspired by org.apache.pekko.stream.impl.fusing.MapAsync
+ *
+ * To get a condensed view of what the buffers and handler behavior is about, have a look there too.
+ */
+
+ private lazy val decider = inheritedAttributes.mandatoryAttribute[SupervisionStrategy].decider
+
+ // the current connection epoch. Reconnects increment this epoch by 1.
+ private var currentJmsProducerEpoch = 0
+
+ // available producers for sending messages. Initially full, but might contain less elements if
+ // messages are currently in-flight.
+ private val jmsProducers: Buffer[JmsMessageProducer] = Buffer(settings.sessionCount, settings.sessionCount)
+
+ // in-flight messages with the producers that were used to send them.
+ private val inFlightMessages: Buffer[Holder[E]] =
+ Buffer(settings.sessionCount, settings.sessionCount)
+
+ protected val destination: Destination = stage.destination
+ protected val jmsSettings: JmsProducerSettings = settings
+
+ override def preStart(): Unit = {
+ ec = executionContext(inheritedAttributes)
+ super.preStart()
+ initSessionAsync()
+ }
+
+ override protected def onSessionOpened(jmsSession: JmsProducerSession): Unit =
+ sessionOpened(Try {
+ jmsProducers.enqueue(JmsMessageProducer(jmsSession, settings, currentJmsProducerEpoch))
+ // startup situation: while producer pool was empty, the out port might have pulled. If so, pull from in port.
+ // Note that a message might be already in-flight; that's fine since this stage pre-fetches message from
+ // upstream anyway to increase throughput once the stream is started.
+ if (isAvailable(out)) pullIfNeeded()
+ })
+
+ override protected def connectionFailed(ex: Throwable): Unit = {
+ jmsProducers.clear()
+ currentJmsProducerEpoch += 1
+ super.connectionFailed(ex)
+ }
+
+ setHandler(out,
+ new OutHandler {
+ override def onPull(): Unit = pushNextIfPossible()
+
+ override def onDownstreamFinish(cause: Throwable): Unit = publishAndCompleteStage()
+ })
+
+ setHandler(
+ in,
+ new InHandler {
+ override def onUpstreamFinish(): Unit = if (inFlightMessages.isEmpty) publishAndCompleteStage()
+
+ override def onUpstreamFailure(ex: Throwable): Unit = {
+ publishAndFailStage(ex)
+ }
+
+ override def onPush(): Unit = {
+ val elem: E = grab(in)
+ elem match {
+ case _: JmsPassThrough[_] =>
+ val holder = new Holder[E](NotYetThere)
+ inFlightMessages.enqueue(holder)
+ holder(Success(elem))
+ pushNextIfPossible()
+ case m: JmsEnvelope[_] =>
+ // create a holder object to capture the in-flight message, and enqueue it to preserve message order
+ val holder = new Holder[E](NotYetThere)
+ inFlightMessages.enqueue(holder)
+ sendWithRetries(SendAttempt(m.asInstanceOf[E], holder))
+ case other =>
+ log.warning("unhandled element []", other)
+ }
+
+ // immediately ask for the next element if producers are available.
+ pullIfNeeded()
+ }
+ })
+
+ private def publishAndCompleteStage(): Unit = {
+ val previous = updateState(InternalConnectionState.JmsConnectorStopping(Success(Done)))
+ closeSessions()
+ closeConnectionAsync(JmsConnector.connection(previous))
+ completeStage()
+ }
+
+ override def onTimer(timerKey: Any): Unit = timerKey match {
+ case s: SendAttempt[E @unchecked] => sendWithRetries(s)
+ case _ => super.onTimer(timerKey)
+ }
+
+ private def sendWithRetries(send: SendAttempt[E]): Unit = {
+ import send._
+ if (jmsProducers.nonEmpty) {
+ val jmsProducer: JmsMessageProducer = jmsProducers.dequeue()
+ Future(jmsProducer.send(envelope)).andThen {
+ case tried => sendCompletedCB.invoke((send, tried, jmsProducer))
+ }
+ } else {
+ nextTryOrFail(send, RetrySkippedOnMissingConnection)
+ }
+ }
+
+ def nextTryOrFail(send: SendAttempt[E], ex: Throwable): Unit = {
+ import send._
+ import settings.sendRetrySettings._
+ if (maxRetries < 0 || attempt + 1 <= maxRetries) {
+ val nextAttempt = attempt + 1
+ val delay = if (backoffMaxed) maxBackoff else waitTime(nextAttempt)
+ val backoffNowMaxed = backoffMaxed || delay == maxBackoff
+ scheduleOnce(send.copy(attempt = nextAttempt, backoffMaxed = backoffNowMaxed), delay)
+ } else {
+ holder(Failure(ex))
+ handleFailure(ex, holder)
+ }
+ }
+
+ private val sendCompletedCB = getAsyncCallback[(SendAttempt[E], Try[Unit], JmsMessageProducer)] {
+ case (send, outcome, jmsProducer) =>
+ // same epoch indicates that the producer belongs to the current alive connection.
+ if (jmsProducer.epoch == currentJmsProducerEpoch) jmsProducers.enqueue(jmsProducer)
+
+ import send._
+
+ outcome match {
+ case Success(_) =>
+ holder(Success(send.envelope))
+ pushNextIfPossible()
+ case Failure(t: jms.JMSException) =>
+ nextTryOrFail(send, t)
+ case Failure(t) =>
+ holder(Failure(t))
+ handleFailure(t, holder)
+ }
+ }
+
+ override def postStop(): Unit = finishStop()
+
+ private def pullIfNeeded(): Unit =
+ if (jmsProducers.nonEmpty // only pull if a producer is available in the pool.
+ && !inFlightMessages.isFull // and a place is available in the in-flight queue.
+ && !hasBeenPulled(in))
+ tryPull(in)
+
+ private def pushNextIfPossible(): Unit =
+ if (inFlightMessages.isEmpty) {
+ // no messages in flight, are we about to complete?
+ if (isClosed(in)) publishAndCompleteStage() else pullIfNeeded()
+ } else if (inFlightMessages.peek().elem eq NotYetThere) {
+ // next message to be produced is still not there, we need to wait.
+ pullIfNeeded()
+ } else if (isAvailable(out)) {
+ val holder = inFlightMessages.dequeue()
+ holder.elem match {
+ case Success(elem) =>
+ push(out, elem)
+ pullIfNeeded() // Ask for the next element.
+
+ case Failure(ex) => handleFailure(ex, holder)
+ }
+ }
+
+ private def handleFailure(ex: Throwable, holder: Holder[E]): Unit =
+ holder.supervisionDirectiveFor(decider, ex) match {
+ case Supervision.Stop => failStage(ex) // fail only if supervision asks for it.
+ case _ => pushNextIfPossible()
+ }
+ }
+}
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[jakartams] object JmsProducerStage {
+
+ val NotYetThere = Failure(new Exception with NoStackTrace)
+
+ /*
+ * NOTE: the following code is heavily inspired by org.apache.pekko.stream.impl.fusing.MapAsync
+ *
+ * To get a condensed view of what the Holder is about, have a look there too.
+ */
+ class Holder[A](var elem: Try[A]) extends (Try[A] => Unit) {
+
+ // To support both fail-fast when the supervision directive is Stop
+ // and not calling the decider multiple times, we need to cache the decider result and re-use that
+ private var cachedSupervisionDirective: OptionVal[Supervision.Directive] = OptionVal.None
+
+ def supervisionDirectiveFor(decider: Supervision.Decider, ex: Throwable): Supervision.Directive =
+ cachedSupervisionDirective match {
+ case OptionVal.Some(d) => d
+ case OptionVal.None =>
+ val d = decider(ex)
+ cachedSupervisionDirective = OptionVal.Some(d)
+ d
+ case other => throw new MatchError(other)
+ }
+
+ override def apply(t: Try[A]): Unit = elem = t
+ }
+
+ case class SendAttempt[E <: JmsEnvelope[_]](envelope: E,
+ holder: Holder[E],
+ attempt: Int = 0,
+ backoffMaxed: Boolean = false)
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsTxSourceStage.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsTxSourceStage.scala
new file mode 100644
index 000000000..88caf7338
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/JmsTxSourceStage.scala
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import jakarta.jms
+import org.apache.pekko
+import org.apache.pekko.annotation.InternalApi
+import org.apache.pekko.stream.connectors.jakartams._
+import org.apache.pekko.stream.stage.{ GraphStageLogic, GraphStageWithMaterializedValue }
+import org.apache.pekko.stream.{ Attributes, Outlet, SourceShape }
+
+import scala.concurrent.{ Await, TimeoutException }
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[jakartams] final class JmsTxSourceStage(settings: JmsConsumerSettings, destination: Destination)
+ extends GraphStageWithMaterializedValue[SourceShape[TxEnvelope], JmsConsumerMatValue] {
+
+ private val out = Outlet[TxEnvelope]("JmsSource.out")
+
+ override def shape: SourceShape[TxEnvelope] = SourceShape[TxEnvelope](out)
+
+ override protected def initialAttributes: Attributes = Attributes.name("JmsTxConsumer")
+
+ override def createLogicAndMaterializedValue(
+ inheritedAttributes: Attributes): (GraphStageLogic, JmsConsumerMatValue) = {
+ val logic = new JmsTxSourceStageLogic(inheritedAttributes)
+ (logic, logic.consumerControl)
+ }
+
+ private final class JmsTxSourceStageLogic(inheritedAttributes: Attributes)
+ extends SourceStageLogic[TxEnvelope](shape, out, settings, destination, inheritedAttributes) {
+ protected def createSession(connection: jms.Connection,
+ createDestination: jms.Session => jakarta.jms.Destination) = {
+ val session =
+ connection.createSession(true, settings.acknowledgeMode.getOrElse(AcknowledgeMode.SessionTransacted).mode)
+ new JmsConsumerSession(connection, session, createDestination(session), graphStageDestination)
+ }
+
+ protected def pushMessage(msg: TxEnvelope): Unit = push(out, msg)
+
+ override protected def onSessionOpened(jmsSession: JmsConsumerSession): Unit =
+ jmsSession match {
+ case session: JmsSession =>
+ session
+ .createConsumer(settings.selector)
+ .map { consumer =>
+ consumer.setMessageListener(new jms.MessageListener {
+
+ def onMessage(message: jms.Message): Unit =
+ try {
+ val envelope = TxEnvelope(message, session)
+ handleMessage.invoke(envelope)
+ try {
+ // JMS spec defines that commit/rollback must be done on the same thread.
+ // While some JMS implementations work without this constraint, IBM MQ is
+ // very strict about the spec and throws exceptions when called from a different thread.
+ val action = Await.result(envelope.commitFuture, settings.ackTimeout)
+ action()
+ } catch {
+ case _: TimeoutException =>
+ val exception = new JmsTxAckTimeout(settings.ackTimeout)
+ session.session.rollback()
+ if (settings.failStreamOnAckTimeout) {
+ handleError.invoke(exception)
+ } else {
+ log.warning(exception.getMessage)
+ }
+ }
+ } catch {
+ case e: IllegalArgumentException => handleError.invoke(e) // Invalid envelope. Fail the stage.
+ case e: jms.JMSException => handleError.invoke(e)
+ }
+ })
+ }
+ .onComplete(sessionOpenedCB.invoke)
+
+ case _ =>
+ throw new IllegalArgumentException(
+ "Session must be of type JmsSession, it is a " +
+ jmsSession.getClass.getName)
+ }
+ }
+
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/Sessions.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/Sessions.scala
new file mode 100644
index 000000000..1c2250374
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/Sessions.scala
@@ -0,0 +1,137 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import jakarta.jms
+import org.apache.pekko
+import org.apache.pekko.annotation.InternalApi
+import org.apache.pekko.stream.connectors.jakartams.{ Destination, DurableTopic }
+import org.apache.pekko.util.OptionVal
+
+import java.util.concurrent.ArrayBlockingQueue
+import scala.annotation.tailrec
+import scala.concurrent.{ ExecutionContext, Future }
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[jakartams] sealed trait JmsSession {
+
+ def connection: jms.Connection
+
+ def session: jms.Session
+
+ private[jakartams] def abortSession(): Unit = closeSession()
+
+ private[jakartams] def closeSession(): Unit = session.close()
+}
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[jakartams] final class JmsProducerSession(val connection: jms.Connection,
+ val session: jms.Session,
+ val jmsDestination: jms.Destination)
+ extends JmsSession
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[jakartams] class JmsConsumerSession(val connection: jms.Connection,
+ val session: jms.Session,
+ val jmsDestination: jms.Destination,
+ val settingsDestination: Destination)
+ extends JmsSession {
+
+ private[jakartams] def createConsumer(
+ selector: Option[String])(implicit ec: ExecutionContext): Future[jms.MessageConsumer] =
+ Future {
+ (selector, settingsDestination) match {
+ case (None, t: DurableTopic) =>
+ session.createDurableSubscriber(jmsDestination.asInstanceOf[jms.Topic], t.subscriberName)
+
+ case (Some(expr), t: DurableTopic) =>
+ session.createDurableSubscriber(jmsDestination.asInstanceOf[jms.Topic], t.subscriberName, expr, false)
+
+ case (Some(expr), _) =>
+ session.createConsumer(jmsDestination, expr)
+
+ case (None, _) =>
+ session.createConsumer(jmsDestination)
+ }
+ }
+}
+
+case object SessionClosed
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private[jakartams] final class JmsAckSession(override val connection: jms.Connection,
+ override val session: jms.Session,
+ override val jmsDestination: jms.Destination,
+ override val settingsDestination: Destination,
+ val maxPendingAcks: Int)
+ extends JmsConsumerSession(connection, session, jmsDestination, settingsDestination) {
+
+ private val ackQueue = new ArrayBlockingQueue[Either[SessionClosed.type, () => Unit]](maxPendingAcks + 1)
+ private[jakartams] var pendingAck = 0
+ private var listenerRunning = true
+
+ def isListenerRunning: Boolean = listenerRunning
+
+ def maxPendingAcksReached: Boolean = pendingAck > maxPendingAcks
+
+ def ack(message: jms.Message): Unit = ackQueue.put(Right(message.acknowledge _))
+
+ override def closeSession(): Unit = stopMessageListenerAndCloseSession()
+
+ override def abortSession(): Unit = stopMessageListenerAndCloseSession()
+
+ private def stopMessageListenerAndCloseSession(): Unit = {
+ try {
+ drainAcks()
+ } finally {
+ ackQueue.put(Left(SessionClosed))
+ session.close()
+ }
+ }
+
+ def ackBackpressure() = {
+ ackQueue.take() match {
+ case Left(SessionClosed) =>
+ listenerRunning = false
+ case Right(action) =>
+ action()
+ pendingAck -= 1
+ }
+ }
+
+ @tailrec
+ def drainAcks(): Unit =
+ OptionVal(ackQueue.poll()) match {
+ case OptionVal.Some(Left(SessionClosed)) =>
+ listenerRunning = false
+ case OptionVal.Some(Right(action)) =>
+ action()
+ pendingAck -= 1
+ drainAcks()
+ case OptionVal.None =>
+ case other => throw new MatchError(other)
+ }
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/SoftReferenceCache.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/SoftReferenceCache.scala
new file mode 100644
index 000000000..9a780c3cb
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/SoftReferenceCache.scala
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import org.apache.pekko
+import org.apache.pekko.annotation.InternalApi
+
+import scala.collection.mutable
+import scala.ref.SoftReference
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private final class SoftReferenceCache[K, V <: AnyRef] {
+
+ private val cache = mutable.HashMap[K, SoftReference[V]]()
+
+ def lookup(key: K, default: => V): V =
+ cache.get(key) match {
+ case Some(ref) =>
+ ref.get match {
+ case Some(value) => value
+ case None =>
+ purgeCache() // facing a garbage collected soft reference, purge other entries.
+ update(key, default)
+ }
+
+ case None => update(key, default)
+ }
+
+ private def update(key: K, value: V): V = {
+ cache.put(key, new SoftReference(value))
+ value
+ }
+
+ private def purgeCache(): Unit =
+ cache --= cache.collect { case (key, ref) if ref.get.isEmpty => key }.toVector
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/SourceStageLogic.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/SourceStageLogic.scala
new file mode 100644
index 000000000..c0cdadc3f
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/impl/SourceStageLogic.scala
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.impl
+
+import jakarta.jms
+import org.apache.pekko
+import pekko.annotation.InternalApi
+import pekko.stream.connectors.jakartams.impl.InternalConnectionState.JmsConnectorStopping
+import pekko.stream.connectors.jakartams.{ Destination, JmsConsumerSettings }
+import pekko.stream.scaladsl.Source
+import pekko.stream.stage.{ OutHandler, StageLogging, TimerGraphStageLogic }
+import pekko.stream.{ Attributes, Materializer, Outlet, SourceShape }
+import pekko.{ Done, NotUsed }
+
+import java.util.concurrent.atomic.AtomicBoolean
+import scala.collection.mutable
+import scala.concurrent.duration.FiniteDuration
+import scala.util.{ Failure, Success }
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private trait JmsConsumerConnector extends JmsConnector[JmsConsumerSession] {
+ this: TimerGraphStageLogic with GraphStageCompanion with StageLogging =>
+
+ override val startConnection = true
+
+ protected def createSession(connection: jms.Connection,
+ createDestination: jms.Session => jms.Destination): JmsConsumerSession
+
+}
+
+/**
+ * Internal API.
+ */
+@InternalApi
+private abstract class SourceStageLogic[T](shape: SourceShape[T],
+ out: Outlet[T],
+ settings: JmsConsumerSettings,
+ val destination: Destination,
+ inheritedAttributes: Attributes)
+ extends TimerGraphStageLogic(shape)
+ with JmsConsumerConnector
+ with GraphStageCompanion
+ with StageLogging {
+
+ final override def graphStageMaterializer: Materializer = materializer
+
+ final override def graphStageDestination: Destination = destination
+
+ final override def scheduleOnceOnGraphStage(timerKey: Any, delay: FiniteDuration): Unit =
+ scheduleOnce(timerKey, delay)
+
+ final override def isTimerActiveOnGraphStage(timerKey: Any): Boolean = isTimerActive(timerKey)
+
+ final override def cancelTimerOnGraphStage(timerKey: Any): Unit = cancelTimer(timerKey)
+
+ override protected def jmsSettings: JmsConsumerSettings = settings
+ private val queue = mutable.Queue[T]()
+ private val stopping = new AtomicBoolean(false)
+ private var stopped = false
+
+ private val markStopped = getAsyncCallback[Done.type] { _ =>
+ stopped = true
+ finishStop()
+ if (queue.isEmpty) completeStage()
+ }
+
+ private val markAborted = getAsyncCallback[Throwable] { ex =>
+ stopped = true
+ finishStop()
+ failStage(ex)
+ }
+
+ protected val handleError = getAsyncCallback[Throwable] { e =>
+ updateState(JmsConnectorStopping(Failure(e)))
+ failStage(e)
+ }
+
+ override def preStart(): Unit = {
+ ec = executionContext(inheritedAttributes)
+ super.preStart()
+ initSessionAsync()
+ }
+
+ private[jakartams] val handleMessage = getAsyncCallback[T] { msg =>
+ if (isAvailable(out)) {
+ if (queue.isEmpty) {
+ pushMessage(msg)
+ } else {
+ pushMessage(queue.dequeue())
+ queue.enqueue(msg)
+ }
+ } else {
+ queue.enqueue(msg)
+ }
+ }
+
+ protected def pushMessage(msg: T): Unit
+
+ setHandler(
+ out,
+ new OutHandler {
+ override def onPull(): Unit = {
+ if (queue.nonEmpty) pushMessage(queue.dequeue())
+ if (stopped && queue.isEmpty) completeStage()
+ }
+
+ override def onDownstreamFinish(cause: Throwable): Unit = {
+ // no need to keep messages in the queue, downstream will never pull them.
+ queue.clear()
+ // keep processing async callbacks for stopSessions.
+ setKeepGoing(true)
+ stopSessions()
+ }
+ })
+
+ private def stopSessions(): Unit =
+ if (stopping.compareAndSet(false, true)) {
+ val status = updateState(JmsConnectorStopping(Success(Done)))
+ val connectionFuture = JmsConnector.connection(status)
+
+ closeSessionsAsync().onComplete { _ =>
+ closeConnectionAsync(connectionFuture).onComplete { _ =>
+ // By this time, after stopping connection, closing sessions, all async message submissions to this
+ // stage should have been invoked. We invoke markStopped as the last item so it gets delivered after
+ // all JMS messages are delivered. This will allow the stage to complete after all pending messages
+ // are delivered, thus preventing message loss due to premature stage completion.
+ markStopped.invoke(Done)
+ }
+ }
+ }
+
+ private def abortSessions(ex: Throwable): Unit =
+ if (stopping.compareAndSet(false, true)) {
+ if (log.isDebugEnabled) log.debug("aborting sessions ({})", ex.toString)
+ val status = updateState(JmsConnectorStopping(Failure(ex)))
+ val connectionFuture = JmsConnector.connection(status)
+ abortSessionsAsync().onComplete { _ =>
+ closeConnectionAsync(connectionFuture).onComplete { _ =>
+ markAborted.invoke(ex)
+ }
+ }
+ }
+
+ def consumerControl: JmsConsumerMatValue = new JmsConsumerMatValue {
+ override def shutdown(): Unit = stopSessions()
+ override def abort(ex: Throwable): Unit = abortSessions(ex)
+ override def connected: Source[InternalConnectionState, NotUsed] =
+ Source.future(connectionStateSource).flatMapConcat(identity)
+ }
+
+ override def postStop(): Unit = finishStop()
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsConnectorState.java b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsConnectorState.java
new file mode 100644
index 000000000..36485fb04
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsConnectorState.java
@@ -0,0 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.javadsl;
+
+public enum JmsConnectorState {
+
+ Disconnected, Connecting, Connected, Completing, Completed, Failing, Failed
+
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsConsumer.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsConsumer.scala
new file mode 100644
index 000000000..cc2f695b5
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsConsumer.scala
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.javadsl
+
+import jakarta.jms.Message
+import org.apache.pekko
+import org.apache.pekko.NotUsed
+import org.apache.pekko.stream.connectors.jakartams._
+import org.apache.pekko.stream.javadsl.Source
+import org.apache.pekko.util.ccompat.JavaConverters._
+
+/**
+ * Factory methods to create JMS consumers.
+ */
+object JmsConsumer {
+
+ /**
+ * Creates a source emitting [[jakarta.jms.Message]] instances, and materializes a
+ * control instance to shut down the consumer.
+ */
+ def create(settings: JmsConsumerSettings): pekko.stream.javadsl.Source[Message, JmsConsumerControl] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsConsumer.apply(settings).mapMaterializedValue(
+ toConsumerControl).asJava
+
+ /**
+ * Creates a source emitting Strings, and materializes a
+ * control instance to shut down the consumer.
+ */
+ def textSource(settings: JmsConsumerSettings): pekko.stream.javadsl.Source[String, JmsConsumerControl] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsConsumer.textSource(settings).mapMaterializedValue(
+ toConsumerControl).asJava
+
+ /**
+ * Creates a source emitting byte arrays, and materializes a
+ * control instance to shut down the consumer.
+ */
+ def bytesSource(
+ settings: JmsConsumerSettings): pekko.stream.javadsl.Source[Array[Byte], JmsConsumerControl] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsConsumer.bytesSource(settings).mapMaterializedValue(
+ toConsumerControl).asJava
+
+ /**
+ * Creates a source emitting maps, and materializes a
+ * control instance to shut down the consumer.
+ */
+ def mapSource(
+ settings: JmsConsumerSettings): pekko.stream.javadsl.Source[java.util.Map[String, Any], JmsConsumerControl] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsConsumer
+ .mapSource(settings)
+ .map(_.asJava)
+ .mapMaterializedValue(toConsumerControl)
+ .asJava
+
+ /**
+ * Creates a source emitting de-serialized objects, and materializes a
+ * control instance to shut down the consumer.
+ */
+ def objectSource(
+ settings: JmsConsumerSettings): pekko.stream.javadsl.Source[java.io.Serializable, JmsConsumerControl] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsConsumer.objectSource(settings).mapMaterializedValue(
+ toConsumerControl).asJava
+
+ /**
+ * Creates a source emitting [[pekko.stream.connectors.jakartams.AckEnvelope AckEnvelope]] instances, and materializes a
+ * control instance to shut down the consumer.
+ * It requires explicit acknowledgements on the envelopes. The acknowledgements must be called on the envelope and not on the message inside.
+ */
+ def ackSource(
+ settings: JmsConsumerSettings): pekko.stream.javadsl.Source[AckEnvelope, JmsConsumerControl] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsConsumer.ackSource(settings).mapMaterializedValue(
+ toConsumerControl).asJava
+
+ /**
+ * Creates a source emitting [[pekko.stream.connectors.jakartams.TxEnvelope TxEnvelope]] instances, and materializes a
+ * control instance to shut down the consumer.
+ * It requires explicit committing or rollback on the envelopes.
+ */
+ def txSource(settings: JmsConsumerSettings): pekko.stream.javadsl.Source[TxEnvelope, JmsConsumerControl] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsConsumer.txSource(settings).mapMaterializedValue(
+ toConsumerControl).asJava
+
+ /**
+ * Creates a source browsing a JMS destination (which does not consume the messages)
+ * and emitting [[jakarta.jms.Message]] instances.
+ */
+ def browse(settings: JmsBrowseSettings): pekko.stream.javadsl.Source[Message, NotUsed] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsConsumer.browse(settings).asJava
+
+ private def toConsumerControl(scalaControl: scaladsl.JmsConsumerControl) = new JmsConsumerControl {
+
+ override def connectorState(): Source[JmsConnectorState, NotUsed] =
+ scalaControl.connectorState.map(_.asJava).asJava
+
+ override def shutdown(): Unit = scalaControl.shutdown()
+
+ override def abort(ex: Throwable): Unit = scalaControl.abort(ex)
+ }
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsConsumerControl.java b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsConsumerControl.java
new file mode 100644
index 000000000..a8bbb7428
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsConsumerControl.java
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.javadsl;
+
+import org.apache.pekko.NotUsed;
+import org.apache.pekko.stream.KillSwitch;
+import org.apache.pekko.stream.javadsl.Source;
+
+public interface JmsConsumerControl extends KillSwitch {
+
+ /**
+ * source that provides connector status change information.
+ * Only the most recent connector state is buffered if the source is not consumed.
+ */
+ Source<JmsConnectorState, NotUsed> connectorState();
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsProducer.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsProducer.scala
new file mode 100644
index 000000000..18663ce33
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsProducer.scala
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.javadsl
+
+import org.apache.pekko
+import org.apache.pekko.stream.connectors.jakartams.{ scaladsl, JmsEnvelope, JmsMessage, JmsProducerSettings }
+import org.apache.pekko.stream.javadsl.Source
+import org.apache.pekko.stream.scaladsl.{ Flow, Keep }
+import org.apache.pekko.util.ByteString
+import org.apache.pekko.util.FutureConverters._
+import org.apache.pekko.util.ccompat.JavaConverters._
+import org.apache.pekko.{ Done, NotUsed }
+
+import java.util.concurrent.CompletionStage
+
+/**
+ * Factory methods to create JMS producers.
+ */
+object JmsProducer {
+
+ /**
+ * Create a flow to send [[pekko.stream.connectors.jakartams.JmsMessage JmsMessage]] sub-classes to
+ * a JMS broker.
+ */
+ def flow[R <: JmsMessage](
+ settings: JmsProducerSettings): pekko.stream.javadsl.Flow[R, R, JmsProducerStatus] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsProducer.flow(settings).mapMaterializedValue(
+ toProducerStatus).asJava
+
+ /**
+ * Create a flow to send [[pekko.stream.connectors.jakartams.JmsEnvelope JmsEnvelope]] sub-classes to
+ * a JMS broker to support pass-through of data.
+ */
+ def flexiFlow[PassThrough](
+ settings: JmsProducerSettings)
+ : pekko.stream.javadsl.Flow[JmsEnvelope[PassThrough], JmsEnvelope[PassThrough], JmsProducerStatus] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsProducer
+ .flexiFlow[PassThrough](settings)
+ .mapMaterializedValue(toProducerStatus)
+ .asJava
+
+ /**
+ * Create a sink to send [[pekko.stream.connectors.jakartams.JmsMessage JmsMessage]] sub-classes to
+ * a JMS broker.
+ */
+ def sink[R <: JmsMessage](
+ settings: JmsProducerSettings): pekko.stream.javadsl.Sink[R, CompletionStage[Done]] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsProducer
+ .sink(settings)
+ .mapMaterializedValue(_.asJava)
+ .asJava
+
+ /**
+ * Create a sink to send Strings as text messages to a JMS broker.
+ */
+ def textSink(settings: JmsProducerSettings): pekko.stream.javadsl.Sink[String, CompletionStage[Done]] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsProducer
+ .textSink(settings)
+ .mapMaterializedValue(_.asJava)
+ .asJava
+
+ /**
+ * Create a sink to send byte arrays to a JMS broker.
+ */
+ def bytesSink(
+ settings: JmsProducerSettings): pekko.stream.javadsl.Sink[Array[Byte], CompletionStage[Done]] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsProducer
+ .bytesSink(settings)
+ .mapMaterializedValue(_.asJava)
+ .asJava
+
+ /**
+ * Create a sink to send [[pekko.util.ByteString ByteString]]s to a JMS broker.
+ */
+ def byteStringSink(
+ settings: JmsProducerSettings): pekko.stream.javadsl.Sink[ByteString, CompletionStage[Done]] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsProducer
+ .byteStringSink(settings)
+ .mapMaterializedValue(_.asJava)
+ .asJava
+
+ /**
+ * Create a sink to send map structures to a JMS broker.
+ */
+ def mapSink(
+ settings: JmsProducerSettings): pekko.stream.javadsl.Sink[java.util.Map[String, Any], CompletionStage[Done]] = {
+
+ val scalaSink =
+ pekko.stream.connectors.jakartams.scaladsl.JmsProducer
+ .mapSink(settings)
+ .mapMaterializedValue(_.asJava)
+ val javaToScalaConversion =
+ Flow.fromFunction((javaMap: java.util.Map[String, Any]) => javaMap.asScala.toMap)
+ javaToScalaConversion.toMat(scalaSink)(Keep.right).asJava
+ }
+
+ /**
+ * Create a sink to send serialized objects to a JMS broker.
+ */
+ def objectSink(
+ settings: JmsProducerSettings): pekko.stream.javadsl.Sink[java.io.Serializable, CompletionStage[Done]] =
+ pekko.stream.connectors.jakartams.scaladsl.JmsProducer
+ .objectSink(settings)
+ .mapMaterializedValue(_.asJava)
+ .asJava
+
+ private def toProducerStatus(scalaStatus: scaladsl.JmsProducerStatus) = new JmsProducerStatus {
+
+ override def connectorState: Source[JmsConnectorState, NotUsed] =
+ scalaStatus.connectorState.map(_.asJava).asJava
+ }
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsProducerStatus.java b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsProducerStatus.java
new file mode 100644
index 000000000..0798f65f6
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsProducerStatus.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.javadsl;
+
+import org.apache.pekko.NotUsed;
+import org.apache.pekko.stream.javadsl.Source;
+
+public interface JmsProducerStatus {
+
+ /**
+ * source that provides connector status change information.
+ * Only the most recent connector state is buffered if the source is not consumed.
+ */
+ Source<JmsConnectorState, NotUsed> connectorState();
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/scaladsl/JmsConnectorState.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/scaladsl/JmsConnectorState.scala
new file mode 100644
index 000000000..f093d77a4
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/scaladsl/JmsConnectorState.scala
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.scaladsl
+
+import org.apache.pekko
+import org.apache.pekko.NotUsed
+import org.apache.pekko.stream.KillSwitch
+import org.apache.pekko.stream.connectors.jakartams.javadsl
+import org.apache.pekko.stream.connectors.jakartams.scaladsl.JmsConnectorState._
+import org.apache.pekko.stream.scaladsl.Source
+
+trait JmsProducerStatus {
+
+ /**
+ * source that provides connector status change information.
+ * Only the most recent connector state is buffered if the source is not consumed.
+ */
+ def connectorState: Source[JmsConnectorState, NotUsed]
+
+}
+
+/**
+ * Handle to shut down consumers and to inspect the connectivity to the JMS broker.
+ */
+trait JmsConsumerControl extends KillSwitch {
+
+ /**
+ * source that provides connector status change information.
+ * Only the most recent connector state is buffered if the source is not consumed.
+ */
+ def connectorState: Source[JmsConnectorState, NotUsed]
+
+}
+
+sealed trait JmsConnectorState {
+ final def asJava: javadsl.JmsConnectorState = this match {
+ case Disconnected => javadsl.JmsConnectorState.Disconnected
+ case Connecting(_) => javadsl.JmsConnectorState.Connecting
+ case Connected => javadsl.JmsConnectorState.Connected
+ case Completing => javadsl.JmsConnectorState.Completing
+ case Completed => javadsl.JmsConnectorState.Completed
+ case Failing(_) => javadsl.JmsConnectorState.Failing
+ case Failed(_) => javadsl.JmsConnectorState.Failed
+ }
+}
+
+object JmsConnectorState {
+ case object Disconnected extends JmsConnectorState
+ case class Connecting(attempt: Int) extends JmsConnectorState
+ case object Connected extends JmsConnectorState
+ case object Completing extends JmsConnectorState
+ case object Completed extends JmsConnectorState
+ case class Failing(exception: Throwable) extends JmsConnectorState
+ case class Failed(exception: Throwable) extends JmsConnectorState
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/scaladsl/JmsConsumer.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/scaladsl/JmsConsumer.scala
new file mode 100644
index 000000000..7ceb24873
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/scaladsl/JmsConsumer.scala
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.scaladsl
+
+import jakarta.jms
+import org.apache.pekko
+import org.apache.pekko.NotUsed
+import org.apache.pekko.stream.connectors.jakartams._
+import org.apache.pekko.stream.connectors.jakartams.impl._
+import org.apache.pekko.stream.scaladsl.Source
+import org.apache.pekko.util.ccompat.JavaConverters._
+
+/**
+ * Factory methods to create JMS consumers.
+ */
+object JmsConsumer {
+
+ /**
+ * Creates a source emitting [[jakarta.jms.Message]] instances, and materializes a
+ * control instance to shut down the consumer.
+ */
+ def apply(settings: JmsConsumerSettings): Source[jakarta.jms.Message, JmsConsumerControl] =
+ settings.destination match {
+ case None => throw new IllegalArgumentException(noConsumerDestination(settings))
+ case Some(destination) =>
+ Source.fromGraph(new JmsConsumerStage(settings, destination)).mapMaterializedValue(toConsumerControl)
+ }
+
+ /**
+ * Creates a source emitting Strings, and materializes a
+ * control instance to shut down the consumer.
+ */
+ def textSource(settings: JmsConsumerSettings): Source[String, JmsConsumerControl] =
+ apply(settings).map(msg => msg.asInstanceOf[jms.TextMessage].getText)
+
+ /**
+ * Creates a source emitting maps, and materializes a
+ * control instance to shut down the consumer.
+ */
+ def mapSource(settings: JmsConsumerSettings): Source[Map[String, Any], JmsConsumerControl] =
+ apply(settings).map { msg =>
+ val mapMessage = msg.asInstanceOf[jms.MapMessage]
+
+ mapMessage.getMapNames.asScala.foldLeft(Map[String, Any]()) { (result, key) =>
+ val keyAsString = key.toString
+ val value = mapMessage.getObject(keyAsString)
+ result.+(keyAsString -> value)
+ }
+ }
+
+ /**
+ * Creates a source emitting byte arrays, and materializes a
+ * control instance to shut down the consumer.
+ */
+ def bytesSource(settings: JmsConsumerSettings): Source[Array[Byte], JmsConsumerControl] =
+ apply(settings).map { msg =>
+ val byteMessage = msg.asInstanceOf[jms.BytesMessage]
+ val byteArray = new Array[Byte](byteMessage.getBodyLength.toInt)
+ byteMessage.readBytes(byteArray)
+ byteArray
+ }
+
+ /**
+ * Creates a source emitting de-serialized objects, and materializes a
+ * control instance to shut down the consumer.
+ */
+ def objectSource(settings: JmsConsumerSettings): Source[java.io.Serializable, JmsConsumerControl] =
+ apply(settings).map(msg => msg.asInstanceOf[jms.ObjectMessage].getObject)
+
+ /**
+ * Creates a source emitting [[pekko.stream.connectors.jakartams.AckEnvelope AckEnvelope]] instances, and materializes a
+ * control instance to shut down the consumer.
+ * It requires explicit acknowledgements on the envelopes. The acknowledgements must be called on the envelope and not on the message inside.
+ */
+ def ackSource(settings: JmsConsumerSettings): Source[AckEnvelope, JmsConsumerControl] = settings.destination match {
+ case None => throw new IllegalArgumentException(noConsumerDestination(settings))
+ case Some(destination) =>
+ Source.fromGraph(new JmsAckSourceStage(settings, destination)).mapMaterializedValue(toConsumerControl)
+ }
+
+ /**
+ * Creates a source emitting [[pekko.stream.connectors.jakartams.TxEnvelope TxEnvelope]] instances, and materializes a
+ * control instance to shut down the consumer.
+ * It requires explicit committing or rollback on the envelopes.
+ */
+ def txSource(settings: JmsConsumerSettings): Source[TxEnvelope, JmsConsumerControl] = settings.destination match {
+ case None => throw new IllegalArgumentException(noConsumerDestination(settings))
+ case Some(destination) =>
+ Source.fromGraph(new JmsTxSourceStage(settings, destination)).mapMaterializedValue(toConsumerControl)
+ }
+
+ /**
+ * Creates a source browsing a JMS destination (which does not consume the messages)
+ * and emitting [[jakarta.jms.Message]] instances.
+ * Completes: when all messages have been read
+ */
+ def browse(settings: JmsBrowseSettings): Source[jakarta.jms.Message, NotUsed] = settings.destination match {
+ case None => throw new IllegalArgumentException(noBrowseDestination(settings))
+ case Some(destination) => Source.fromGraph(new JmsBrowseStage(settings, destination))
+ }
+
+ private def noConsumerDestination(settings: JmsConsumerSettings) =
+ s"""Unable to create JmsConsumer: its needs a destination to read messages from, but none was provided in
+ |$settings
+ |Please use withQueue, withTopic or withDestination to specify a destination.""".stripMargin
+
+ private def noBrowseDestination(settings: JmsBrowseSettings) =
+ s"""Unable to create JmsConsumer browser: its needs a destination to read messages from, but none was provided in
+ |$settings
+ |Please use withQueue or withDestination to specify a destination.""".stripMargin
+
+ private def toConsumerControl(internal: JmsConsumerMatValue) = new JmsConsumerControl {
+
+ override def shutdown(): Unit = internal.shutdown()
+
+ override def abort(ex: Throwable): Unit = internal.abort(ex)
+
+ override def connectorState: Source[JmsConnectorState, NotUsed] = transformConnectorState(internal.connected)
+ }
+
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/scaladsl/JmsProducer.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/scaladsl/JmsProducer.scala
new file mode 100644
index 000000000..8b3b50386
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/scaladsl/JmsProducer.scala
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.scaladsl
+
+import org.apache.pekko
+import org.apache.pekko.stream.connectors.jakartams._
+import org.apache.pekko.stream.connectors.jakartams.impl.{ JmsProducerMatValue, JmsProducerStage }
+import org.apache.pekko.stream.scaladsl.{ Flow, Keep, Sink, Source }
+import org.apache.pekko.util.ByteString
+import org.apache.pekko.{ Done, NotUsed }
+
+import scala.concurrent.Future
+
+/**
+ * Factory methods to create JMS producers.
+ */
+object JmsProducer {
+
+ /**
+ * Create a flow to send [[pekko.stream.connectors.jakartams.JmsMessage JmsMessage]] sub-classes to
+ * a JMS broker.
+ */
+ def flow[T <: JmsMessage](settings: JmsProducerSettings): Flow[T, T, JmsProducerStatus] =
+ settings.destination match {
+ case None => throw new IllegalArgumentException(noProducerDestination(settings))
+ case Some(destination) =>
+ Flow[T]
+ .viaMat(Flow.fromGraph(new JmsProducerStage[T, NotUsed](settings, destination)))(Keep.right)
+ .mapMaterializedValue(toProducerStatus)
+ }
+
+ /**
+ * Create a flow to send [[pekko.stream.connectors.jakartams.JmsEnvelope JmsEnvelope]] sub-classes to
+ * a JMS broker to support pass-through of data.
+ */
+ def flexiFlow[PassThrough](
+ settings: JmsProducerSettings): Flow[JmsEnvelope[PassThrough], JmsEnvelope[PassThrough], JmsProducerStatus] =
+ settings.destination match {
+ case None => throw new IllegalArgumentException(noProducerDestination(settings))
+ case Some(destination) =>
+ Flow
+ .fromGraph(new JmsProducerStage[JmsEnvelope[PassThrough], PassThrough](settings, destination))
+ .mapMaterializedValue(toProducerStatus)
+ }
+
+ /**
+ * Create a sink to send [[pekko.stream.connectors.jakartams.JmsMessage JmsMessage]] sub-classes to
+ * a JMS broker.
+ */
+ def sink(settings: JmsProducerSettings): Sink[JmsMessage, Future[Done]] =
+ flow(settings).toMat(Sink.ignore)(Keep.right)
+
+ /**
+ * Create a sink to send Strings as text messages to a JMS broker.
+ */
+ def textSink(settings: JmsProducerSettings): Sink[String, Future[Done]] =
+ Flow.fromFunction((s: String) => JmsTextMessage(s)).via(flow(settings)).toMat(Sink.ignore)(Keep.right)
+
+ /**
+ * Create a sink to send byte arrays to a JMS broker.
+ */
+ def bytesSink(settings: JmsProducerSettings): Sink[Array[Byte], Future[Done]] =
+ Flow.fromFunction((s: Array[Byte]) => JmsByteMessage(s)).via(flow(settings)).toMat(Sink.ignore)(Keep.right)
+
+ /**
+ * Create a sink to send [[pekko.util.ByteString ByteString]]s to a JMS broker.
+ */
+ def byteStringSink(settings: JmsProducerSettings): Sink[ByteString, Future[Done]] =
+ Flow.fromFunction((s: ByteString) => JmsByteStringMessage(s)).via(flow(settings)).toMat(Sink.ignore)(Keep.right)
+
+ /**
+ * Create a sink to send map structures to a JMS broker.
+ */
+ def mapSink(settings: JmsProducerSettings): Sink[Map[String, Any], Future[Done]] =
+ Flow.fromFunction((s: Map[String, Any]) => JmsMapMessage(s)).via(flow(settings)).toMat(Sink.ignore)(Keep.right)
+
+ /**
+ * Create a sink to send serialized objects to a JMS broker.
+ */
+ def objectSink(settings: JmsProducerSettings): Sink[java.io.Serializable, Future[Done]] =
+ Flow
+ .fromFunction((s: java.io.Serializable) => JmsObjectMessage(s))
+ .via(flow(settings))
+ .toMat(Sink.ignore)(Keep.right)
+
+ private def toProducerStatus(internal: JmsProducerMatValue) = new JmsProducerStatus {
+
+ override def connectorState: Source[JmsConnectorState, NotUsed] = transformConnectorState(internal.connected)
+ }
+
+ private def noProducerDestination(settings: JmsProducerSettings) =
+ s"""Unable to create JmsProducer: it needs a default destination to send messages to, but none was provided in
+ |$settings
+ |Please use withQueue, withTopic or withDestination to specify a destination.""".stripMargin
+}
diff --git a/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/scaladsl/package.scala b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/scaladsl/package.scala
new file mode 100644
index 000000000..0a5b9e04a
--- /dev/null
+++ b/jakartams/src/main/scala/org/apache/pekko/stream/connectors/jakartams/scaladsl/package.scala
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams
+
+import org.apache.pekko
+import org.apache.pekko.annotation.InternalApi
+import org.apache.pekko.stream.connectors.jakartams.impl.InternalConnectionState
+import org.apache.pekko.stream.scaladsl.Source
+import org.apache.pekko.{ Done, NotUsed }
+
+import scala.util.{ Failure, Success }
+
+package object scaladsl {
+ @InternalApi private[scaladsl] def transformConnectorState(source: Source[InternalConnectionState, NotUsed]) = {
+ import InternalConnectionState._
+ source.map {
+ case JmsConnectorDisconnected => JmsConnectorState.Disconnected
+ case _: JmsConnectorConnected => JmsConnectorState.Connected
+ case i: JmsConnectorInitializing => JmsConnectorState.Connecting(i.attempt + 1)
+ case JmsConnectorStopping(Success(Done)) => JmsConnectorState.Completing
+ case JmsConnectorStopping(Failure(t)) => JmsConnectorState.Failing(t)
+ case JmsConnectorStopped(Success(Done)) => JmsConnectorState.Completed
+ case JmsConnectorStopped(Failure(t)) => JmsConnectorState.Failed(t)
+ case other => throw new MatchError(other)
+ }
+ }
+}
diff --git a/jakartams/src/test/java/docs/javadsl/JmsBufferedAckConnectorsTest.java b/jakartams/src/test/java/docs/javadsl/JmsBufferedAckConnectorsTest.java
new file mode 100644
index 000000000..c619e0a22
--- /dev/null
+++ b/jakartams/src/test/java/docs/javadsl/JmsBufferedAckConnectorsTest.java
@@ -0,0 +1,392 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package docs.javadsl;
+
+import com.typesafe.config.Config;
+import jakarta.jms.ConnectionFactory;
+import jakarta.jms.JMSException;
+import jakarta.jms.Message;
+import jakarta.jms.TextMessage;
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+import org.apache.activemq.artemis.jms.client.ActiveMQQueue;
+import org.apache.activemq.artemis.junit.EmbeddedActiveMQResource;
+import org.apache.pekko.Done;
+import org.apache.pekko.actor.ActorSystem;
+import org.apache.pekko.japi.Pair;
+import org.apache.pekko.stream.connectors.jakartams.*;
+import org.apache.pekko.stream.connectors.jakartams.javadsl.JmsConsumer;
+import org.apache.pekko.stream.connectors.jakartams.javadsl.JmsConsumerControl;
+import org.apache.pekko.stream.connectors.jakartams.javadsl.JmsProducer;
+import org.apache.pekko.stream.connectors.testkit.javadsl.LogCapturingJunit4;
+import org.apache.pekko.stream.javadsl.Sink;
+import org.apache.pekko.stream.javadsl.Source;
+import org.apache.pekko.testkit.javadsl.TestKit;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+
+public class JmsBufferedAckConnectorsTest {
+
+ @Rule
+ public final LogCapturingJunit4 logCapturing = new LogCapturingJunit4();
+
+ private static ActorSystem system;
+ private static Config consumerConfig;
+ private static Config producerConfig;
+
+ @BeforeClass
+ public static void setup() {
+ system = ActorSystem.create();
+ consumerConfig = system.settings().config().getConfig(JmsConsumerSettings.configPath());
+ producerConfig = system.settings().config().getConfig(JmsProducerSettings.configPath());
+ }
+
+ @AfterClass
+ public static void teardown() {
+ TestKit.shutdownActorSystem(system);
+ }
+
+ private List<JmsTextMessage> createTestMessageList() {
+ List<Integer> intsIn = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ List<JmsTextMessage> msgsIn = new ArrayList<>();
+ for (Integer n : intsIn) {
+ msgsIn.add(
+ JmsTextMessage.create(n.toString())
+ .withProperty("Number", n)
+ .withProperty("IsOdd", n % 2 == 1)
+ .withProperty("IsEven", n % 2 == 0));
+ }
+
+ return msgsIn;
+ }
+
+ @Test
+ public void publishAndConsume() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+
+ Sink<String, CompletionStage<Done>> jmsSink =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+ Source.from(in).runWith(jmsSink, system);
+
+ Source<AckEnvelope, JmsConsumerControl> jmsSource =
+ JmsConsumer.ackSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withBufferSize(5)
+ .withQueue("test"));
+
+ CompletionStage<List<String>> result =
+ jmsSource
+ .take(in.size())
+ .map(env -> new Pair<>(env, ((TextMessage) env.message()).getText()))
+ .map(
+ pair -> {
+ pair.first().acknowledge();
+ return pair.second();
+ })
+ .runWith(Sink.seq(), system);
+ List<String> out = new ArrayList<>(result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ Collections.sort(out);
+ assertEquals(in, out);
+ });
+ }
+
+ @Test
+ public void publishAndConsumeJmsTextMessagesWithProperties() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ // #source
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<JmsTextMessage> msgsIn = createTestMessageList();
+
+ Source.from(msgsIn).runWith(jmsSink, system);
+
+ // #source
+ Source<org.apache.pekko.stream.connectors.jakartams.AckEnvelope, JmsConsumerControl> jmsSource =
+ JmsConsumer.ackSource(
+ JmsConsumerSettings.create(system, connectionFactory)
+ .withSessionCount(5)
+ .withQueue("test"));
+
+ CompletionStage<List<jakarta.jms.Message>> result =
+ jmsSource
+ .take(msgsIn.size())
+ .map(
+ envelope -> {
+ envelope.acknowledge();
+ return envelope.message();
+ })
+ .runWith(Sink.seq(), system);
+ // #source
+
+ List<Message> outMessages =
+ new ArrayList<>(result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ outMessages.sort(
+ (a, b) -> {
+ try {
+ return a.getIntProperty("Number") - b.getIntProperty("Number");
+ } catch (JMSException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ int msgIdx = 0;
+ for (Message outMsg : outMessages) {
+ assertEquals(
+ outMsg.getIntProperty("Number"),
+ msgsIn.get(msgIdx).properties().get("Number").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsOdd"),
+ msgsIn.get(msgIdx).properties().get("IsOdd").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsEven"),
+ (msgsIn.get(msgIdx).properties().get("IsEven").get()));
+ msgIdx++;
+ }
+ });
+ }
+
+ @Test
+ public void publishAndConsumeJmsTextMessagesWithHeaders() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<JmsTextMessage> msgsIn =
+ createTestMessageList().stream()
+ .map(jmsTextMessage -> jmsTextMessage.withHeader(JmsType.create("type")))
+ .map(
+ jmsTextMessage ->
+ jmsTextMessage.withHeader(JmsCorrelationId.create("correlationId")))
+ .map(jmsTextMessage -> jmsTextMessage.withHeader(JmsReplyTo.queue("test-reply")))
+ .collect(Collectors.toList());
+
+ Source.from(msgsIn).runWith(jmsSink, system);
+
+ Source<AckEnvelope, JmsConsumerControl> jmsSource =
+ JmsConsumer.ackSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withQueue("test"));
+
+ CompletionStage<List<Message>> result =
+ jmsSource
+ .take(msgsIn.size())
+ .map(
+ env -> {
+ env.acknowledge();
+ return env.message();
+ })
+ .runWith(Sink.seq(), system);
+
+ List<Message> outMessages =
+ new ArrayList<>(result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ outMessages.sort(
+ (a, b) -> {
+ try {
+ return a.getIntProperty("Number") - b.getIntProperty("Number");
+ } catch (JMSException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ int msgIdx = 0;
+ for (Message outMsg : outMessages) {
+ assertEquals(
+ outMsg.getIntProperty("Number"),
+ msgsIn.get(msgIdx).properties().get("Number").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsOdd"),
+ msgsIn.get(msgIdx).properties().get("IsOdd").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsEven"),
+ (msgsIn.get(msgIdx).properties().get("IsEven").get()));
+ assertEquals(outMsg.getJMSType(), "type");
+ assertEquals(outMsg.getJMSCorrelationID(), "correlationId");
+ assertEquals(((ActiveMQQueue) outMsg.getJMSReplyTo()).getQueueName(), "test-reply");
+ msgIdx++;
+ }
+ });
+ }
+
+ @Test
+ public void publishJmsTextMessagesWithPropertiesAndConsumeThemWithASelector() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<JmsTextMessage> msgsIn = createTestMessageList();
+
+ Source.from(msgsIn).runWith(jmsSink, system);
+
+ Source<AckEnvelope, JmsConsumerControl> jmsSource =
+ JmsConsumer.ackSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withBufferSize(5)
+ .withQueue("test")
+ .withSelector("IsOdd = TRUE"));
+
+ List<JmsTextMessage> oddMsgsIn =
+ msgsIn.stream()
+ .filter(msg -> Integer.valueOf(msg.body()) % 2 == 1)
+ .collect(Collectors.toList());
+ assertEquals(5, oddMsgsIn.size());
+
+ CompletionStage<List<Message>> result =
+ jmsSource
+ .take(oddMsgsIn.size())
+ .map(
+ env -> {
+ env.acknowledge();
+ return env.message();
+ })
+ .runWith(Sink.seq(), system);
+
+ List<Message> outMessages =
+ new ArrayList<>(result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ outMessages.sort(
+ (a, b) -> {
+ try {
+ return a.getIntProperty("Number") - b.getIntProperty("Number");
+ } catch (JMSException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ int msgIdx = 0;
+ for (Message outMsg : outMessages) {
+ assertEquals(
+ outMsg.getIntProperty("Number"),
+ oddMsgsIn.get(msgIdx).properties().get("Number").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsOdd"),
+ oddMsgsIn.get(msgIdx).properties().get("IsOdd").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsEven"),
+ (oddMsgsIn.get(msgIdx).properties().get("IsEven").get()));
+ assertEquals(1, outMsg.getIntProperty("Number") % 2);
+ msgIdx++;
+ }
+ });
+ }
+
+ @Test
+ public void publishAndConsumeTopic() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+ List<String> inNumbers =
+ IntStream.range(0, 10).boxed().map(String::valueOf).collect(Collectors.toList());
+
+ Sink<String, CompletionStage<Done>> jmsTopicSink =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withTopic("topic"));
+ Sink<String, CompletionStage<Done>> jmsTopicSink2 =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withTopic("topic"));
+
+ Source<AckEnvelope, JmsConsumerControl> jmsTopicSource =
+ JmsConsumer.ackSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(1)
+ .withBufferSize(5)
+ .withTopic("topic"));
+ Source<AckEnvelope, JmsConsumerControl> jmsTopicSource2 =
+ JmsConsumer.ackSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(1)
+ .withBufferSize(5)
+ .withTopic("topic"));
+
+ CompletionStage<List<String>> result =
+ jmsTopicSource
+ .take(in.size() + inNumbers.size())
+ .map(
+ env -> {
+ env.acknowledge();
+ return ((TextMessage) env.message()).getText();
+ })
+ .runWith(Sink.seq(), system)
+ .thenApply(l -> l.stream().sorted().collect(Collectors.toList()));
+ CompletionStage<List<String>> result2 =
+ jmsTopicSource2
+ .take(in.size() + inNumbers.size())
+ .map(
+ env -> {
+ env.acknowledge();
+ return ((TextMessage) env.message()).getText();
+ })
+ .runWith(Sink.seq(), system)
+ .thenApply(l -> l.stream().sorted().collect(Collectors.toList()));
+
+ Thread.sleep(500);
+
+ Source.from(in).runWith(jmsTopicSink, system);
+ Source.from(inNumbers).runWith(jmsTopicSink2, system);
+
+ assertEquals(
+ Stream.concat(in.stream(), inNumbers.stream()).sorted().collect(Collectors.toList()),
+ result.toCompletableFuture().get(5, TimeUnit.SECONDS));
+ assertEquals(
+ Stream.concat(in.stream(), inNumbers.stream()).sorted().collect(Collectors.toList()),
+ result2.toCompletableFuture().get(5, TimeUnit.SECONDS));
+ });
+ }
+
+ private void withServer(ConsumerChecked<EmbeddedActiveMQResource> test) throws Exception {
+ EmbeddedActiveMQResource server = new EmbeddedActiveMQResource();
+ try {
+ server.start();
+ test.accept(server);
+ Thread.sleep(500);
+ } finally {
+ server.stop();
+ }
+ }
+
+ private void withConnectionFactory(ConsumerChecked<ConnectionFactory> test) throws Exception {
+ withServer(
+ server -> test.accept(new ActiveMQConnectionFactory(server.getVmURL()))
+ );
+ }
+
+ @FunctionalInterface
+ private interface ConsumerChecked<T> {
+ void accept(T elt) throws Exception;
+ }
+}
diff --git a/jakartams/src/test/java/docs/javadsl/JmsConnectorsTest.java b/jakartams/src/test/java/docs/javadsl/JmsConnectorsTest.java
new file mode 100644
index 000000000..b0643cd3a
--- /dev/null
+++ b/jakartams/src/test/java/docs/javadsl/JmsConnectorsTest.java
@@ -0,0 +1,930 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package docs.javadsl;
+
+import com.typesafe.config.Config;
+import jakarta.jms.*;
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+import org.apache.activemq.artemis.jms.client.ActiveMQQueue;
+import org.apache.activemq.artemis.jms.client.ActiveMQSession;
+import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage;
+import org.apache.activemq.artemis.junit.EmbeddedActiveMQResource;
+import org.apache.pekko.Done;
+import org.apache.pekko.NotUsed;
+import org.apache.pekko.actor.ActorSystem;
+import org.apache.pekko.japi.Pair;
+import org.apache.pekko.stream.connectors.jakartams.Destination;
+import org.apache.pekko.stream.connectors.jakartams.*;
+import org.apache.pekko.stream.connectors.jakartams.javadsl.JmsConsumer;
+import org.apache.pekko.stream.connectors.jakartams.javadsl.JmsConsumerControl;
+import org.apache.pekko.stream.connectors.jakartams.javadsl.JmsProducer;
+import org.apache.pekko.stream.connectors.jakartams.javadsl.JmsProducerStatus;
+import org.apache.pekko.stream.connectors.testkit.javadsl.LogCapturingJunit4;
+import org.apache.pekko.stream.javadsl.Flow;
+import org.apache.pekko.stream.javadsl.Keep;
+import org.apache.pekko.stream.javadsl.Sink;
+import org.apache.pekko.stream.javadsl.Source;
+import org.apache.pekko.testkit.javadsl.TestKit;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import scala.util.Failure;
+import scala.util.Success;
+import scala.util.Try;
+
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static junit.framework.TestCase.assertTrue;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+final class DummyJavaTests implements java.io.Serializable {
+
+ private static final long serialVersionUID = 1234567L;
+
+ private final String value;
+
+ DummyJavaTests(String value) {
+ this.value = value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+
+ if (o instanceof DummyJavaTests) {
+ return ((DummyJavaTests) o).value.equals(this.value);
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return value != null ? value.hashCode() : 0;
+ }
+}
+
+public class JmsConnectorsTest {
+
+ @Rule
+ public final LogCapturingJunit4 logCapturing = new LogCapturingJunit4();
+
+ private static ActorSystem system;
+ private static Config producerConfig;
+ private static Config browseConfig;
+
+ @BeforeClass
+ public static void setup() {
+ system = ActorSystem.create();
+ producerConfig = system.settings().config().getConfig(JmsProducerSettings.configPath());
+ browseConfig = system.settings().config().getConfig(JmsBrowseSettings.configPath());
+ }
+
+ @AfterClass
+ public static void teardown() {
+ TestKit.shutdownActorSystem(system);
+ }
+
+ private List<JmsTextMessage> createTestMessageList() {
+ List<Integer> intsIn = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ List<JmsTextMessage> msgsIn = new ArrayList<>();
+ for (Integer n : intsIn) {
+
+ // #create-messages-with-properties
+ JmsTextMessage message =
+ org.apache.pekko.stream.connectors.jakartams.JmsTextMessage.create(n.toString())
+ .withProperty("Number", n)
+ .withProperty("IsOdd", n % 2 == 1)
+ .withProperty("IsEven", n % 2 == 0);
+ // #create-messages-with-properties
+
+ msgsIn.add(message);
+ }
+
+ return msgsIn;
+ }
+
+ @Test
+ public void publishAndConsumeJmsTextMessage() throws Exception {
+ withServer(
+ server -> {
+ // #connection-factory
+ // #text-sink
+ // #text-source
+ ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(server.getVmURL());
+ // #text-source
+ // #connection-factory
+ // #text-sink
+
+ // #text-sink
+
+ Sink<String, CompletionStage<Done>> jmsSink =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(system, connectionFactory).withQueue("test"));
+
+ List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+ CompletionStage<Done> finished = Source.from(in).runWith(jmsSink, system);
+ // #text-sink
+
+ // #text-source
+ Source<String, JmsConsumerControl> jmsSource =
+ JmsConsumer.textSource(
+ JmsConsumerSettings.create(system, connectionFactory).withQueue("test"));
+
+ CompletionStage<List<String>> result =
+ jmsSource.take(in.size()).runWith(Sink.seq(), system);
+ // #text-source
+
+ assertEquals(Done.getInstance(), finished.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ assertEquals(in, result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ });
+ }
+
+ @Test
+ public void publishAndConsumeJmsObjectMessage() throws Exception {
+ withServer(
+ server -> {
+ // #connection-factory-object
+ // #object-sink
+ // #object-source
+ ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(server.getVmURL());
+ //connectionFactory.(Arrays.asList(DummyJavaTests.class.getPackage().getName()));
+
+ // #object-source
+ // #connection-factory-object
+ // #object-sink
+
+ // #object-sink
+ Sink<java.io.Serializable, CompletionStage<Done>> jmsSink =
+ JmsProducer.objectSink(
+ JmsProducerSettings.create(system, connectionFactory).withQueue("test"));
+
+ java.io.Serializable in = new DummyJavaTests("javaTest");
+ CompletionStage<Done> finished = Source.single(in).runWith(jmsSink, system);
+ // #object-sink
+
+ // #object-source
+ Source<java.io.Serializable, JmsConsumerControl> jmsSource =
+ JmsConsumer.objectSource(
+ JmsConsumerSettings.create(system, connectionFactory).withQueue("test"));
+
+ CompletionStage<java.io.Serializable> result =
+ jmsSource.take(1).runWith(Sink.head(), system);
+ // #object-source
+
+ assertEquals(Done.getInstance(), finished.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ Object resultObject = result.toCompletableFuture().get(3, TimeUnit.SECONDS);
+ assertEquals(resultObject, in);
+ });
+ }
+
+ @Test
+ public void publishAndConsumeJmsByteMessage() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ // #bytearray-sink
+ Sink<byte[], CompletionStage<Done>> jmsSink =
+ JmsProducer.bytesSink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ byte[] in = "ThisIsATest".getBytes(StandardCharsets.UTF_8);
+ CompletionStage<Done> finished = Source.single(in).runWith(jmsSink, system);
+ // #bytearray-sink
+
+ // #bytearray-source
+ Source<byte[], JmsConsumerControl> jmsSource =
+ JmsConsumer.bytesSource(
+ JmsConsumerSettings.create(system, connectionFactory).withQueue("test"));
+
+ CompletionStage<byte[]> result = jmsSource.take(1).runWith(Sink.head(), system);
+ // #bytearray-source
+
+ assertEquals(Done.getInstance(), finished.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ byte[] resultArray = result.toCompletableFuture().get(3, TimeUnit.SECONDS);
+ assertEquals("ThisIsATest", new String(resultArray, StandardCharsets.UTF_8));
+ });
+ }
+
+ @Test
+ public void publishAndConsumeJmsMapMessage() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ // #map-sink
+ // #map-source
+
+ // #map-sink
+ // #map-source
+ // #map-sink
+ Sink<Map<String, Object>, CompletionStage<Done>> jmsSink =
+ JmsProducer.mapSink(
+ JmsProducerSettings.create(system, connectionFactory).withQueue("test"));
+
+ Map<String, Object> in = new HashMap<>();
+ in.put("string value", "value");
+ in.put("int value", 42);
+ in.put("double value", 43.0);
+ in.put("short value", (short) 7);
+ in.put("boolean value", true);
+ in.put("long value", 7L);
+ in.put("bytearray", "AStringAsByteArray".getBytes(StandardCharsets.UTF_8));
+ in.put("byte", (byte) 1);
+
+ CompletionStage<Done> finished = Source.single(in).runWith(jmsSink, system);
+ // #map-sink
+
+ // #map-source
+ Source<Map<String, Object>, JmsConsumerControl> jmsSource =
+ JmsConsumer.mapSource(
+ JmsConsumerSettings.create(system, connectionFactory).withQueue("test"));
+
+ CompletionStage<Map<String, Object>> resultStage =
+ jmsSource.take(1).runWith(Sink.head(), system);
+ // #map-source
+
+ Map<String, Object> resultMap =
+ resultStage.toCompletableFuture().get(3, TimeUnit.SECONDS);
+
+ assertEquals(resultMap.get("string value"), in.get("string value"));
+ assertEquals(resultMap.get("int value"), in.get("int value"));
+ assertEquals(resultMap.get("double value"), in.get("double value"));
+ assertEquals(resultMap.get("short value"), in.get("short value"));
+ assertEquals(resultMap.get("boolean value"), in.get("boolean value"));
+ assertEquals(resultMap.get("long value"), in.get("long value"));
+ assertEquals(resultMap.get("byte"), in.get("byte"));
+
+ assertEquals(Done.getInstance(), finished.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ byte[] resultByteArray = (byte[]) resultMap.get("bytearray");
+ assertEquals(new String(resultByteArray, StandardCharsets.UTF_8), "AStringAsByteArray");
+ });
+ }
+
+ @Test
+ public void publishAndConsumeJmsTextMessagesWithProperties() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ int expectedMessages = 2;
+
+ // #create-jms-sink
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ CompletionStage<Done> finished =
+ Source.from(Arrays.asList("Message A", "Message B"))
+ .map(JmsTextMessage::create)
+ .runWith(jmsSink, system);
+ // #create-jms-sink
+
+ // #jms-source
+ Source<jakarta.jms.Message, JmsConsumerControl> jmsSource =
+ JmsConsumer.create(
+ JmsConsumerSettings.create(system, connectionFactory).withQueue("test"));
+
+ Pair<JmsConsumerControl, CompletionStage<List<String>>> controlAndResult =
+ jmsSource
+ .take(expectedMessages)
+ .map(
+ msg -> {
+ if (msg instanceof TextMessage) {
+ TextMessage t = (TextMessage) msg;
+ return t.getText();
+ } else
+ throw new RuntimeException("unexpected message type " + msg.getClass());
+ })
+ .toMat(Sink.seq(), Keep.both())
+ .run(system);
+
+ // #jms-source
+
+ CompletionStage<List<String>> result = controlAndResult.second();
+ List<String> outMessages = result.toCompletableFuture().get(3, TimeUnit.SECONDS);
+ assertEquals("unexpected number of elements", expectedMessages, outMessages.size());
+ // #jms-source
+ JmsConsumerControl control = controlAndResult.first();
+ control.shutdown();
+ // #jms-source
+ });
+ }
+
+ @Test
+ public void publishAndConsumeJmsTextMessagesWithHeaders() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ // #create-messages-with-headers
+ List<JmsTextMessage> msgsIn =
+ createTestMessageList().stream()
+ .map(
+ jmsTextMessage ->
+ jmsTextMessage
+ .withHeader(JmsType.create("type"))
+ .withHeader(JmsCorrelationId.create("correlationId"))
+ .withHeader(JmsReplyTo.queue("test-reply"))
+ .withHeader(JmsTimeToLive.create(999, TimeUnit.SECONDS))
+ .withHeader(JmsPriority.create(2))
+ .withHeader(JmsDeliveryMode.create(DeliveryMode.NON_PERSISTENT)))
+ .collect(Collectors.toList());
+ // #create-messages-with-headers
+
+ Source.from(msgsIn).runWith(jmsSink, system);
+
+ Source<Message, JmsConsumerControl> jmsSource =
+ JmsConsumer.create(
+ JmsConsumerSettings.create(system, connectionFactory).withQueue("test"));
+
+ CompletionStage<List<Message>> result =
+ jmsSource.take(msgsIn.size()).runWith(Sink.seq(), system);
+
+ List<Message> outMessages = result.toCompletableFuture().get(3, TimeUnit.SECONDS);
+ int msgIdx = 0;
+ for (Message outMsg : outMessages) {
+ assertEquals(
+ outMsg.getIntProperty("Number"),
+ msgsIn.get(msgIdx).properties().get("Number").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsOdd"),
+ msgsIn.get(msgIdx).properties().get("IsOdd").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsEven"),
+ (msgsIn.get(msgIdx).properties().get("IsEven").get()));
+ assertEquals(outMsg.getJMSType(), "type");
+ assertEquals(outMsg.getJMSCorrelationID(), "correlationId");
+ assertEquals(((ActiveMQQueue) outMsg.getJMSReplyTo()).getQueueName(), "test-reply");
+
+ assertTrue(outMsg.getJMSExpiration() != 0);
+ assertEquals(2, outMsg.getJMSPriority());
+ assertEquals(DeliveryMode.NON_PERSISTENT, outMsg.getJMSDeliveryMode());
+ msgIdx++;
+ }
+ });
+ }
+
+ // #custom-destination
+ Function<jakarta.jms.Session, jakarta.jms.Destination> createQueue(String destinationName) {
+ return (session) -> {
+ ActiveMQSession amqSession = (ActiveMQSession) session;
+ try {
+ return amqSession.createQueue("my-" + destinationName);
+ } catch (JMSException e) {
+ throw new RuntimeException(e);
+ }
+ };
+ }
+ // #custom-destination
+
+ @Test
+ public void useCustomDestination() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory)
+ .withDestination(new CustomDestination("custom", createQueue("custom"))));
+
+ List<JmsTextMessage> msgsIn = createTestMessageList();
+
+ Source.from(msgsIn).runWith(jmsSink, system);
+ // #custom-destination
+
+ Source<Message, JmsConsumerControl> jmsSource =
+ JmsConsumer.create(
+ JmsConsumerSettings.create(system, connectionFactory)
+ .withDestination(new CustomDestination("custom", createQueue("custom"))));
+ // #custom-destination
+
+ CompletionStage<List<Message>> result =
+ jmsSource.take(msgsIn.size()).runWith(Sink.seq(), system);
+ List<Message> outMessages = result.toCompletableFuture().get(3, TimeUnit.SECONDS);
+ assertEquals(10, outMessages.size());
+ });
+ }
+
+ @Test
+ public void publishJmsTextMessagesWithPropertiesAndConsumeThemWithASelector() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<JmsTextMessage> msgsIn = createTestMessageList();
+
+ Source.from(msgsIn).runWith(jmsSink, system);
+
+ // #source-with-selector
+ Source<Message, JmsConsumerControl> jmsSource =
+ JmsConsumer.create(
+ JmsConsumerSettings.create(system, connectionFactory)
+ .withQueue("test")
+ .withSelector("IsOdd = TRUE"));
+ // #source-with-selector
+
+ List<JmsTextMessage> oddMsgsIn =
+ msgsIn.stream()
+ .filter(msg -> Integer.valueOf(msg.body()) % 2 == 1)
+ .collect(Collectors.toList());
+ assertEquals(5, oddMsgsIn.size());
+
+ CompletionStage<List<Message>> result =
+ jmsSource.take(oddMsgsIn.size()).runWith(Sink.seq(), system);
+
+ List<Message> outMessages = result.toCompletableFuture().get(4, TimeUnit.SECONDS);
+ int msgIdx = 0;
+ for (Message outMsg : outMessages) {
+ assertEquals(
+ outMsg.getIntProperty("Number"),
+ oddMsgsIn.get(msgIdx).properties().get("Number").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsOdd"),
+ oddMsgsIn.get(msgIdx).properties().get("IsOdd").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsEven"),
+ (oddMsgsIn.get(msgIdx).properties().get("IsEven").get()));
+ assertEquals(1, outMsg.getIntProperty("Number") % 2);
+ msgIdx++;
+ }
+ });
+ }
+
+ @Test
+ public void publishAndConsumeTopic() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+ List<String> inNumbers =
+ IntStream.range(0, 10).boxed().map(String::valueOf).collect(Collectors.toList());
+
+ Sink<String, CompletionStage<Done>> jmsTopicSink =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withTopic("topic"));
+
+ Sink<String, CompletionStage<Done>> jmsTopicSink2 =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withTopic("topic"));
+
+ Source<String, JmsConsumerControl> jmsTopicSource =
+ JmsConsumer.textSource(
+ JmsConsumerSettings.create(system, connectionFactory).withTopic("topic"));
+
+ Source<String, JmsConsumerControl> jmsTopicSource2 =
+ JmsConsumer.textSource(
+ JmsConsumerSettings.create(system, connectionFactory).withTopic("topic"));
+
+ CompletionStage<List<String>> result =
+ jmsTopicSource
+ .take(in.size() + inNumbers.size())
+ .runWith(Sink.seq(), system)
+ .thenApply(l -> l.stream().sorted().collect(Collectors.toList()));
+
+ CompletionStage<List<String>> result2 =
+ jmsTopicSource2
+ .take(in.size() + inNumbers.size())
+ .runWith(Sink.seq(), system)
+ .thenApply(l -> l.stream().sorted().collect(Collectors.toList()));
+
+ Thread.sleep(500);
+
+ CompletionStage<Done> finished = Source.from(in).runWith(jmsTopicSink, system);
+ Source.from(inNumbers).runWith(jmsTopicSink2, system);
+
+ assertEquals(
+ Stream.concat(in.stream(), inNumbers.stream()).sorted().collect(Collectors.toList()),
+ result.toCompletableFuture().get(5, TimeUnit.SECONDS));
+ assertEquals(
+ Stream.concat(in.stream(), inNumbers.stream()).sorted().collect(Collectors.toList()),
+ result2.toCompletableFuture().get(5, TimeUnit.SECONDS));
+ });
+ }
+
+ @Test
+ public void sinkNormalCompletion() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory)
+ .withQueue("test")
+ .withConnectionRetrySettings(
+ ConnectionRetrySettings.create(system).withMaxRetries(0)));
+
+ List<JmsTextMessage> msgsIn = createTestMessageList();
+
+ CompletionStage<Done> completionFuture = Source.from(msgsIn).runWith(jmsSink, system);
+ Done completed = completionFuture.toCompletableFuture().get(3, TimeUnit.SECONDS);
+ assertEquals(completed, Done.getInstance());
+ });
+ }
+
+ @Test
+ public void sinkExceptionalCompletion() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ CompletionStage<Done> completionFuture =
+ Source.<JmsTextMessage>failed(new RuntimeException("Simulated error"))
+ .runWith(jmsSink, system);
+
+ try {
+ completionFuture.toCompletableFuture().get(3, TimeUnit.SECONDS);
+ fail("Not completed exceptionally");
+ } catch (ExecutionException e) {
+ Throwable cause = e.getCause();
+ assertTrue(cause instanceof RuntimeException);
+ }
+ });
+ }
+
+ @Test
+ public void sinkExceptionalCompletionOnDisconnect() throws Exception {
+ withServer(
+ server -> {
+ ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(server.getVmURL());
+
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory)
+ .withQueue("test")
+ .withConnectionRetrySettings(
+ ConnectionRetrySettings.create(system).withMaxRetries(0)));
+
+ List<JmsTextMessage> msgsIn = createTestMessageList();
+
+ CompletionStage<Done> completionFuture =
+ Source.from(msgsIn)
+ .mapAsync(
+ 1,
+ m ->
+ CompletableFuture.supplyAsync(
+ () -> {
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ return m;
+ }))
+ .runWith(jmsSink, system);
+
+ try { // Make sure connection got started before stopping.
+ Thread.sleep(500);
+ } catch (InterruptedException e) {
+ fail("Sleep interrupted.");
+ }
+
+ server.stop();
+
+ try {
+ completionFuture.toCompletableFuture().get(3, TimeUnit.SECONDS);
+ fail("Not completed exceptionally");
+ } catch (ExecutionException e) {
+ Throwable cause = e.getCause();
+ assertTrue(cause instanceof JMSException);
+ }
+ });
+ }
+
+ @Test
+ public void browse() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<String, CompletionStage<Done>> jmsSink =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+
+ Source.from(in).runWith(jmsSink, system).toCompletableFuture().get();
+
+ // #browse-source
+ Source<jakarta.jms.Message, NotUsed> browseSource =
+ JmsConsumer.browse(
+ JmsBrowseSettings.create(system, connectionFactory).withQueue("test"));
+
+ CompletionStage<List<jakarta.jms.Message>> result =
+ browseSource.runWith(Sink.seq(), system);
+ // #browse-source
+
+ List<String> resultText =
+ result.toCompletableFuture().get().stream()
+ .map(
+ message -> ((ActiveMQTextMessage) message).getText())
+ .collect(Collectors.toList());
+
+ assertEquals(in, resultText);
+ });
+ }
+
+ @Test
+ public void publishAndConsumeDurableTopic() throws Exception {
+ withServer(
+ server -> {
+ ConnectionFactory producerConnectionFactory = new ActiveMQConnectionFactory(server.getVmURL());
+ // #create-connection-factory-with-client-id
+ ConnectionFactory consumerConnectionFactory = new ActiveMQConnectionFactory(server.getVmURL());
+ ((ActiveMQConnectionFactory) consumerConnectionFactory)
+ .setClientID(getClass().getSimpleName());
+ // #create-connection-factory-with-client-id
+
+ List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+
+ Sink<String, CompletionStage<Done>> jmsTopicSink =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(producerConfig, producerConnectionFactory)
+ .withTopic("topic"));
+
+ // #create-durable-topic-source
+ Source<String, JmsConsumerControl> jmsTopicSource =
+ JmsConsumer.textSource(
+ JmsConsumerSettings.create(system, consumerConnectionFactory)
+ .withDurableTopic("topic", "durable-test"));
+ // #create-durable-topic-source
+
+ // #run-durable-topic-source
+ CompletionStage<List<String>> result =
+ jmsTopicSource.take(in.size()).runWith(Sink.seq(), system);
+ // #run-durable-topic-source
+
+ Thread.sleep(500);
+
+ Source.from(in).runWith(jmsTopicSink, system);
+
+ assertEquals(in, result.toCompletableFuture().get(5, TimeUnit.SECONDS));
+ });
+ }
+
+ @Test
+ public void producerFlow() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ // #flow-producer
+ Flow<JmsTextMessage, JmsTextMessage, JmsProducerStatus> flow =
+ JmsProducer.flow(
+ JmsProducerSettings.create(system, connectionFactory).withQueue("test"));
+
+ List<JmsTextMessage> input = createTestMessageList();
+
+ CompletionStage<List<JmsTextMessage>> result =
+ Source.from(input).via(flow).runWith(Sink.seq(), system);
+ // #flow-producer
+
+ assertEquals(input, result.toCompletableFuture().get());
+ });
+ }
+
+ @Test
+ public void directedProducerFlow() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ // #run-directed-flow-producer
+ Flow<JmsTextMessage, JmsTextMessage, JmsProducerStatus> flowSink =
+ JmsProducer.flow(
+ JmsProducerSettings.create(system, connectionFactory).withQueue("test"));
+
+ List<JmsTextMessage> input = new ArrayList<>();
+ for (Integer n : Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) {
+ String queueName = (n % 2 == 0) ? "even" : "odd";
+ input.add(JmsTextMessage.create(n.toString()).toQueue(queueName));
+ }
+
+ Source.from(input).via(flowSink).runWith(Sink.seq(), system);
+ // #run-directed-flow-producer
+
+ CompletionStage<List<Integer>> even =
+ JmsConsumer.textSource(
+ JmsConsumerSettings.create(system, connectionFactory).withQueue("even"))
+ .take(5)
+ .map(Integer::parseInt)
+ .runWith(Sink.seq(), system);
+
+ CompletionStage<List<Integer>> odd =
+ JmsConsumer.textSource(
+ JmsConsumerSettings.create(system, connectionFactory).withQueue("odd"))
+ .take(5)
+ .map(Integer::parseInt)
+ .runWith(Sink.seq(), system);
+
+ assertEquals(Arrays.asList(1, 3, 5, 7, 9), odd.toCompletableFuture().get());
+ assertEquals(Arrays.asList(2, 4, 6, 8, 10), even.toCompletableFuture().get());
+ });
+ }
+
+ @Test
+ public void failAfterRetry() throws Exception {
+ withServer(
+ server -> {
+ ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(server.getVmURL());
+ server.stop();
+ long startTime = System.currentTimeMillis();
+ CompletionStage<List<Message>> result =
+ JmsConsumer.create(
+ JmsConsumerSettings.create(system, connectionFactory)
+ .withConnectionRetrySettings(
+ ConnectionRetrySettings.create(system).withMaxRetries(4))
+ .withQueue("test"))
+ .runWith(Sink.seq(), system);
+
+ CompletionStage<Try<List<Message>>> tryFuture =
+ result.handle(
+ (l, e) -> {
+ if (l != null) return Success.apply(l);
+ else return Failure.apply(e);
+ });
+
+ Try<List<Message>> tryResult = tryFuture.toCompletableFuture().get();
+ long endTime = System.currentTimeMillis();
+
+ assertTrue("Total retry is too short", endTime - startTime > 100L + 400L + 900L + 1600L);
+ assertTrue("Result must be a failure", tryResult.isFailure());
+ Throwable exception = tryResult.failed().get();
+ assertTrue(
+ "Did not fail with a ConnectionRetryException",
+ exception instanceof ConnectionRetryException);
+ assertTrue(
+ "Cause of failure is not a JMSException",
+ exception.getCause() instanceof JMSException);
+ });
+ }
+
+ @Test
+ public void passThroughMessageEnvelopes() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ // #run-flexi-flow-producer
+ Flow<JmsEnvelope<String>, JmsEnvelope<String>, JmsProducerStatus> jmsProducer =
+ JmsProducer.flexiFlow(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<String> data = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+ List<JmsEnvelope<String>> input = new ArrayList<>();
+ for (String s : data) {
+ String passThrough = s;
+ input.add(JmsTextMessage.create(s, passThrough));
+ }
+
+ CompletionStage<List<String>> result =
+ Source.from(input)
+ .via(jmsProducer)
+ .map(JmsEnvelope::passThrough)
+ .runWith(Sink.seq(), system);
+ // #run-flexi-flow-producer
+ assertEquals(data, result.toCompletableFuture().get());
+ });
+ }
+
+ @Test
+ public void passThroughEmptyMessageEnvelopes() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Pair<JmsConsumerControl, CompletionStage<List<String>>> switchAndItems =
+ JmsConsumer.textSource(
+ JmsConsumerSettings.create(system, connectionFactory).withQueue("test"))
+ .toMat(Sink.seq(), Keep.both())
+ .run(system);
+
+ // #run-flexi-flow-pass-through-producer
+ Flow<JmsEnvelope<String>, JmsEnvelope<String>, JmsProducerStatus> jmsProducer =
+ JmsProducer.flexiFlow(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<String> data = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+ List<JmsEnvelope<String>> input = new ArrayList<>();
+ for (String s : data) {
+ String passThrough = s;
+ input.add(JmsPassThrough.create(passThrough));
+ }
+
+ CompletionStage<List<String>> result =
+ Source.from(input)
+ .via(jmsProducer)
+ .map(JmsEnvelope::passThrough)
+ .runWith(Sink.seq(), system);
+ // #run-flexi-flow-pass-through-producer
+
+ assertEquals(data, result.toCompletableFuture().get());
+
+ Thread.sleep(500);
+
+ switchAndItems.first().shutdown();
+ assertTrue(switchAndItems.second().toCompletableFuture().get().isEmpty());
+ });
+ }
+
+ @Test
+ public void requestReplyWithTempQueues() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Connection connection = connectionFactory.createConnection();
+ connection.start();
+ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ TemporaryQueue tempQueue = session.createTemporaryQueue();
+ Destination tempQueueDest =
+ org.apache.pekko.stream.connectors.jakartams.Destination.createDestination(tempQueue);
+ String message = "ThisIsATest";
+ Function<String, String> reverse = (in) -> new StringBuilder(in).reverse().toString();
+ String correlationId = UUID.randomUUID().toString();
+
+ Sink<JmsTextMessage, CompletionStage<Done>> toRespondSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(system, connectionFactory).withQueue("test"));
+
+ CompletionStage<Done> toRespondStreamCompletion =
+ Source.single(
+ JmsTextMessage.create(message)
+ .withHeader(JmsCorrelationId.create(correlationId))
+ .withHeader(new JmsReplyTo(tempQueueDest)))
+ .runWith(toRespondSink, system);
+
+ // #request-reply
+ JmsConsumerControl respondStreamControl =
+ JmsConsumer.create(
+ JmsConsumerSettings.create(system, connectionFactory).withQueue("test"))
+ .map(JmsMessageFactory::create)
+ .collectType(JmsTextMessage.class)
+ .map(
+ textMessage -> {
+ JmsTextMessage m = JmsTextMessage.create(reverse.apply(textMessage.body()));
+ for (JmsHeader h : textMessage.getHeaders())
+ if (h.getClass().equals(JmsReplyTo.class))
+ m = m.to(((JmsReplyTo) h).jmsDestination());
+ else if (h.getClass().equals(JmsCorrelationId.class))
+ m = m.withHeader(h);
+ return m;
+ })
+ .via(
+ JmsProducer.flow(
+ JmsProducerSettings.create(system, connectionFactory)
+ .withQueue("ignored")))
+ .to(Sink.ignore())
+ .run(system);
+ // #request-reply
+
+ // getting ConnectionRetryException when trying to listen using streams, assuming it's
+ // because a different session can't listen on the original session's TemporaryQueue
+ MessageConsumer consumer = session.createConsumer(tempQueue);
+ Message msg = consumer.receive(5000);
+
+ assertEquals(Done.done(), toRespondStreamCompletion.toCompletableFuture().get());
+
+ assertTrue(msg instanceof TextMessage);
+ assertEquals(correlationId, msg.getJMSCorrelationID());
+ assertEquals(reverse.apply(message), ((TextMessage) msg).getText());
+
+ respondStreamControl.shutdown();
+
+ connection.close();
+ });
+ }
+
+ private void withServer(ConsumerChecked<EmbeddedActiveMQResource> test) throws Exception {
+ EmbeddedActiveMQResource server = new EmbeddedActiveMQResource();
+ try {
+ server.start();
+ test.accept(server);
+ Thread.sleep(500);
+ } finally {
+ if (server.getServer().getActiveMQServer().isStarted()) {
+ server.stop();
+ }
+ }
+ }
+
+ private void withConnectionFactory(ConsumerChecked<ConnectionFactory> test) throws Exception {
+ withServer(
+ server -> test.accept(new ActiveMQConnectionFactory(server.getVmURL()))
+ );
+ }
+
+ @FunctionalInterface
+ private interface ConsumerChecked<T> {
+ void accept(T elt) throws Exception;
+ }
+}
diff --git a/jakartams/src/test/java/docs/javadsl/JmsIbmmqConnectorsTest.java b/jakartams/src/test/java/docs/javadsl/JmsIbmmqConnectorsTest.java
new file mode 100644
index 000000000..e282aea35
--- /dev/null
+++ b/jakartams/src/test/java/docs/javadsl/JmsIbmmqConnectorsTest.java
@@ -0,0 +1,223 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package docs.javadsl;
+
+import com.ibm.mq.jakarta.jms.MQConnectionFactory;
+import com.ibm.mq.jakarta.jms.MQQueueConnectionFactory;
+import com.ibm.mq.jakarta.jms.MQQueueSession;
+import com.ibm.mq.jakarta.jms.MQTopicConnectionFactory;
+import com.ibm.msg.client.jakarta.wmq.common.CommonConstants;
+import jakarta.jms.Destination;
+import jakarta.jms.JMSException;
+import jakarta.jms.Session;
+import jakarta.jms.TextMessage;
+import org.apache.pekko.Done;
+import org.apache.pekko.actor.ActorSystem;
+import org.apache.pekko.stream.connectors.jakartams.CustomDestination;
+import org.apache.pekko.stream.connectors.jakartams.JmsConsumerSettings;
+import org.apache.pekko.stream.connectors.jakartams.JmsProducerSettings;
+import org.apache.pekko.stream.connectors.jakartams.TxEnvelope;
+import org.apache.pekko.stream.connectors.jakartams.javadsl.JmsConsumer;
+import org.apache.pekko.stream.connectors.jakartams.javadsl.JmsConsumerControl;
+import org.apache.pekko.stream.connectors.jakartams.javadsl.JmsProducer;
+import org.apache.pekko.stream.connectors.testkit.javadsl.LogCapturingJunit4;
+import org.apache.pekko.stream.javadsl.Sink;
+import org.apache.pekko.stream.javadsl.Source;
+import org.apache.pekko.testkit.javadsl.TestKit;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.function.Function;
+
+import static org.junit.Assert.assertEquals;
+
+public class JmsIbmmqConnectorsTest {
+
+ @Rule
+ public final LogCapturingJunit4 logCapturing = new LogCapturingJunit4();
+
+ private static ActorSystem system;
+ private static MQQueueConnectionFactory queueConnectionFactory;
+ private static MQTopicConnectionFactory topicConnectionFactory;
+
+ @BeforeClass
+ public static void setup() throws JMSException {
+ system = ActorSystem.create();
+ // #ibmmq-connection-factory
+ // Create the IBM MQ MQQueueConnectionFactory
+ MQQueueConnectionFactory connectionFactory = new MQQueueConnectionFactory();
+
+ // #ibmmq-connection-factory
+ JmsIbmmqConnectorsTest.queueConnectionFactory =
+ (MQQueueConnectionFactory) initDefaultFactory(connectionFactory);
+ JmsIbmmqConnectorsTest.topicConnectionFactory =
+ (MQTopicConnectionFactory) initDefaultFactory(new MQTopicConnectionFactory());
+ }
+
+ private static MQConnectionFactory initDefaultFactory(MQConnectionFactory connectionFactory)
+ throws JMSException {
+ // #ibmmq-connection-factory
+ // align to docker image: ibmcom/mq:9.1.1.0
+ connectionFactory.setHostName("localhost");
+ connectionFactory.setPort(1414);
+ connectionFactory.setQueueManager("QM1");
+ connectionFactory.setChannel("DEV.APP.SVRCONN");
+
+ // #ibmmq-connection-factory
+ return connectionFactory;
+ }
+
+ @AfterClass
+ public static void teardown() {
+ TestKit.shutdownActorSystem(system);
+ }
+
+ @Test
+ public void publishAndConsumeQueue()
+ throws JMSException, InterruptedException, ExecutionException, TimeoutException {
+
+ // #ibmmq-queue
+ // Connect to IBM MQ over TCP/IP
+ queueConnectionFactory.setTransportType(CommonConstants.WMQ_CM_CLIENT);
+ String queueName = "DEV.QUEUE.1";
+
+ Sink<String, CompletionStage<Done>> jmsSink =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(system, queueConnectionFactory).withQueue(queueName));
+
+ // #ibmmq-queue
+
+ List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+ Source.from(in).runWith(jmsSink, system);
+
+ // #ibmmq-queue
+ // Option1: create Source using default factory with just name
+ Source<TxEnvelope, JmsConsumerControl> txJmsSource =
+ JmsConsumer.txSource(
+ JmsConsumerSettings.create(system, queueConnectionFactory).withQueue(queueName));
+
+ // #ibmmq-queue
+
+ CompletionStage<List<String>> result =
+ txJmsSource
+ .take(in.size())
+ .map(
+ envelope -> {
+ envelope.commit();
+ if (envelope.message() instanceof TextMessage) {
+ TextMessage message = (TextMessage) envelope.message();
+ return message.getText();
+ } else {
+ throw new RuntimeException(
+ "unexpected message type " + envelope.message().getClass());
+ }
+ })
+ .runWith(Sink.seq(), system);
+
+ List<String> out = new ArrayList<>(result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ Collections.sort(out);
+ assertEquals(in, out);
+ }
+
+ @Test
+ public void publishAndConsumeCustomDestination()
+ throws JMSException, InterruptedException, ExecutionException, TimeoutException {
+
+ queueConnectionFactory.setTransportType(CommonConstants.WMQ_CM_CLIENT);
+
+ // #ibmmq-custom-destination
+ // Option2: create Source using custom factory
+ String customQueue = "DEV.QUEUE.3";
+ // #ibmmq-custom-destination
+
+ // "app" clients are limited to perform create queue
+ // existing queue in use
+ Sink<String, CompletionStage<Done>> jmsSink =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(system, queueConnectionFactory)
+ .withDestination(new CustomDestination("custom", createQueue(customQueue))));
+
+ List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+
+ Source.from(in).runWith(jmsSink, system);
+
+ // #ibmmq-custom-destination
+ Source<String, JmsConsumerControl> jmsSource =
+ JmsConsumer.textSource(
+ JmsConsumerSettings.create(system, queueConnectionFactory)
+ .withDestination(new CustomDestination("custom", createQueue(customQueue))));
+
+ // #ibmmq-custom-destination
+
+ CompletionStage<List<String>> result = jmsSource.take(in.size()).runWith(Sink.seq(), system);
+
+ assertEquals(in.size(), result.toCompletableFuture().get(5, TimeUnit.SECONDS).size());
+ }
+
+ @Test
+ public void publishAndConsumeTopic()
+ throws JMSException, InterruptedException, ExecutionException, TimeoutException {
+
+ List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+
+ // #ibmmq-topic
+ // Connect to IBM MQ over TCP/IP
+ topicConnectionFactory.setTransportType(CommonConstants.WMQ_CM_CLIENT);
+ String testTopicName = "dev/";
+
+ Sink<String, CompletionStage<Done>> jmsTopicSink =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(system, topicConnectionFactory).withTopic(testTopicName));
+
+ // Option1: create Source using default factory with just name
+ Source<String, JmsConsumerControl> jmsTopicSource =
+ JmsConsumer.textSource(
+ JmsConsumerSettings.create(system, topicConnectionFactory).withTopic(testTopicName));
+ // #ibmmq-topic
+
+ CompletionStage<List<String>> result =
+ jmsTopicSource.take(in.size()).runWith(Sink.seq(), system);
+
+ Thread.sleep(500);
+
+ Source.from(in).runWith(jmsTopicSink, system);
+
+ assertEquals(in, result.toCompletableFuture().get(5, TimeUnit.SECONDS));
+ }
+
+ // #ibmmq-custom-destination
+ Function<Session, Destination> createQueue(String destinationName) {
+ return (session) -> {
+ // cast to correct session implementation: MQQueueSession, MQTopicSession, MQSession
+ MQQueueSession mqSession = (MQQueueSession) session;
+ try {
+ return mqSession.createQueue(destinationName);
+ } catch (JMSException e) {
+ throw new RuntimeException(e);
+ }
+ };
+ }
+ // #ibmmq-custom-destination
+
+}
diff --git a/jakartams/src/test/java/docs/javadsl/JmsSettingsTest.java b/jakartams/src/test/java/docs/javadsl/JmsSettingsTest.java
new file mode 100644
index 000000000..6e7ba2345
--- /dev/null
+++ b/jakartams/src/test/java/docs/javadsl/JmsSettingsTest.java
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package docs.javadsl;
+
+import com.typesafe.config.Config;
+import com.typesafe.config.ConfigFactory;
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+import org.apache.activemq.artemis.junit.EmbeddedActiveMQResource;
+import org.apache.pekko.stream.connectors.jakartams.*;
+import org.apache.pekko.stream.connectors.testkit.javadsl.LogCapturingJunit4;
+import org.junit.Rule;
+import org.junit.Test;
+import scala.Option;
+
+import java.time.Duration;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertEquals;
+
+// #retry-settings #send-retry-settings
+
+public class JmsSettingsTest {
+
+ @Rule
+ public final LogCapturingJunit4 logCapturing = new LogCapturingJunit4();
+
+ @Test
+ public void producerSettings() throws Exception {
+
+ Config config = ConfigFactory.load();
+ // #retry-settings
+ Config connectionRetryConfig = config.getConfig("pekko.connectors.jakartams.connection-retry");
+ // reiterating the values from reference.conf
+ ConnectionRetrySettings retrySettings =
+ ConnectionRetrySettings.create(connectionRetryConfig)
+ .withConnectTimeout(Duration.ofSeconds(10))
+ .withInitialRetry(Duration.ofMillis(100))
+ .withBackoffFactor(2.0)
+ .withMaxBackoff(Duration.ofMinutes(1))
+ .withMaxRetries(10);
+ // #retry-settings
+
+ ConnectionRetrySettings retrySettings2 = ConnectionRetrySettings.create(connectionRetryConfig);
+ assertEquals(retrySettings.toString(), retrySettings2.toString());
+
+ // #send-retry-settings
+ Config sendRetryConfig = config.getConfig("pekko.connectors.jakartams.send-retry");
+ // reiterating the values from reference.conf
+ SendRetrySettings sendRetrySettings =
+ SendRetrySettings.create(sendRetryConfig)
+ .withInitialRetry(Duration.ofMillis(20))
+ .withBackoffFactor(1.5d)
+ .withMaxBackoff(Duration.ofMillis(500))
+ .withMaxRetries(10);
+ // #send-retry-settings
+ SendRetrySettings sendRetrySettings2 = SendRetrySettings.create(sendRetryConfig);
+ assertEquals(sendRetrySettings.toString(), sendRetrySettings2.toString());
+ EmbeddedActiveMQResource server = new EmbeddedActiveMQResource();
+ // #producer-settings
+ Config producerConfig = config.getConfig(JmsProducerSettings.configPath());
+ JmsProducerSettings settings =
+ JmsProducerSettings.create(producerConfig, new ActiveMQConnectionFactory(server.getVmURL()))
+ .withTopic("target-topic")
+ .withCredentials(Credentials.create("username", "password"))
+ .withConnectionRetrySettings(retrySettings)
+ .withSendRetrySettings(sendRetrySettings)
+ .withSessionCount(10)
+ .withTimeToLive(Duration.ofHours(1));
+ // #producer-settings
+ }
+
+ @Test
+ public void consumerSettings() throws Exception {
+ Config config = ConfigFactory.load();
+ Config connectionRetryConfig = config.getConfig("pekko.connectors.jakartams.connection-retry");
+ ConnectionRetrySettings retrySettings = ConnectionRetrySettings.create(connectionRetryConfig);
+ EmbeddedActiveMQResource server = new EmbeddedActiveMQResource();
+
+ // #consumer-settings
+ Config consumerConfig = config.getConfig(JmsConsumerSettings.configPath());
+ JmsConsumerSettings settings =
+ JmsConsumerSettings.create(consumerConfig, new ActiveMQConnectionFactory(server.getVmURL()))
+ .withTopic("message-topic")
+ .withCredentials(Credentials.create("username", "password"))
+ .withConnectionRetrySettings(retrySettings)
+ .withSessionCount(10)
+ .withAcknowledgeMode(AcknowledgeMode.AutoAcknowledge())
+ .withSelector("Important = TRUE");
+ // #consumer-settings
+ assertThat(settings.sessionCount(), is(10));
+ assertThat(settings.acknowledgeMode(), is(Option.apply(AcknowledgeMode.AutoAcknowledge())));
+ }
+}
diff --git a/jakartams/src/test/java/docs/javadsl/JmsTxConnectorsTest.java b/jakartams/src/test/java/docs/javadsl/JmsTxConnectorsTest.java
new file mode 100644
index 000000000..90bd6e661
--- /dev/null
+++ b/jakartams/src/test/java/docs/javadsl/JmsTxConnectorsTest.java
@@ -0,0 +1,394 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package docs.javadsl;
+
+import com.typesafe.config.Config;
+import jakarta.jms.ConnectionFactory;
+import jakarta.jms.JMSException;
+import jakarta.jms.Message;
+import jakarta.jms.TextMessage;
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+import org.apache.activemq.artemis.jms.client.ActiveMQQueue;
+import org.apache.activemq.artemis.junit.EmbeddedActiveMQResource;
+import org.apache.pekko.Done;
+import org.apache.pekko.actor.ActorSystem;
+import org.apache.pekko.japi.Pair;
+import org.apache.pekko.stream.connectors.jakartams.*;
+import org.apache.pekko.stream.connectors.jakartams.javadsl.JmsConsumer;
+import org.apache.pekko.stream.connectors.jakartams.javadsl.JmsConsumerControl;
+import org.apache.pekko.stream.connectors.jakartams.javadsl.JmsProducer;
+import org.apache.pekko.stream.connectors.testkit.javadsl.LogCapturingJunit4;
+import org.apache.pekko.stream.javadsl.Sink;
+import org.apache.pekko.stream.javadsl.Source;
+import org.apache.pekko.testkit.javadsl.TestKit;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+
+public class JmsTxConnectorsTest {
+
+ @Rule
+ public final LogCapturingJunit4 logCapturing = new LogCapturingJunit4();
+
+ private static ActorSystem system;
+ private static Config consumerConfig;
+ private static Config producerConfig;
+
+ @BeforeClass
+ public static void setup() {
+ system = ActorSystem.create();
+ consumerConfig = system.settings().config().getConfig(JmsConsumerSettings.configPath());
+ producerConfig = system.settings().config().getConfig(JmsProducerSettings.configPath());
+ }
+
+ @AfterClass
+ public static void teardown() {
+ TestKit.shutdownActorSystem(system);
+ }
+
+ private List<JmsTextMessage> createTestMessageList() {
+ List<Integer> intsIn = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ List<JmsTextMessage> msgsIn = new ArrayList<>();
+ for (Integer n : intsIn) {
+ msgsIn.add(
+ JmsTextMessage.create(n.toString())
+ .withProperty("Number", n)
+ .withProperty("IsOdd", n % 2 == 1)
+ .withProperty("IsEven", n % 2 == 0));
+ }
+
+ return msgsIn;
+ }
+
+ @Test
+ public void publishAndConsume() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<String, CompletionStage<Done>> jmsSink =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+ Source.from(in).runWith(jmsSink, system);
+
+ Source<TxEnvelope, JmsConsumerControl> jmsSource =
+ JmsConsumer.txSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withQueue("test"));
+
+ CompletionStage<List<String>> result =
+ jmsSource
+ .take(in.size())
+ .map(env -> new Pair<>(env, ((TextMessage) env.message()).getText()))
+ .map(
+ pair -> {
+ pair.first().commit();
+ return pair.second();
+ })
+ .runWith(Sink.seq(), system);
+
+ List<String> out = new ArrayList<>(result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ Collections.sort(out);
+ assertEquals(in, out);
+ });
+ }
+
+ @Test
+ public void publishAndConsumeJmsTextMessagesWithProperties() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<JmsTextMessage> msgsIn = createTestMessageList();
+ Source.from(msgsIn).runWith(jmsSink, system);
+
+ // #source
+ Source<org.apache.pekko.stream.connectors.jakartams.TxEnvelope, JmsConsumerControl> jmsSource =
+ JmsConsumer.txSource(
+ JmsConsumerSettings.create(system, connectionFactory)
+ .withSessionCount(5)
+ .withAckTimeout(Duration.ofSeconds(1))
+ .withQueue("test"));
+
+ CompletionStage<List<jakarta.jms.Message>> result =
+ jmsSource
+ .take(msgsIn.size())
+ .map(
+ txEnvelope -> {
+ txEnvelope.commit();
+ return txEnvelope.message();
+ })
+ .runWith(Sink.seq(), system);
+ // #source
+
+ List<Message> outMessages =
+ new ArrayList<>(result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ outMessages.sort(
+ (a, b) -> {
+ try {
+ return a.getIntProperty("Number") - b.getIntProperty("Number");
+ } catch (JMSException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ int msgIdx = 0;
+ for (Message outMsg : outMessages) {
+ assertEquals(
+ outMsg.getIntProperty("Number"),
+ msgsIn.get(msgIdx).properties().get("Number").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsOdd"),
+ msgsIn.get(msgIdx).properties().get("IsOdd").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsEven"),
+ (msgsIn.get(msgIdx).properties().get("IsEven").get()));
+ msgIdx++;
+ }
+ });
+ }
+
+ @Test
+ public void publishAndConsumeJmsTextMessagesWithHeaders() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<JmsTextMessage> msgsIn =
+ createTestMessageList().stream()
+ .map(jmsTextMessage -> jmsTextMessage.withHeader(JmsType.create("type")))
+ .map(
+ jmsTextMessage ->
+ jmsTextMessage.withHeader(JmsCorrelationId.create("correlationId")))
+ .map(jmsTextMessage -> jmsTextMessage.withHeader(JmsReplyTo.queue("test-reply")))
+ .collect(Collectors.toList());
+
+ Source.from(msgsIn).runWith(jmsSink, system);
+
+ Source<TxEnvelope, JmsConsumerControl> jmsSource =
+ JmsConsumer.txSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withQueue("test"));
+
+ CompletionStage<List<Message>> result =
+ jmsSource
+ .take(msgsIn.size())
+ .map(
+ env -> {
+ env.commit();
+ return env.message();
+ })
+ .runWith(Sink.seq(), system);
+
+ List<Message> outMessages =
+ new ArrayList<>(result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ outMessages.sort(
+ (a, b) -> {
+ try {
+ return a.getIntProperty("Number") - b.getIntProperty("Number");
+ } catch (JMSException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ int msgIdx = 0;
+ for (Message outMsg : outMessages) {
+ assertEquals(
+ outMsg.getIntProperty("Number"),
+ msgsIn.get(msgIdx).properties().get("Number").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsOdd"),
+ msgsIn.get(msgIdx).properties().get("IsOdd").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsEven"),
+ (msgsIn.get(msgIdx).properties().get("IsEven").get()));
+ assertEquals(outMsg.getJMSType(), "type");
+ assertEquals(outMsg.getJMSCorrelationID(), "correlationId");
+ assertEquals(((ActiveMQQueue) outMsg.getJMSReplyTo()).getQueueName(), "test-reply");
+ msgIdx++;
+ }
+ });
+ }
+
+ @Test
+ public void publishJmsTextMessagesWithPropertiesAndConsumeThemWithASelector() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<JmsTextMessage> msgsIn = createTestMessageList();
+
+ Source.from(msgsIn).runWith(jmsSink, system);
+
+ Source<TxEnvelope, JmsConsumerControl> jmsSource =
+ JmsConsumer.txSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withQueue("test")
+ .withSelector("IsOdd = TRUE"));
+
+ List<JmsTextMessage> oddMsgsIn =
+ msgsIn.stream()
+ .filter(msg -> Integer.valueOf(msg.body()) % 2 == 1)
+ .collect(Collectors.toList());
+ assertEquals(5, oddMsgsIn.size());
+
+ CompletionStage<List<Message>> result =
+ jmsSource
+ .take(oddMsgsIn.size())
+ .map(
+ env -> {
+ env.commit();
+ return env.message();
+ })
+ .runWith(Sink.seq(), system);
+
+ List<Message> outMessages =
+ new ArrayList<>(result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ outMessages.sort(
+ (a, b) -> {
+ try {
+ return a.getIntProperty("Number") - b.getIntProperty("Number");
+ } catch (JMSException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ int msgIdx = 0;
+ for (Message outMsg : outMessages) {
+ assertEquals(
+ outMsg.getIntProperty("Number"),
+ oddMsgsIn.get(msgIdx).properties().get("Number").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsOdd"),
+ oddMsgsIn.get(msgIdx).properties().get("IsOdd").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsEven"),
+ (oddMsgsIn.get(msgIdx).properties().get("IsEven").get()));
+ assertEquals(1, outMsg.getIntProperty("Number") % 2);
+ msgIdx++;
+ }
+ });
+ }
+
+ @Test
+ public void publishAndConsumeTopic() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+ List<String> inNumbers =
+ IntStream.range(0, 10).boxed().map(String::valueOf).collect(Collectors.toList());
+
+ Sink<String, CompletionStage<Done>> jmsTopicSink =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withTopic("topic"));
+
+ Sink<String, CompletionStage<Done>> jmsTopicSink2 =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withTopic("topic"));
+
+ Source<TxEnvelope, JmsConsumerControl> jmsTopicSource =
+ JmsConsumer.txSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(1)
+ .withTopic("topic"));
+
+ Source<TxEnvelope, JmsConsumerControl> jmsTopicSource2 =
+ JmsConsumer.txSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(1)
+ .withTopic("topic"));
+
+ CompletionStage<List<String>> result =
+ jmsTopicSource
+ .take(in.size() + inNumbers.size())
+ .map(
+ env -> {
+ env.commit();
+ return ((TextMessage) env.message()).getText();
+ })
+ .runWith(Sink.seq(), system)
+ .thenApply(l -> l.stream().sorted().collect(Collectors.toList()));
+
+ CompletionStage<List<String>> result2 =
+ jmsTopicSource2
+ .take(in.size() + inNumbers.size())
+ .map(
+ env -> {
+ env.commit();
+ return ((TextMessage) env.message()).getText();
+ })
+ .runWith(Sink.seq(), system)
+ .thenApply(l -> l.stream().sorted().collect(Collectors.toList()));
+
+ Thread.sleep(500);
+
+ Source.from(in).runWith(jmsTopicSink, system);
+
+ Source.from(inNumbers).runWith(jmsTopicSink2, system);
+
+ assertEquals(
+ Stream.concat(in.stream(), inNumbers.stream()).sorted().collect(Collectors.toList()),
+ result.toCompletableFuture().get(5, TimeUnit.SECONDS));
+ assertEquals(
+ Stream.concat(in.stream(), inNumbers.stream()).sorted().collect(Collectors.toList()),
+ result2.toCompletableFuture().get(5, TimeUnit.SECONDS));
+ });
+ }
+
+ private void withServer(ConsumerChecked<EmbeddedActiveMQResource> test) throws Exception {
+ EmbeddedActiveMQResource server = new EmbeddedActiveMQResource();
+ try {
+ server.start();
+ test.accept(server);
+ Thread.sleep(500);
+ } finally {
+ if (server.getServer().getActiveMQServer().isStarted()) {
+ server.stop();
+ }
+ }
+ }
+
+ private void withConnectionFactory(ConsumerChecked<ConnectionFactory> test) throws Exception {
+ withServer(
+ server -> test.accept(new ActiveMQConnectionFactory(server.getVmURL()))
+ );
+ }
+
+ @FunctionalInterface
+ private interface ConsumerChecked<T> {
+ void accept(T elt) throws Exception;
+ }
+}
diff --git a/jakartams/src/test/java/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsAckConnectorsTest.java b/jakartams/src/test/java/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsAckConnectorsTest.java
new file mode 100644
index 000000000..3a7010e90
--- /dev/null
+++ b/jakartams/src/test/java/org/apache/pekko/stream/connectors/jakartams/javadsl/JmsAckConnectorsTest.java
@@ -0,0 +1,387 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.stream.connectors.jakartams.javadsl;
+
+import com.typesafe.config.Config;
+import jakarta.jms.ConnectionFactory;
+import jakarta.jms.JMSException;
+import jakarta.jms.Message;
+import jakarta.jms.TextMessage;
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+import org.apache.activemq.artemis.jms.client.ActiveMQQueue;
+import org.apache.activemq.artemis.junit.EmbeddedActiveMQResource;
+import org.apache.pekko.Done;
+import org.apache.pekko.actor.ActorSystem;
+import org.apache.pekko.japi.Pair;
+import org.apache.pekko.stream.connectors.jakartams.*;
+import org.apache.pekko.stream.connectors.testkit.javadsl.LogCapturingJunit4;
+import org.apache.pekko.stream.javadsl.Sink;
+import org.apache.pekko.stream.javadsl.Source;
+import org.apache.pekko.testkit.javadsl.TestKit;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+
+import java.util.*;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+
+public class JmsAckConnectorsTest {
+
+ @Rule
+ public final LogCapturingJunit4 logCapturing = new LogCapturingJunit4();
+
+ private static ActorSystem system;
+ private static Config consumerConfig;
+ private static Config producerConfig;
+
+ @BeforeClass
+ public static void setup() {
+ system = ActorSystem.create();
+ consumerConfig = system.settings().config().getConfig(JmsConsumerSettings.configPath());
+ producerConfig = system.settings().config().getConfig(JmsProducerSettings.configPath());
+ }
+
+ @AfterClass
+ public static void teardown() {
+ TestKit.shutdownActorSystem(system);
+ }
+
+ private List<JmsTextMessage> createTestMessageList() {
+ List<Integer> intsIn = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ List<JmsTextMessage> msgsIn = new ArrayList<>();
+ for (Integer n : intsIn) {
+ final Map<String, Object> map = new HashMap<>();
+ map.put("Number", n);
+ map.put("IsOdd", n % 2 == 1);
+ map.put("IsEven", n % 2 == 0);
+
+ msgsIn.add(JmsTextMessage.create(n.toString()).withProperties(map));
+ }
+
+ return msgsIn;
+ }
+
+ @Test
+ public void publishAndConsume() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<String, CompletionStage<Done>> jmsSink =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+ Source.from(in).runWith(jmsSink, system);
+
+ Source<AckEnvelope, JmsConsumerControl> jmsSource =
+ JmsConsumer.ackSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withBufferSize(0)
+ .withQueue("test"));
+
+ CompletionStage<List<String>> result =
+ jmsSource
+ .take(in.size())
+ .map(env -> new Pair<>(env, ((TextMessage) env.message()).getText()))
+ .map(
+ pair -> {
+ pair.first().acknowledge();
+ return pair.second();
+ })
+ .runWith(Sink.seq(), system);
+ List<String> out = new ArrayList<>(result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ Collections.sort(out);
+ assertEquals(in, out);
+ });
+ }
+
+ @Test
+ public void publishAndConsumeJmsTextMessagesWithProperties() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<JmsTextMessage> msgsIn = createTestMessageList();
+
+ Source.from(msgsIn).runWith(jmsSink, system);
+
+ Source<AckEnvelope, JmsConsumerControl> jmsSource =
+ JmsConsumer.ackSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withBufferSize(0)
+ .withQueue("test"));
+
+ CompletionStage<List<Message>> result =
+ jmsSource
+ .take(msgsIn.size())
+ .map(
+ env -> {
+ env.acknowledge();
+ return env.message();
+ })
+ .runWith(Sink.seq(), system);
+
+ List<Message> outMessages =
+ new ArrayList<>(result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ outMessages.sort(
+ (a, b) -> {
+ try {
+ return a.getIntProperty("Number") - b.getIntProperty("Number");
+ } catch (JMSException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ int msgIdx = 0;
+ for (Message outMsg : outMessages) {
+ assertEquals(
+ outMsg.getIntProperty("Number"),
+ msgsIn.get(msgIdx).properties().get("Number").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsOdd"),
+ msgsIn.get(msgIdx).properties().get("IsOdd").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsEven"),
+ (msgsIn.get(msgIdx).properties().get("IsEven").get()));
+ msgIdx++;
+ }
+ });
+ }
+
+ @Test
+ public void publishAndConsumeJmsTextMessagesWithHeaders() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<JmsTextMessage> msgsIn =
+ createTestMessageList().stream()
+ .map(jmsTextMessage -> jmsTextMessage.withHeader(JmsType.create("type")))
+ .map(
+ jmsTextMessage ->
+ jmsTextMessage.withHeader(JmsCorrelationId.create("correlationId")))
+ .map(jmsTextMessage -> jmsTextMessage.withHeader(JmsReplyTo.queue("test-reply")))
+ .collect(Collectors.toList());
+
+ Source.from(msgsIn).runWith(jmsSink, system);
+
+ Source<AckEnvelope, JmsConsumerControl> jmsSource =
+ JmsConsumer.ackSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withBufferSize(0)
+ .withQueue("test"));
+
+ CompletionStage<List<Message>> result =
+ jmsSource
+ .take(msgsIn.size())
+ .map(
+ env -> {
+ env.acknowledge();
+ return env.message();
+ })
+ .runWith(Sink.seq(), system);
+
+ List<Message> outMessages =
+ new ArrayList<>(result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ outMessages.sort(
+ (a, b) -> {
+ try {
+ return a.getIntProperty("Number") - b.getIntProperty("Number");
+ } catch (JMSException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ int msgIdx = 0;
+ for (Message outMsg : outMessages) {
+ assertEquals(
+ outMsg.getIntProperty("Number"),
+ msgsIn.get(msgIdx).properties().get("Number").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsOdd"),
+ msgsIn.get(msgIdx).properties().get("IsOdd").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsEven"),
+ (msgsIn.get(msgIdx).properties().get("IsEven").get()));
+ assertEquals(outMsg.getJMSType(), "type");
+ assertEquals(outMsg.getJMSCorrelationID(), "correlationId");
+ assertEquals(((ActiveMQQueue) outMsg.getJMSReplyTo()).getQueueName(), "test-reply");
+ msgIdx++;
+ }
+ });
+ }
+
+ @Test
+ public void publishJmsTextMessagesWithPropertiesAndConsumeThemWithASelector() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ Sink<JmsTextMessage, CompletionStage<Done>> jmsSink =
+ JmsProducer.sink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withQueue("test"));
+
+ List<JmsTextMessage> msgsIn = createTestMessageList();
+
+ Source.from(msgsIn).runWith(jmsSink, system);
+
+ Source<AckEnvelope, JmsConsumerControl> jmsSource =
+ JmsConsumer.ackSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withBufferSize(0)
+ .withQueue("test")
+ .withSelector("IsOdd = TRUE"));
+
+ List<JmsTextMessage> oddMsgsIn =
+ msgsIn.stream()
+ .filter(msg -> Integer.parseInt(msg.body()) % 2 == 1)
+ .collect(Collectors.toList());
+ assertEquals(5, oddMsgsIn.size());
+
+ CompletionStage<List<Message>> result =
+ jmsSource
+ .take(oddMsgsIn.size())
+ .map(
+ env -> {
+ env.acknowledge();
+ return env.message();
+ })
+ .runWith(Sink.seq(), system);
+
+ List<Message> outMessages =
+ new ArrayList<>(result.toCompletableFuture().get(3, TimeUnit.SECONDS));
+ outMessages.sort(
+ (a, b) -> {
+ try {
+ return a.getIntProperty("Number") - b.getIntProperty("Number");
+ } catch (JMSException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ int msgIdx = 0;
+ for (Message outMsg : outMessages) {
+ assertEquals(
+ outMsg.getIntProperty("Number"),
+ oddMsgsIn.get(msgIdx).properties().get("Number").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsOdd"),
+ oddMsgsIn.get(msgIdx).properties().get("IsOdd").get());
+ assertEquals(
+ outMsg.getBooleanProperty("IsEven"),
+ (oddMsgsIn.get(msgIdx).properties().get("IsEven").get()));
+ assertEquals(1, outMsg.getIntProperty("Number") % 2);
+ msgIdx++;
+ }
+ });
+ }
+
+ @Test
+ public void publishAndConsumeTopic() throws Exception {
+ withConnectionFactory(
+ connectionFactory -> {
+ List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");
+ List<String> inNumbers =
+ IntStream.range(0, 10).boxed().map(String::valueOf).collect(Collectors.toList());
+
+ Sink<String, CompletionStage<Done>> jmsTopicSink =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withTopic("topic"));
+ Sink<String, CompletionStage<Done>> jmsTopicSink2 =
+ JmsProducer.textSink(
+ JmsProducerSettings.create(producerConfig, connectionFactory).withTopic("topic"));
+
+ Source<AckEnvelope, JmsConsumerControl> jmsTopicSource =
+ JmsConsumer.ackSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(1)
+ .withBufferSize(0)
+ .withTopic("topic"));
+ Source<AckEnvelope, JmsConsumerControl> jmsTopicSource2 =
+ JmsConsumer.ackSource(
+ JmsConsumerSettings.create(consumerConfig, connectionFactory)
+ .withSessionCount(1)
+ .withBufferSize(0)
+ .withTopic("topic"));
+
+ CompletionStage<List<String>> result =
+ jmsTopicSource
+ .take(in.size() + inNumbers.size())
+ .map(
+ env -> {
+ env.acknowledge();
+ return ((TextMessage) env.message()).getText();
+ })
+ .runWith(Sink.seq(), system)
+ .thenApply(l -> l.stream().sorted().collect(Collectors.toList()));
+ CompletionStage<List<String>> result2 =
+ jmsTopicSource2
+ .take(in.size() + inNumbers.size())
+ .map(
+ env -> {
+ env.acknowledge();
+ return ((TextMessage) env.message()).getText();
+ })
+ .runWith(Sink.seq(), system)
+ .thenApply(l -> l.stream().sorted().collect(Collectors.toList()));
+
+ Thread.sleep(500);
+
+ Source.from(in).runWith(jmsTopicSink, system);
+ Source.from(inNumbers).runWith(jmsTopicSink2, system);
+
+ assertEquals(
+ Stream.concat(in.stream(), inNumbers.stream()).sorted().collect(Collectors.toList()),
+ result.toCompletableFuture().get(5, TimeUnit.SECONDS));
+ assertEquals(
+ Stream.concat(in.stream(), inNumbers.stream()).sorted().collect(Collectors.toList()),
+ result2.toCompletableFuture().get(5, TimeUnit.SECONDS));
+ });
+ }
+
+ private void withServer(ConsumerChecked<EmbeddedActiveMQResource> test) throws Exception {
+ EmbeddedActiveMQResource server = new EmbeddedActiveMQResource();
+ try {
+ server.start();
+ test.accept(server);
+ Thread.sleep(500);
+ } finally {
+ if (server.getServer().getActiveMQServer().isStarted()) {
+ server.stop();
+ }
+ }
+ }
+
+ private void withConnectionFactory(ConsumerChecked<ConnectionFactory> test) throws Exception {
+ withServer(
+ server -> test.accept(new ActiveMQConnectionFactory(server.getVmURL()))
+ );
+ }
+
+ @FunctionalInterface
+ private interface ConsumerChecked<T> {
+ void accept(T elt) throws Exception;
+ }
+}
diff --git a/jakartams/src/test/resources/application.conf b/jakartams/src/test/resources/application.conf
new file mode 100644
index 000000000..a1d8c93dd
--- /dev/null
+++ b/jakartams/src/test/resources/application.conf
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: Apache-2.0
+
+pekko {
+ loggers = ["org.apache.pekko.event.slf4j.Slf4jLogger"]
+ logging-filter = "org.apache.pekko.event.slf4j.Slf4jLoggingFilter"
+ loglevel = "DEBUG"
+}
diff --git a/jakartams/src/test/resources/logback-test.xml b/jakartams/src/test/resources/logback-test.xml
new file mode 100644
index 000000000..f46a7452f
--- /dev/null
+++ b/jakartams/src/test/resources/logback-test.xml
@@ -0,0 +1,29 @@
+<configuration>
+ <appender name="FILE" class="ch.qos.logback.core.FileAppender">
+ <file>target/jms.log</file>
+ <append>false</append>
+ <encoder>
+ <pattern>%d{ISO8601} %-5level [%thread] [%logger{36}] %msg%n</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <pattern>%d{HH:mm:ss.SSS} %-5level [%-20.20thread] %-36.36logger{36} %msg%n%rEx</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="CapturingAppender" class="org.apache.pekko.stream.connectors.testkit.CapturingAppender"/>
+
+ <logger name="org.apache.pekko.stream.connectors.testkit.CapturingAppenderDelegate">
+ <appender-ref ref="STDOUT"/>
+ </logger>
+
+ <logger name="org.apache.pekko" level="DEBUG"/>
+ <logger name="org.apache.activemq" level="info"/>
+
+ <root level="debug">
+ <appender-ref ref="CapturingAppender"/>
+ <appender-ref ref="FILE"/>
+ </root>
+</configuration>
diff --git a/jakartams/src/test/scala/docs/scaladsl/JmsBufferedAckConnectorsSpec.scala b/jakartams/src/test/scala/docs/scaladsl/JmsBufferedAckConnectorsSpec.scala
new file mode 100644
index 000000000..30fa145dc
--- /dev/null
+++ b/jakartams/src/test/scala/docs/scaladsl/JmsBufferedAckConnectorsSpec.scala
@@ -0,0 +1,407 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package docs.scaladsl
+
+import jakarta.jms.{ JMSException, TextMessage }
+import org.apache.activemq.artemis.api.jms.ActiveMQJMSConstants
+import org.apache.pekko.Done
+import org.apache.pekko.stream.connectors.jakartams._
+import org.apache.pekko.stream.connectors.jakartams.scaladsl.{ JmsConsumer, JmsConsumerControl, JmsProducer }
+import org.apache.pekko.stream.scaladsl.{ Flow, Keep, Sink, Source }
+import org.apache.pekko.stream.testkit.scaladsl.TestSink
+import org.apache.pekko.stream.{ KillSwitches, ThrottleMode }
+import org.scalatest.Inspectors._
+import org.scalatest.time.Span.convertSpanToDuration
+
+import java.util.concurrent.{ LinkedBlockingQueue, TimeUnit }
+import scala.annotation.tailrec
+import scala.collection.{ immutable, mutable }
+import scala.concurrent.Future
+import scala.concurrent.duration._
+import scala.util.{ Failure, Success }
+
+class JmsBufferedAckConnectorsSpec extends JmsSharedServerSpec {
+
+ override implicit val patienceConfig: PatienceConfig = PatienceConfig(2.minutes)
+
+ "The JMS Ack Connectors" should {
+ "publish and consume strings through a queue" in withConnectionFactory() { connectionFactory =>
+ val queueName = createName("test")
+ val jmsSink: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue(queueName))
+
+ val in = (0 to 25).map(i => ('a' + i).asInstanceOf[Char].toString)
+ Source(in).runWith(jmsSink)
+
+ val jmsSource: Source[AckEnvelope, JmsConsumerControl] = JmsConsumer.ackSource(
+ JmsConsumerSettings(system, connectionFactory).withSessionCount(5).withQueue(queueName))
+
+ val result = jmsSource
+ .take(in.size)
+ .map(env => (env, env.message.asInstanceOf[TextMessage].getText))
+ .map { case (env, text) => env.acknowledge(); text }
+ .runWith(Sink.seq)
+
+ result.futureValue should contain theSameElementsAs in
+ }
+
+ "publish and consume JMS text messages with properties through a queue" in withConnectionFactory() {
+ connectionFactory =>
+ val queueName = createName("numbers")
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue(queueName))
+
+ val msgsIn = (1 to 100).map { n =>
+ JmsTextMessage(n.toString)
+ .withProperty("Number", n)
+ .withProperty("IsOdd", n % 2 == 1)
+ .withProperty("IsEven", n % 2 == 0)
+ }
+
+ Source(msgsIn).runWith(jmsSink)
+
+ // #source
+ val jmsSource: Source[AckEnvelope, JmsConsumerControl] = JmsConsumer.ackSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withQueue(queueName))
+
+ val result: Future[immutable.Seq[jakarta.jms.Message]] =
+ jmsSource
+ .take(msgsIn.size)
+ .map { ackEnvelope =>
+ ackEnvelope.acknowledge()
+ ackEnvelope.message
+ }
+ .runWith(Sink.seq)
+ // #source
+
+ // The sent message and the receiving one should have the same properties
+ val sortedResult = result.futureValue.sortBy(msg => msg.getIntProperty("Number"))
+ forAll(sortedResult.zip(msgsIn)) {
+ case (out, in) =>
+ out.getIntProperty("Number") shouldEqual in.properties("Number")
+ out.getBooleanProperty("IsOdd") shouldEqual in.properties("IsOdd")
+ out.getBooleanProperty("IsEven") shouldEqual in.properties("IsEven")
+ }
+ }
+
+ "publish JMS text messages with properties through a queue and consume them with a selector" in withConnectionFactory() {
+ connectionFactory =>
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue("numbers"))
+
+ val msgsIn = (1 to 100).map { n =>
+ JmsTextMessage(n.toString)
+ .withProperty("Number", n)
+ .withProperty("IsOdd", n % 2 == 1)
+ .withProperty("IsEven", n % 2 == 0)
+ }
+ Source(msgsIn).runWith(jmsSink)
+
+ val jmsSource = JmsConsumer.ackSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withQueue("numbers")
+ .withSelector("IsOdd = TRUE"))
+
+ val oddMsgsIn = msgsIn.filter(msg => msg.body.toInt % 2 == 1)
+ val result = jmsSource
+ .take(oddMsgsIn.size)
+ .map { env =>
+ env.acknowledge()
+ env.message
+ }
+ .runWith(Sink.seq)
+ // We should have only received the odd numbers in the list
+
+ val sortedResult = result.futureValue.sortBy(msg => msg.getIntProperty("Number"))
+ forAll(sortedResult.zip(oddMsgsIn)) {
+ case (out, in) =>
+ out.getIntProperty("Number") shouldEqual in.properties("Number")
+ out.getBooleanProperty("IsOdd") shouldEqual in.properties("IsOdd")
+ out.getBooleanProperty("IsEven") shouldEqual in.properties("IsEven")
+ // Make sure we are only receiving odd numbers
+ out.getIntProperty("Number") % 2 shouldEqual 1
+ }
+ }
+
+ "applying backpressure when the consumer is slower than the producer" in withConnectionFactory() {
+ connectionFactory =>
+ val queueName = createName("test")
+ val in = (0 to 25).map(i => ('a' + i).asInstanceOf[Char].toString)
+ Source(in).runWith(
+ JmsProducer.textSink(JmsProducerSettings(producerConfig, connectionFactory).withQueue(queueName)))
+
+ val jmsSource: Source[AckEnvelope, JmsConsumerControl] = JmsConsumer.ackSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory).withSessionCount(5).withQueue(queueName))
+
+ val result = jmsSource
+ .throttle(10, 1.second, 1, ThrottleMode.shaping)
+ .take(in.size)
+ .map(env => (env, env.message.asInstanceOf[TextMessage].getText))
+ .map { case (env, text) => env.acknowledge(); text }
+ .runWith(Sink.seq)
+
+ result.futureValue should contain theSameElementsAs in
+ }
+
+ "disconnection should fail the stage after exhausting retries" in withServer() { server =>
+ val connectionFactory = server.createConnectionFactory
+ val result = JmsConsumer
+ .ackSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withQueue("test")
+ .withConnectionRetrySettings(ConnectionRetrySettings(system).withMaxRetries(3)))
+ .runWith(Sink.seq)
+ Thread.sleep(500)
+ server.stop()
+ val ex = result.failed.futureValue
+ ex shouldBe a[ConnectionRetryException]
+ ex.getCause shouldBe a[JMSException]
+ }
+
+ "publish and consume elements through a topic " in withConnectionFactory() { connectionFactory =>
+ import system.dispatcher
+
+ val topicName = createName("topic")
+ val jmsTopicSink: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings(producerConfig, connectionFactory).withTopic(topicName))
+ val jmsTopicSink2: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings(producerConfig, connectionFactory).withTopic(topicName))
+
+ val in = List("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k")
+ val inNumbers = (1 to 10).map(_.toString)
+
+ val jmsTopicSource: Source[AckEnvelope, JmsConsumerControl] = JmsConsumer.ackSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory).withSessionCount(1).withTopic(topicName))
+ val jmsSource2: Source[AckEnvelope, JmsConsumerControl] = JmsConsumer.ackSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory).withSessionCount(1).withTopic(topicName))
+
+ val expectedSize = in.size + inNumbers.size
+ val result1 = jmsTopicSource
+ .take(expectedSize)
+ .map(env => (env, env.message.asInstanceOf[TextMessage].getText))
+ .map { case (env, text) => env.acknowledge(); text }
+ .runWith(Sink.seq)
+ .map(_.sorted)
+ val result2 = jmsSource2
+ .take(expectedSize)
+ .map(env => (env, env.message.asInstanceOf[TextMessage].getText))
+ .map { case (env, text) => env.acknowledge(); text }
+ .runWith(Sink.seq)
+ .map(_.sorted)
+
+ // We wait a little to be sure that the source is connected
+ Thread.sleep(500)
+
+ Source(in).runWith(jmsTopicSink)
+ Source(inNumbers).runWith(jmsTopicSink2)
+
+ val expectedList: List[String] = in ++ inNumbers
+ result1.futureValue should contain theSameElementsAs expectedList
+ result2.futureValue should contain theSameElementsAs expectedList
+ }
+
+ "ensure no message loss when stopping a stream" in withConnectionFactory() { connectionFactory =>
+ val queueName = createName("numbers")
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue(queueName))
+
+ val (publishKillSwitch, publishedData) = Source
+ .unfold(1)(n => Some(n + 1 -> n))
+ .throttle(15, 1.second, 2, ThrottleMode.shaping) // Higher than consumption rate.
+ .viaMat(KillSwitches.single)(Keep.right)
+ .alsoTo(Flow[Int].map(n => JmsTextMessage(n.toString).withProperty("Number", n)).to(jmsSink))
+ .toMat(Sink.seq)(Keep.both)
+ .run()
+
+ val jmsSource: Source[AckEnvelope, JmsConsumerControl] = JmsConsumer.ackSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withQueue(queueName))
+
+ val resultQueue = new LinkedBlockingQueue[String]()
+
+ val (killSwitch, streamDone) = jmsSource
+ .throttle(10, 1.second, 2, ThrottleMode.shaping)
+ .toMat(
+ Sink.foreach { env =>
+ resultQueue.add(env.message.asInstanceOf[TextMessage].getText)
+ env.acknowledge()
+ })(Keep.both)
+ .run()
+
+ // Need to wait for the stream to have started and running for sometime
+ Thread.sleep(2000)
+
+ killSwitch.shutdown()
+
+ streamDone.futureValue shouldBe Done
+
+ // Keep publishing for another 2 seconds to make sure we killed the consumption mid-stream.
+ Thread.sleep(2000)
+
+ publishKillSwitch.shutdown()
+ val numsIn = publishedData.futureValue
+
+ resultQueue.size should be < numsIn.size
+
+ val killSwitch2 = jmsSource
+ .to(
+ Sink.foreach { env =>
+ resultQueue.add(env.message.asInstanceOf[TextMessage].getText)
+ env.acknowledge()
+ })
+ .run()
+
+ val resultList = new mutable.ArrayBuffer[String](numsIn.size)
+
+ @tailrec
+ def keepPolling(): Unit =
+ Option(resultQueue.poll(2, TimeUnit.SECONDS)) match {
+ case Some(entry) =>
+ resultList += entry
+ keepPolling()
+ case None =>
+ }
+
+ keepPolling()
+
+ killSwitch2.shutdown()
+
+ resultList.toSet should contain.theSameElementsAs(numsIn.map(_.toString))
+ }
+
+ "ensure no message loss when aborting a stream" in withConnectionFactory() { connectionFactory =>
+ val queueName = createName("numbers")
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue(queueName))
+
+ val (publishKillSwitch, publishedData) = Source
+ .unfold(1)(n => Some(n + 1 -> n))
+ .throttle(15, 1.second, 2, ThrottleMode.shaping) // Higher than consumption rate.
+ .viaMat(KillSwitches.single)(Keep.right)
+ .alsoTo(Flow[Int].map(n => JmsTextMessage(n.toString).withProperty("Number", n)).to(jmsSink))
+ .toMat(Sink.seq)(Keep.both)
+ .run()
+
+ // We need this ack mode for AMQ to not lose messages as ack normally acks any messages read on the session.
+ val individualAck = new AcknowledgeMode(ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE)
+
+ val jmsSource: Source[AckEnvelope, JmsConsumerControl] = JmsConsumer.ackSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withQueue(queueName)
+ .withAcknowledgeMode(individualAck))
+
+ val resultQueue = new LinkedBlockingQueue[String]()
+
+ val (killSwitch, streamDone) = jmsSource
+ .throttle(10, 1.second, 2, ThrottleMode.shaping)
+ .toMat(
+ Sink.foreach { env =>
+ resultQueue.add(env.message.asInstanceOf[TextMessage].getText)
+ env.acknowledge()
+ })(Keep.both)
+ .run()
+
+ // Need to wait for the stream to have started and running for sometime.
+ Thread.sleep(2000)
+
+ val ex = new Exception("Test exception")
+ killSwitch.abort(ex)
+
+ import scala.concurrent.ExecutionContext.Implicits.global
+
+ val resultTry = streamDone.map(Success(_)).recover { case e => Failure(e) }.futureValue
+
+ // Keep publishing for another 2 seconds to make sure we killed the consumption mid-stream.
+ Thread.sleep(2000)
+
+ publishKillSwitch.shutdown()
+ val numsIn = publishedData.futureValue
+
+ // Ensure we break the stream while reading, not all input should have been read.
+ resultQueue.size should be < numsIn.size
+ resultTry shouldBe Failure(ex)
+
+ val killSwitch2 = jmsSource
+ .to(
+ Sink.foreach { env =>
+ resultQueue.add(env.message.asInstanceOf[TextMessage].getText)
+ env.acknowledge()
+ })
+ .run()
+
+ val resultList = new mutable.ArrayBuffer[String](numsIn.size)
+
+ @tailrec
+ def keepPolling(): Unit =
+ Option(resultQueue.poll(2, TimeUnit.SECONDS)) match {
+ case Some(entry) =>
+ resultList += entry
+ keepPolling()
+ case None =>
+ }
+
+ keepPolling()
+
+ killSwitch2.shutdown()
+
+ resultList.toSet should contain.theSameElementsAs(numsIn.map(_.toString))
+ }
+
+ "send acknowledgments back to the broker after max.ack.interval" in withConnectionFactory() { connectionFactory =>
+ val testQueue = "test"
+ val aMessage = "message"
+ val maxAckInterval = 1.second
+ Source
+ .single(aMessage)
+ .runWith(JmsProducer.textSink(JmsProducerSettings(producerConfig, connectionFactory).withQueue(testQueue)))
+ val source = JmsConsumer.ackSource(
+ JmsConsumerSettings(system, connectionFactory)
+ .withMaxPendingAcks(100)
+ .withMaxAckInterval(maxAckInterval)
+ .withQueue(testQueue))
+
+ val (consumerControl, probe) = source
+ .map { env =>
+ env.acknowledge()
+ env.message match {
+ case message: TextMessage => Some(message.getText)
+ case _ => None
+
+ }
+ }
+ .toMat(TestSink.probe)(Keep.both)
+ .run()
+
+ probe.requestNext(convertSpanToDuration(patienceConfig.timeout)) shouldBe Some(aMessage)
+
+ eventually {
+ isQueueEmpty(testQueue) shouldBe true
+ }
+
+ consumerControl.shutdown()
+ probe.expectComplete()
+
+ // Consuming again should give us no elements, as msg was acked and therefore removed from the broker
+ val (emptyConsumerControl, emptySourceProbe) = source.toMat(TestSink.probe)(Keep.both).run()
+ emptySourceProbe.ensureSubscription().expectNoMessage()
+ emptyConsumerControl.shutdown()
+ emptySourceProbe.expectComplete()
+ }
+ }
+}
diff --git a/jakartams/src/test/scala/docs/scaladsl/JmsConnectorsSpec.scala b/jakartams/src/test/scala/docs/scaladsl/JmsConnectorsSpec.scala
new file mode 100644
index 000000000..726d8eabc
--- /dev/null
+++ b/jakartams/src/test/scala/docs/scaladsl/JmsConnectorsSpec.scala
@@ -0,0 +1,1221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package docs.scaladsl
+
+import jakarta.jms._
+import org.apache.activemq.artemis.jms.client.{ ActiveMQConnectionFactory, ActiveMQQueue, ActiveMQSession }
+import org.apache.pekko.stream._
+import org.apache.pekko.stream.connectors.jakartams._
+import org.apache.pekko.stream.connectors.jakartams.scaladsl._
+import org.apache.pekko.stream.scaladsl.{ Flow, Keep, Sink, Source }
+import org.apache.pekko.{ Done, NotUsed }
+import org.mockito.ArgumentMatchers._
+import org.mockito.Mockito._
+import org.mockito.invocation.InvocationOnMock
+import org.mockito.stubbing.Answer
+
+import java.nio.charset.StandardCharsets
+import java.util.UUID
+import java.util.concurrent.atomic.AtomicInteger
+import java.util.concurrent.{ CountDownLatch, LinkedBlockingQueue, ThreadLocalRandom, TimeUnit }
+import scala.annotation.tailrec
+import scala.collection.{ immutable, mutable }
+import scala.concurrent.Future
+import scala.concurrent.duration._
+import scala.util.{ Failure, Success }
+
+final case class DummyObject(payload: String)
+
+class JmsConnectorsSpec extends JmsSpec {
+
+ override implicit val patienceConfig: PatienceConfig = PatienceConfig(2.minutes)
+
+ "The JMS Connectors" should {
+ "publish and consume strings through a queue" in withServer() { server =>
+ val url = server.getBrokerUrl
+ // #connection-factory
+ // #text-sink
+ // #text-source
+ val connectionFactory: jakarta.jms.ConnectionFactory = new ActiveMQConnectionFactory(url)
+ // #connection-factory
+ // #text-sink
+ // #text-source
+
+ // #text-sink
+
+ val jmsSink: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings(system, connectionFactory).withQueue("test"))
+
+ val in = List("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k")
+ val streamCompletion: Future[Done] =
+ Source(in)
+ .runWith(jmsSink)
+ // #text-sink
+
+ // #text-source
+ val jmsSource: Source[String, JmsConsumerControl] = JmsConsumer.textSource(
+ JmsConsumerSettings(system, connectionFactory).withQueue("test"))
+
+ val result: Future[immutable.Seq[String]] = jmsSource.take(in.size).runWith(Sink.seq)
+ // #text-source
+
+ streamCompletion.futureValue shouldEqual Done
+ result.futureValue shouldEqual in
+ }
+
+ "publish and consume serializable objects through a queue" in withConnectionFactory() { connFactory =>
+ // #object-sink
+ // #object-source
+ val connectionFactory = connFactory.asInstanceOf[ActiveMQConnectionFactory]
+ // connectionFactory.setTrustedPackages(List(classOf[DummyObject].getPackage.getName).asJava)
+ // #object-sink
+ // #object-source
+
+ // #object-sink
+
+ val jmsSink: Sink[Serializable, Future[Done]] = JmsProducer.objectSink(
+ JmsProducerSettings(system, connectionFactory).withQueue("test"))
+ val in = DummyObject("ThisIsATest")
+ val streamCompletion: Future[Done] =
+ Source
+ .single(in)
+ .runWith(jmsSink)
+ // #object-sink
+
+ // #object-source
+ val jmsSource: Source[java.io.Serializable, JmsConsumerControl] = JmsConsumer.objectSource(
+ JmsConsumerSettings(system, connectionFactory).withQueue("test"))
+
+ val result: Future[java.io.Serializable] =
+ jmsSource
+ .take(1)
+ .runWith(Sink.head)
+ // #object-source
+
+ streamCompletion.futureValue shouldEqual Done
+ result.futureValue shouldEqual in
+ }
+
+ "publish and consume bytearray through a queue" in withConnectionFactory() { connectionFactory =>
+ // #bytearray-sink
+ val jmsSink: Sink[Array[Byte], Future[Done]] = JmsProducer.bytesSink(
+ JmsProducerSettings(system, connectionFactory).withQueue("test"))
+ val in: Array[Byte] = "ThisIsATest".getBytes(StandardCharsets.UTF_8)
+ val streamCompletion: Future[Done] =
+ Source
+ .single(in)
+ .runWith(jmsSink)
+ // #bytearray-sink
+
+ // #bytearray-source
+ val jmsSource: Source[Array[Byte], JmsConsumerControl] = JmsConsumer.bytesSource(
+ JmsConsumerSettings(system, connectionFactory).withQueue("test"))
+
+ val result: Future[Array[Byte]] =
+ jmsSource
+ .take(1)
+ .runWith(Sink.head)
+ // #bytearray-source
+
+ streamCompletion.futureValue shouldEqual Done
+ result.futureValue shouldEqual in
+ }
+
+ "publish and consume map through a queue" in withConnectionFactory() { connectionFactory =>
+ // #map-sink
+ val jmsSink: Sink[Map[String, Any], Future[Done]] = JmsProducer.mapSink(
+ JmsProducerSettings(system, connectionFactory).withQueue("test"))
+
+ val input = List(
+ Map[String, Any](
+ "string" -> "value",
+ "int value" -> 42,
+ "double value" -> 43.toDouble,
+ "short value" -> 7.toShort,
+ "boolean value" -> true,
+ "long value" -> 7.toLong,
+ "bytearray" -> "AStringAsByteArray".getBytes(StandardCharsets.UTF_8),
+ "byte" -> 1.toByte))
+
+ val streamCompletion: Future[Done] =
+ Source(input)
+ .runWith(jmsSink)
+ // #map-sink
+
+ // #map-source
+ val jmsSource: Source[Map[String, Any], JmsConsumerControl] = JmsConsumer.mapSource(
+ JmsConsumerSettings(system, connectionFactory).withQueue("test"))
+
+ val result: Future[immutable.Seq[Map[String, Any]]] =
+ jmsSource
+ .take(1)
+ .runWith(Sink.seq)
+ // #map-source
+
+ streamCompletion.futureValue shouldEqual Done
+ result.futureValue.zip(input).foreach {
+ case (out, in) =>
+ out("string") shouldEqual in("string")
+ out("int value") shouldEqual in("int value")
+ out("double value") shouldEqual in("double value")
+ out("short value") shouldEqual in("short value")
+ out("boolean value") shouldEqual in("boolean value")
+ out("long value") shouldEqual in("long value")
+ out("byte") shouldEqual in("byte")
+
+ val outBytes = out("bytearray").asInstanceOf[Array[Byte]]
+ new String(outBytes, StandardCharsets.UTF_8) shouldBe "AStringAsByteArray"
+ }
+ }
+
+ "publish and consume JMS text messages with properties through a queue" in withConnectionFactory() {
+ connectionFactory =>
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue("numbers"))
+
+ // #create-messages-with-properties
+ val msgsIn = (1 to 10).toList.map { n =>
+ org.apache.pekko.stream.connectors.jakartams
+ .JmsTextMessage(n.toString)
+ .withProperty("Number", n)
+ .withProperty("IsOdd", n % 2 == 1)
+ .withProperty("IsEven", n % 2 == 0)
+ }
+ // #create-messages-with-properties
+
+ Source(msgsIn).runWith(jmsSink)
+
+ // #jms-source
+ val jmsSource: Source[jakarta.jms.Message, JmsConsumerControl] = JmsConsumer(
+ JmsConsumerSettings(system, connectionFactory).withQueue("numbers"))
+
+ val (control, result): (JmsConsumerControl, Future[immutable.Seq[String]]) =
+ jmsSource
+ .take(msgsIn.size)
+ .map {
+ case t: jakarta.jms.TextMessage => t.getText
+ case other => sys.error(s"unexpected message type ${other.getClass}")
+ }
+ .toMat(Sink.seq)(Keep.both)
+ .run()
+ // #jms-source
+
+ result.futureValue should have size 10
+ // #jms-source
+
+ control.shutdown()
+ // #jms-source
+ }
+
+ "publish and consume JMS text messages" in withConnectionFactory() { connectionFactory =>
+ // #create-jms-sink
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue("numbers"))
+
+ val finished: Future[Done] =
+ Source(immutable.Seq("Message A", "Message B"))
+ .map(JmsTextMessage(_))
+ .runWith(jmsSink)
+ // #create-jms-sink
+
+ val jmsSource: Source[Message, JmsConsumerControl] = JmsConsumer(
+ JmsConsumerSettings(consumerConfig, connectionFactory).withQueue("numbers"))
+
+ val result: Future[Seq[Message]] = jmsSource.take(2).runWith(Sink.seq)
+
+ finished.futureValue shouldBe Done
+
+ result.futureValue.zip(immutable.Seq("Message A", "Message B")).foreach {
+ case (out, in) =>
+ out.asInstanceOf[TextMessage].getText shouldEqual in
+ }
+ }
+
+ "publish and consume JMS text messages with header through a queue" in withConnectionFactory() {
+ connectionFactory =>
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue("numbers"))
+
+ // #create-messages-with-headers
+ val msgsIn = (1 to 10).toList.map { n =>
+ JmsTextMessage(n.toString)
+ .withHeader(JmsType("type"))
+ .withHeader(JmsCorrelationId("correlationId"))
+ .withHeader(JmsReplyTo.queue("test-reply"))
+ .withHeader(JmsTimeToLive(FiniteDuration(999, TimeUnit.SECONDS)))
+ .withHeader(JmsPriority(2))
+ .withHeader(JmsDeliveryMode(DeliveryMode.NON_PERSISTENT))
+ }
+ // #create-messages-with-headers
+
+ Source(msgsIn).runWith(jmsSink)
+
+ val jmsSource: Source[Message, JmsConsumerControl] = JmsConsumer(
+ JmsConsumerSettings(consumerConfig, connectionFactory).withQueue("numbers"))
+
+ val result: Future[Seq[Message]] = jmsSource.take(msgsIn.size).runWith(Sink.seq)
+
+ // The sent message and the receiving one should have the same properties
+ result.futureValue.foreach { outMsg =>
+ outMsg.getJMSType shouldBe "type"
+ outMsg.getJMSCorrelationID shouldBe "correlationId"
+ outMsg.getJMSReplyTo.asInstanceOf[ActiveMQQueue].getQueueName shouldBe "test-reply"
+ outMsg.getJMSExpiration should not be 0
+ outMsg.getJMSPriority shouldBe 2
+ outMsg.getJMSDeliveryMode shouldBe DeliveryMode.NON_PERSISTENT
+ }
+ }
+
+ "publish and consume JMS text messages through a queue with custom queue creator " in withConnectionFactory() {
+ connectionFactory =>
+ // #custom-destination
+ def createQueue(destinationName: String): Session => jakarta.jms.Queue = { (session: Session) =>
+ val amqSession = session.asInstanceOf[ActiveMQSession]
+ amqSession.createQueue(s"my-$destinationName")
+ }
+ // #custom-destination
+
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory)
+ .withDestination(CustomDestination("custom", createQueue("custom"))))
+
+ val msgsIn: immutable.Seq[JmsTextMessage] = (1 to 10).toList.map { n =>
+ JmsTextMessage(n.toString)
+ }
+
+ Source(msgsIn).runWith(jmsSink)
+
+ // #custom-destination
+
+ val jmsSource: Source[jakarta.jms.Message, JmsConsumerControl] = JmsConsumer(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withDestination(CustomDestination("custom", createQueue("custom"))))
+ // #custom-destination
+
+ val result: Future[immutable.Seq[jakarta.jms.Message]] = jmsSource.take(msgsIn.size).runWith(Sink.seq)
+
+ // The sent message and the receiving one should have the same properties
+ result.futureValue.zip(msgsIn).foreach {
+ case (out, in) =>
+ out.asInstanceOf[TextMessage].getText shouldEqual in.body
+ }
+ }
+
+ "publish JMS text messages with properties through a queue and consume them with a selector" in withConnectionFactory() {
+ connectionFactory =>
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue("numbers"))
+
+ val msgsIn = (1 to 10).toList.map { n =>
+ JmsTextMessage(n.toString)
+ .withProperty("Number", n)
+ .withProperty("IsOdd", n % 2 == 1)
+ .withProperty("IsEven", n % 2 == 0)
+ }
+ Source(msgsIn).runWith(jmsSink)
+
+ // #source-with-selector
+ val jmsSource = JmsConsumer(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withQueue("numbers")
+ .withSelector("IsOdd = TRUE"))
+ // #source-with-selector
+
+ val oddMsgsIn = msgsIn.filter(msg => msg.body.toInt % 2 == 1)
+ val result = jmsSource.take(oddMsgsIn.size).runWith(Sink.seq)
+
+ // We should have only received the odd numbers in the list
+ result.futureValue.zip(oddMsgsIn).foreach {
+ case (out, in) =>
+ out.getIntProperty("Number") shouldEqual in.properties("Number")
+ out.getBooleanProperty("IsOdd") shouldEqual in.properties("IsOdd")
+ out.getBooleanProperty("IsEven") shouldEqual in.properties("IsEven")
+ // Make sure we are only receiving odd numbers
+ out.getIntProperty("Number") % 2 shouldEqual 1
+ }
+ }
+
+ "applying backpressure when the consumer is slower than the producer" in withConnectionFactory() {
+ connectionFactory =>
+ val in = List("a", "b", "c")
+ Source(in).runWith(
+ JmsProducer.textSink(JmsProducerSettings(producerConfig, connectionFactory).withQueue("test")))
+
+ val result = JmsConsumer
+ .textSource(JmsConsumerSettings(consumerConfig, connectionFactory).withBufferSize(1).withQueue("test"))
+ .throttle(1, 1.second, 1, ThrottleMode.shaping)
+ .take(in.size)
+ .runWith(Sink.seq)
+
+ result.futureValue shouldEqual in
+ }
+
+ "disconnection should fail the stage after exhausting retries" in withServer() { server =>
+ val connectionFactory = server.createConnectionFactory
+ val result = JmsConsumer(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withQueue("test")
+ .withConnectionRetrySettings(ConnectionRetrySettings(system).withMaxRetries(3))).runWith(Sink.seq)
+ Thread.sleep(500)
+ server.stop()
+ val ex = result.failed.futureValue
+ ex shouldBe a[ConnectionRetryException]
+ ex.getCause shouldBe a[JMSException]
+ }
+
+ "publish and consume elements through a topic with custom topic creator" in withConnectionFactory() {
+ connectionFactory =>
+ def createTopic(destinationName: String): Session => jakarta.jms.Topic = { (session: Session) =>
+ val amqSession = session.asInstanceOf[ActiveMQSession]
+ amqSession.createTopic(s"my-$destinationName")
+ }
+
+ // #create-custom-jms-topic-sink
+ val jmsTopicSink: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings(producerConfig, connectionFactory)
+ .withDestination(CustomDestination("topic", createTopic("topic"))))
+ // #create-custom-jms-topic-sink
+ val jmsTopicSink2: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings(producerConfig, connectionFactory)
+ .withDestination(CustomDestination("topic", createTopic("topic"))))
+
+ val in = List("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k")
+ val inNumbers = (1 to 10).map(_.toString)
+
+ // #create-custom-jms-topic-source
+ val jmsTopicSource: Source[String, JmsConsumerControl] = JmsConsumer.textSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withDestination(CustomDestination("topic", createTopic("topic"))))
+ // #create-custom-jms-topic-source
+ val jmsSource2: Source[String, JmsConsumerControl] = JmsConsumer.textSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withDestination(CustomDestination("topic", createTopic("topic"))))
+
+ val expectedSize = in.size + inNumbers.size
+
+ import scala.concurrent.ExecutionContext.Implicits.global
+
+ val result1 = jmsTopicSource.take(expectedSize).runWith(Sink.seq).map(_.sorted)
+ val result2 = jmsSource2.take(expectedSize).runWith(Sink.seq).map(_.sorted)
+
+ // We wait a little to be sure that the source is connected
+ Thread.sleep(500)
+
+ Source(in).runWith(jmsTopicSink)
+
+ Source(inNumbers).runWith(jmsTopicSink2)
+
+ val expectedList: List[String] = in ++ inNumbers
+ result1.futureValue shouldEqual expectedList.sorted
+ result2.futureValue shouldEqual expectedList.sorted
+ }
+
+ "publish and consume elements through a topic " in withConnectionFactory() { connectionFactory =>
+ import system.dispatcher
+
+ // #create-topic-sink
+ val jmsTopicSink: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings(producerConfig, connectionFactory).withTopic("topic"))
+ // #create-topic-sink
+ val jmsTopicSink2: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings(producerConfig, connectionFactory).withTopic("topic"))
+
+ val in = List("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k")
+ val inNumbers = (1 to 10).map(_.toString)
+
+ // #create-topic-source
+ val jmsTopicSource: Source[String, JmsConsumerControl] = JmsConsumer.textSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory).withTopic("topic"))
+ // #create-topic-source
+ val jmsSource2: Source[String, JmsConsumerControl] = JmsConsumer.textSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory).withTopic("topic"))
+
+ val expectedSize = in.size + inNumbers.size
+ // #run-topic-source
+ val result1 = jmsTopicSource.take(expectedSize).runWith(Sink.seq).map(_.sorted)
+ val result2 = jmsSource2.take(expectedSize).runWith(Sink.seq).map(_.sorted)
+ // #run-topic-source
+
+ // We wait a little to be sure that the source is connected
+ Thread.sleep(500)
+
+ // #run-topic-sink
+ Source(in).runWith(jmsTopicSink)
+ // #run-topic-sink
+ Source(inNumbers).runWith(jmsTopicSink2)
+
+ val expectedList: List[String] = in ++ inNumbers
+ result1.futureValue shouldEqual expectedList.sorted
+ result2.futureValue shouldEqual expectedList.sorted
+ }
+
+ "publish and consume JMS text messages through a queue without acknowledgingg them" in withConnectionFactory() {
+ connectionFactory =>
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue("numbers"))
+
+ val msgsIn = (1 to 10).toList.map { n =>
+ JmsTextMessage(n.toString)
+ }
+
+ Source(msgsIn).runWith(jmsSink)
+
+ val jmsSource: Source[Message, JmsConsumerControl] = JmsConsumer(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withQueue("numbers")
+ .withAcknowledgeMode(AcknowledgeMode.ClientAcknowledge))
+
+ val result = jmsSource
+ .take(msgsIn.size)
+ .map {
+ case textMessage: TextMessage =>
+ textMessage.getText
+ case other => fail(s"didn't match `$other`")
+ }
+ .runWith(Sink.seq)
+
+ result.futureValue shouldEqual msgsIn.map(_.body)
+
+ // messages were not acknowledged, may be delivered again
+ jmsSource
+ .takeWithin(5.seconds)
+ .runWith(Sink.seq)
+ .futureValue should not be empty
+ }
+
+ "sink successful completion" in withConnectionFactory() { connFactory =>
+ val connectionFactory = new CachedConnectionFactory(connFactory)
+
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue("numbers"))
+
+ val msgsIn = (1 to 10).toList.map { n =>
+ JmsTextMessage(n.toString)
+ }
+
+ val completionFuture: Future[Done] = Source(msgsIn).runWith(jmsSink)
+ completionFuture.futureValue shouldBe Done
+
+ // make sure connection was closed
+ eventually {
+ val isClosedField =
+ connectionFactory.cachedConnection.getClass.getDeclaredFields.filter(x => x.getName == "closed").head
+ isClosedField.setAccessible(true)
+
+ val isClosedValue = isClosedField.get(connectionFactory.cachedConnection)
+ isClosedValue shouldBe true
+ }
+ }
+
+ "sink exceptional completion" in withConnectionFactory() { connFactory =>
+ val connectionFactory = new CachedConnectionFactory(connFactory)
+
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory)
+ .withQueue("numbers")
+ .withConnectionRetrySettings(ConnectionRetrySettings(system).withMaxRetries(0)))
+
+ val completionFuture: Future[Done] = Source
+ .failed[JmsTextMessage](new RuntimeException("Simulated error"))
+ .runWith(jmsSink)
+
+ completionFuture.failed.futureValue shouldBe a[RuntimeException]
+ // make sure connection was closed
+ eventually {
+ val isClosedField =
+ connectionFactory.cachedConnection.getClass.getDeclaredFields.filter(x => x.getName == "closed").head
+ isClosedField.setAccessible(true)
+
+ val isClosedValue = isClosedField.get(connectionFactory.cachedConnection)
+ isClosedValue shouldBe true
+ }
+ }
+
+ "producer disconnect exceptional completion" in withServer() { server =>
+ import system.dispatcher
+
+ val connectionFactory = new CachedConnectionFactory(server.createConnectionFactory)
+
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory)
+ .withQueue("numbers")
+ .withConnectionRetrySettings(ConnectionRetrySettings(system).withMaxRetries(2)))
+
+ val completionFuture: Future[Done] = Source(0 to 10)
+ .mapAsync(1)(n =>
+ Future {
+ Thread.sleep(100)
+ JmsTextMessage(n.toString)
+ })
+ .runWith(jmsSink)
+
+ server.stop()
+
+ val exception = completionFuture.failed.futureValue
+ exception shouldBe a[ConnectionRetryException]
+ exception.getCause shouldBe a[JMSException]
+
+ // connection should be either
+ // - not yet initialized before broker stop, or
+ // - closed on broker stop (if preStart came first).
+ if (connectionFactory.cachedConnection != null) {
+ connectionFactory.cachedConnection shouldBe Symbol("closed")
+ }
+ }
+
+ "ensure no message loss when stopping a stream" in withConnectionFactory() { connectionFactory =>
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue("numbers"))
+
+ val (publishKillSwitch, publishedData) = Source
+ .unfold(1)(n => Some(n + 1 -> n))
+ .throttle(15, 1.second, 2, ThrottleMode.shaping) // Higher than consumption rate.
+ .viaMat(KillSwitches.single)(Keep.right)
+ .alsoTo(Flow[Int].map(n => JmsTextMessage(n.toString).withProperty("Number", n)).to(jmsSink))
+ .toMat(Sink.seq)(Keep.both)
+ .run()
+
+ val jmsSource: Source[Message, JmsConsumerControl] = JmsConsumer(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withBufferSize(5)
+ .withQueue("numbers"))
+
+ val resultQueue = new LinkedBlockingQueue[String]()
+
+ val (killSwitch, streamDone) = jmsSource
+ .throttle(10, 1.second, 2, ThrottleMode.shaping)
+ .toMat(Sink.foreach(msg => resultQueue.add(msg.asInstanceOf[TextMessage].getText)))(Keep.both)
+ .run()
+
+ // Need to wait for the stream to have started and running for sometime.
+ Thread.sleep(2000)
+
+ killSwitch.shutdown()
+
+ streamDone.futureValue shouldBe Done
+
+ // Keep publishing for another 2 seconds to make sure we killed the consumption mid-stream.
+ Thread.sleep(2000)
+
+ publishKillSwitch.shutdown()
+ val numsIn = publishedData.futureValue
+
+ // Ensure we break the stream while reading, not all input should have been read.
+ resultQueue.size should be < numsIn.size
+
+ val killSwitch2 = jmsSource
+ .to(Sink.foreach(msg => resultQueue.add(msg.asInstanceOf[TextMessage].getText)))
+ .run()
+
+ val resultList = new mutable.ArrayBuffer[String](numsIn.size)
+
+ @tailrec
+ def keepPolling(): Unit =
+ Option(resultQueue.poll(2, TimeUnit.SECONDS)) match {
+ case Some(entry) =>
+ resultList += entry
+ keepPolling()
+ case None =>
+ }
+
+ keepPolling()
+
+ killSwitch2.shutdown()
+
+ resultList.sortBy(_.toInt) should contain theSameElementsAs numsIn.map(_.toString)
+ }
+
+ "lose some elements when aborting a stream" in withConnectionFactory() { connectionFactory =>
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue("numbers"))
+
+ val (publishKillSwitch, publishedData) = Source
+ .unfold(1)(n => Some(n + 1 -> n))
+ .throttle(15, 1.second, 2, ThrottleMode.shaping) // Higher than consumption rate.
+ .viaMat(KillSwitches.single)(Keep.right)
+ .alsoTo(Flow[Int].map(n => JmsTextMessage(n.toString).withProperty("Number", n)).to(jmsSink))
+ .toMat(Sink.seq)(Keep.both)
+ .run()
+
+ val jmsSource: Source[AckEnvelope, JmsConsumerControl] = JmsConsumer.ackSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withBufferSize(5)
+ .withQueue("numbers"))
+
+ val resultQueue = new LinkedBlockingQueue[String]()
+
+ val (killSwitch, streamDone) = jmsSource
+ .throttle(10, 1.second, 2, ThrottleMode.shaping)
+ .toMat(
+ Sink.foreach { env =>
+ resultQueue.add(env.message.asInstanceOf[TextMessage].getText)
+ env.acknowledge()
+ })(Keep.both)
+ .run()
+
+ // Need to wait for the stream to have started and running for sometime.
+ Thread.sleep(2000)
+
+ val ex = new Exception("Test exception")
+ killSwitch.abort(ex)
+
+ import system.dispatcher
+ val resultTry = streamDone.map(Success(_)).recover { case e => Failure(e) }.futureValue
+
+ // Keep publishing for another 2 seconds to make sure we killed the consumption mid-stream.
+ Thread.sleep(2000)
+
+ publishKillSwitch.shutdown()
+ val numsIn = publishedData.futureValue
+
+ // Ensure we break the stream while reading, not all input should have been read.
+ resultQueue.size should be < numsIn.size
+ resultTry shouldBe Failure(ex)
+
+ val killSwitch2 = jmsSource
+ .to(
+ Sink.foreach { env =>
+ resultQueue.add(env.message.asInstanceOf[TextMessage].getText)
+ env.acknowledge()
+ })
+ .run()
+
+ val resultList = new mutable.ArrayBuffer[String](numsIn.size)
+
+ @tailrec
+ def keepPolling(): Unit =
+ Option(resultQueue.poll(2, TimeUnit.SECONDS)) match {
+ case Some(entry) =>
+ resultList += entry
+ keepPolling()
+ case None =>
+ }
+
+ keepPolling()
+
+ killSwitch2.shutdown()
+
+ // We may have lost some messages here, but most of them should have arrived.
+ resultList.size should be > (numsIn.size / 2)
+ resultList.size should be < numsIn.size
+ resultList.size shouldBe resultList.toSet.size // no duplicates
+ }
+
+ "only fail after maxBackoff retry" in withServer() { server =>
+ val connectionFactory = server.createConnectionFactory
+ server.stop()
+ val startTime = System.currentTimeMillis
+ val result = JmsConsumer(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withConnectionRetrySettings(ConnectionRetrySettings(system).withMaxRetries(4))
+ .withQueue("test")).runWith(Sink.seq)
+
+ val ex = result.failed.futureValue
+ val endTime = System.currentTimeMillis
+
+ (endTime - startTime) shouldBe >(100L + 400L + 900L + 1600L)
+ ex shouldBe a[ConnectionRetryException]
+ ex.getCause shouldBe a[JMSException]
+ }
+
+ "browse" in withConnectionFactory() { connectionFactory =>
+ val in = List(1 to 100).map(_.toString())
+
+ withClue("write some messages") {
+ Source(in)
+ .runWith(JmsProducer.textSink(JmsProducerSettings(producerConfig, connectionFactory).withQueue("test")))
+ .futureValue
+ }
+
+ withClue("browse the messages") {
+ // #browse-source
+
+ val browseSource: Source[jakarta.jms.Message, NotUsed] = JmsConsumer.browse(
+ JmsBrowseSettings(system, connectionFactory)
+ .withQueue("test"))
+
+ val result: Future[immutable.Seq[jakarta.jms.Message]] =
+ browseSource.runWith(Sink.seq)
+ // #browse-source
+
+ result.futureValue.collect { case msg: TextMessage => msg.getText } shouldEqual in
+ }
+
+ withClue("browse the messages again") {
+ // the messages should not have been consumed
+ val result = JmsConsumer
+ .browse(JmsBrowseSettings(browseConfig, connectionFactory).withQueue("test"))
+ .collect { case msg: TextMessage => msg.getText }
+ .runWith(Sink.seq)
+
+ result.futureValue shouldEqual in
+ }
+ }
+
+ "producer flow" in withConnectionFactory() { connectionFactory =>
+ // #flow-producer
+
+ val flow: Flow[JmsMessage, JmsMessage, JmsProducerStatus] =
+ JmsProducer.flow(
+ JmsProducerSettings(system, connectionFactory)
+ .withQueue("test"))
+
+ val input: immutable.Seq[JmsTextMessage] =
+ (1 to 100).map(i => JmsTextMessage(i.toString))
+
+ val result: Future[Seq[JmsMessage]] = Source(input)
+ .via(flow)
+ .runWith(Sink.seq)
+ // #flow-producer
+
+ result.futureValue should ===(input)
+ }
+
+ "accept message-defined destinations" in withConnectionFactory() { connectionFactory =>
+ // #run-directed-flow-producer
+ val flowSink: Flow[JmsMessage, JmsMessage, JmsProducerStatus] =
+ JmsProducer.flow(
+ JmsProducerSettings(system, connectionFactory).withQueue("test"))
+
+ val input = (1 to 100).map { i =>
+ val queueName = if (i % 2 == 0) "even" else "odd"
+ JmsTextMessage(i.toString).toQueue(queueName)
+ }
+ Source(input).via(flowSink).runWith(Sink.ignore)
+ // #run-directed-flow-producer
+
+ val jmsEvenSource: Source[String, JmsConsumerControl] = JmsConsumer.textSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory).withQueue("even"))
+ val jmsOddSource: Source[String, JmsConsumerControl] = JmsConsumer.textSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory).withQueue("odd"))
+
+ jmsEvenSource.take(input.size / 2).map(_.toInt).runWith(Sink.seq).futureValue shouldBe (2 to 100 by 2)
+ jmsOddSource.take(input.size / 2).map(_.toInt).runWith(Sink.seq).futureValue shouldBe (1 to 99 by 2)
+ }
+
+ "fail if message destination is not defined" in {
+ val connectionFactory = new ActiveMQConnectionFactory("vm://localhost:1234")
+
+ an[IllegalArgumentException] shouldBe thrownBy {
+ JmsProducer.flow(JmsProducerSettings(producerConfig, connectionFactory))
+ }
+ }
+
+ "publish and consume strings through a queue with multiple sessions" in withConnectionFactory() {
+ connectionFactory =>
+ val jmsSink: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue("test").withSessionCount(5))
+
+ val in = List("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k")
+ val sinkOut = Source(in).runWith(jmsSink)
+
+ val jmsSource: Source[String, JmsConsumerControl] = JmsConsumer.textSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory).withSessionCount(5).withQueue("test"))
+
+ val result = jmsSource.take(in.size).runWith(Sink.seq)
+
+ sinkOut.futureValue shouldBe Done
+ result.futureValue should contain allElementsOf in
+ }
+
+ "produce elements in order" in withMockedProducer { ctx =>
+ import ctx._
+ val delays = new AtomicInteger()
+ val textMessage = mock[TextMessage]
+
+ val delayedSend = new Answer[Unit] {
+ override def answer(invocation: InvocationOnMock): Unit = {
+ delays.incrementAndGet()
+ Thread.sleep(ThreadLocalRandom.current().nextInt(1, 10))
+ }
+ }
+
+ when(session.createTextMessage(anyString())).thenReturn(textMessage)
+ when(producer.send(any[jakarta.jms.Destination], any[Message], anyInt(), anyInt(), anyLong()))
+ .thenAnswer(delayedSend)
+
+ val in = (1 to 50).map(i => JmsTextMessage(i.toString))
+ val jmsFlow = JmsProducer.flow[JmsTextMessage](
+ JmsProducerSettings(producerConfig, factory).withQueue("test").withSessionCount(8))
+
+ val result = Source(in).via(jmsFlow).toMat(Sink.seq)(Keep.right).run()
+
+ result.futureValue shouldEqual in
+ delays.get shouldBe 50
+ }
+
+ "fail fast on the first failing send" in withMockedProducer { ctx =>
+ import ctx._
+ val sendLatch = new CountDownLatch(3)
+ val receiveLatch = new CountDownLatch(3)
+
+ val messages = (1 to 10).map(i => mock[TextMessage] -> i).toMap
+ messages.foreach {
+ case (msg, i) => when(session.createTextMessage(i.toString)).thenReturn(msg)
+ }
+
+ val failOnFifthAndDelayFourthItem = new Answer[Unit] {
+ override def answer(invocation: InvocationOnMock): Unit = {
+ val msgNo = messages(invocation.getArgument[TextMessage](1))
+ msgNo match {
+ case 1 | 2 | 3 =>
+ sendLatch.countDown() // first three sends work...
+ case 4 =>
+ Thread.sleep(30000) // this one gets delayed...
+ case 5 =>
+ sendLatch.await()
+ receiveLatch.await()
+ throw new RuntimeException("Mocked send failure") // this one fails.
+ case _ => ()
+ }
+ }
+ }
+ when(producer.send(any[jakarta.jms.Destination], any[Message], anyInt(), anyInt(), anyLong()))
+ .thenAnswer(failOnFifthAndDelayFourthItem)
+
+ val in = (1 to 10).map(i => JmsTextMessage(i.toString))
+ val done = JmsTextMessage("done")
+ val jmsFlow = JmsProducer.flow[JmsTextMessage](
+ JmsProducerSettings(producerConfig, factory).withQueue("test").withSessionCount(8))
+ val result = Source(in)
+ .via(jmsFlow)
+ .alsoTo(Sink.foreach(_ => receiveLatch.countDown()))
+ .recover { case _ => done }
+ .toMat(Sink.seq)(Keep.right)
+ .run()
+
+ // expect send failure on no 5. to cause immediate stream failure (after no. 1, 2 and 3),
+ // even though no 4. is still in-flight.
+ result.futureValue shouldEqual in.take(3) :+ done
+ }
+
+ "put back JmsProducer to the pool when send fails" in withMockedProducer { ctx =>
+ import ctx._
+
+ val messages = (1 to 10).map(i => mock[TextMessage] -> i).toMap
+ messages.foreach {
+ case (msg, i) => when(session.createTextMessage(i.toString)).thenReturn(msg)
+ }
+
+ val failOnEvenCount = new Answer[Unit] {
+ override def answer(invocation: InvocationOnMock): Unit = {
+ val msgNo = messages(invocation.getArgument[TextMessage](1))
+ if (msgNo % 2 == 0) throw new RuntimeException("Mocked send failure")
+ }
+ }
+
+ when(producer.send(any[jakarta.jms.Destination], any[Message], anyInt(), anyInt(), anyLong()))
+ .thenAnswer(failOnEvenCount)
+
+ val decider: Supervision.Decider = {
+ case _: RuntimeException => Supervision.Resume
+ case _ => Supervision.Stop
+ }
+ val jmsFlow = JmsProducer
+ .flow[JmsTextMessage](JmsProducerSettings(producerConfig, factory).withQueue("test").withSessionCount(2))
+ .withAttributes(ActorAttributes.supervisionStrategy(decider))
+
+ val in = (1 to 10).map(i => JmsTextMessage(i.toString))
+ val result = Source(in).via(jmsFlow).toMat(Sink.seq)(Keep.right).run()
+
+ result.futureValue.map(_.body.toInt) shouldEqual Seq(1, 3, 5, 7, 9)
+ }
+
+ val mockMessages = (0 until 10).map(_.toString)
+
+ val mockMessageGenerator = new Answer[Unit]() {
+ override def answer(invocation: InvocationOnMock): Unit = {
+ val listener = invocation.getArgument[MessageListener](0)
+ mockMessages.foreach { s =>
+ val message = mock[TextMessage]
+ when(message.getText).thenReturn(s)
+ listener.onMessage(message)
+ }
+ }
+ }
+
+ "reconnect when timing out establishing a connection" in {
+ val factory = mock[ConnectionFactory]
+ val connection = mock[Connection]
+ val session = mock[Session]
+ val consumer = mock[MessageConsumer]
+ @volatile var connectCount = 0
+ val connectTimeout = 2.seconds
+ val connectDelay = 10.seconds
+
+ when(factory.createConnection()).thenAnswer(new Answer[Connection]() {
+ override def answer(invocation: InvocationOnMock): Connection = {
+ connectCount += 1
+ if (connectCount == 1) Thread.sleep(connectDelay.toMillis) // Cause a connect timeout
+ connection
+ }
+ })
+
+ when(connection.createSession(anyBoolean(), anyInt())).thenReturn(session)
+ when(session.createConsumer(any[jakarta.jms.Destination])).thenReturn(consumer)
+ when(consumer.setMessageListener(any[MessageListener])).thenAnswer(mockMessageGenerator)
+
+ val jmsSource = JmsConsumer.textSource(
+ JmsConsumerSettings(consumerConfig, factory)
+ .withQueue("test")
+ .withConnectionRetrySettings(ConnectionRetrySettings(system).withConnectTimeout(connectTimeout)))
+
+ val startTime = System.nanoTime
+ val resultFuture = jmsSource.take(10).runWith(Sink.seq)
+ val result = resultFuture.futureValue
+ val timeTaken = Duration.fromNanos(System.nanoTime - startTime)
+
+ result should contain theSameElementsAs mockMessages
+ connectCount shouldBe 2
+ timeTaken should be > connectTimeout
+ timeTaken should be < connectDelay
+ }
+
+ "reconnect when timing out starting a connection" in {
+ val factory = mock[ConnectionFactory]
+ val connection = mock[Connection]
+ val session = mock[Session]
+ val consumer = mock[MessageConsumer]
+ @volatile var connectStartCount = 0
+ val connectTimeout = 2.seconds
+ val connectStartDelay = 10.seconds
+
+ when(factory.createConnection()).thenReturn(connection)
+
+ when(connection.start()).thenAnswer(new Answer[Unit]() {
+ override def answer(invocation: InvocationOnMock): Unit = {
+ connectStartCount += 1
+ if (connectStartCount == 1) Thread.sleep(connectStartDelay.toMillis) // first connection start to timeout
+ }
+ })
+
+ when(connection.createSession(anyBoolean(), anyInt())).thenReturn(session)
+ when(session.createConsumer(any[jakarta.jms.Destination])).thenReturn(consumer)
+ when(consumer.setMessageListener(any[MessageListener])).thenAnswer(mockMessageGenerator)
+
+ val jmsSource = JmsConsumer.textSource(
+ JmsConsumerSettings(consumerConfig, factory)
+ .withQueue("test")
+ .withConnectionRetrySettings(ConnectionRetrySettings(system).withConnectTimeout(connectTimeout)))
+
+ val startTime = System.nanoTime
+ val resultFuture = jmsSource.take(10).runWith(Sink.seq)
+ val result = resultFuture.futureValue
+ val timeTaken = Duration.fromNanos(System.nanoTime - startTime)
+
+ result should contain theSameElementsAs mockMessages
+ connectStartCount shouldBe 2
+ timeTaken should be > connectTimeout
+ timeTaken should be < connectStartDelay
+ }
+
+ "reconnect when runtime connection exception occurs" in {
+ val factory = mock[ConnectionFactory]
+ val connection = mock[Connection]
+ val session = mock[Session]
+ val consumer = mock[MessageConsumer]
+ @volatile var connectCount = 0
+ @volatile var exceptionListener: Option[ExceptionListener] = None
+ val messageGroups = mockMessages.grouped(3)
+
+ when(factory.createConnection()).thenAnswer(new Answer[Connection]() {
+ override def answer(invocation: InvocationOnMock): Connection = {
+ connectCount += 1
+ connection
+ }
+ })
+
+ when(connection.createSession(anyBoolean(), anyInt())).thenReturn(session)
+
+ when(connection.setExceptionListener(any[ExceptionListener])).thenAnswer(new Answer[Unit]() {
+ override def answer(invocation: InvocationOnMock): Unit =
+ exceptionListener = Option(invocation.getArgument[ExceptionListener](0))
+ })
+
+ when(session.createConsumer(any[jakarta.jms.Destination])).thenReturn(consumer)
+
+ when(consumer.setMessageListener(any[MessageListener])).thenAnswer(new Answer[Unit]() {
+ override def answer(invocation: InvocationOnMock): Unit = {
+ val listener = invocation.getArgument[MessageListener](0)
+ val thisMessageGroup = messageGroups.next()
+ thisMessageGroup.foreach { s =>
+ val message = mock[TextMessage]
+ when(message.getText).thenReturn(s)
+ listener.onMessage(message)
+ }
+ if (messageGroups.hasNext) {
+ exceptionListener.foreach(_.onException(new JMSException("Mock: causing an exception while consuming")))
+ }
+ }
+ })
+
+ val jmsSource = JmsConsumer.textSource(
+ JmsConsumerSettings(consumerConfig, factory)
+ .withQueue("test"))
+
+ val resultFuture = jmsSource.take(mockMessages.size).runWith(Sink.seq)
+
+ resultFuture.futureValue should contain theSameElementsAs mockMessages
+
+ // Connects 1 time at start and 3 times each 3 messages.
+ connectCount shouldBe 4
+ }
+
+ "pass through message envelopes" in withConnectionFactory() { connectionFactory =>
+ // #run-flexi-flow-producer
+ val jmsProducer: Flow[JmsEnvelope[String], JmsEnvelope[String], JmsProducerStatus] =
+ JmsProducer.flexiFlow[String](
+ JmsProducerSettings(system, connectionFactory).withQueue("test"))
+
+ val data = List("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k")
+ val in: immutable.Seq[JmsTextMessagePassThrough[String]] =
+ data.map(t => JmsTextMessage(t).withPassThrough(t))
+
+ val result = Source(in)
+ .via(jmsProducer)
+ .map(_.passThrough) // extract the value passed through
+ .runWith(Sink.seq)
+ // #run-flexi-flow-producer
+
+ result.futureValue shouldEqual data
+
+ val sentData =
+ JmsConsumer
+ .textSource(JmsConsumerSettings(consumerConfig, connectionFactory).withQueue("test"))
+ .take(data.size)
+ .runWith(Sink.seq)
+
+ sentData.futureValue shouldEqual data
+ }
+
+ "pass through empty envelopes" in {
+ val connectionFactory = mock[ConnectionFactory]
+ val connection = mock[Connection]
+ val session = mock[Session]
+ val producer = mock[MessageProducer]
+ val message = mock[TextMessage]
+
+ when(connectionFactory.createConnection()).thenReturn(connection)
+ when(connection.createSession(anyBoolean(), anyInt())).thenReturn(session)
+ when(session.createProducer(any[jakarta.jms.Destination])).thenReturn(producer)
+ when(session.createTextMessage(any[String])).thenReturn(message)
+
+ // #run-flexi-flow-pass-through-producer
+ val jmsProducer = JmsProducer.flexiFlow[String](
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue("topic"))
+
+ val data = List("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k")
+ val in = data.map(t => JmsPassThrough(t))
+
+ val result = Source(in).via(jmsProducer).map(_.passThrough).runWith(Sink.seq)
+ // #run-flexi-flow-pass-through-producer
+
+ result.futureValue shouldEqual data
+
+ verify(session, never()).createTextMessage(any[String])
+ verify(producer, never()).send(any[jakarta.jms.Destination], any[Message], any[Int], any[Int], any[Long])
+ }
+ }
+
+ "publish and subscribe with a durable subscription" in withServer() { server =>
+ import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory
+ val producerConnectionFactory = server.createConnectionFactory
+ // #create-connection-factory-with-client-id
+ val consumerConnectionFactory = server.createConnectionFactory
+ consumerConnectionFactory.setClientID(getClass.getSimpleName)
+ // #create-connection-factory-with-client-id
+
+ val jmsTopicSink: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings(producerConfig, producerConnectionFactory).withTopic("topic"))
+
+ val in = List("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k")
+
+ // #create-durable-topic-source
+ val jmsTopicSource = JmsConsumer.textSource(
+ JmsConsumerSettings(consumerConfig, consumerConnectionFactory)
+ .withDurableTopic("topic", "durable-test"))
+ // #create-durable-topic-source
+
+ // #run-durable-topic-source
+ val result = jmsTopicSource.take(in.size).runWith(Sink.seq)
+ // #run-durable-topic-source
+
+ // We wait a little to be sure that the source is connected
+ Thread.sleep(500)
+
+ Source(in).runWith(jmsTopicSink)
+
+ result.futureValue shouldEqual in
+ }
+
+ "support request/reply with temporary queues" in withConnectionFactory() { connectionFactory =>
+ val connection = connectionFactory.createConnection()
+ connection.start()
+ val session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)
+ val tempQueue = session.createTemporaryQueue()
+ val tempQueueDest = connectors.jakartams.Destination(tempQueue)
+ val message = "ThisIsATest"
+ val correlationId = UUID.randomUUID().toString
+
+ val toRespondSink: Sink[JmsMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(system, connectionFactory).withQueue("test"))
+
+ val toRespondStreamCompletion: Future[Done] =
+ Source
+ .single(
+ JmsTextMessage(message)
+ .withHeader(JmsCorrelationId(correlationId))
+ .withHeader(JmsReplyTo(tempQueueDest)))
+ .runWith(toRespondSink)
+
+ // #request-reply
+ val respondStreamControl: JmsConsumerControl =
+ JmsConsumer(JmsConsumerSettings(system, connectionFactory).withQueue("test"))
+ .collect {
+ case message: TextMessage => JmsTextMessage(message)
+ }
+ .map { textMessage =>
+ textMessage.headers.foldLeft(JmsTextMessage(textMessage.body.reverse)) {
+ case (acc, rt: JmsReplyTo) => acc.to(rt.jmsDestination)
+ case (acc, cId: JmsCorrelationId) => acc.withHeader(cId)
+ case (acc, _) => acc
+ }
+ }
+ .via {
+ JmsProducer.flow(
+ JmsProducerSettings(system, connectionFactory).withQueue("ignored"))
+ }
+ .to(Sink.ignore)
+ .run()
+ // #request-reply
+
+ // getting ConnectionRetryException when trying to listen using streams, assuming it's because
+ // a different session can't listen on the original session's TemporaryQueue
+ val consumer = session.createConsumer(tempQueue)
+ val result = Future(consumer.receive(5.seconds.toMillis))(system.dispatcher)
+
+ toRespondStreamCompletion.futureValue shouldEqual Done
+
+ val msg = result.futureValue
+ msg shouldBe a[TextMessage]
+ msg.getJMSCorrelationID shouldEqual correlationId
+ msg.asInstanceOf[TextMessage].getText shouldEqual message.reverse
+
+ respondStreamControl.shutdown()
+
+ connection.close()
+ }
+}
diff --git a/jakartams/src/test/scala/docs/scaladsl/JmsIbmmqConnectorsSpec.scala b/jakartams/src/test/scala/docs/scaladsl/JmsIbmmqConnectorsSpec.scala
new file mode 100644
index 000000000..79d0411d3
--- /dev/null
+++ b/jakartams/src/test/scala/docs/scaladsl/JmsIbmmqConnectorsSpec.scala
@@ -0,0 +1,160 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package docs.scaladsl
+
+import com.ibm.mq.jakarta.jms.{ MQQueueConnectionFactory, MQQueueSession, MQTopicConnectionFactory }
+import com.ibm.msg.client.jakarta.wmq.common.CommonConstants
+import org.apache.pekko
+import pekko.Done
+import pekko.stream.connectors.jakartams._
+import pekko.stream.connectors.jakartams.scaladsl.{ JmsConsumer, JmsConsumerControl, JmsProducer }
+import pekko.stream.scaladsl.{ Sink, Source }
+import jakarta.jms.{ Session, TextMessage }
+
+import scala.collection.immutable
+import scala.concurrent.duration._
+import scala.concurrent.Future
+
+class JmsIbmmqConnectorsSpec extends JmsSpec {
+ override implicit val patienceConfig: PatienceConfig = PatienceConfig(2.minutes)
+
+ "The JMS Ibmmq Connectors" should {
+ val queueConnectionFactory = {
+ // #ibmmq-connection-factory
+ // Create the IBM MQ MQQueueConnectionFactory
+ val connectionFactory = new MQQueueConnectionFactory()
+
+ // align to docker image: ibmcom/mq:9.1.1.0
+ connectionFactory.setHostName("localhost")
+ connectionFactory.setPort(1414)
+ connectionFactory.setQueueManager("QM1")
+ connectionFactory.setChannel("DEV.APP.SVRCONN")
+
+ // #ibmmq-connection-factory
+
+ connectionFactory
+ }
+
+ "publish and consume strings through a queue" in {
+
+ // #ibmmq-queue
+ // Connect to IBM MQ over TCP/IP
+ queueConnectionFactory.setTransportType(CommonConstants.WMQ_CM_CLIENT)
+ val queueName = "DEV.QUEUE.1"
+
+ val jmsSink: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings(producerConfig, queueConnectionFactory)
+ .withQueue(queueName))
+
+ // #ibmmq-queue
+
+ val in = (0 to 25).map(i => ('a' + i).asInstanceOf[Char].toString)
+ Source(in).runWith(jmsSink)
+
+ // #ibmmq-queue
+ // Option1: create Source using default factory with just name
+ val jmsSource: Source[TxEnvelope, JmsConsumerControl] = JmsConsumer.txSource(
+ JmsConsumerSettings(consumerConfig, queueConnectionFactory)
+ .withQueue(queueName))
+
+ // #ibmmq-queue
+
+ val result = jmsSource
+ .take(in.size)
+ .map(env => (env, env.message.asInstanceOf[TextMessage].getText))
+ .map { case (env, text) => env.commit(); text }
+ .runWith(Sink.seq)
+
+ result.futureValue should contain theSameElementsAs in
+ }
+
+ "publish and consume strings through a queue with custom destination" in {
+
+ queueConnectionFactory.setTransportType(CommonConstants.WMQ_CM_CLIENT)
+ // #ibmmq-custom-destination
+ // Option2: create Source using custom factory
+ val customQueue = "DEV.QUEUE.3"
+ // #ibmmq-custom-destination
+
+ val jmsSink: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings
+ .create(system, queueConnectionFactory)
+ .withDestination(CustomDestination("custom", createQueue(customQueue))))
+
+ val in = (0 to 25).map(i => ('a' + i).asInstanceOf[Char].toString)
+
+ val streamCompletion: Future[Done] = Source(in).runWith(jmsSink)
+
+ // #ibmmq-custom-destination
+ val jmsSource: Source[String, JmsConsumerControl] = JmsConsumer.textSource(
+ JmsConsumerSettings
+ .create(system, queueConnectionFactory)
+ .withDestination(CustomDestination("custom", createQueue(customQueue))))
+
+ // #ibmmq-custom-destination
+
+ val result: Future[immutable.Seq[String]] = jmsSource.take(in.size).runWith(Sink.seq)
+
+ streamCompletion.futureValue shouldEqual Done
+ result.futureValue shouldEqual in
+ }
+ // #ibmmq-custom-destination
+ def createQueue(destinationName: String): Session => jakarta.jms.Queue = { (session: Session) =>
+ // cast to correct session implementation: MQQueueSession, MQTopicSession, MQSession
+ val mqSession = session.asInstanceOf[MQQueueSession]
+ mqSession.createQueue(destinationName)
+ }
+ // #ibmmq-custom-destination
+
+ "publish and consume strings through a topic" in {
+ // Create the IBM MQ MQTopicConnectionFactory
+ val topicConnectionFactory = new MQTopicConnectionFactory()
+ topicConnectionFactory.setHostName("localhost")
+ topicConnectionFactory.setPort(1414)
+ topicConnectionFactory.setQueueManager("QM1")
+ topicConnectionFactory.setChannel("DEV.APP.SVRCONN")
+
+ // #ibmmq-topic
+ // Connect to IBM MQ over TCP/IP
+ topicConnectionFactory.setTransportType(CommonConstants.WMQ_CM_CLIENT)
+ val testTopicName = "dev/"
+
+ val jmsTopicSink: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings
+ .create(system, topicConnectionFactory)
+ .withTopic(testTopicName))
+
+ // Option1: create Source using default factory with just name
+ val jmsTopicSource: Source[String, JmsConsumerControl] = JmsConsumer
+ .textSource(
+ JmsConsumerSettings
+ .create(system, topicConnectionFactory)
+ .withTopic(testTopicName))
+
+ // #ibmmq-topic
+
+ val in = (0 to 25).map(i => ('a' + i).asInstanceOf[Char].toString)
+
+ val result: Future[immutable.Seq[String]] = jmsTopicSource.take(in.size).runWith(Sink.seq)
+
+ Thread.sleep(500)
+
+ val streamCompletion: Future[Done] = Source(in).runWith(jmsTopicSink)
+
+ streamCompletion.futureValue shouldEqual Done
+ result.futureValue shouldEqual in
+ }
+ }
+
+}
diff --git a/jakartams/src/test/scala/docs/scaladsl/JmsSettingsSpec.scala b/jakartams/src/test/scala/docs/scaladsl/JmsSettingsSpec.scala
new file mode 100644
index 000000000..530c05ca4
--- /dev/null
+++ b/jakartams/src/test/scala/docs/scaladsl/JmsSettingsSpec.scala
@@ -0,0 +1,177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package docs.scaladsl
+
+import com.typesafe.config.{ Config, ConfigFactory }
+import org.apache.activemq.artemis.junit.EmbeddedActiveMQResource
+import org.apache.pekko.stream.connectors.jakartams._
+import org.scalatest.OptionValues
+
+import scala.concurrent.duration._
+
+class JmsSettingsSpec extends JmsSpec with OptionValues {
+ val server = new EmbeddedActiveMQServer(new EmbeddedActiveMQResource())
+ private val connectionFactory = server.createConnectionFactory
+
+ "Jms producer" should {
+ "have producer settings" in {
+
+ // #retry-settings-case-class
+ // reiterating defaults from reference.conf
+ val retrySettings = ConnectionRetrySettings(system)
+ .withConnectTimeout(10.seconds)
+ .withInitialRetry(100.millis)
+ .withBackoffFactor(2.0d)
+ .withMaxBackoff(1.minute)
+ .withMaxRetries(10)
+ // #retry-settings-case-class
+
+ // #send-retry-settings
+ // reiterating defaults from reference.conf
+ val sendRetrySettings = SendRetrySettings(system)
+ .withInitialRetry(20.millis)
+ .withBackoffFactor(1.5d)
+ .withMaxBackoff(500.millis)
+ .withMaxRetries(10)
+ // #send-retry-settings
+
+ // #producer-settings
+ val producerConfig: Config = system.settings.config.getConfig(JmsProducerSettings.configPath)
+ val settings = JmsProducerSettings(producerConfig, connectionFactory)
+ .withTopic("target-topic")
+ .withCredentials(Credentials("username", "password"))
+ .withSessionCount(1)
+ // #producer-settings
+
+ val retrySettings2 = ConnectionRetrySettings(system)
+ retrySettings.toString should be(retrySettings2.toString)
+
+ val sendRetrySettings2 = SendRetrySettings(system)
+ sendRetrySettings.toString should be(sendRetrySettings2.toString)
+
+ val producerSettings2 = JmsProducerSettings(producerConfig, settings.connectionFactory)
+ .withTopic("target-topic")
+ .withCredentials(Credentials("username", "password"))
+ settings.toString should be(producerSettings2.toString)
+
+ }
+ }
+
+ "Jms consumer" should {
+ "have consumer settings" in {
+
+ val connectionRetryConfig: Config = system.settings.config.getConfig(ConnectionRetrySettings.configPath)
+ val retrySettings = ConnectionRetrySettings(connectionRetryConfig)
+ .withConnectTimeout(10.seconds)
+ .withInitialRetry(100.millis)
+ .withBackoffFactor(2.0d)
+ .withMaxBackoff(1.minute)
+ .withMaxRetries(10)
+
+ // #consumer-settings
+ val consumerConfig: Config = system.settings.config.getConfig(JmsConsumerSettings.configPath)
+ // reiterating defaults from reference.conf
+ val settings = JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withQueue("target-queue")
+ .withCredentials(Credentials("username", "password"))
+ .withConnectionRetrySettings(retrySettings)
+ .withSessionCount(1)
+ .withBufferSize(100)
+ .withAckTimeout(1.second)
+ // #consumer-settings
+
+ val retrySettings2 = ConnectionRetrySettings(system)
+ retrySettings.toString should be(retrySettings2.toString)
+
+ val consumerSettings2 = JmsConsumerSettings(consumerConfig, settings.connectionFactory)
+ .withQueue("target-queue")
+ .withCredentials(Credentials("username", "password"))
+ settings.toString should be(consumerSettings2.toString)
+ }
+
+ "read from user config" in {
+ val config = ConfigFactory.parseString("""
+ |connection-retry {
+ | connect-timeout = 10 seconds
+ | initial-retry = 100 millis
+ | backoff-factor = 2
+ | max-backoff = 1 minute
+ | # infinite, or positive integer
+ | max-retries = 10
+ |}
+ |credentials {
+ | username = "some text"
+ | password = "other text"
+ |}
+ |session-count = 10
+ |buffer-size = 1000
+ |selector = "some text" # optional
+ |acknowledge-mode = duplicates-ok
+ |ack-timeout = 5 second
+ """.stripMargin).withFallback(consumerConfig).resolve()
+
+ val settings = JmsConsumerSettings(config, connectionFactory)
+ settings.credentials.value should be(Credentials("some text", "other text"))
+ settings.sessionCount should be(10)
+ settings.bufferSize should be(1000)
+ settings.selector.value should be("some text")
+ settings.acknowledgeMode.value should be(AcknowledgeMode.DupsOkAcknowledge)
+ settings.ackTimeout should be(5.seconds)
+ }
+
+ "read numeric acknowledge mode" in {
+ val config = ConfigFactory.parseString("""
+ |connection-retry {
+ | connect-timeout = 10 seconds
+ | initial-retry = 100 millis
+ | backoff-factor = 2
+ | max-backoff = 1 minute
+ | # infinite, or positive integer
+ | max-retries = 10
+ |}
+ |// credentials {
+ |// username = "some text"
+ |// password = "some text"
+ |// }
+ |session-count = 1
+ |buffer-size = 100
+ |// selector = "some text" # optional
+ |acknowledge-mode = 42
+ |ack-timeout = 1 second
+ """.stripMargin).withFallback(consumerConfig).resolve()
+
+ val settings = JmsConsumerSettings(config, connectionFactory)
+ settings.acknowledgeMode.value should be(new AcknowledgeMode(42))
+ }
+ }
+
+ "Browse settings" should {
+ "read from config" in {
+ val retrySettings = ConnectionRetrySettings(system)
+ // #browse-settings
+ val browseConfig: Config = system.settings.config.getConfig(JmsBrowseSettings.configPath)
+ val settings = JmsBrowseSettings(browseConfig, connectionFactory)
+ .withQueue("target-queue")
+ .withCredentials(Credentials("username", "password"))
+ .withConnectionRetrySettings(retrySettings)
+ // #browse-settings
+
+ val settings2 = JmsBrowseSettings(browseConfig, settings.connectionFactory)
+ .withQueue("target-queue")
+ .withCredentials(Credentials("username", "password"))
+
+ settings.toString should be(settings2.toString)
+ }
+ }
+}
diff --git a/jakartams/src/test/scala/docs/scaladsl/JmsTxConnectorsSpec.scala b/jakartams/src/test/scala/docs/scaladsl/JmsTxConnectorsSpec.scala
new file mode 100644
index 000000000..069658087
--- /dev/null
+++ b/jakartams/src/test/scala/docs/scaladsl/JmsTxConnectorsSpec.scala
@@ -0,0 +1,695 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) since 2016 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package docs.scaladsl
+
+import jakarta.jms.TextMessage
+import org.apache.pekko
+import pekko.Done
+import pekko.stream._
+import pekko.stream.connectors.jakartams._
+import pekko.stream.connectors.jakartams.scaladsl.{ JmsConsumer, JmsConsumerControl, JmsProducer }
+import pekko.stream.scaladsl.{ Flow, Keep, RestartSource, Sink, Source }
+import org.scalatest.Inspectors._
+import org.slf4j.LoggerFactory
+
+import java.util.concurrent.{ ConcurrentHashMap, LinkedBlockingQueue, TimeUnit }
+import scala.annotation.tailrec
+import scala.collection.{ immutable, mutable }
+import scala.concurrent.duration._
+import scala.concurrent.{ Await, Future, Promise }
+import scala.util.{ Failure, Success }
+
+class JmsTxConnectorsSpec extends JmsSharedServerSpec {
+
+ private final val log = LoggerFactory.getLogger(classOf[JmsTxConnectorsSpec])
+
+ override implicit val patienceConfig: PatienceConfig = PatienceConfig(2.minutes)
+
+ "The JMS Transactional Connectors" should {
+ "publish and consume strings through a queue" in withConnectionFactory() { connectionFactory =>
+ val queueName = createName("test")
+ val jmsSink: Sink[String, Future[Done]] = JmsProducer.textSink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue(queueName))
+
+ val in = (0 to 25).map(i => ('a' + i).asInstanceOf[Char].toString)
+ Source(in).runWith(jmsSink)
+
+ val jmsSource: Source[TxEnvelope, JmsConsumerControl] = JmsConsumer.txSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory).withSessionCount(5).withQueue(queueName))
+
+ val result = jmsSource
+ .take(in.size)
+ .map(env => (env, env.message.asInstanceOf[TextMessage].getText))
+ .map { case (env, text) => env.commit(); text }
+ .runWith(Sink.seq)
+
+ result.futureValue should contain theSameElementsAs in
+ }
+
+ "publish and consume JMS text messages with properties through a queue" in withConnectionFactory() {
+ val queueName = createName("numbers")
+ connectionFactory =>
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue(queueName))
+
+ val msgsIn = (1 to 100).map { n =>
+ JmsTextMessage(n.toString)
+ .withProperty("Number", n)
+ .withProperty("IsOdd", n % 2 == 1)
+ .withProperty("IsEven", n % 2 == 0)
+ }
+
+ Source(msgsIn).runWith(jmsSink)
+
+ // #source
+ val jmsSource: Source[TxEnvelope, JmsConsumerControl] = JmsConsumer.txSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withAckTimeout(1.second)
+ .withQueue(queueName))
+
+ val result: Future[immutable.Seq[jakarta.jms.Message]] =
+ jmsSource
+ .take(msgsIn.size)
+ .map { txEnvelope =>
+ txEnvelope.commit()
+ txEnvelope.message
+ }
+ .runWith(Sink.seq)
+ // #source
+
+ // The sent message and the receiving one should have the same properties
+ val sortedResult = result.futureValue.sortBy(msg => msg.getIntProperty("Number"))
+ forAll(sortedResult.zip(msgsIn)) {
+ case (out, in) =>
+ out.getIntProperty("Number") shouldEqual in.properties("Number")
+ out.getBooleanProperty("IsOdd") shouldEqual in.properties("IsOdd")
+ out.getBooleanProperty("IsEven") shouldEqual in.properties("IsEven")
+ }
+ }
+
+ "ensure re-delivery when rollback JMS text messages through a queue" in withConnectionFactory() {
+ connectionFactory =>
+ val queueName = createName("numbers")
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue(queueName))
+ val msgsIn = (1 to 100).map { n =>
+ JmsTextMessage(n.toString).withProperty("Number", n)
+ }
+
+ Source(msgsIn).runWith(jmsSink)
+
+ val jmsSource: Source[TxEnvelope, JmsConsumerControl] = JmsConsumer.txSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory).withSessionCount(5).withQueue(queueName))
+
+ val expectedElements = ((1 to 100) ++ (2 to 100 by 2)).map(_.toString)
+
+ val rolledBackSet = ConcurrentHashMap.newKeySet[Int]()
+
+ val result = jmsSource
+ .take(expectedElements.size)
+ .map { env =>
+ val id = env.message.getIntProperty("Number")
+ if (id % 2 == 0 && !rolledBackSet.contains(id)) {
+ rolledBackSet.add(id)
+ env.rollback()
+ } else {
+ env.commit()
+ }
+ env.message.asInstanceOf[TextMessage].getText
+ }
+ .runWith(Sink.seq)
+
+ result.futureValue should contain theSameElementsAs expectedElements
+ }
+
+ "publish JMS text messages with properties through a queue and consume them with a selector" in withConnectionFactory() {
+ connectionFactory =>
+ val queueName = createName("numbers")
+ val jmsSink: Sink[JmsTextMessage, Future[Done]] = JmsProducer.sink(
+ JmsProducerSettings(producerConfig, connectionFactory).withQueue(queueName))
+
+ val msgsIn = (1 to 100).map { n =>
+ JmsTextMessage(n.toString)
+ .withProperty("Number", n)
+ .withProperty("IsOdd", n % 2 == 1)
+ .withProperty("IsEven", n % 2 == 0)
+ }
+ Source(msgsIn).runWith(jmsSink)
+
+ val jmsSource = JmsConsumer.txSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withSessionCount(5)
+ .withQueue(queueName)
+ .withSelector("IsOdd = TRUE"))
+
+ val oddMsgsIn = msgsIn.filter(msg => msg.body.toInt % 2 == 1)
+ val result = jmsSource
+ .take(oddMsgsIn.size)
+ .map { env =>
+ env.commit()
+ env.message
+ }
+ .runWith(Sink.seq)
+ // We should have only received the odd numbers in the list
+
+ val sortedResult = result.futureValue.sortBy(msg => msg.getIntProperty("Number"))
+ forAll(sortedResult.zip(oddMsgsIn)) {
+ case (out, in) =>
+ out.getIntProperty("Number") shouldEqual in.properties("Number")
+ out.getBooleanProperty("IsOdd") shouldEqual in.properties("IsOdd")
+ out.getBooleanProperty("IsEven") shouldEqual in.properties("IsEven")
+ // Make sure we are only receiving odd numbers
+ out.getIntProperty("Number") % 2 shouldEqual 1
+ }
+ }
+
+ "applying backpressure when the consumer is slower than the producer" in withConnectionFactory() {
+ connectionFactory =>
+ val in = (0 to 25).map(i => ('a' + i).asInstanceOf[Char].toString)
+ val queueName = createName("test")
+ Source(in).runWith(
+ JmsProducer.textSink(JmsProducerSettings(producerConfig, connectionFactory).withQueue(queueName)))
+
+ val jmsSource: Source[TxEnvelope, JmsConsumerControl] = JmsConsumer.txSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory).withSessionCount(5).withQueue(queueName))
+
+ val result = jmsSource
+ .throttle(10, 1.second, 1, ThrottleMode.shaping)
+ .take(in.size)
+ .map(env => (env, env.message.asInstanceOf[TextMessage].getText))
+ .map { case (env, text) => env.commit(); text }
+ .runWith(Sink.seq)
+
+ result.futureValue should contain theSameElementsAs in
+ }
+
+ "disconnection should fail the stage after exhausting retries" in withServer() { server =>
+ val queueName = createName("test")
+ val connectionFactory = server.createConnectionFactory
+ val result = JmsConsumer
+ .txSource(
+ JmsConsumerSettings(consumerConfig, connectionFactory)
+ .withQueue(queueName)
+ .withConnectionRetrySettings(ConnectionRetrySettings(system).withMaxRetries(3)))
+ .runWith(Sink.seq)
+ Thread.sleep(500)
+
+ server.getServer.getActiveMQServer.stop()
+ val ex = result.failed.futureValue
+ ex shouldBe a[ConnectionRetryException]
+ // ex.getCause shouldBe a[JMSException]
+ }
+
+ // Trying to illustrate https://github.com/akka/alpakka/issues/2103
+ // Unfinished: this requires a broker persisting its data
+ "read messages after broker restart" ignore withServer() { server =>
+ val queueName = createName("restarting")
... 2174 lines suppressed ...
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pekko.apache.org
For additional commands, e-mail: commits-help@pekko.apache.org