Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions log4j-mongodb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>

</dependencies>

<build>
Expand All @@ -151,7 +150,7 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
<skip>false</skip>
</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,41 @@ 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);
} catch (final IllegalArgumentException e) {
LOGGER.error("Invalid MongoDB database name `{}`.", effectiveDatabaseName, e);
return null;
}
// Validate the provided collectionName property
try {
MongoNamespace.checkCollectionNameValidity(effectiveCollectionName);
} catch (final IllegalArgumentException e) {
LOGGER.error("Invalid MongoDB collection name `{}`.", effectiveCollectionName, e);
return null;
}

return new MongoDbProvider(connectionString, capped, collectionSize, effectiveDatabaseName, effectiveCollectionName);
}

public B setConnectionStringSource(final String connectionStringSource) {
Expand All @@ -73,6 +106,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 +137,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 {

@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,107 @@
package org.apache.logging.log4j.mongodb;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;


class MongoDbProviderTest {

private String validConnectionStringWithoutDatabase = "mongodb://localhost:27017";
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(provider, "Returned provider is null");
assertEquals(this.collectionName, provider.getConnection().getCollection().getNamespace().getCollectionName(), "Collection names do not match");
assertEquals( this.databaseName, provider.getConnection().getCollection().getNamespace().getDatabaseName(), "Database names do not match");

}

@Test
void createProviderWithoutDatabaseName() {

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

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


}

@Test
void createProviderWithoutDatabaseNameWithCollectionName(){

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

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



}

@Test
void createProviderWithoutCollectionName(){

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

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


}

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

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

}

@Test
void createProviderConfigOverridesConnectionString() {

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

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

}




}
Copy link
Member

Choose a reason for hiding this comment

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

I see you switched all IT configuration to use the new {database,collection}Name attributes, don't. This effectively removes the checks verifying that the old style is still working. Could you revert all your resources/*.xml changes, please? (Keep the new resource files you added for new tests.)

Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
https://logging.apache.org/xml/ns/log4j-config-3.xsd">
<Appenders>
<NoSql name="MONGO">
<MongoDb connection="mongodb://localhost:${sys:log4j.mongo.port:-27017}/testDb.MongoDbAdditionalFieldsIT"/>
<MongoDb connection="mongodb://localhost:${sys:log4j.mongo.port:-27017}" databaseName="testDb" collectionName="MongoDbAdditionalFieldsIT"/>
<KeyValuePair key="A" value="1"/>
<KeyValuePair key="B" value="2"/>
<KeyValuePair key="env1" value="${env:PATH}"/>
Expand Down
2 changes: 1 addition & 1 deletion log4j-mongodb/src/test/resources/MongoDbAuthFailureIT.xml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
<Appenders>
<NoSql name="MONGO">
<MongoDb
connection="mongodb://log4jUser:12345678@localhost:${sys:log4j.mongo.port:-27017}/testDb.MongoDbAuthFailureIT" />
connection="mongodb://log4jUser:12345678@localhost:${sys:log4j.mongo.port:-27017}" databaseName="testDb" collectionName="MongoDbAuthFailureIT" />
</NoSql>
</Appenders>
<Loggers>
Expand Down
4 changes: 3 additions & 1 deletion log4j-mongodb/src/test/resources/MongoDbCappedIntIT.xml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
<Appenders>
<NoSql name="MONGO">
<MongoDb
connection="mongodb://localhost:${sys:log4j.mongo.port:-27017}/testDb.MongoDbCappedIntIT"
connection="mongodb://localhost:${sys:log4j.mongo.port:-27017}"
databaseName="testDb"
collectionName="MongoDbCappedIntIT"
capped="true"
collectionSize="1073741824"/>
</NoSql>
Expand Down
Loading
Loading