This is an automated email from the ASF dual-hosted git repository.

fmariani pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel-spring-boot-examples.git


The following commit(s) were added to refs/heads/main by this push:
     new cc1648b  add multi pooled datasources with 2PC example
cc1648b is described below

commit cc1648b174b012692dc9edc21faf783fecfe4744
Author: Rinaldo Pitzer Júnior <[email protected]>
AuthorDate: Fri Aug 30 15:30:49 2024 -0300

    add multi pooled datasources with 2PC example
---
 README.adoc                                        |   2 +
 multi-datasource-2pc/.gitignore                    |   2 +
 multi-datasource-2pc/pom.xml                       | 152 +++++++++++++++++++++
 multi-datasource-2pc/readme.adoc                   |  75 ++++++++++
 .../main/java/sample/camel/DataSourcesConfig.java  |  84 ++++++++++++
 .../main/java/sample/camel/MyCamelApplication.java |  37 +++++
 .../src/main/java/sample/camel/MyCamelRouter.java  |  90 ++++++++++++
 .../src/main/resources/application.properties      |  66 +++++++++
 .../src/main/resources/schema-ds1.sql              |   4 +
 .../src/main/resources/schema-ds2.sql              |   4 +
 .../sample/camel/MyCamelApplicationJUnit5Test.java | 120 ++++++++++++++++
 .../src/test/resources/application-test.properties |  21 +++
 12 files changed, 657 insertions(+)

diff --git a/README.adoc b/README.adoc
index 110e73f..90ce436 100644
--- a/README.adoc
+++ b/README.adoc
@@ -83,6 +83,8 @@ Number of Examples: 59 (0 deprecated)
 
 | link:arangodb/README.adoc[Arangodb] (arangodb) | Database | An example 
showing the Camel ArangoDb component with Spring Boot
 
+| link:multi-datasource-2pc/readme.adoc[Multi Datasource 2pc] 
(multi-datasource-2pc) | Database | An example showing how to work with Camel 
and Spring Boot using multiple pooled datasources with two-phase commit
+
 | link:dynamic-router-eip/README.adoc[Dynamic Router Eip] (dynamic-router-eip) 
| EIP | Dynamic Router EIP component examples
 
 | link:load-balancer-eip/README.adoc[Load Balancer Eip] (load-balancer-eip) | 
EIP | An example showing Load Balancer EIP with Camel and Spring Boot
diff --git a/multi-datasource-2pc/.gitignore b/multi-datasource-2pc/.gitignore
new file mode 100644
index 0000000..ceb75d0
--- /dev/null
+++ b/multi-datasource-2pc/.gitignore
@@ -0,0 +1,2 @@
+transaction-logs
+test-transactions-logs
\ No newline at end of file
diff --git a/multi-datasource-2pc/pom.xml b/multi-datasource-2pc/pom.xml
new file mode 100644
index 0000000..7fc025e
--- /dev/null
+++ b/multi-datasource-2pc/pom.xml
@@ -0,0 +1,152 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Licensed to the Apache Software Foundation (ASF) under one or more
+    contributor license agreements.  See the NOTICE file distributed with
+    this work for additional information regarding copyright ownership.
+    The ASF licenses this file to You under the Apache License, Version 2.0
+    (the "License"); you may not use this file except in compliance with
+    the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"; 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/maven-v4_0_0.xsd";>
+
+    <modelVersion>4.0.0</modelVersion>
+
+    <parent>
+        <groupId>org.apache.camel.springboot.example</groupId>
+        <artifactId>examples</artifactId>
+        <version>4.8.0-SNAPSHOT</version>
+    </parent>
+
+    <artifactId>camel-example-spring-boot-muti-datasources-2pc</artifactId>
+    <name>Camel SB Examples :: Multiple pooled datasources with two-phase 
commit</name>
+    <description>An example showing how to work with Camel and Spring Boot 
using multiple pooled datasources with two-phase commit</description>
+
+    <properties>
+        <category>Database</category>
+
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+        
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+    </properties>
+
+    <dependencyManagement>
+        <dependencies>
+            <!-- Camel BOM -->
+            <dependency>
+                <groupId>org.apache.camel.springboot</groupId>
+                <artifactId>camel-spring-boot-bom</artifactId>
+                <version>${project.version}</version>
+                <type>pom</type>
+                <scope>import</scope>
+            </dependency>
+            <!-- Spring Boot BOM -->
+            <dependency>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-dependencies</artifactId>
+                <version>${spring-boot-version}</version>
+                <type>pom</type>
+                <scope>import</scope>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+
+    <dependencies>
+
+        <!-- Spring Boot -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-actuator</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-jdbc</artifactId>
+        </dependency>
+
+        <!-- Camel -->
+        <dependency>
+            <groupId>org.apache.camel.springboot</groupId>
+            <artifactId>camel-spring-boot-starter</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.camel.springboot</groupId>
+            <artifactId>camel-stream-starter</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.camel.springboot</groupId>
+            <artifactId>camel-spring-jdbc-starter</artifactId>
+        </dependency>
+
+        <!-- Datasources -->
+        <dependency>
+            <groupId>dev.snowdrop</groupId>
+            <artifactId>narayana-spring-boot-starter</artifactId>
+            <version>3.2.0</version>
+        </dependency>
+        <dependency>
+            <groupId>io.agroal</groupId>
+            <artifactId>agroal-spring-boot-starter</artifactId>
+            <version>2.5</version>
+        </dependency>
+        <dependency>
+            <groupId>org.postgresql</groupId>
+            <artifactId>postgresql</artifactId>
+        </dependency>
+
+        <!-- test -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.camel</groupId>
+            <artifactId>camel-test-spring-junit5</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-testcontainers</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.testcontainers</groupId>
+            <artifactId>postgresql</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.testcontainers</groupId>
+            <artifactId>junit-jupiter</artifactId>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+                <version>${spring-boot-version}</version>
+                <executions>
+                    <execution>
+                        <goals>
+                            <goal>repackage</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+</project>
diff --git a/multi-datasource-2pc/readme.adoc b/multi-datasource-2pc/readme.adoc
new file mode 100644
index 0000000..dd4f0d5
--- /dev/null
+++ b/multi-datasource-2pc/readme.adoc
@@ -0,0 +1,75 @@
+== Camel Spring Boot with multiple pooled datasources and 2PC
+
+This example shows how to set up multiple pooled datasources with Camel Spring 
Boot and have them working with two-phase commit.
+
+One of the databases has a non-unique `name` column, while the other has a 
unique one. When trying to insert repeated names in both databases at the same 
time, the second `prepare` should fail making the transaction rollback for both 
databases.
+
+=== Classes and resources
+
+* `MyCamelRouter`: where the camel routes are defined
+* `DataSourcesConfig`: where the datasources' beans are created
+* `MyCamelApplication`: the Spring Boot main class
+* `application.properties`: configuration for the datasources and others
+* `schema-ds1.sql` and `schema-ds2.sql`: initializers for the databases
+
+=== How to run
+
+. Run the database containers. Notice the commands have extra arguments to 
enable initialization and two-phase commit.
++
+[source,console]
+----
+podman run --rm --name db1 -e POSTGRES_PASSWORD=password -p 5432:5432 -v 
./src/main/resources/schema-ds1.sql:/docker-entrypoint-initdb.d/init.sql:Z 
docker.io/library/postgres:latest -c max_prepared_transactions=10
+----
++
+[source,console]
+----
+podman run --rm --name db2 -e POSTGRES_PASSWORD=password -p 5433:5432 -v 
./src/main/resources/schema-ds2.sql:/docker-entrypoint-initdb.d/init.sql:Z 
docker.io/library/postgres:latest -c max_prepared_transactions=10
+----
+
+. Then run the example using
+[source,console]
+mvn spring-boot:run
+
+. Every few seconds you can see in the logs that a new insert is created, but 
when it tries to insert a non-unique name then the transaction rollbacks and 
the names are not inserted in any of the databases.
++
+[source,log]
+----
+[read #8 - Delay] info                  : Exchange[ExchangePattern: InOnly, 
BodyType: String, Body: There are 4 names in the ds2 database.]
+[timer://runOnce] info                  : Exchange[Id: 
0B8F2317CCE5D8D-000000000000000D, RouteGroup: null, RouteId: route2, 
ExchangePattern: InOnly, Properties: 
{CamelAggregationStrategy={split1=UseOriginalAggregationStrategy}, 
CamelCorrelationId=0B8F2317CCE5D8D-0000000000000000, CamelSplitComplete=false, 
CamelSplitIndex=4, CamelSplitSize=6, 
CamelStreamCacheUnitOfWork=DefaultUnitOfWork, 
CamelToEndpoint=log://info?showAll=true}, Headers: {}, BodyType: String, Body: 
Maria]
+[timer://runOnce] route2                : insert into the first database 
(non-unique)
+[timer://runOnce] route2                : insert into the second database 
(unique)
+[timer://runOnce] com.arjuna.ats.jta    : ARJUNA016041: prepare on < 
formatId=131077, gtrid_length=29, bqual_length=36, 
tx_uid=0:ffff0a057e34:aedb:66cc8122:39, node_name=1, 
branch_uid=0:ffff0a057e34:aedb:66cc8122:3f, subordinatenodename=null, 
eis_name=java:comp/env/jdbc/ds2 > (io.agroal.narayana.BaseXAResource@65fecc5) 
failed with exception XAException.XA_RBINTEGRITY
+...
+Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value 
violates unique constraint "names_name_key"
+...
+[timer://runOnce] com.arjuna.ats.arjuna : ARJUNA012073: BasicAction.End() - 
prepare phase of action-id 0:ffff0a057e34:aedb:66cc8122:39 failed.
+[timer://runOnce] com.arjuna.ats.arjuna : ARJUNA012075: Action Aborting
+----
+
+=== Cleanup
+
+. Clear Narayana transaction logs:
+[source,console]
+rm -rf transaction-logs
+
+. Stop the running containers
+
+=== Running the tests
+
+. Run the tests using
+[source,console]
+mvn clean test
+
+=== Extra details
+
+The `name` column in the second database is set up with `UNIQUE DEFERRABLE 
INITIALLY DEFERRED`. This configuration delays the constraint check to only be 
evaluated in the commit phase. Without this argument there would be an 
exception thrown immediately during the `INSERT` command, causing the 
transaction to be rolled-back immediately. This is only set up this way to make 
the example clearer.
+
+=== Help and contributions
+
+If you hit any problem using Camel or have some feedback, then please
+https://camel.apache.org/support.html[let us know].
+
+We also love contributors, so
+https://camel.apache.org/contributing.html[get involved] :-)
+
+The Camel riders!
\ No newline at end of file
diff --git 
a/multi-datasource-2pc/src/main/java/sample/camel/DataSourcesConfig.java 
b/multi-datasource-2pc/src/main/java/sample/camel/DataSourcesConfig.java
new file mode 100644
index 0000000..7d9a465
--- /dev/null
+++ b/multi-datasource-2pc/src/main/java/sample/camel/DataSourcesConfig.java
@@ -0,0 +1,84 @@
+package sample.camel;
+
+import io.agroal.springframework.boot.AgroalDataSource;
+import io.agroal.springframework.boot.AgroalDataSourceAutoConfiguration;
+import io.agroal.springframework.boot.jndi.AgroalDataSourceJndiBinder;
+import org.jboss.tm.XAResourceRecoveryRegistry;
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.config.BeanPostProcessor;
+import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
+import 
org.springframework.boot.autoconfigure.sql.init.SqlDataSourceScriptDatabaseInitializer;
+import 
org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration;
+import 
org.springframework.boot.autoconfigure.sql.init.SqlInitializationProperties;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.boot.sql.init.DatabaseInitializationSettings;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.jta.JtaTransactionManager;
+
+import javax.sql.DataSource;
+
+@Configuration
+public class DataSourcesConfig {
+
+    // -- first data source config
+
+    @Bean("ds1properties")
+    @ConfigurationProperties("app.datasource.ds1")
+    public DataSourceProperties firstDataSourceProperties() {
+        return new DataSourceProperties();
+    }
+
+    @Bean("ds1")
+    @ConfigurationProperties("app.datasource.ds1.agroal")
+    public AgroalDataSource firstDataSource(
+        @Qualifier("ds1properties") DataSourceProperties properties,
+        JtaTransactionManager jtaPlatform,
+        XAResourceRecoveryRegistry xaResourceRecoveryRegistry,
+        ObjectProvider<AgroalDataSourceJndiBinder> jndiBinder) {
+
+        return new AgroalDataSourceAutoConfiguration(jtaPlatform, 
xaResourceRecoveryRegistry)
+            .dataSource(properties, false, false, jndiBinder);
+    }
+
+    @Bean("ds1jdbc")
+    public JdbcTemplate firstDataSourceJdbcTemplate(@Qualifier("ds1") 
DataSource dataSource) {
+        return new JdbcTemplate(dataSource);
+    }
+
+    // -- second data source config
+
+    @Bean("ds2properties")
+    @ConfigurationProperties("app.datasource.ds2")
+    public DataSourceProperties secondDataSourceProperties() {
+        return new DataSourceProperties();
+    }
+
+    @Bean("ds2init")
+    @ConfigurationProperties("app.datasource.ds2.sql.init")
+    public SqlInitializationProperties secondDataSourceInit() {
+        return new SqlInitializationProperties();
+    }
+
+    @Bean("ds2")
+    @ConfigurationProperties("app.datasource.ds2.agroal")
+    public AgroalDataSource secondDataSource(
+        @Qualifier("ds2properties") DataSourceProperties properties,
+        JtaTransactionManager jtaPlatform,
+        XAResourceRecoveryRegistry xaResourceRecoveryRegistry,
+        ObjectProvider<AgroalDataSourceJndiBinder> jndiBinder) {
+
+        return new AgroalDataSourceAutoConfiguration(jtaPlatform, 
xaResourceRecoveryRegistry)
+            .dataSource(properties, false, false, jndiBinder);
+    }
+
+    @Bean("ds2jdbc")
+    public JdbcTemplate secondDataSourceJdbcTemplate(@Qualifier("ds2") 
DataSource dataSource) {
+        return new JdbcTemplate(dataSource);
+    }
+
+}
diff --git 
a/multi-datasource-2pc/src/main/java/sample/camel/MyCamelApplication.java 
b/multi-datasource-2pc/src/main/java/sample/camel/MyCamelApplication.java
new file mode 100644
index 0000000..6c91e07
--- /dev/null
+++ b/multi-datasource-2pc/src/main/java/sample/camel/MyCamelApplication.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package sample.camel;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+//CHECKSTYLE:OFF
+/**
+ * A sample Spring Boot application that starts the Camel routes.
+ */
+@SpringBootApplication
+public class MyCamelApplication {
+
+    /**
+     * A main method to start this application.
+     */
+    public static void main(String[] args) {
+        SpringApplication.run(MyCamelApplication.class, args);
+    }
+
+}
+//CHECKSTYLE:ON
diff --git a/multi-datasource-2pc/src/main/java/sample/camel/MyCamelRouter.java 
b/multi-datasource-2pc/src/main/java/sample/camel/MyCamelRouter.java
new file mode 100644
index 0000000..f716392
--- /dev/null
+++ b/multi-datasource-2pc/src/main/java/sample/camel/MyCamelRouter.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package sample.camel;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.spring.spi.TransactionErrorHandler;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.print.attribute.standard.MediaSize;
+import java.security.SecureRandom;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * A simple Camel route that triggers from a timer and keeps trying to insert 
names in 2 databases.
+ * <p/>
+ * Use <tt>@Component</tt> to make Camel auto-detect this route when starting.
+ */
+@Component
+public class MyCamelRouter extends RouteBuilder {
+
+    public static final List<String> NAMES = List.of(
+        "Maria",
+        "João",
+        "Diego",
+        "Ramona",
+        "Maria",
+        "Ramona"
+    );
+
+    @Override
+    public void configure() throws Exception {
+        // route to insert names in the database
+        // split the list and send each name to be processed
+        from("timer://runOnce?repeatCount=1&delay=1000")
+            .id("split")
+            .setBody(constant(NAMES))
+            .split(body())
+            .to("direct:processName");
+
+        from("direct:processName")
+            .transacted()
+            .id("processName")
+            .delay(simple("{{myPeriod}}"))
+            .to("log:info?showAll=true")
+            .setHeader("name", body())
+            // prepare the insert SQL
+            .setBody(simple("insert into names(name) 
values('${header.name}')"))
+            .log("insert into the first database (non-unique)")
+            .to("spring-jdbc:ds1?resetAutoCommit=false")
+            .log("insert into the second database (unique)")
+            .to("spring-jdbc:ds2?resetAutoCommit=false");
+
+        // route to print inserted names
+        from("timer:query?period={{myPeriod}}")
+            .routeId("query1")
+            .delay(200)
+            .setBody(constant("select count(*) as \"C\" from names"))
+            .to("spring-jdbc:ds1")
+            .setBody(simple("There are ${body[0][C]} names in the ds1 
database."))
+            .to("log:info");
+
+        // route to print inserted names
+        from("timer:query?period={{myPeriod}}")
+            .routeId("query2")
+            .delay(200)
+            .setBody(constant("select count(*) as \"C\" from names"))
+            .to("spring-jdbc:ds2")
+            .setBody(simple("There are ${body[0][C]} names in the ds2 
database."))
+            .to("log:info");
+    }
+
+}
diff --git a/multi-datasource-2pc/src/main/resources/application.properties 
b/multi-datasource-2pc/src/main/resources/application.properties
new file mode 100644
index 0000000..eb5ace2
--- /dev/null
+++ b/multi-datasource-2pc/src/main/resources/application.properties
@@ -0,0 +1,66 @@
+## ---------------------------------------------------------------------------
+## Licensed to the Apache Software Foundation (ASF) under one or more
+## contributor license agreements.  See the NOTICE file distributed with
+## this work for additional information regarding copyright ownership.
+## The ASF licenses this file to You under the Apache License, Version 2.0
+## (the "License"); you may not use this file except in compliance with
+## the License.  You may obtain a copy of the License at
+##
+##      http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+## See the License for the specific language governing permissions and
+## limitations under the License.
+## ---------------------------------------------------------------------------
+
+# the name of Camel
+camel.springboot.name = My2PcCamel
+# how often to trigger the timer (millis)
+myPeriod = 3000
+
+# remove datasource autoconfiguration
+spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,io.agroal.springframework.boot.AgroalDataSourceAutoConfiguration
+
+spring.jta=true
+
+# first datasource general configuration
+app.datasource.ds1.generate-unique-name=false
+app.datasource.ds1.name=ds1
+app.datasource.ds1.url=jdbc:postgresql://localhost:5432/postgres
+app.datasource.ds1.xa.data-source-class-name=org.postgresql.xa.PGXADataSource
+app.datasource.ds1.username=postgres
+app.datasource.ds1.password=password
+# first datasource specific agroal configuration
+# all properties can be found as setter methods on 
io.agroal.springframework.boot.AgroalDataSource
+app.datasource.ds1.agroal.max-size=25
+app.datasource.ds1.agroal.idle-timeout=0
+app.datasource.ds1.agroal.lifetime-timeout=0
+
+# second datasource general configuration
+app.datasource.ds2.generate-unique-name=false
+app.datasource.ds2.name=ds2
+app.datasource.ds2.url=jdbc:postgresql://localhost:5433/postgres
+app.datasource.ds2.xa.data-source-class-name=org.postgresql.xa.PGXADataSource
+app.datasource.ds2.username=postgres
+app.datasource.ds2.password=password
+# second datasource specific agroal configuration
+# all properties can be found as setter methods on 
io.agroal.springframework.boot.AgroalDataSource
+app.datasource.ds2.agroal.max-size=25
+app.datasource.ds2.agroal.idle-timeout=0
+app.datasource.ds2.agroal.lifetime-timeout=0
+
+# disable default sql initialization
+spring.sql.init.mode=never
+
+# to configure general logging levels:
+#logging.level.org.springframework = DEBUG
+#logging.level.org.apache.camel.spring.boot = DEBUG
+#logging.level.org.apache.camel.impl = DEBUG
+#logging.level.io.agroal = DEBUG
+# transaction management and 2-phase-commit logging:
+#logging.level.org.jboss.narayana = DEBUG
+#logging.level.com.arjuna = DEBUG
+#logging.level.org.postgresql = DEBUG
+
diff --git a/multi-datasource-2pc/src/main/resources/schema-ds1.sql 
b/multi-datasource-2pc/src/main/resources/schema-ds1.sql
new file mode 100755
index 0000000..5e4c6e3
--- /dev/null
+++ b/multi-datasource-2pc/src/main/resources/schema-ds1.sql
@@ -0,0 +1,4 @@
+DROP TABLE IF EXISTS names;
+CREATE TABLE names (
+    name VARCHAR(255)
+);
diff --git a/multi-datasource-2pc/src/main/resources/schema-ds2.sql 
b/multi-datasource-2pc/src/main/resources/schema-ds2.sql
new file mode 100644
index 0000000..4d0543a
--- /dev/null
+++ b/multi-datasource-2pc/src/main/resources/schema-ds2.sql
@@ -0,0 +1,4 @@
+DROP TABLE IF EXISTS names;
+CREATE TABLE names (
+    name VARCHAR(255) UNIQUE DEFERRABLE INITIALLY DEFERRED
+);
diff --git 
a/multi-datasource-2pc/src/test/java/sample/camel/MyCamelApplicationJUnit5Test.java
 
b/multi-datasource-2pc/src/test/java/sample/camel/MyCamelApplicationJUnit5Test.java
new file mode 100644
index 0000000..89d4170
--- /dev/null
+++ 
b/multi-datasource-2pc/src/test/java/sample/camel/MyCamelApplicationJUnit5Test.java
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package sample.camel;
+
+import java.nio.file.Paths;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import net.bytebuddy.utility.dispatcher.JavaDispatcher;
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.NotifyBuilder;
+import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
+import org.apache.camel.test.spring.junit5.EnableRouteCoverage;
+import org.apache.camel.util.FileUtil;
+import org.junit.After;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.testcontainers.context.ImportTestcontainers;
+import org.springframework.core.env.Environment;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+import org.springframework.test.context.jdbc.Sql;
+import org.springframework.test.context.jdbc.SqlConfig;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+@Testcontainers
+@CamelSpringBootTest
+@SpringBootTest(classes = MyCamelApplication.class)
+@EnableRouteCoverage
+@ActiveProfiles("test")
+public class MyCamelApplicationJUnit5Test {
+
+    @Container
+    static PostgreSQLContainer db1 = new PostgreSQLContainer<>()
+        .withInitScript("schema-ds1.sql")
+        .withDatabaseName("postgres")
+        .withUsername("postgres")
+        .withPassword("password")
+        .withCommand("postgres -c max_prepared_transactions=10");
+
+    @Container
+    static PostgreSQLContainer db2 = new PostgreSQLContainer<>()
+        .withInitScript("schema-ds2.sql")
+        .withDatabaseName("postgres")
+        .withUsername("postgres")
+        .withPassword("password")
+        .withCommand("postgres -c max_prepared_transactions=10");
+
+    @Autowired
+    private CamelContext camelContext;
+
+    @Autowired
+    @Qualifier("ds1jdbc")
+    private JdbcTemplate jdbcTemplate1;
+
+    @Autowired
+    @Qualifier("ds2jdbc")
+    private JdbcTemplate jdbcTemplate2;
+
+    @DynamicPropertySource
+    static void dbProperties(DynamicPropertyRegistry registry) {
+        registry.add("app.datasource.ds1.url",
+            () -> "jdbc:postgresql://" + db1.getHost() + ":" + 
db1.getFirstMappedPort() + "/" + db1.getDatabaseName());
+        registry.add("app.datasource.ds2.url",
+            () -> "jdbc:postgresql://" + db2.getHost() + ":" + 
db2.getFirstMappedPort() + "/" + db2.getDatabaseName());
+    }
+
+    @AfterAll
+    static void tearDownAll(@Autowired Environment environment) {
+        String transactionLogs = environment.getProperty("narayana.log-dir");
+        FileUtil.removeDir(Paths.get(transactionLogs).toFile());
+    }
+
+    @Test
+    public void shouldProduceMessages() {
+        int numberOfNames = MyCamelRouter.NAMES.size();
+        int numberOfDistinctNames = new HashSet<>(MyCamelRouter.NAMES).size();
+
+        NotifyBuilder notifyProcessed = new 
NotifyBuilder(camelContext).wereSentTo("direct:processName").whenDone(numberOfNames).create();
+        assertTrue(notifyProcessed.matches(20, TimeUnit.SECONDS));
+
+        List<Map<String, Object>> count1 = jdbcTemplate1.queryForList("select 
COUNT(name) as C from names");
+        List<Map<String, Object>> count2 = jdbcTemplate2.queryForList("select 
COUNT(name) as C from names");
+
+        assertEquals(numberOfDistinctNames, ((Long) 
count1.get(0).get("C")).intValue());
+        assertEquals(numberOfDistinctNames, ((Long) 
count2.get(0).get("C")).intValue());
+    }
+
+}
diff --git 
a/multi-datasource-2pc/src/test/resources/application-test.properties 
b/multi-datasource-2pc/src/test/resources/application-test.properties
new file mode 100644
index 0000000..8286366
--- /dev/null
+++ b/multi-datasource-2pc/src/test/resources/application-test.properties
@@ -0,0 +1,21 @@
+## ---------------------------------------------------------------------------
+## Licensed to the Apache Software Foundation (ASF) under one or more
+## contributor license agreements.  See the NOTICE file distributed with
+## this work for additional information regarding copyright ownership.
+## The ASF licenses this file to You under the Apache License, Version 2.0
+## (the "License"); you may not use this file except in compliance with
+## the License.  You may obtain a copy of the License at
+##
+##      http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+## See the License for the specific language governing permissions and
+## limitations under the License.
+## ---------------------------------------------------------------------------
+
+# test profile properties
+
+myPeriod = 1000
+narayana.log-dir = test-transactions-logs

Reply via email to