Skip to content

Commit aa1e91c

Browse files
committed
DATAMONGO-442 - Polishing.
Reformat code according to Spring Data style. Add test for authenticated use. Add JavaDoc to newly introduced methods. Allow configuration of an authentication database. Update reference documentation. Original pull request: spring-projects#419.
1 parent 9737464 commit aa1e91c

File tree

6 files changed

+266
-67
lines changed

6 files changed

+266
-67
lines changed

spring-data-mongodb-log4j/src/main/java/org/springframework/data/mongodb/log4j/MongoLog4jAppender.java

+68-18
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,27 @@
1515
*/
1616
package org.springframework.data.mongodb.log4j;
1717

18-
import com.mongodb.*;
18+
import java.net.UnknownHostException;
19+
import java.util.Arrays;
20+
import java.util.Calendar;
21+
import java.util.Collections;
22+
import java.util.List;
23+
import java.util.Map;
24+
1925
import org.apache.log4j.AppenderSkeleton;
2026
import org.apache.log4j.Level;
2127
import org.apache.log4j.MDC;
2228
import org.apache.log4j.PatternLayout;
2329
import org.apache.log4j.spi.LoggingEvent;
2430

25-
import java.net.UnknownHostException;
26-
import java.util.*;
31+
import com.mongodb.BasicDBList;
32+
import com.mongodb.BasicDBObject;
33+
import com.mongodb.DB;
34+
import com.mongodb.Mongo;
35+
import com.mongodb.MongoClient;
36+
import com.mongodb.MongoCredential;
37+
import com.mongodb.ServerAddress;
38+
import com.mongodb.WriteConcern;
2739

2840
/**
2941
* Log4j appender writing log entries into a MongoDB instance.
@@ -51,6 +63,7 @@ public class MongoLog4jAppender extends AppenderSkeleton {
5163
protected int port = 27017;
5264
protected String username;
5365
protected String password;
66+
protected String authenticationDatabase;
5467
protected String database = "logs";
5568
protected String collectionPattern = "%c";
5669
protected PatternLayout collectionLayout = new PatternLayout(collectionPattern);
@@ -60,8 +73,7 @@ public class MongoLog4jAppender extends AppenderSkeleton {
6073
protected Mongo mongo;
6174
protected DB db;
6275

63-
public MongoLog4jAppender() {
64-
}
76+
public MongoLog4jAppender() {}
6577

6678
public MongoLog4jAppender(boolean isActive) {
6779
super(isActive);
@@ -83,20 +95,51 @@ public void setPort(int port) {
8395
this.port = port;
8496
}
8597

98+
/**
99+
* @return
100+
* @since 1.10
101+
*/
102+
public String getUsername() {
103+
return username;
104+
}
105+
106+
/**
107+
* @param username may be {@literal null} for unauthenticated access.
108+
* @since 1.10
109+
*/
110+
public void setUsername(String username) {
111+
this.username = username;
112+
}
113+
114+
/**
115+
* @return
116+
* @since 1.10
117+
*/
86118
public String getPassword() {
87119
return password;
88120
}
89121

122+
/**
123+
* @param password may be {@literal null} for unauthenticated access.
124+
* @since 1.10
125+
*/
90126
public void setPassword(String password) {
91127
this.password = password;
92128
}
93129

94-
public String getUsername() {
95-
return username;
130+
/**
131+
* @return
132+
*/
133+
public String getAuthenticationDatabase() {
134+
return authenticationDatabase;
96135
}
97136

98-
public void setUsername(String username) {
99-
this.username = username;
137+
/**
138+
* @param authenticationDatabase may be {@literal null} to use {@link #getDatabase()} as authentication database.
139+
* @since 1.10
140+
*/
141+
public void setAuthenticationDatabase(String authenticationDatabase) {
142+
this.authenticationDatabase = authenticationDatabase;
100143
}
101144

102145
public String getDatabase() {
@@ -141,26 +184,33 @@ public void setInfoOrLowerWriteConcern(String wc) {
141184
}
142185

143186
protected void connectToMongo() throws UnknownHostException {
144-
ServerAddress serverAddress = new ServerAddress(host, port);
145-
connectToMongoHandlingCredentials(serverAddress);
187+
188+
this.mongo = createMongoClient();
146189
this.db = mongo.getDB(database);
147190
}
148191

149-
private void connectToMongoHandlingCredentials(ServerAddress serverAddress) {
192+
private MongoClient createMongoClient() throws UnknownHostException {
193+
194+
ServerAddress serverAddress = new ServerAddress(host, port);
195+
150196
if (null == password || null == username) {
151-
this.mongo = new MongoClient(serverAddress);
152-
} else {
153-
MongoCredential mongoCredential = MongoCredential.createCredential(username, database, password.toCharArray());
154-
List<MongoCredential> credentials = Collections.singletonList(mongoCredential);
155-
this.mongo = new MongoClient(serverAddress, credentials);
197+
return new MongoClient(serverAddress);
156198
}
199+
200+
String authenticationDatabaseToUse = authenticationDatabase == null ? this.database : authenticationDatabase;
201+
MongoCredential mongoCredential = MongoCredential.createCredential(username,
202+
authenticationDatabaseToUse, password.toCharArray());
203+
List<MongoCredential> credentials = Collections.singletonList(mongoCredential);
204+
return new MongoClient(serverAddress, credentials);
157205
}
158206

159207
/*
160208
* (non-Javadoc)
161209
* @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent)
162210
*/
163-
@Override @SuppressWarnings({ "unchecked" }) protected void append(final LoggingEvent event) {
211+
@Override
212+
@SuppressWarnings({ "unchecked" })
213+
protected void append(final LoggingEvent event) {
164214
if (null == db) {
165215
try {
166216
connectToMongo();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
/*
2+
* Copyright 2016 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.data.mongodb.log4j;
17+
18+
import static org.hamcrest.Matchers.*;
19+
import static org.junit.Assert.*;
20+
21+
import java.util.Calendar;
22+
import java.util.Collections;
23+
24+
import org.apache.log4j.LogManager;
25+
import org.apache.log4j.Logger;
26+
import org.apache.log4j.MDC;
27+
import org.apache.log4j.PropertyConfigurator;
28+
import org.junit.After;
29+
import org.junit.Before;
30+
import org.junit.Test;
31+
32+
import com.mongodb.BasicDBList;
33+
import com.mongodb.BasicDBObject;
34+
import com.mongodb.BasicDBObjectBuilder;
35+
import com.mongodb.DB;
36+
import com.mongodb.DBCursor;
37+
import com.mongodb.MongoClient;
38+
import com.mongodb.MongoCredential;
39+
import com.mongodb.ServerAddress;
40+
41+
/**
42+
* Integration tests for {@link MongoLog4jAppender} using authentication.
43+
*
44+
* @author Mark Paluch
45+
*/
46+
public class MongoLog4jAppenderAuthenticationIntegrationTests {
47+
48+
private final static String username = "admin";
49+
private final static String password = "test";
50+
private final static String authenticationDatabase = "logs";
51+
52+
MongoClient mongo;
53+
DB db;
54+
String collection;
55+
ServerAddress serverLocation;
56+
57+
Logger log;
58+
59+
@Before
60+
public void setUp() throws Exception {
61+
62+
serverLocation = new ServerAddress("localhost", 27017);
63+
64+
mongo = new MongoClient(serverLocation);
65+
db = mongo.getDB("logs");
66+
67+
BasicDBList roles = new BasicDBList();
68+
roles.add("dbOwner");
69+
db.command(new BasicDBObjectBuilder().add("createUser", username).add("pwd", password).add("roles", roles).get());
70+
mongo.close();
71+
72+
mongo = new MongoClient(serverLocation, Collections
73+
.singletonList(MongoCredential.createCredential(username, authenticationDatabase, password.toCharArray())));
74+
db = mongo.getDB("logs");
75+
76+
Calendar now = Calendar.getInstance();
77+
collection = String.valueOf(now.get(Calendar.YEAR)) + String.format("%1$02d", now.get(Calendar.MONTH) + 1);
78+
79+
LogManager.resetConfiguration();
80+
PropertyConfigurator.configure(getClass().getResource("/log4j-with-authentication.properties"));
81+
82+
log = Logger.getLogger(MongoLog4jAppenderIntegrationTests.class.getName());
83+
}
84+
85+
@After
86+
public void tearDown() {
87+
88+
if (db != null) {
89+
db.getCollection(collection).remove(new BasicDBObject());
90+
db.command(new BasicDBObject("dropUser", username));
91+
}
92+
93+
LogManager.resetConfiguration();
94+
PropertyConfigurator.configure(getClass().getResource("/log4j.properties"));
95+
}
96+
97+
@Test
98+
public void testLogging() {
99+
100+
log.debug("DEBUG message");
101+
log.info("INFO message");
102+
log.warn("WARN message");
103+
log.error("ERROR message");
104+
105+
DBCursor msgs = db.getCollection(collection).find();
106+
assertThat(msgs.count(), is(4));
107+
}
108+
109+
@Test
110+
public void testProperties() {
111+
MDC.put("property", "one");
112+
log.debug("DEBUG message");
113+
}
114+
}

spring-data-mongodb-log4j/src/test/java/org/springframework/data/mongodb/log4j/MongoLog4jAppenderIntegrationTests.java

+28-26
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,24 @@
1515
*/
1616
package org.springframework.data.mongodb.log4j;
1717

18-
import com.mongodb.*;
18+
import static org.hamcrest.Matchers.*;
19+
import static org.junit.Assert.*;
20+
21+
import java.util.Calendar;
22+
23+
import org.apache.log4j.LogManager;
1924
import org.apache.log4j.Logger;
2025
import org.apache.log4j.MDC;
26+
import org.apache.log4j.PropertyConfigurator;
2127
import org.junit.After;
2228
import org.junit.Before;
2329
import org.junit.Test;
2430

25-
import java.net.UnknownHostException;
26-
import java.util.Calendar;
27-
import java.util.Collections;
28-
29-
import static org.hamcrest.Matchers.is;
30-
import static org.junit.Assert.assertThat;
31+
import com.mongodb.BasicDBObject;
32+
import com.mongodb.DB;
33+
import com.mongodb.DBCursor;
34+
import com.mongodb.MongoClient;
35+
import com.mongodb.ServerAddress;
3136

3237
/**
3338
* Integration tests for {@link MongoLog4jAppender}.
@@ -38,27 +43,33 @@
3843
*/
3944
public class MongoLog4jAppenderIntegrationTests {
4045

41-
private static final Logger log = Logger.getLogger(MongoLog4jAppenderIntegrationTests.class.getName());
42-
private MongoClient mongo;
43-
private DB db;
44-
private String collection;
45-
private ServerAddress serverLocation;
46+
MongoClient mongo;
47+
DB db;
48+
String collection;
49+
ServerAddress serverLocation;
50+
Logger log;
4651

47-
@Before public void setUp() throws Exception {
52+
@Before
53+
public void setUp() throws Exception {
4854
serverLocation = new ServerAddress("localhost", 27017);
4955

5056
mongo = new MongoClient(serverLocation);
5157
db = mongo.getDB("logs");
5258

5359
Calendar now = Calendar.getInstance();
5460
collection = String.valueOf(now.get(Calendar.YEAR)) + String.format("%1$02d", now.get(Calendar.MONTH) + 1);
61+
62+
log = Logger.getLogger(MongoLog4jAppenderIntegrationTests.class.getName());
5563
}
5664

57-
@After public void tearDown() {
65+
@After
66+
public void tearDown() {
5867
db.getCollection(collection).remove(new BasicDBObject());
5968
}
6069

61-
@Test public void testLogging() {
70+
@Test
71+
public void testLogging() {
72+
6273
log.debug("DEBUG message");
6374
log.info("INFO message");
6475
log.warn("WARN message");
@@ -68,18 +79,9 @@ public class MongoLog4jAppenderIntegrationTests {
6879
assertThat(msgs.count(), is(4));
6980
}
7081

71-
/**
72-
* @see DATAMONGO-442
73-
*/
74-
@Test public void testLoggingWithCredentials() throws UnknownHostException {
75-
MongoCredential credential = MongoCredential.createCredential("username", "logs", "password".toCharArray());
76-
mongo = new MongoClient(serverLocation, Collections.singletonList(credential));
77-
testLogging();
78-
}
79-
80-
@Test public void testProperties() {
82+
@Test
83+
public void testProperties() {
8184
MDC.put("property", "one");
8285
log.debug("DEBUG message");
8386
}
84-
8587
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
log4j.rootCategory=INFO, mongo
2+
3+
log4j.appender.mongo=org.springframework.data.mongodb.log4j.MongoLog4jAppender
4+
log4j.appender.mongo.layout=org.apache.log4j.PatternLayout
5+
log4j.appender.mongo.layout.ConversionPattern=%d %p [%c] - <%m>%n
6+
log4j.appender.mongo.host = localhost
7+
log4j.appender.mongo.port = 27017
8+
log4j.appender.mongo.database = logs
9+
log4j.appender.mongo.username = admin
10+
log4j.appender.mongo.password = test
11+
log4j.appender.mongo.authenticationDatabase = logs
12+
log4j.appender.mongo.collectionPattern = %X{year}%X{month}
13+
log4j.appender.mongo.applicationId = my.application
14+
log4j.appender.mongo.warnOrHigherWriteConcern = FSYNC_SAFE
15+
16+
log4j.category.org.springframework.data.mongodb=DEBUG
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
log4j.rootCategory=INFO, stdout
1+
log4j.rootCategory=INFO, mongo
22

3-
log4j.appender.stdout=org.springframework.data.mongodb.log4j.MongoLog4jAppender
4-
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
5-
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
6-
log4j.appender.stdout.host = localhost
7-
log4j.appender.stdout.port = 27017
8-
log4j.appender.stdout.database = logs
9-
log4j.appender.stdout.collectionPattern = %X{year}%X{month}
10-
log4j.appender.stdout.applicationId = my.application
11-
log4j.appender.stdout.warnOrHigherWriteConcern = FSYNC_SAFE
3+
log4j.appender.mongo=org.springframework.data.mongodb.log4j.MongoLog4jAppender
4+
log4j.appender.mongo.layout=org.apache.log4j.PatternLayout
5+
log4j.appender.mongo.layout.ConversionPattern=%d %p [%c] - <%m>%n
6+
log4j.appender.mongo.host = localhost
7+
log4j.appender.mongo.port = 27017
8+
log4j.appender.mongo.database = logs
9+
log4j.appender.mongo.collectionPattern = %X{year}%X{month}
10+
log4j.appender.mongo.applicationId = my.application
11+
log4j.appender.mongo.warnOrHigherWriteConcern = FSYNC_SAFE
1212

1313
log4j.category.org.springframework.data.mongodb=DEBUG

0 commit comments

Comments
 (0)