View Javadoc
1   package de.dlr.shepard.common.mongoDB;
2   
3   import com.mongodb.ConnectionString;
4   import com.mongodb.client.MongoClient;
5   import com.mongodb.client.MongoDatabase;
6   import io.quarkus.logging.Log;
7   import jakarta.annotation.PostConstruct;
8   import jakarta.enterprise.context.ApplicationScoped;
9   import jakarta.enterprise.inject.Produces;
10  import jakarta.inject.Inject;
11  import jakarta.inject.Named;
12  import org.eclipse.microprofile.config.inject.ConfigProperty;
13  
14  /**
15   * Wrapper for Quarkus MongoDB client.
16   *
17   * Enables consistent injection of the correct MongoDB database.
18   */
19  @ApplicationScoped
20  public class MongoClientWrapper {
21  
22    @ConfigProperty(name = "quarkus.mongodb.connection-string")
23    String connectionStringProperty;
24  
25    @Inject
26    MongoClient mongoClient;
27  
28    private MongoDatabase mongoDatabase;
29  
30    private static final String DEFAULT_DATABASE_NAME = "database";
31  
32    /**
33     * Retrieve MongoDB database name from connection string and initialize a MongoDatabase object after injection.
34     *
35     * This is needed since the function relies on an injection of the 'connectionStringProperty'.
36     */
37    @PostConstruct
38    public void init() {
39      String databaseName = determineDatabaseName(connectionStringProperty);
40      try {
41        this.mongoDatabase = mongoClient.getDatabase(databaseName);
42      } catch (IllegalArgumentException e) {
43        Log.error("Could not get MongoDB database because of invalid database name: " + databaseName);
44        throw e;
45      }
46    }
47  
48    protected static String determineDatabaseName(String connectionString) {
49      String dbName = new ConnectionString(connectionString).getDatabase();
50      if (dbName == null || dbName.isBlank()) {
51        Log.warn(
52          "Could not retrieve a MongoDB database name from the connection string. Using fallback default database name: 'database'."
53        );
54        return DEFAULT_DATABASE_NAME;
55      }
56      return dbName;
57    }
58  
59    /**
60     * Producer injection function to return the initialized MongoDatabase object.
61     *
62     * The MongoDatabase object can be injected in other classes similar to the following example.
63     * Keep in mind that the string 'mongoDatabase' shall not be changed in order to make the injection work.
64     * <pre>
65     * {@code
66     * @Inject
67     * @Named("mongoDatabase")
68     * MongoDatabase mongoDatabase;
69     * }
70     * </pre>
71     */
72    @Produces
73    @Named("mongoDatabase")
74    public MongoDatabase getMongoDatabase() {
75      return this.mongoDatabase;
76    }
77  }