Skip to content

Commit 9384a01

Browse files
author
Juraj Veverka
committed
mongodb example created
1 parent d2b4d03 commit 9384a01

File tree

11 files changed

+353
-0
lines changed

11 files changed

+353
-0
lines changed

mongodb-demo/.gitignore

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
.gradle
2+
.settings
3+
bin
4+
out
5+
build
6+
.classpath
7+
.project
8+
.idea
9+
*.iml
10+

mongodb-demo/README.md

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# MongoDB demo
2+
Simple MongoDB 4.0.1 / Java demo
3+
4+
### Quick install MongoDB on localhost
5+
Download MongoDB binary from [here](https://www.mongodb.com/download-center#community).
6+
Java documentation is [here](http://mongodb.github.io/mongo-java-driver/3.6/).
7+
- unpack mongo tar package
8+
```tar xzvf mongodb-linux-x86_64-4.0.1.tgz```
9+
- make database directory
10+
```mkdir -p mongodb-linux-x86_64-4.0.1/data/db```
11+
- run mongodb server
12+
```
13+
cd mongodb-linux-x86_64-4.0.1/bin
14+
./mongod --dbpath ../data/db
15+
```
16+
- create database and user
17+
```
18+
cd mongodb-linux-x86_64-4.0.1/bin
19+
./mongo
20+
use testdb
21+
db.createUser({user: "testuser", pwd: "secret", roles: [ "readWrite", "dbAdmin" ]})
22+
```
23+
- setup is complete. next time start mongodb with command
24+
```./mongod --dbpath ../data/db```
25+
26+
### Build and run
27+
Just run Main in the project or see unit tests. Database server has to be started first.
28+
```
29+
gradle clean build distZip
30+
```
31+
32+
### Start integration tests
33+
1. Start mongo DB in new terminal window.
34+
```
35+
./mongod --dbpath ../data/db
36+
```
37+
2. Start integration tests.
38+
```
39+
gradle clean test -Dtest.profile=integration
40+
```
41+
42+
### Useful mongodb queries
43+
```
44+
cd mongodb-linux-x86_64-4.0.1/bin
45+
./mongo
46+
use testdb
47+
db.roles.find()
48+
db.roles.insert({"_id": "1", "description": "aaa" })
49+
db.roles.remove({ "_id": "1" }, { justOne: true})
50+
db.roles.drop()
51+
```

mongodb-demo/build.gradle

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
apply plugin: 'java'
3+
apply plugin: 'application'
4+
5+
sourceCompatibility = 10
6+
targetCompatibility = 10
7+
8+
mainClassName = 'itx.examples.mongodb.Main'
9+
10+
repositories {
11+
mavenCentral()
12+
}
13+
14+
dependencies {
15+
compile 'org.mongodb:mongodb-driver:3.8.1'
16+
compile 'org.slf4j:slf4j-api:1.8.0-beta2'
17+
compile 'org.slf4j:slf4j-simple:1.8.0-beta2'
18+
testCompile 'org.testng:testng:6.14.3'
19+
}
20+
21+
test {
22+
useTestNG()
23+
//testLogging.showStandardStreams = true
24+
testLogging {
25+
events "passed", "skipped", "failed"
26+
}
27+
28+
if (System.properties['test.profile'] != 'integration') {
29+
exclude '**/*ITTest*'
30+
}
31+
}
32+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package itx.examples.mongodb;
2+
3+
import com.mongodb.MongoClient;
4+
import com.mongodb.MongoClientOptions;
5+
import com.mongodb.client.MongoDatabase;
6+
import itx.examples.mongodb.dto.Role;
7+
import itx.examples.mongodb.services.RoleService;
8+
import itx.examples.mongodb.services.RoleServiceImpl;
9+
import org.bson.codecs.configuration.CodecRegistry;
10+
import org.bson.codecs.pojo.PojoCodecProvider;
11+
import org.slf4j.Logger;
12+
import org.slf4j.LoggerFactory;
13+
14+
import java.util.Collection;
15+
16+
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
17+
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
18+
19+
public class Main {
20+
21+
final private static Logger LOG = LoggerFactory.getLogger(Main.class);
22+
23+
public static void main(String[] args ) {
24+
LOG.info("MongoDB demo starting ...");
25+
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
26+
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
27+
MongoClient mongoClient = new MongoClient( Utils.SERVER_HOSTNAME, MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build());
28+
MongoDatabase database = mongoClient.getDatabase(Utils.DB_NAME);
29+
RoleService roleService = new RoleServiceImpl(database);
30+
Collection<Role> roles = roleService.getRoles();
31+
LOG.info("Roles: {}", roles.size());
32+
LOG.info("MongoDB demo done.");
33+
}
34+
35+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package itx.examples.mongodb;
2+
3+
public final class Utils {
4+
5+
private Utils() {
6+
throw new UnsupportedOperationException("Do not instantiate utility class.");
7+
}
8+
9+
public static final String SERVER_HOSTNAME = "localhost";
10+
public static final String DB_NAME = "testdb";
11+
public static final String ROLES_COLLECTION_NAME = "roles";
12+
13+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package itx.examples.mongodb.dto;
2+
3+
public class Role {
4+
5+
private String id;
6+
private String description;
7+
8+
public Role() {
9+
}
10+
11+
public Role(String id, String description) {
12+
this.id = id;
13+
this.description = description;
14+
}
15+
16+
public String getId() {
17+
return id;
18+
}
19+
20+
public String getDescription() {
21+
return description;
22+
}
23+
24+
public void setId(String id) {
25+
this.id = id;
26+
}
27+
28+
public void setDescription(String description) {
29+
this.description = description;
30+
}
31+
32+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package itx.examples.mongodb.services;
2+
3+
public class DataException extends Exception {
4+
5+
public DataException() {
6+
}
7+
8+
public DataException(String message) {
9+
super(message);
10+
}
11+
12+
public DataException(String message, Throwable cause) {
13+
super(message, cause);
14+
}
15+
16+
public DataException(Throwable cause) {
17+
super(cause);
18+
}
19+
20+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package itx.examples.mongodb.services;
2+
3+
import itx.examples.mongodb.dto.Role;
4+
5+
import java.util.Collection;
6+
7+
public interface RoleService {
8+
9+
Collection<Role> getRoles();
10+
11+
void insertRole(Role role) throws DataException;
12+
13+
void removeRole(String id) throws DataException;
14+
15+
void removeAll() throws DataException;
16+
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package itx.examples.mongodb.services;
2+
3+
import com.mongodb.client.MongoCollection;
4+
import com.mongodb.client.MongoCursor;
5+
import com.mongodb.client.MongoDatabase;
6+
import com.mongodb.client.result.DeleteResult;
7+
import itx.examples.mongodb.Utils;
8+
import itx.examples.mongodb.dto.Role;
9+
import org.slf4j.Logger;
10+
import org.slf4j.LoggerFactory;
11+
12+
import java.util.ArrayList;
13+
import java.util.Collection;
14+
15+
import static com.mongodb.client.model.Filters.eq;
16+
17+
public class RoleServiceImpl implements RoleService {
18+
19+
final private static Logger LOG = LoggerFactory.getLogger(RoleServiceImpl.class);
20+
21+
private MongoDatabase database;
22+
23+
public RoleServiceImpl(MongoDatabase database) {
24+
this.database = database;
25+
}
26+
27+
@Override
28+
public Collection<Role> getRoles() {
29+
LOG.info("getRoles");
30+
MongoCollection<Role> collection = database.getCollection(Utils.ROLES_COLLECTION_NAME, Role.class);
31+
Collection<Role> roles = new ArrayList<>();
32+
MongoCursor<Role> rolesIterator = collection.find().iterator();
33+
while (rolesIterator.hasNext()) {
34+
roles.add(rolesIterator.next());
35+
}
36+
return roles;
37+
}
38+
39+
@Override
40+
public void insertRole(Role role) throws DataException {
41+
LOG.info("insert role: {} {}", role.getId(), role.getDescription());
42+
MongoCollection<Role> collection = database.getCollection(Utils.ROLES_COLLECTION_NAME, Role.class);
43+
collection.insertOne(role);
44+
}
45+
46+
@Override
47+
public void removeRole(String id) throws DataException {
48+
LOG.info("remove role: {}", id);
49+
MongoCollection<Role> collection = database.getCollection(Utils.ROLES_COLLECTION_NAME, Role.class);
50+
DeleteResult deleteResult = collection.deleteOne(eq("_id", id));
51+
LOG.info("deleted {}", deleteResult.getDeletedCount());
52+
}
53+
54+
@Override
55+
public void removeAll() throws DataException {
56+
LOG.info("remove all");
57+
MongoCollection<Role> collection = database.getCollection(Utils.ROLES_COLLECTION_NAME, Role.class);
58+
collection.drop();
59+
}
60+
61+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
log4j.rootLogger=INFO, STDOUT
2+
log4j.logger.deng=INFO
3+
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
4+
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
5+
log4j.appender.STDOUT.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package itx.examples.mongodb;
2+
3+
import com.mongodb.MongoClient;
4+
import com.mongodb.MongoClientOptions;
5+
import com.mongodb.client.MongoDatabase;
6+
import itx.examples.mongodb.dto.Role;
7+
import itx.examples.mongodb.services.DataException;
8+
import itx.examples.mongodb.services.RoleService;
9+
import itx.examples.mongodb.services.RoleServiceImpl;
10+
import org.bson.codecs.configuration.CodecRegistry;
11+
import org.bson.codecs.pojo.PojoCodecProvider;
12+
import org.testng.Assert;
13+
import org.testng.annotations.AfterClass;
14+
import org.testng.annotations.BeforeClass;
15+
import org.testng.annotations.Test;
16+
17+
import java.util.Collection;
18+
19+
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
20+
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
21+
22+
public class RoleServiceITTest {
23+
24+
private MongoClient mongoClient;
25+
private MongoDatabase database;
26+
private RoleService roleService;
27+
28+
@BeforeClass
29+
public void init() throws DataException {
30+
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
31+
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
32+
mongoClient = new MongoClient( Utils.SERVER_HOSTNAME, MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build());
33+
database = mongoClient.getDatabase(Utils.DB_NAME);
34+
roleService = new RoleServiceImpl(database);
35+
roleService.removeAll();
36+
}
37+
38+
@Test
39+
public void testRolesService() throws DataException {
40+
41+
Collection<Role> roles = roleService.getRoles();
42+
Assert.assertNotNull(roles);
43+
Assert.assertTrue(roles.isEmpty());
44+
45+
roleService.insertRole(new Role("1", "aaa"));
46+
roles = roleService.getRoles();
47+
Assert.assertNotNull(roles);
48+
Assert.assertTrue(roles.size() == 1);
49+
50+
roleService.insertRole(new Role("2", "bbb"));
51+
roles = roleService.getRoles();
52+
Assert.assertNotNull(roles);
53+
Assert.assertTrue(roles.size() == 2);
54+
55+
roleService.removeRole("1");
56+
roles = roleService.getRoles();
57+
Assert.assertNotNull(roles);
58+
Assert.assertTrue(roles.size() == 1);
59+
60+
roleService.removeRole("2");
61+
roles = roleService.getRoles();
62+
Assert.assertNotNull(roles);
63+
Assert.assertTrue(roles.isEmpty());
64+
65+
}
66+
67+
@AfterClass
68+
public void destroy() {
69+
try {
70+
roleService.removeAll();
71+
} catch (DataException e) {
72+
e.printStackTrace();
73+
}
74+
mongoClient.close();
75+
}
76+
77+
}

0 commit comments

Comments
 (0)