You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by da...@apache.org on 2019/12/16 04:58:32 UTC

[camel] branch master updated: CAMEL-14258: switching com.mongodb.MongoClient to com.mongodb.client.MongoClient (#3405)

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

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/master by this push:
     new daae1c1  CAMEL-14258: switching com.mongodb.MongoClient to com.mongodb.client.MongoClient (#3405)
daae1c1 is described below

commit daae1c1bd62ea5d19bb807c6c0124d5289aaada4
Author: Pasquale Congiusti <pa...@gmail.com>
AuthorDate: Mon Dec 16 05:58:20 2019 +0100

    CAMEL-14258: switching com.mongodb.MongoClient to com.mongodb.client.MongoClient (#3405)
    
    * Changing the connection bean to the new one
    * Adding support for explicit WriteConcern and ReadPreferences
    * Updated unit test to fit new client
---
 .../src/main/docs/mongodb-component.adoc           |   6 +-
 .../camel/component/mongodb/MongoDbComponent.java  |   2 +-
 .../camel/component/mongodb/MongoDbEndpoint.java   | 119 ++++++++++++---------
 .../camel/component/mongodb/MongoDbProducer.java   |   4 +-
 .../mongodb/MongoDbTailTrackingManager.java        |   2 +-
 .../mongodb/meta/MongoDBMetaExtension.java         |   5 +-
 .../idempotent/MongoDbIdempotentRepository.java    |   2 +-
 .../verifier/MongoComponentVerifierExtension.java  |   5 +-
 .../component/mongodb/AbstractMongoDbTest.java     |   2 +-
 .../component/mongodb/EmbedMongoConfiguration.java |  45 +-------
 .../mongodb/MongoDbConnectionBeansTest.java        |   2 +-
 .../camel/component/mongodb/MongoDbIndexTest.java  |   4 +-
 .../component/mongodb/MongoDbOperationsTest.java   |   7 +-
 .../mongodb/MongoDbReadPreferenceOptionTest.java   |  37 +++----
 14 files changed, 113 insertions(+), 129 deletions(-)

diff --git a/components/camel-mongodb/src/main/docs/mongodb-component.adoc b/components/camel-mongodb/src/main/docs/mongodb-component.adoc
index 937614b..8cd608f 100644
--- a/components/camel-mongodb/src/main/docs/mongodb-component.adoc
+++ b/components/camel-mongodb/src/main/docs/mongodb-component.adoc
@@ -96,7 +96,7 @@ with the following path and query parameters:
 |===
 
 
-=== Query Parameters (24 parameters):
+=== Query Parameters (26 parameters):
 
 
 [width="100%",cols="2,5,^1,2",options="header"]
@@ -117,7 +117,9 @@ with the following path and query parameters:
 | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean
 | *cursorRegenerationDelay* (advanced) | MongoDB tailable cursors will block until new data arrives. If no new data is inserted, after some time the cursor will be automatically freed and closed by the MongoDB server. The client is expected to regenerate the cursor if needed. This value specifies the time to wait before attempting to fetch a new cursor, and if the attempt fails, how long before the next attempt is made. Default value is 1000ms. | 1000 | long
 | *dynamicity* (advanced) | Sets whether this endpoint will attempt to dynamically resolve the target database and collection from the incoming Exchange properties. Can be used to override at runtime the database and collection specified on the otherwise static endpoint URI. It is disabled by default to boost performance. Enabling it will take a minimal performance hit. | false | boolean
+| *readPreference* (advanced) | Configure how MongoDB clients route read operations to the members of a replica set. Possible values are PRIMARY, PRIMARY_PREFERRED, SECONDARY, SECONDARY_PREFERRED or NEAREST | PRIMARY | String
 | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean
+| *writeConcern* (advanced) | Configure the connection bean with the level of acknowledgment requested from MongoDB for write operations to a standalone mongod, replicaset or cluster. Possible values are ACKNOWLEDGED, W1, W2, W3, UNACKNOWLEDGED, JOURNALED or MAJORITY. | ACKNOWLEDGED | String
 | *writeResultAsHeader* (advanced) | In write operations, it determines whether instead of returning WriteResult as the body of the OUT message, we transfer the IN message to the OUT and attach the WriteResult as a header. | false | boolean
 | *streamFilter* (changeStream) | Filter condition for change streams consumer. |  | String
 | *persistentId* (tail) | One tail tracking collection can host many trackers for several tailable consumers. To keep them separate, each tracker should have its own unique persistentId. |  | String
@@ -155,7 +157,7 @@ The component supports 5 options, which are listed below.
 | *camel.component.mongodb.bridge-error-handler* | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | Boolean
 | *camel.component.mongodb.enabled* | Whether to enable auto configuration of the mongodb component. This is enabled by default. |  | Boolean
 | *camel.component.mongodb.lazy-start-producer* | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed th [...]
-| *camel.component.mongodb.mongo-connection* | Set a client used for connection: all endpoints generated from the component will share this connection bean. The option is a com.mongodb.MongoClient type. |  | String
+| *camel.component.mongodb.mongo-connection* | Set a client used for connection: all endpoints generated from the component will share this connection bean. The option is a com.mongodb.client.MongoClient type. |  | String
 |===
 // spring-boot-auto-configure options: END
 
diff --git a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbComponent.java b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbComponent.java
index c0a9838..9cf699d 100644
--- a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbComponent.java
+++ b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbComponent.java
@@ -21,7 +21,7 @@ import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
 
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
 import org.apache.camel.CamelContext;
 import org.apache.camel.Endpoint;
 import org.apache.camel.component.mongodb.meta.MongoDBMetaExtension;
diff --git a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java
index 9c28a81..8409b62 100644
--- a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java
+++ b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java
@@ -24,10 +24,10 @@ import java.util.Map;
 import java.util.stream.StreamSupport;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.mongodb.MongoClient;
 import com.mongodb.ReadPreference;
 import com.mongodb.WriteConcern;
 import com.mongodb.WriteResult;
+import com.mongodb.client.MongoClient;
 import com.mongodb.client.MongoCollection;
 import com.mongodb.client.MongoDatabase;
 import org.apache.camel.Consumer;
@@ -76,9 +76,15 @@ public class MongoDbEndpoint extends DefaultEndpoint {
     private MongoDbOperation operation;
     @UriParam(defaultValue = "true")
     private boolean createCollection = true;
-    private WriteConcern writeConcernRef;
     @UriParam(label = "advanced")
     private boolean dynamicity;
+    @UriParam(label = "advanced", defaultValue = "ACKNOWLEDGED",
+            enums = "ACKNOWLEDGED,W1,W2,W3,UNACKNOWLEDGED,JOURNALED,MAJORITY")
+    private String writeConcern = "ACKNOWLEDGED";
+    @UriParam(label = "advanced",
+            defaultValue = "PRIMARY",
+            enums = "PRIMARY,PRIMARY_PREFERRED,SECONDARY,SECONDARY_PREFERRED,NEAREST")
+    private String readPreference = "PRIMARY";
     @UriParam(label = "advanced")
     private boolean writeResultAsHeader;
     @UriParam(label = "consumer")
@@ -211,7 +217,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
 
     /**
      * Initialises the MongoDB connection using the Mongo object provided to the endpoint
-     * 
+     *
      * @throws CamelMongoDbException
      */
     public void initializeConnection() throws CamelMongoDbException {
@@ -229,8 +235,9 @@ public class MongoDbEndpoint extends DefaultEndpoint {
             }
             mongoCollection = mongoDatabase.getCollection(collection, Document.class);
 
-            log.debug("MongoDb component initialised and endpoint bound to MongoDB collection with the following parameters. Address list: {}, Db: {}, Collection: {}",
-                      new Object[] {mongoConnection.getAllAddress().toString(), mongoDatabase.getName(), collection});
+            log.debug("MongoDb component initialised and endpoint bound to MongoDB collection with the following parameters. "
+                            + "Cluster description: {}, Db: {}, Collection: {}",
+                    new Object[]{mongoConnection.getClusterDescription(), mongoDatabase.getName(), collection});
 
             try {
                 if (ObjectHelper.isNotEmpty(collectionIndex)) {
@@ -301,7 +308,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
         message.setBody(dbObj);
         return exchange;
     }
-    
+
     @Override
     protected void doStart() throws Exception {
         if (mongoConnection == null) {
@@ -374,7 +381,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
 
     /**
      * Sets the name of the MongoDB database to target
-     * 
+     *
      * @param database name of the MongoDB database
      */
     public void setDatabase(String database) {
@@ -388,7 +395,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
     /**
      * Create collection during initialisation if it doesn't exist. Default is
      * true.
-     * 
+     *
      * @param createCollection true or false
      */
     public void setCreateCollection(boolean createCollection) {
@@ -401,7 +408,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
 
     /**
      * Sets the Mongo instance that represents the backing connection
-     * 
+     *
      * @param mongoConnection the connection to the database
      */
     public void setMongoConnection(MongoClient mongoConnection) {
@@ -412,44 +419,13 @@ public class MongoDbEndpoint extends DefaultEndpoint {
         return mongoConnection;
     }
 
-    public WriteConcern getWriteConcern() {
-        return getMongoConnection().getWriteConcern();
-    }
-
-    /**
-     * Set the {@link WriteConcern} for write operations on MongoDB, passing in
-     * the bean ref to a custom WriteConcern which exists in the Registry. You
-     * can also use standard WriteConcerns by passing in their key.
-     * 
-     * @param writeConcernRef the name of the bean in the registry that
-     *            represents the WriteConcern to use
-     */
-    public void setWriteConcernRef(String writeConcernRef) {
-        WriteConcern wc = this.getCamelContext().getRegistry().lookupByNameAndType(writeConcernRef, WriteConcern.class);
-        if (wc == null) {
-            String msg = "Camel MongoDB component could not find the WriteConcern in the Registry. Verify that the " + "provided bean name (" + writeConcernRef
-                         + ")  is correct. Aborting initialization.";
-            throw new IllegalArgumentException(msg);
-        }
-
-        this.writeConcernRef = wc;
-    }
-
-    public WriteConcern getWriteConcernRef() {
-        return writeConcernRef;
-    }
-
-    public ReadPreference getReadPreference() {
-        return getMongoConnection().getReadPreference();
-    }
-
     /**
      * Sets whether this endpoint will attempt to dynamically resolve the target
      * database and collection from the incoming Exchange properties. Can be
      * used to override at runtime the database and collection specified on the
      * otherwise static endpoint URI. It is disabled by default to boost
      * performance. Enabling it will take a minimal performance hit.
-     * 
+     *
      * @see MongoDbConstants#DATABASE
      * @see MongoDbConstants#COLLECTION
      * @param dynamicity true or false indicated whether target database and
@@ -502,7 +478,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
      * not specified, the current database will be picked by default. Dynamicity
      * will not be taken into account even if enabled, i.e. the tail tracking
      * database will not vary past endpoint initialisation.
-     * 
+     *
      * @param tailTrackDb database name
      */
     public void setTailTrackDb(String tailTrackDb) {
@@ -517,7 +493,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
      * Collection where tail tracking information will be persisted. If not
      * specified, {@link MongoDbTailTrackingConfig#DEFAULT_COLLECTION} will be
      * used by default.
-     * 
+     *
      * @param tailTrackCollection collection name
      */
     public void setTailTrackCollection(String tailTrackCollection) {
@@ -531,7 +507,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
     /**
      * Field where the last tracked value will be placed. If not specified,
      * {@link MongoDbTailTrackingConfig#DEFAULT_FIELD} will be used by default.
-     * 
+     *
      * @param tailTrackField field name
      */
     public void setTailTrackField(String tailTrackField) {
@@ -543,7 +519,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
      * the last consumed message across system restarts. The next time the
      * system is up, the endpoint will recover the cursor from the point where
      * it last stopped slurping records.
-     * 
+     *
      * @param persistentTailTracking true or false
      */
     public void setPersistentTailTracking(boolean persistentTailTracking) {
@@ -562,7 +538,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
      * tail tracking). Can be of type Integer, Date, String, etc. NOTE: No
      * support for dot notation at the current time, so the field should be at
      * the top level of the document.
-     * 
+     *
      * @param tailTrackIncreasingField
      */
     public void setTailTrackIncreasingField(String tailTrackIncreasingField) {
@@ -588,7 +564,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
      * the cursor if needed. This value specifies the time to wait before
      * attempting to fetch a new cursor, and if the attempt fails, how long
      * before the next attempt is made. Default value is 1000ms.
-     * 
+     *
      * @param cursorRegenerationDelay delay specified in milliseconds
      */
     public void setCursorRegenerationDelay(long cursorRegenerationDelay) {
@@ -603,7 +579,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
      * One tail tracking collection can host many trackers for several tailable
      * consumers. To keep them separate, each tracker should have its own unique
      * persistentId.
-     * 
+     *
      * @param persistentId the value of the persistent ID to use for this
      *            tailable consumer
      */
@@ -623,7 +599,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
      * In write operations, it determines whether instead of returning
      * {@link WriteResult} as the body of the OUT message, we transfer the IN
      * message to the OUT and attach the WriteResult as a header.
-     * 
+     *
      * @param writeResultAsHeader flag to indicate if this option is enabled
      */
     public void setWriteResultAsHeader(boolean writeResultAsHeader) {
@@ -635,7 +611,7 @@ public class MongoDbEndpoint extends DefaultEndpoint {
     }
 
     /**
-     * Convert the output of the producer to the selected type : DocumentList Document or MongoIterable. 
+     * Convert the output of the producer to the selected type : DocumentList Document or MongoIterable.
      * DocumentList or MongoIterable applies to findAll and aggregate. Document applies to all other operations.
      * @param outputType
      */
@@ -661,4 +637,47 @@ public class MongoDbEndpoint extends DefaultEndpoint {
     public void setStreamFilter(String streamFilter) {
         this.streamFilter = streamFilter;
     }
+
+    /**
+     * Configure the connection bean with the level of acknowledgment requested
+     * from MongoDB for write operations to a standalone mongod, replicaset or cluster. Possible values are
+     * ACKNOWLEDGED, W1, W2, W3, UNACKNOWLEDGED, JOURNALED or MAJORITY.
+     *
+     * @param writeConcern
+     */
+    public void setWriteConcern(String writeConcern) {
+        this.writeConcern = writeConcern;
+    }
+
+    public String getWriteConcern() {
+        return this.writeConcern;
+    }
+
+    public WriteConcern getWriteConcernBean() {
+        WriteConcern writeConcernBean = WriteConcern.valueOf(getWriteConcern());
+        if (writeConcernBean == null) {
+            throw new IllegalArgumentException(String.format("Unknown WriteConcern configuration %s", getWriteConcern()));
+        }
+        return writeConcernBean;
+    }
+
+    /**
+     * Configure how MongoDB clients route read operations to the members of a replica set. Possible values are
+     * PRIMARY, PRIMARY_PREFERRED, SECONDARY, SECONDARY_PREFERRED or NEAREST
+     *
+     * @param readPreference
+     */
+    public void setReadPreference(String readPreference) {
+        this.readPreference = readPreference;
+    }
+
+    public String getReadPreference() {
+        return this.readPreference;
+    }
+
+    public ReadPreference getReadPreferenceBean() {
+        // will throw an IllegalArgumentException if the input is incorrect
+        return ReadPreference.valueOf(getReadPreference());
+    }
+
 }
diff --git a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbProducer.java b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbProducer.java
index 71a771f..1e94473 100644
--- a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbProducer.java
+++ b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbProducer.java
@@ -191,7 +191,7 @@ public class MongoDbProducer extends DefaultProducer {
         // resolution logic on every Exchange if they won't be using this
         // functionality at all
         if (!endpoint.isDynamicity()) {
-            return endpoint.getMongoCollection().withWriteConcern(endpoint.getWriteConcern());
+            return endpoint.getMongoCollection().withWriteConcern(endpoint.getWriteConcernBean());
         }
 
         String dynamicDB = exchange.getIn().getHeader(DATABASE, String.class);
@@ -203,7 +203,7 @@ public class MongoDbProducer extends DefaultProducer {
         MongoCollection<Document> dbCol;
 
         if (dynamicDB == null && dynamicCollection == null) {
-            dbCol = endpoint.getMongoCollection().withWriteConcern(endpoint.getWriteConcern());
+            dbCol = endpoint.getMongoCollection().withWriteConcern(endpoint.getWriteConcernBean());
         } else {
             MongoDatabase db = calculateDb(exchange);
 
diff --git a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbTailTrackingManager.java b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbTailTrackingManager.java
index 99662bc..d4675fc 100644
--- a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbTailTrackingManager.java
+++ b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbTailTrackingManager.java
@@ -16,7 +16,7 @@
  */
 package org.apache.camel.component.mongodb;
 
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
 import com.mongodb.client.MongoCollection;
 import com.mongodb.client.model.FindOneAndUpdateOptions;
 import com.mongodb.client.model.ReturnDocument;
diff --git a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/meta/MongoDBMetaExtension.java b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/meta/MongoDBMetaExtension.java
index bca0131..0f9f506 100644
--- a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/meta/MongoDBMetaExtension.java
+++ b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/meta/MongoDBMetaExtension.java
@@ -23,8 +23,9 @@ import java.util.Optional;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.node.ObjectNode;
-import com.mongodb.MongoClient;
 import com.mongodb.MongoClientURI;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
 import com.mongodb.client.model.Filters;
 import org.apache.camel.CamelContext;
 import org.apache.camel.component.extension.metadata.AbstractMetaDataExtension;
@@ -59,7 +60,7 @@ public class MongoDBMetaExtension extends AbstractMetaDataExtension {
         MongoClientURI connectionURI = new MongoClientURI(mongoConf.getMongoClientURI());
 
         JsonNode collectionInfoRoot;
-        try (MongoClient mongoConnection = new MongoClient(connectionURI)) {
+        try (MongoClient mongoConnection = MongoClients.create(connectionURI.getURI())) {
             Document collectionInfo = mongoConnection.getDatabase(textParameters.get("database"))
                     .listCollections()
                     .filter(Filters.eq("name", textParameters.get("collection")))
diff --git a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/processor/idempotent/MongoDbIdempotentRepository.java b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/processor/idempotent/MongoDbIdempotentRepository.java
index acb5d9a..8c6d8aa 100644
--- a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/processor/idempotent/MongoDbIdempotentRepository.java
+++ b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/processor/idempotent/MongoDbIdempotentRepository.java
@@ -17,7 +17,7 @@
 package org.apache.camel.component.mongodb.processor.idempotent;
 
 import com.mongodb.ErrorCategory;
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
 import com.mongodb.client.MongoCollection;
 import com.mongodb.client.result.DeleteResult;
 import org.apache.camel.api.management.ManagedOperation;
diff --git a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/verifier/MongoComponentVerifierExtension.java b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/verifier/MongoComponentVerifierExtension.java
index 0cc390f..72a41a2 100644
--- a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/verifier/MongoComponentVerifierExtension.java
+++ b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/verifier/MongoComponentVerifierExtension.java
@@ -18,11 +18,12 @@ package org.apache.camel.component.mongodb.verifier;
 
 import java.util.Map;
 
-import com.mongodb.MongoClient;
 import com.mongodb.MongoClientOptions;
 import com.mongodb.MongoClientURI;
 import com.mongodb.MongoSecurityException;
 import com.mongodb.MongoTimeoutException;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
 import org.apache.camel.component.extension.verifier.DefaultComponentVerifierExtension;
 import org.apache.camel.component.extension.verifier.ResultBuilder;
 import org.apache.camel.component.extension.verifier.ResultErrorBuilder;
@@ -69,7 +70,7 @@ public class MongoComponentVerifierExtension extends DefaultComponentVerifierExt
         MongoClientURI connectionURI = new MongoClientURI(mongoConf.getMongoClientURI(), optionsBuilder);
 
         LOG.info("Testing connection against {}", connectionURI);
-        try (MongoClient mongoClient = new MongoClient(connectionURI)) {
+        try (MongoClient mongoClient = MongoClients.create(connectionURI.getURI())) {
             // Just ping the server
             mongoClient.getDatabase(connectionURI.getDatabase()).runCommand(Document.parse("{ ping: 1 }"));
             LOG.info("Testing connection successful!");
diff --git a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/AbstractMongoDbTest.java b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/AbstractMongoDbTest.java
index b9ca2df..1a60901 100644
--- a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/AbstractMongoDbTest.java
+++ b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/AbstractMongoDbTest.java
@@ -18,7 +18,7 @@ package org.apache.camel.component.mongodb;
 
 import java.util.Formatter;
 
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
 import com.mongodb.client.MongoCollection;
 import com.mongodb.client.MongoDatabase;
 import org.apache.camel.CamelContext;
diff --git a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/EmbedMongoConfiguration.java b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/EmbedMongoConfiguration.java
index 57649dc..9ed2e3c 100644
--- a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/EmbedMongoConfiguration.java
+++ b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/EmbedMongoConfiguration.java
@@ -19,10 +19,8 @@ package org.apache.camel.component.mongodb;
 import java.io.IOException;
 import java.net.UnknownHostException;
 
-import com.mongodb.MongoClient;
-import com.mongodb.MongoClientURI;
-import com.mongodb.ReadPreference;
-import com.mongodb.WriteConcern;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
 import de.flapdoodle.embed.mongo.MongodExecutable;
 import de.flapdoodle.embed.mongo.MongodStarter;
 import de.flapdoodle.embed.mongo.config.IMongodConfig;
@@ -33,8 +31,6 @@ import org.bson.Document;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 
-import static com.mongodb.MongoClientOptions.builder;
-import static com.mongodb.ServerAddress.defaultHost;
 import static de.flapdoodle.embed.mongo.distribution.Version.Main.PRODUCTION;
 import static de.flapdoodle.embed.process.runtime.Network.localhostIsIPv6;
 import static org.springframework.util.SocketUtils.findAvailableTcpPort;
@@ -56,7 +52,7 @@ public class EmbedMongoConfiguration {
             mongodExecutable.start();
 
             // init replica set
-            MongoClient client = new MongoClient("localhost", PORT);
+            MongoClient client = MongoClients.create("mongodb://localhost:" + PORT);
             client.getDatabase("admin").runCommand(new Document("replSetInitiate", new Document()));
 
         } catch (IOException e) {
@@ -66,42 +62,11 @@ public class EmbedMongoConfiguration {
 
     @Bean
     public MongoClient myDb() throws UnknownHostException {
-        return new MongoClient(defaultHost(), PORT);
-    }
-
-    @Bean
-    public MongoClient myDbP() throws UnknownHostException {
-        MongoClientURI uri = new MongoClientURI("mongodb://localhost:" + PORT, builder().readPreference(ReadPreference.primary()));
-        return new MongoClient(uri);
-    }
-
-    @Bean
-    public MongoClient myDbPP() throws UnknownHostException {
-        MongoClientURI uri = new MongoClientURI("mongodb://localhost:" + PORT, builder().readPreference(ReadPreference.primaryPreferred()));
-        return new MongoClient(uri);
+        return MongoClients.create("mongodb://localhost:" + PORT);
     }
 
     @Bean
     public MongoClient myDbS() throws UnknownHostException {
-        MongoClientURI uri = new MongoClientURI("mongodb://localhost:" + PORT, builder().readPreference(ReadPreference.secondary()));
-        return new MongoClient(uri);
-    }
-
-    @Bean
-    public MongoClient myDbWCA() throws UnknownHostException {
-        MongoClientURI uri = new MongoClientURI("mongodb://localhost:" + PORT, builder().writeConcern(WriteConcern.ACKNOWLEDGED));
-        return new MongoClient(uri);
-    }
-
-    @Bean
-    public MongoClient myDbSP() throws UnknownHostException {
-        MongoClientURI uri = new MongoClientURI("mongodb://localhost:" + PORT, builder().readPreference(ReadPreference.secondaryPreferred()));
-        return new MongoClient(uri);
-    }
-
-    @Bean
-    public MongoClient myDbN() throws UnknownHostException {
-        MongoClientURI uri = new MongoClientURI("mongodb://localhost:" + PORT, builder().readPreference(ReadPreference.nearest()));
-        return new MongoClient(uri);
+        return MongoClients.create("mongodb://localhost:" + PORT);
     }
 }
diff --git a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbConnectionBeansTest.java b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbConnectionBeansTest.java
index cc12f1a..60e9368 100644
--- a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbConnectionBeansTest.java
+++ b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbConnectionBeansTest.java
@@ -16,7 +16,7 @@
  */
 package org.apache.camel.component.mongodb;
 
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
 import org.apache.camel.Endpoint;
 import org.junit.jupiter.api.Test;
 
diff --git a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbIndexTest.java b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbIndexTest.java
index dc1c477..7ecbce2 100644
--- a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbIndexTest.java
+++ b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbIndexTest.java
@@ -127,7 +127,9 @@ public class MongoDbIndexTest extends AbstractMongoDbTest {
         b = testCollection.find(eq(MONGO_ID, "testInsertDynamicityEnabledDBOnly")).first();
         assertNull(b, "There is a record with 'testInsertDynamicityEnabledDBAndCollection' _id in the test collection");
 
-        assertFalse(mongo.getUsedDatabases().contains("otherDB"), "The otherDB database should not exist");
+        for (String db : mongo.listDatabaseNames()) {
+            assertFalse(db.contains("otherDB"), "The otherDB database should not exist");
+        }
     }
 
     @Test
diff --git a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbOperationsTest.java b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbOperationsTest.java
index 1d0a0ac..c875b2b 100644
--- a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbOperationsTest.java
+++ b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbOperationsTest.java
@@ -21,7 +21,8 @@ import java.util.Formatter;
 import java.util.HashMap;
 import java.util.List;
 
-import com.mongodb.MongoClient;
+import com.mongodb.MongoClientSettings;
+import com.mongodb.client.MongoClient;
 import com.mongodb.client.model.Filters;
 import com.mongodb.client.result.DeleteResult;
 import com.mongodb.client.result.UpdateResult;
@@ -219,8 +220,8 @@ public class MongoDbOperationsTest extends AbstractMongoDbTest {
 
         Bson updateObj = combine(set("scientist", "Darwin"), currentTimestamp("lastModified"));
 
-        String updates = "[" + extraField.toBsonDocument(Document.class, MongoClient.getDefaultCodecRegistry()).toJson() + ","
-                         + updateObj.toBsonDocument(Document.class, MongoClient.getDefaultCodecRegistry()).toJson() + "]";
+        String updates = "[" + extraField.toBsonDocument(Document.class, MongoClientSettings.getDefaultCodecRegistry()).toJson() + ","
+                         + updateObj.toBsonDocument(Document.class, MongoClientSettings.getDefaultCodecRegistry()).toJson() + "]";
 
         Exchange resultExchange = template.request("direct:update", new Processor() {
             @Override
diff --git a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbReadPreferenceOptionTest.java b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbReadPreferenceOptionTest.java
index 03b56a1..11375d6 100644
--- a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbReadPreferenceOptionTest.java
+++ b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbReadPreferenceOptionTest.java
@@ -32,61 +32,54 @@ public class MongoDbReadPreferenceOptionTest extends AbstractMongoDbTest {
     @Test
     public void testInvalidReadPreferenceOptionValue() throws Exception {
         try {
-            createMongoDbEndpoint("mongodb:myDb?database={{mongodb.testDb}}&readPreference=foo");
+            endpoint = createMongoDbEndpoint("mongodb:myDb?database={{mongodb.testDb}}&readPreference=foo");
+            endpoint.getReadPreferenceBean();
             fail("Should have thrown exception");
-        } catch (ResolveEndpointFailedException refe) {
-            assertTrue(refe.getMessage().endsWith("Unknown parameters=[{readPreference=foo}]"), refe.getMessage());
+        } catch (IllegalArgumentException e) {
+            assertTrue(e.getMessage().startsWith("No match for read preference"));
         }
     }
 
     @Test
     public void testNoReadPreferenceOptionValue() throws Exception {
         endpoint = createMongoDbEndpoint("mongodb:myDb?database={{mongodb.testDb}}");
-        assertSame(ReadPreference.primary(), endpoint.getReadPreference());
-        assertSame(ReadPreference.primary(), endpoint.getMongoConnection().getReadPreference());
+        assertSame(ReadPreference.primary(), endpoint.getReadPreferenceBean());
         // the default is primary
     }
 
     @Test
     public void testPrimaryReadPreferenceOptionValue() throws Exception {
-        endpoint = createMongoDbEndpoint("mongodb:myDbP?database={{mongodb.testDb}}");
-        assertSame(ReadPreference.primary(), endpoint.getReadPreference());
-        assertSame(ReadPreference.primary(), endpoint.getMongoConnection().getReadPreference());
+        endpoint = createMongoDbEndpoint("mongodb:myDb?database={{mongodb.testDb}}&readPreference=primary");
+        assertSame(ReadPreference.primary(), endpoint.getReadPreferenceBean());
     }
 
     @Test
     public void testPrimaryPreferredReadPreferenceOptionValue() throws Exception {
-        endpoint = createMongoDbEndpoint("mongodb:myDbPP?database={{mongodb.testDb}}");
-        assertSame(ReadPreference.primaryPreferred(), endpoint.getReadPreference());
-        assertSame(ReadPreference.primaryPreferred(), endpoint.getMongoConnection().getReadPreference());
+        endpoint = createMongoDbEndpoint("mongodb:myDb?database={{mongodb.testDb}}&readPreference=primaryPreferred");
+        assertSame(ReadPreference.primaryPreferred(), endpoint.getReadPreferenceBean());
     }
 
     @Test
     public void testSecondaryReadPreferenceOptionValue() throws Exception {
-        endpoint = createMongoDbEndpoint("mongodb:myDbS?database={{mongodb.testDb}}");
-        assertSame(ReadPreference.secondary(), endpoint.getReadPreference());
-        assertSame(ReadPreference.secondary(), endpoint.getMongoConnection().getReadPreference());
+        endpoint = createMongoDbEndpoint("mongodb:myDb?database={{mongodb.testDb}}&readPreference=secondary");
+        assertSame(ReadPreference.secondary(), endpoint.getReadPreferenceBean());
     }
 
     @Test
     public void testSecondaryPreferredReadPreferenceOptionValue() throws Exception {
-        endpoint = createMongoDbEndpoint("mongodb:myDbSP?database={{mongodb.testDb}}");
-        assertSame(ReadPreference.secondaryPreferred(), endpoint.getReadPreference());
-        assertSame(ReadPreference.secondaryPreferred(), endpoint.getMongoConnection().getReadPreference());
+        endpoint = createMongoDbEndpoint("mongodb:myDb?database={{mongodb.testDb}}&readPreference=secondaryPreferred");
+        assertSame(ReadPreference.secondaryPreferred(), endpoint.getReadPreferenceBean());
     }
 
     @Test
     public void testNearestReadPreferenceOptionValue() throws Exception {
-        endpoint = createMongoDbEndpoint("mongodb:myDbN?database={{mongodb.testDb}}");
-        assertSame(ReadPreference.nearest(), endpoint.getReadPreference());
-        assertSame(ReadPreference.nearest(), endpoint.getMongoConnection().getReadPreference());
+        endpoint = createMongoDbEndpoint("mongodb:myDb?database={{mongodb.testDb}}&readPreference=nearest");
+        assertSame(ReadPreference.nearest(), endpoint.getReadPreferenceBean());
     }
 
     private MongoDbEndpoint createMongoDbEndpoint(String uri) throws Exception {
         Endpoint mongoEndpoint = context().getComponent("mongodb").createEndpoint(uri);
         mongoEndpoint.start();
         return MongoDbEndpoint.class.cast(mongoEndpoint);
-
     }
-
 }