Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add collectionName and databaseName attributes to MongoDbProvider #3322

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
9 changes: 7 additions & 2 deletions log4j-mongodb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>3.0.0-SNAPSHOT</version>
jesmith17 marked this conversation as resolved.
Show resolved Hide resolved
</dependency>

<dependency>
Expand Down Expand Up @@ -141,7 +142,11 @@
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
jesmith17 marked this conversation as resolved.
Show resolved Hide resolved

<build>
Expand All @@ -151,7 +156,7 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
<skip>false</skip>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can remove the entire <configuration>, since <skip>false is the default.

</configuration>
<dependencies>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,20 +59,19 @@ private static MongoCollection<Document> getOrCreateMongoCollection(
}
}

private final ConnectionString connectionString;

private final MongoCollection<Document> collection;
private final MongoClient mongoClient;

public MongoDbConnection(
final ConnectionString connectionString,
final MongoClient mongoClient,
final MongoDatabase mongoDatabase,
final String collectionName,
final boolean isCapped,
final Long sizeInBytes) {
this.connectionString = connectionString;
this.mongoClient = mongoClient;
this.collection =
getOrCreateMongoCollection(mongoDatabase, connectionString.getCollection(), isCapped, sizeInBytes);
getOrCreateMongoCollection(mongoDatabase, collectionName, isCapped, sizeInBytes);
}

@Override
Expand Down Expand Up @@ -107,7 +106,15 @@ public void insertObject(final NoSqlObject<Document> object) {
@Override
public String toString() {
return String.format(
"Mongo4Connection [connectionString=%s, collection=%s, mongoClient=%s]",
connectionString, collection, mongoClient);
"Mongo4Connection [collection=%s, mongoClient=%s]", collection, mongoClient);
}

/*
* This method is exposed to help support unit tests for the MongoDbProvider class.
*
*/
public MongoCollection<Document> getCollection(){
return this.collection;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoNamespace;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
Expand Down Expand Up @@ -54,9 +55,43 @@ public static class Builder<B extends Builder<B>> extends AbstractFilterable.Bui
@PluginAttribute("capped")
private boolean capped = false;

@PluginAttribute("collectionName")
private String collectionName = null;

@PluginAttribute("databaseName")
private String databaseName = null;

@Override
public MongoDbProvider build() {
return new MongoDbProvider(connectionStringSource, capped, collectionSize);
LOGGER.debug("Creating ConnectionString {}...", connectionStringSource);
ConnectionString connectionString;
try {
connectionString = new ConnectionString(connectionStringSource);
} catch (final IllegalArgumentException e) {
LOGGER.error("Invalid MongoDB connection string `{}`.", connectionStringSource, e);
return null;
}

String effectiveDatabaseName = databaseName != null ? databaseName : connectionString.getDatabase();
String effectiveCollectionName = collectionName != null ? collectionName: connectionString.getCollection();
// Validate the provided databaseName property
try {
MongoNamespace.checkDatabaseNameValidity(effectiveDatabaseName);
databaseName = effectiveDatabaseName;
jesmith17 marked this conversation as resolved.
Show resolved Hide resolved
} catch (final IllegalArgumentException e) {
LOGGER.error("Invalid MongoDB database name `{}`.", effectiveDatabaseName, e);
return null;
}
// Validate the provided collectionName property
try {
MongoNamespace.checkCollectionNameValidity(effectiveCollectionName);
collectionName = effectiveCollectionName;
jesmith17 marked this conversation as resolved.
Show resolved Hide resolved
} catch (final IllegalArgumentException e) {
LOGGER.error("Invalid MongoDB collection name `{}`.", effectiveCollectionName, e);
return null;
}

return new MongoDbProvider(connectionString, capped, collectionSize, databaseName, collectionName);
}

public B setConnectionStringSource(final String connectionStringSource) {
Expand All @@ -73,6 +108,16 @@ public B setCollectionSize(final long collectionSize) {
this.collectionSize = collectionSize;
return asBuilder();
}

public B setCollectionName(final String collectionName) {
this.collectionName = collectionName;
return asBuilder();
}

public B setDatabaseName(final String databaseName) {
this.databaseName = databaseName;
return asBuilder();
}
}

private static final Logger LOGGER = StatusLogger.getLogger();
Expand All @@ -94,47 +139,49 @@ public static <B extends Builder<B>> B newBuilder() {

private final Long collectionSize;
private final boolean isCapped;
private final String collectionName;
private final MongoClient mongoClient;
private final MongoDatabase mongoDatabase;
private final ConnectionString connectionString;

private MongoDbProvider(final String connectionStringSource, final boolean isCapped, final Long collectionSize) {
LOGGER.debug("Creating ConnectionString {}...", connectionStringSource);
this.connectionString = new ConnectionString(connectionStringSource);
private MongoDbProvider(final ConnectionString connectionString, final boolean isCapped, final Long collectionSize, final String databaseName, final String collectionName) {

LOGGER.debug("Created ConnectionString {}", connectionString);
this.connectionString = connectionString;
LOGGER.debug("Creating MongoClientSettings...");
// @formatter:off
final MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(this.connectionString)
.applyConnectionString(connectionString)
.codecRegistry(CODEC_REGISTRIES)
.build();
// @formatter:on
LOGGER.debug("Created MongoClientSettings {}", settings);
LOGGER.debug("Creating MongoClient {}...", settings);
this.mongoClient = MongoClients.create(settings);
LOGGER.debug("Created MongoClient {}", mongoClient);
final String databaseName = this.connectionString.getDatabase();
LOGGER.debug("Getting MongoDatabase {}...", databaseName);
this.mongoDatabase = this.mongoClient.getDatabase(databaseName);
LOGGER.debug("Got MongoDatabase {}", mongoDatabase);
this.collectionName = collectionName;
this.isCapped = isCapped;
this.collectionSize = collectionSize;
}

@Override
public MongoDbConnection getConnection() {
return new MongoDbConnection(connectionString, mongoClient, mongoDatabase, isCapped, collectionSize);
return new MongoDbConnection(mongoClient, mongoDatabase, collectionName, isCapped, collectionSize);
}

@Override
public String toString() {
return String.format(
"%s [connectionString=%s, collectionSize=%s, isCapped=%s, mongoClient=%s, mongoDatabase=%s]",
"%s [connectionString=%s, collectionSize=%s, isCapped=%s, mongoClient=%s, mongoDatabase=%s, collectionName=%s]",
MongoDbProvider.class.getSimpleName(),
connectionString,
collectionSize,
isCapped,
mongoClient,
mongoDatabase);
mongoDatabase,
collectionName);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* 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 org.apache.logging.log4j.mongodb;

import com.mongodb.client.MongoClient;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
import org.apache.logging.log4j.test.junit.UsingStatusListener;
import org.junit.jupiter.api.Test;

@UsingMongoDb
@LoggerContextSource("MongoDbCollectionNameIT.xml")
// Print debug status logger output upon failure
@UsingStatusListener
class MongoDbCollectionNameIT extends AbstractMongoDbCappedIT {
ppkarwasz marked this conversation as resolved.
Show resolved Hide resolved

@Test
@Override
protected void test(LoggerContext ctx, MongoClient mongoClient) {
super.test(ctx, mongoClient);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* 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 org.apache.logging.log4j.mongodb;

import com.mongodb.client.MongoClient;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
import org.apache.logging.log4j.test.junit.UsingStatusListener;
import org.junit.jupiter.api.Test;

@UsingMongoDb
@LoggerContextSource("MongoDbDatabaseAndCollectionNameIT.xml")
// Print debug status logger output upon failure
@UsingStatusListener
class MongoDbDatabaseAndCollectionNameIT extends AbstractMongoDbCappedIT {

@Test
@Override
protected void test(LoggerContext ctx, MongoClient mongoClient) {
super.test(ctx, mongoClient);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package org.apache.logging.log4j.mongodb;

import org.junit.jupiter.api.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
jesmith17 marked this conversation as resolved.
Show resolved Hide resolved


class MongoDbProviderTest {

private String validConnectionStringWithoutDatabase = "mongodb://localhost:27017";
private String invalidConnectionString = "test:test";
private String validConnectionStringWithDatabase = "mongodb://localhost:27017/logging";
private String validConnectionStringWithDatabaseAndCollection = "mongodb://localhost:27017/logging.logs";

private String collectionName = "logsTest";
private String databaseName = "loggingTest";




@Test
void createProviderWithDatabaseAndCollectionProvidedViaConfig() {

MongoDbProvider provider = MongoDbProvider.newBuilder()
.setConnectionStringSource(this.validConnectionStringWithoutDatabase)
.setDatabaseName(this.databaseName)
.setCollectionName(this.collectionName)
.build();

assertNotNull("Returned provider is null", provider);
assertEquals("Collection names do not match", this.collectionName, provider.getConnection().getCollection().getNamespace().getCollectionName());
assertEquals("Database names do not match", this.databaseName, provider.getConnection().getCollection().getNamespace().getDatabaseName());

}

@Test
void createProviderWithoutDatabaseName() {

MongoDbProvider provider = MongoDbProvider.newBuilder()
.setConnectionStringSource(this.validConnectionStringWithoutDatabase)
.build();

assertNull("Provider should be null but was not", provider);


}

@Test
void createProviderWithoutDatabaseNameWithCollectionName(){

MongoDbProvider provider = MongoDbProvider.newBuilder()
.setConnectionStringSource(this.validConnectionStringWithoutDatabase)
.setCollectionName(this.collectionName)
.build();

assertNull("Provider should be null but was not", provider);



}

@Test
void createProviderWithoutCollectionName(){

MongoDbProvider provider = MongoDbProvider.newBuilder()
.setConnectionStringSource(this.validConnectionStringWithoutDatabase)
.setDatabaseName(this.databaseName)
.build();

assertNull("Provider should be null but was not", provider);


}

@Test
void createProviderWithDatabaseOnConnectionString(){
MongoDbProvider provider = MongoDbProvider.newBuilder()
.setConnectionStringSource(this.validConnectionStringWithDatabase)
.setCollectionName(this.collectionName)
.build();

assertNotNull("Provider should be null but was not", provider);
assertEquals("Collection names do not match", this.collectionName, provider.getConnection().getCollection().getNamespace().getCollectionName());
assertEquals("Database names do not match", "logging", provider.getConnection().getCollection().getNamespace().getDatabaseName());

}

@Test
void createProviderConfigOverridesConnectionString() {

MongoDbProvider provider = MongoDbProvider.newBuilder()
.setConnectionStringSource(this.validConnectionStringWithDatabaseAndCollection)
.setCollectionName(this.collectionName)
.setDatabaseName(this.databaseName)
.build();

assertNotNull("Provider should not be null", provider);
assertEquals("Collection name does not match provided configuration", this.collectionName, provider.getConnection().getCollection().getNamespace().getCollectionName());
assertEquals("Database name does not match provided configuration", this.databaseName, provider.getConnection().getCollection().getNamespace().getDatabaseName());

}




}
Loading