Skip to content

Commit

Permalink
mongodb example created
Browse files Browse the repository at this point in the history
  • Loading branch information
Juraj Veverka committed Aug 26, 2018
1 parent d2b4d03 commit 9384a01
Show file tree
Hide file tree
Showing 11 changed files with 353 additions and 0 deletions.
10 changes: 10 additions & 0 deletions mongodb-demo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.gradle
.settings
bin
out
build
.classpath
.project
.idea
*.iml

51 changes: 51 additions & 0 deletions mongodb-demo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# MongoDB demo
Simple MongoDB 4.0.1 / Java demo

### Quick install MongoDB on localhost
Download MongoDB binary from [here](https://www.mongodb.com/download-center#community).
Java documentation is [here](http://mongodb.github.io/mongo-java-driver/3.6/).
- unpack mongo tar package
```tar xzvf mongodb-linux-x86_64-4.0.1.tgz```
- make database directory
```mkdir -p mongodb-linux-x86_64-4.0.1/data/db```
- run mongodb server
```
cd mongodb-linux-x86_64-4.0.1/bin
./mongod --dbpath ../data/db
```
- create database and user
```
cd mongodb-linux-x86_64-4.0.1/bin
./mongo
use testdb
db.createUser({user: "testuser", pwd: "secret", roles: [ "readWrite", "dbAdmin" ]})
```
- setup is complete. next time start mongodb with command
```./mongod --dbpath ../data/db```

### Build and run
Just run Main in the project or see unit tests. Database server has to be started first.
```
gradle clean build distZip
```

### Start integration tests
1. Start mongo DB in new terminal window.
```
./mongod --dbpath ../data/db
```
2. Start integration tests.
```
gradle clean test -Dtest.profile=integration
```

### Useful mongodb queries
```
cd mongodb-linux-x86_64-4.0.1/bin
./mongo
use testdb
db.roles.find()
db.roles.insert({"_id": "1", "description": "aaa" })
db.roles.remove({ "_id": "1" }, { justOne: true})
db.roles.drop()
```
32 changes: 32 additions & 0 deletions mongodb-demo/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

apply plugin: 'java'
apply plugin: 'application'

sourceCompatibility = 10
targetCompatibility = 10

mainClassName = 'itx.examples.mongodb.Main'

repositories {
mavenCentral()
}

dependencies {
compile 'org.mongodb:mongodb-driver:3.8.1'
compile 'org.slf4j:slf4j-api:1.8.0-beta2'
compile 'org.slf4j:slf4j-simple:1.8.0-beta2'
testCompile 'org.testng:testng:6.14.3'
}

test {
useTestNG()
//testLogging.showStandardStreams = true
testLogging {
events "passed", "skipped", "failed"
}

if (System.properties['test.profile'] != 'integration') {
exclude '**/*ITTest*'
}
}

35 changes: 35 additions & 0 deletions mongodb-demo/src/main/java/itx/examples/mongodb/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package itx.examples.mongodb;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.client.MongoDatabase;
import itx.examples.mongodb.dto.Role;
import itx.examples.mongodb.services.RoleService;
import itx.examples.mongodb.services.RoleServiceImpl;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;

public class Main {

final private static Logger LOG = LoggerFactory.getLogger(Main.class);

public static void main(String[] args ) {
LOG.info("MongoDB demo starting ...");
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
MongoClient mongoClient = new MongoClient( Utils.SERVER_HOSTNAME, MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build());
MongoDatabase database = mongoClient.getDatabase(Utils.DB_NAME);
RoleService roleService = new RoleServiceImpl(database);
Collection<Role> roles = roleService.getRoles();
LOG.info("Roles: {}", roles.size());
LOG.info("MongoDB demo done.");
}

}
13 changes: 13 additions & 0 deletions mongodb-demo/src/main/java/itx/examples/mongodb/Utils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package itx.examples.mongodb;

public final class Utils {

private Utils() {
throw new UnsupportedOperationException("Do not instantiate utility class.");
}

public static final String SERVER_HOSTNAME = "localhost";
public static final String DB_NAME = "testdb";
public static final String ROLES_COLLECTION_NAME = "roles";

}
32 changes: 32 additions & 0 deletions mongodb-demo/src/main/java/itx/examples/mongodb/dto/Role.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package itx.examples.mongodb.dto;

public class Role {

private String id;
private String description;

public Role() {
}

public Role(String id, String description) {
this.id = id;
this.description = description;
}

public String getId() {
return id;
}

public String getDescription() {
return description;
}

public void setId(String id) {
this.id = id;
}

public void setDescription(String description) {
this.description = description;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package itx.examples.mongodb.services;

public class DataException extends Exception {

public DataException() {
}

public DataException(String message) {
super(message);
}

public DataException(String message, Throwable cause) {
super(message, cause);
}

public DataException(Throwable cause) {
super(cause);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package itx.examples.mongodb.services;

import itx.examples.mongodb.dto.Role;

import java.util.Collection;

public interface RoleService {

Collection<Role> getRoles();

void insertRole(Role role) throws DataException;

void removeRole(String id) throws DataException;

void removeAll() throws DataException;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package itx.examples.mongodb.services;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import itx.examples.mongodb.Utils;
import itx.examples.mongodb.dto.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;

import static com.mongodb.client.model.Filters.eq;

public class RoleServiceImpl implements RoleService {

final private static Logger LOG = LoggerFactory.getLogger(RoleServiceImpl.class);

private MongoDatabase database;

public RoleServiceImpl(MongoDatabase database) {
this.database = database;
}

@Override
public Collection<Role> getRoles() {
LOG.info("getRoles");
MongoCollection<Role> collection = database.getCollection(Utils.ROLES_COLLECTION_NAME, Role.class);
Collection<Role> roles = new ArrayList<>();
MongoCursor<Role> rolesIterator = collection.find().iterator();
while (rolesIterator.hasNext()) {
roles.add(rolesIterator.next());
}
return roles;
}

@Override
public void insertRole(Role role) throws DataException {
LOG.info("insert role: {} {}", role.getId(), role.getDescription());
MongoCollection<Role> collection = database.getCollection(Utils.ROLES_COLLECTION_NAME, Role.class);
collection.insertOne(role);
}

@Override
public void removeRole(String id) throws DataException {
LOG.info("remove role: {}", id);
MongoCollection<Role> collection = database.getCollection(Utils.ROLES_COLLECTION_NAME, Role.class);
DeleteResult deleteResult = collection.deleteOne(eq("_id", id));
LOG.info("deleted {}", deleteResult.getDeletedCount());
}

@Override
public void removeAll() throws DataException {
LOG.info("remove all");
MongoCollection<Role> collection = database.getCollection(Utils.ROLES_COLLECTION_NAME, Role.class);
collection.drop();
}

}
5 changes: 5 additions & 0 deletions mongodb-demo/src/main/resources/log4j.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
log4j.rootLogger=INFO, STDOUT
log4j.logger.deng=INFO
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package itx.examples.mongodb;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.client.MongoDatabase;
import itx.examples.mongodb.dto.Role;
import itx.examples.mongodb.services.DataException;
import itx.examples.mongodb.services.RoleService;
import itx.examples.mongodb.services.RoleServiceImpl;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.util.Collection;

import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;

public class RoleServiceITTest {

private MongoClient mongoClient;
private MongoDatabase database;
private RoleService roleService;

@BeforeClass
public void init() throws DataException {
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
mongoClient = new MongoClient( Utils.SERVER_HOSTNAME, MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build());
database = mongoClient.getDatabase(Utils.DB_NAME);
roleService = new RoleServiceImpl(database);
roleService.removeAll();
}

@Test
public void testRolesService() throws DataException {

Collection<Role> roles = roleService.getRoles();
Assert.assertNotNull(roles);
Assert.assertTrue(roles.isEmpty());

roleService.insertRole(new Role("1", "aaa"));
roles = roleService.getRoles();
Assert.assertNotNull(roles);
Assert.assertTrue(roles.size() == 1);

roleService.insertRole(new Role("2", "bbb"));
roles = roleService.getRoles();
Assert.assertNotNull(roles);
Assert.assertTrue(roles.size() == 2);

roleService.removeRole("1");
roles = roleService.getRoles();
Assert.assertNotNull(roles);
Assert.assertTrue(roles.size() == 1);

roleService.removeRole("2");
roles = roleService.getRoles();
Assert.assertNotNull(roles);
Assert.assertTrue(roles.isEmpty());

}

@AfterClass
public void destroy() {
try {
roleService.removeAll();
} catch (DataException e) {
e.printStackTrace();
}
mongoClient.close();
}

}

0 comments on commit 9384a01

Please sign in to comment.