├── .gitignore ├── dropwizard-mongo-example ├── src │ ├── test │ │ ├── resources │ │ │ └── config.yaml │ │ └── java │ │ │ └── com │ │ │ └── eeb │ │ │ └── dropwizardmongo │ │ │ └── test │ │ │ └── ServerIntegrationTest.java │ └── main │ │ └── java │ │ └── com │ │ └── eeb │ │ └── dropwizardmongo │ │ └── example │ │ ├── api │ │ └── MongoDocument.java │ │ ├── DropwizardMongoApplication.java │ │ └── resources │ │ └── CollectionIdsResource.java └── pom.xml ├── dropwizard-mongo ├── src │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── eeb │ │ │ └── dropwizardmongo │ │ │ ├── exceptions │ │ │ ├── NullDBNameException.java │ │ │ └── NullCollectionNameException.java │ │ │ ├── configuration │ │ │ └── DropwizardMongoConfiguration.java │ │ │ ├── health │ │ │ └── MongoHealthCheck.java │ │ │ └── factory │ │ │ ├── ServerAddressBuilder.java │ │ │ └── MongoFactory.java │ └── test │ │ └── java │ │ └── com │ │ └── eeb │ │ └── dropwizardmongo │ │ └── test │ │ └── FactoryIntegrationTest.java └── pom.xml ├── pom.xml ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .idea/ 3 | target/ 4 | embedmongo.log 5 | -------------------------------------------------------------------------------- /dropwizard-mongo-example/src/test/resources/config.yaml: -------------------------------------------------------------------------------- 1 | #Mongo connection 2 | mongoDB: 3 | dbName: test 4 | connections: 5 | - host: localhost 6 | port: 27017 7 | # - host: 192.168.1.12 8 | # port: 27017 9 | 10 | 11 | # Logging Settings 12 | logging: 13 | level: INFO 14 | loggers: 15 | "com.eeb.example.dropwizardmongo": DEBUG -------------------------------------------------------------------------------- /dropwizard-mongo/src/main/java/com/eeb/dropwizardmongo/exceptions/NullDBNameException.java: -------------------------------------------------------------------------------- 1 | package com.eeb.dropwizardmongo.exceptions; 2 | 3 | /** 4 | * Exception thrown if the {@link com.eeb.dropwizardmongo.factory.MongoFactory} attempts to build 5 | * a DB object and the configured database name is null. 6 | */ 7 | public class NullDBNameException extends Exception { 8 | 9 | private static final String message = "Attempt made to create a DB object when the configured database name was null or invalid"; 10 | 11 | public NullDBNameException() { 12 | super(message); 13 | } 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /dropwizard-mongo/src/main/java/com/eeb/dropwizardmongo/exceptions/NullCollectionNameException.java: -------------------------------------------------------------------------------- 1 | package com.eeb.dropwizardmongo.exceptions; 2 | 3 | /** 4 | * Exception thrown if the {@link com.eeb.dropwizardmongo.factory.MongoFactory} attempts to build 5 | * a DBCollection object and the configured collection name is null. 6 | */ 7 | public class NullCollectionNameException extends Exception { 8 | private static final String message = "Attempt made to create a DBCollection object when t" + 9 | "he configured collection name was null or invalid"; 10 | 11 | public NullCollectionNameException() { 12 | super(message); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /dropwizard-mongo-example/src/main/java/com/eeb/dropwizardmongo/example/api/MongoDocument.java: -------------------------------------------------------------------------------- 1 | package com.eeb.dropwizardmongo.example.api; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import org.mongojack.ObjectId; 5 | 6 | /** 7 | * This class is a Representation of the most basic parts of a Mongodb document. 8 | */ 9 | public class MongoDocument { 10 | 11 | private String id; 12 | 13 | @ObjectId 14 | @JsonProperty("_id") 15 | public String getId() { 16 | return this.id; 17 | } 18 | 19 | @ObjectId 20 | @JsonProperty("_id") 21 | public void setId(String id) { 22 | this.id = id; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /dropwizard-mongo/src/main/java/com/eeb/dropwizardmongo/configuration/DropwizardMongoConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.eeb.dropwizardmongo.configuration; 2 | 3 | import com.eeb.dropwizardmongo.factory.MongoFactory; 4 | import com.fasterxml.jackson.annotation.JsonCreator; 5 | import com.fasterxml.jackson.annotation.JsonProperty; 6 | import io.dropwizard.Configuration; 7 | 8 | import javax.validation.Valid; 9 | import javax.validation.constraints.NotNull; 10 | 11 | /** 12 | * This class can be used as is or extended to provide support for configuration options for your dropwizard-mongo 13 | * application. 14 | */ 15 | public class DropwizardMongoConfiguration extends Configuration { 16 | 17 | 18 | @Valid 19 | @NotNull 20 | private MongoFactory mongoFactory = new MongoFactory(); 21 | 22 | @JsonCreator 23 | public DropwizardMongoConfiguration(@JsonProperty("mongoDB") MongoFactory mongoFactory) { 24 | this.mongoFactory = mongoFactory; 25 | } 26 | 27 | @JsonProperty("mongoDB") 28 | public MongoFactory getMongoFactory() { 29 | return this.mongoFactory; 30 | } 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /dropwizard-mongo/src/main/java/com/eeb/dropwizardmongo/health/MongoHealthCheck.java: -------------------------------------------------------------------------------- 1 | package com.eeb.dropwizardmongo.health; 2 | 3 | import com.codahale.metrics.health.HealthCheck; 4 | import com.mongodb.MongoClient; 5 | import com.mongodb.MongoClientException; 6 | 7 | /** 8 | * This HealthCheck checks if the MongoDB specified in the configuration file 9 | * is reachable. 10 | */ 11 | public class MongoHealthCheck extends HealthCheck { 12 | 13 | private final MongoClient mongoClient; 14 | 15 | public MongoHealthCheck(MongoClient mongoClient) { 16 | super(); 17 | this.mongoClient = mongoClient; 18 | } 19 | 20 | /** 21 | * Checks if the system database, which exists in all MongoDB instances can be reached. 22 | * @return A Result object 23 | * @throws Exception 24 | */ 25 | @Override 26 | protected Result check() throws Exception { 27 | 28 | try { 29 | mongoClient.getDB("system").getStats(); 30 | }catch(MongoClientException ex) { 31 | return Result.unhealthy(ex.getMessage()); 32 | } 33 | 34 | 35 | return Result.healthy(); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /dropwizard-mongo-example/src/main/java/com/eeb/dropwizardmongo/example/DropwizardMongoApplication.java: -------------------------------------------------------------------------------- 1 | package com.eeb.dropwizardmongo.example; 2 | 3 | import com.eeb.dropwizardmongo.configuration.DropwizardMongoConfiguration; 4 | import com.eeb.dropwizardmongo.health.MongoHealthCheck; 5 | import com.eeb.dropwizardmongo.example.resources.CollectionIdsResource; 6 | import com.mongodb.DB; 7 | import com.mongodb.MongoClient; 8 | import io.dropwizard.Application; 9 | import io.dropwizard.setup.Bootstrap; 10 | import io.dropwizard.setup.Environment; 11 | 12 | /** 13 | * Dropwizard application with DropwizardMongoConfiguration type. 14 | */ 15 | public class DropwizardMongoApplication extends Application { 16 | 17 | @Override 18 | public void initialize(Bootstrap bootstrap) { 19 | 20 | } 21 | 22 | @Override 23 | public void run(DropwizardMongoConfiguration config, Environment environment) throws Exception { 24 | 25 | final MongoClient mongoClient = config.getMongoFactory().buildClient(environment); 26 | final DB db = config.getMongoFactory().buildDB(environment); 27 | 28 | //Register health checks 29 | environment.healthChecks().register("mongo",new MongoHealthCheck(mongoClient)); 30 | 31 | //Register Resources 32 | environment.jersey().register(new CollectionIdsResource(db)); 33 | 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /dropwizard-mongo-example/src/main/java/com/eeb/dropwizardmongo/example/resources/CollectionIdsResource.java: -------------------------------------------------------------------------------- 1 | package com.eeb.dropwizardmongo.example.resources; 2 | 3 | import com.eeb.dropwizardmongo.example.api.MongoDocument; 4 | import com.mongodb.DB; 5 | import com.mongodb.MongoClient; 6 | import org.mongojack.DBCursor; 7 | import org.mongojack.JacksonDBCollection; 8 | 9 | import javax.ws.rs.*; 10 | import javax.ws.rs.core.MediaType; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | /** 15 | * Returns a list of Ids for the specified collection. 16 | */ 17 | @Path("/{collection}/") 18 | @Produces(MediaType.APPLICATION_JSON) 19 | @Consumes(MediaType.APPLICATION_JSON) 20 | public class CollectionIdsResource { 21 | 22 | 23 | private DB mongoDB; 24 | 25 | public CollectionIdsResource(DB mongoDB) { 26 | this.mongoDB = mongoDB; 27 | } 28 | 29 | @GET 30 | public List fetch(@PathParam("collection") String collection) { 31 | final JacksonDBCollection coll = JacksonDBCollection.wrap(mongoDB.getCollection(collection), MongoDocument.class, 32 | String.class); 33 | final DBCursor cursor = coll.find(); 34 | final List l = new ArrayList<>(); 35 | 36 | try { 37 | while(cursor.hasNext()) { 38 | l.add(cursor.next()); 39 | } 40 | }finally { 41 | cursor.close(); 42 | } 43 | 44 | return l; 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /dropwizard-mongo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | parent 7 | com.eeb.dropwizardmongo 8 | 0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | dropwizard-mongo 13 | 14 | jar 15 | 16 | 17 | 18 | io.dropwizard 19 | dropwizard-core 20 | ${dropwizard.version} 21 | 22 | 23 | org.mongodb 24 | mongo-java-driver 25 | 2.12.2 26 | 27 | 28 | 29 | org.mockito 30 | mockito-all 31 | 1.9.5 32 | test 33 | 34 | 35 | junit 36 | junit 37 | 4.10 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /dropwizard-mongo/src/main/java/com/eeb/dropwizardmongo/factory/ServerAddressBuilder.java: -------------------------------------------------------------------------------- 1 | package com.eeb.dropwizardmongo.factory; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import com.mongodb.ServerAddress; 5 | import io.dropwizard.setup.Environment; 6 | 7 | import javax.validation.constraints.Max; 8 | import javax.validation.constraints.Min; 9 | import javax.validation.constraints.NotNull; 10 | import java.net.UnknownHostException; 11 | 12 | /** 13 | * This class builds a Mongo ServerAddress object from a host and port specified in a configuration file. 14 | * 15 | */ 16 | public class ServerAddressBuilder { 17 | 18 | @NotNull 19 | private String host; 20 | 21 | @Min(1) 22 | @Max(65535) 23 | private int port; 24 | 25 | @JsonProperty 26 | public String getHost() { 27 | return host; 28 | } 29 | 30 | @JsonProperty 31 | public void setHost(String host) { 32 | this.host = host; 33 | } 34 | 35 | @JsonProperty 36 | public int getPort() { 37 | return port; 38 | } 39 | 40 | @JsonProperty 41 | public void setPort(int port) { 42 | this.port = port; 43 | } 44 | 45 | /** 46 | * Builds a Monog ServerAddress object for the MongoClient 47 | * @param env - The dropwizard Environment 48 | * @return A Mongo ServerAddress 49 | * 50 | */ 51 | public ServerAddress build(Environment env) throws UnknownHostException { 52 | 53 | return new ServerAddress(host,port); 54 | } 55 | 56 | 57 | 58 | 59 | 60 | } 61 | -------------------------------------------------------------------------------- /dropwizard-mongo-example/src/test/java/com/eeb/dropwizardmongo/test/ServerIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package com.eeb.dropwizardmongo.test; 2 | 3 | import com.eeb.dropwizardmongo.example.DropwizardMongoApplication; 4 | import com.eeb.dropwizardmongo.configuration.DropwizardMongoConfiguration; 5 | import com.eeb.dropwizardmongo.example.api.MongoDocument; 6 | import com.fasterxml.jackson.databind.ObjectMapper; 7 | import com.mongodb.BasicDBObject; 8 | import com.mongodb.DB; 9 | import com.mongodb.DBCollection; 10 | import com.mongodb.MongoClient; 11 | import com.sun.jersey.api.client.Client; 12 | import com.sun.jersey.api.client.ClientResponse; 13 | import io.dropwizard.testing.junit.DropwizardAppRule; 14 | import org.junit.*; 15 | 16 | import java.io.IOException; 17 | import java.net.UnknownHostException; 18 | import java.util.List; 19 | 20 | /** 21 | * End to end tests for the example. The configuration settings for 22 | * the MongoClient can be found in resources/config.yaml. 23 | * 24 | * 25 | */ 26 | public class ServerIntegrationTest { 27 | 28 | @ClassRule 29 | public static final DropwizardAppRule rule = 30 | new DropwizardAppRule<>(DropwizardMongoApplication.class, 31 | ClassLoader.getSystemClassLoader().getResource("config.yaml").getPath()); 32 | 33 | protected static MongoClient mongoClient; 34 | 35 | @BeforeClass 36 | public static void setup() throws UnknownHostException { 37 | mongoClient = rule.getConfiguration().getMongoFactory().buildClient(rule.getEnvironment()); 38 | } 39 | 40 | @Before 41 | public void before() { 42 | final DB test = mongoClient.getDB("test"); 43 | final DBCollection coll = test.getCollection("test"); 44 | coll.remove(new BasicDBObject()); 45 | 46 | coll.insert(new BasicDBObject()); 47 | coll.insert(new BasicDBObject()); 48 | 49 | } 50 | 51 | 52 | @Test 53 | public void getIds() throws IOException { 54 | 55 | final Client client = new Client(); 56 | 57 | final ClientResponse response = client.resource( 58 | "http://localhost:8080/test").get(ClientResponse.class); 59 | 60 | 61 | final ObjectMapper mapper = new ObjectMapper(); 62 | List mList = mapper.readValue(response.getEntity(String.class), List.class); 63 | 64 | assert mList.size() == 2 : "There are only " + mList.size() + " documents in the collection. Expected 2"; 65 | 66 | 67 | } 68 | 69 | 70 | } 71 | -------------------------------------------------------------------------------- /dropwizard-mongo/src/test/java/com/eeb/dropwizardmongo/test/FactoryIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package com.eeb.dropwizardmongo.test; 2 | 3 | import com.codahale.metrics.health.HealthCheck; 4 | import com.eeb.dropwizardmongo.exceptions.NullCollectionNameException; 5 | import com.eeb.dropwizardmongo.exceptions.NullDBNameException; 6 | import com.eeb.dropwizardmongo.factory.MongoFactory; 7 | import com.eeb.dropwizardmongo.factory.ServerAddressBuilder; 8 | import com.eeb.dropwizardmongo.health.MongoHealthCheck; 9 | import com.fasterxml.jackson.databind.ObjectMapper; 10 | import com.mongodb.DB; 11 | import com.mongodb.DBCollection; 12 | import com.mongodb.MongoClient; 13 | import io.dropwizard.lifecycle.setup.LifecycleEnvironment; 14 | import io.dropwizard.setup.Environment; 15 | import org.junit.Before; 16 | import org.junit.Test; 17 | 18 | import java.io.IOException; 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | 22 | import static org.mockito.Mockito.mock; 23 | import static org.mockito.Mockito.when; 24 | 25 | /** 26 | * Integration test for the factory classes. The test will require an available Mongo instance. 27 | */ 28 | public class FactoryIntegrationTest { 29 | 30 | private final LifecycleEnvironment lEnv = mock(LifecycleEnvironment.class); 31 | private final Environment env = mock(Environment.class); 32 | private final ObjectMapper mapper = new ObjectMapper(); 33 | private final String port = "27017"; 34 | private final String config = "{" + 35 | "\"connections\":[{\"host\":\"localhost\",\"port\":"+port+"}]," + 36 | "\"dbName\":\"unittest\"," + 37 | "\"collName\":\"test1\"" + 38 | "}"; 39 | 40 | 41 | @Before 42 | public void before() { 43 | when(env.lifecycle()).thenReturn(lEnv); 44 | } 45 | 46 | 47 | @Test 48 | public void singleAddressClientTest() throws IOException { 49 | final MongoFactory mongoFactory = mapper.readValue(config, MongoFactory.class); 50 | final MongoClient client = mongoFactory.buildClient(env); 51 | assert client != null : "Mongo client is null"; 52 | assert client.getAddress().toString().equals("localhost:"+port+"") : "Client does not contain an address"; 53 | 54 | } 55 | 56 | //@Test 57 | //TODO:Setup a replica 58 | public void multipleAddressTest() throws IOException { 59 | 60 | 61 | } 62 | 63 | @Test 64 | public void testHealthCheck() throws IOException { 65 | final MongoFactory mongoFactory = mapper.readValue(config, MongoFactory.class); 66 | final MongoClient client = mongoFactory.buildClient(env); 67 | assert client != null : "Mongo client is null"; 68 | 69 | final MongoHealthCheck hc = new MongoHealthCheck(client); 70 | final HealthCheck.Result res = hc.execute(); 71 | assert res.isHealthy() : "Mongo is not connected"; 72 | } 73 | 74 | @Test 75 | public void testDBFactory() throws IOException, NullDBNameException { 76 | 77 | final MongoFactory mongoFactory = mapper.readValue(config, MongoFactory.class); 78 | final DB db = mongoFactory.buildDB(env); 79 | assert db != null : "Database object was not created"; 80 | 81 | } 82 | 83 | @Test 84 | public void testCollectionFactory() throws IOException, NullDBNameException, NullCollectionNameException { 85 | 86 | final MongoFactory mongoFactory = mapper.readValue(config, MongoFactory.class); 87 | final DBCollection coll = mongoFactory.buildColl(env); 88 | assert coll != null : "Database object was not created"; 89 | 90 | } 91 | 92 | 93 | 94 | 95 | 96 | } 97 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | com.eeb.dropwizardmongo 7 | parent 8 | 0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | pom 13 | 14 | 15 | dropwizard-mongo-example 16 | dropwizard-mongo 17 | 18 | 19 | 20 | 0.7.1 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | org.apache.maven.plugins 29 | maven-jar-plugin 30 | 2.5 31 | 32 | 33 | 34 | 35 | 36 | org.apache.maven.plugins 37 | maven-jar-plugin 38 | 39 | 40 | 41 | true 42 | 43 | 44 | 45 | 46 | 47 | maven-compiler-plugin 48 | 3.1 49 | 50 | 1.8 51 | 1.8 52 | 53 | 54 | 55 | com.github.joelittlejohn.embedmongo 56 | embedmongo-maven-plugin 57 | 0.1.12 58 | 59 | 60 | start 61 | 62 | start 63 | 64 | 65 | 66 | stop 67 | 68 | stop 69 | 70 | 71 | 72 | 73 | 74 | org.apache.maven.plugins 75 | maven-surefire-plugin 76 | 2.17 77 | 78 | true 79 | 80 | 81 | 82 | unit-test 83 | test 84 | 85 | test 86 | 87 | 88 | 89 | **/*Integration*.java 90 | 91 | false 92 | 93 | 94 | 95 | integration-test 96 | integration-test 97 | 98 | test 99 | 100 | 101 | 102 | **/*Integration*.java 103 | 104 | false 105 | 106 | 107 | 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /dropwizard-mongo-example/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | parent 7 | com.eeb.dropwizardmongo 8 | 0.1-SNAPSHOT 9 | ../ 10 | 11 | 4.0.0 12 | 13 | example 14 | 15 | 16 | 17 | com.eeb.dropwizardmongo 18 | dropwizard-mongo 19 | ${project.version} 20 | 21 | 22 | io.dropwizard 23 | dropwizard-core 24 | ${dropwizard.version} 25 | 26 | 27 | io.dropwizard 28 | dropwizard-testing 29 | ${dropwizard.version} 30 | 31 | 32 | org.mongodb 33 | mongo-java-driver 34 | 2.12.2 35 | 36 | 37 | org.mongojack 38 | mongojack 39 | 2.1.0 40 | 41 | 42 | com.fasterxml.jackson.core 43 | jackson-databind 44 | 45 | 46 | 47 | 52 | 53 | com.fasterxml.jackson.core 54 | jackson-databind 55 | 2.3.3 56 | 57 | 58 | 59 | org.mockito 60 | mockito-all 61 | 1.9.5 62 | test 63 | 64 | 65 | junit 66 | junit 67 | 4.10 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | org.apache.maven.plugins 77 | maven-shade-plugin 78 | 1.6 79 | 80 | true 81 | 82 | 83 | *:* 84 | 85 | META-INF/*.SF 86 | META-INF/*.DSA 87 | META-INF/*.RSA 88 | 89 | 90 | 91 | 92 | 93 | 94 | package 95 | 96 | shade 97 | 98 | 99 | 100 | 102 | 104 | com.eeb.dropwizardmongo.example.DropwizardMongoApplication 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | oss-sonatype 117 | oss-sonatype 118 | https://oss.sonatype.org/content/repositories/snapshots/ 119 | 120 | true 121 | 122 | 123 | 124 | 125 | 126 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #Connect dropwizard to MongoDB 2 | 3 | 4 | *dropwizard-mongo is a set of factories and health checks to be used with [dropwizard](http://dropwizard.github.io/dropwizard/) for connecting to MongoDB.* 5 | 6 | ## Disclaimer 7 | Update 8/1: Major refactor that simplifies usage. Thanks to [kgilmer](https://github.com/kgilmer) for the review. 8 | This project is brand new, so I have a lot of additional work to support the multiple options that can be passed to the MongoClient, DB, and DBCollection objects. 9 | 10 | ##Usage 11 | 12 | ### Installation 13 | 14 | The project artifacts are not currently hosted in a maven repository, so you will need to clone the repo and build the dropwizard-mongo project at a minimum. 15 | 16 | I recommend you use dropwizard-mongo in combination with the [MongoJack](http://mongojack.org/) project for quickest implementation. The dropwizard-mongo-example project shows an example of using MongoJack with dropwizard-mongo. 17 | 18 | ### Updating Your yaml 19 | 20 | If you want the factory to build a [MongoClient](https://api.mongodb.org/java/current/com/mongodb/MongoClient.html) object you can specify the connections in you config file. 21 | 22 | mongoDB: 23 | connections: 24 | - host: localhost 25 | port: 27017 26 | - host: 192.168.1.12 27 | port: 27017 28 | 29 | If you want to the factory to build a [DB](https://api.mongodb.org/java/current/com/mongodb/DB.html) object you will need to further specify the db name in the config. 30 | 31 | mongoDB: 32 | dbName: unittest 33 | connections: 34 | - host: localhost 35 | port: 27017 36 | - host: 192.168.1.12 37 | port: 27017 38 | 39 | Finally, the factory can return a [DBCollection](https://api.mongodb.org/java/current/com/mongodb/DBCollection.html) object 40 | you will need to further specify the collection name in the config. 41 | 42 | mongoDB: 43 | dbName: unittest 44 | collName: test 45 | connections: 46 | - host: localhost 47 | port: 27017 48 | - host: 192.168.1.12 49 | port: 27017 50 | 51 | 52 | ### Updating you configuration 53 | You will need to add a reference to MongoFactory in your class that extends Configuration or 54 | you can extend from com.eeb.dropwizardmongo.configuration.DropwizardMongoConfiguration. 55 | 56 | @Valid 57 | @NotNull 58 | private MongoFactory mongoFactory = new MongoFactory(); 59 | 60 | @JsonProperty("mongoDB") 61 | public MongoFactory getMongoFactory() { 62 | return this.mongoFactory; 63 | } 64 | 65 | @JsonProperty("mongoDB") 66 | public void setMongoFactory(MongoFactory MongoFactory) { 67 | this.mongoFactory = MongoFactory; 68 | } 69 | 70 | 71 | 72 | ### Update your applications run method 73 | Your class that extends from Application needs to be updated to register the health checks and call the 74 | factory method you wish to use. Once you have the object you want you can pass it to your dropwizard resources. 75 | 76 | #### Registering the health checks 77 | final MongoClient mongoClient = config.getMongoFactory().buildClient(environment); 78 | environment.healthChecks().register("mongo",new MongoHealthCheck(mongoClient)); 79 | 80 | #### Building a MongoClient object 81 | final MongoClient mongoClient = config.getMongoFactory().buildClient(environment); 82 | //Register Resources 83 | environment.jersey().register(new CollectionIdsResource(mongoClient)); 84 | 85 | #### Building a DB object 86 | final DB db = config.getMongoFactory().buildDB(environment); 87 | //Register Resources 88 | environment.jersey().register(new CollectionIdsResource(db)); 89 | 90 | #### Building a DBCollection object 91 | final DBCollection coll = config.getMongoFactory().buildColl(environment); 92 | //Register Resources 93 | environment.jersey().register(new CollectionIdsResource(coll)); 94 | 95 | ### Using MongoJack with dropwizard-mongo 96 | 97 | The secret sauce here is MongoJack. It lets me pass my Jackson API objects directly to the MongoDB API as well as returning the results of queries as my API objects. 98 | 99 | Super basic API object representing a MongoDB document: 100 | 101 | public class MongoDocument { 102 | 103 | private String id; 104 | 105 | @ObjectId 106 | @JsonProperty("_id") 107 | public String getId() { 108 | return this.id; 109 | } 110 | 111 | @ObjectId 112 | @JsonProperty("_id") 113 | public void setId(String id) { 114 | this.id = id; 115 | } 116 | 117 | } 118 | 119 | My Resource's GET handler. 120 | 121 | @GET 122 | public List fetch(@PathParam("collection") String collection) { 123 | 124 | JacksonDBCollection coll = JacksonDBCollection.wrap(mongoDB.getCollection(collection), MongoDocument.class, 125 | String.class); 126 | DBCursor cursor = coll.find(); 127 | 128 | List l = new ArrayList<>(); 129 | 130 | try { 131 | while(cursor.hasNext()) { 132 | l.add(cursor.next()); 133 | } 134 | }finally { 135 | cursor.close(); 136 | } 137 | 138 | return l; 139 | } 140 | 141 | MongoJack provides wrappers for the standard MongoDB api calls that will parse MongoDB documents into objects that are Jackson annotated. 142 | 143 | -------------------------------------------------------------------------------- /dropwizard-mongo/src/main/java/com/eeb/dropwizardmongo/factory/MongoFactory.java: -------------------------------------------------------------------------------- 1 | package com.eeb.dropwizardmongo.factory; 2 | 3 | import com.eeb.dropwizardmongo.exceptions.NullCollectionNameException; 4 | import com.eeb.dropwizardmongo.exceptions.NullDBNameException; 5 | import com.fasterxml.jackson.annotation.JsonProperty; 6 | import com.mongodb.DB; 7 | import com.mongodb.DBCollection; 8 | import com.mongodb.MongoClient; 9 | import com.mongodb.ServerAddress; 10 | import io.dropwizard.lifecycle.Managed; 11 | import io.dropwizard.setup.Environment; 12 | import org.hibernate.validator.constraints.NotEmpty; 13 | 14 | import java.net.UnknownHostException; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | /** 19 | * An object of this class creates a single instance of the MongoClient object. 20 | *

21 | * To use this class add it as a field with getters and setters to your Configuration class and call the buildClient 22 | * method in your applications run method. The resulting MongoClient can then be passed to your Resources
23 | *

24 | * An example of the yaml configuration:
25 | *
26 | *


 27 |  *     mongoClient:
 28 |  *         dbname: unittest
 29 |  *         collName: test1
 30 |  *         connections:
 31 |  *            - host: localhost
 32 |  *              port: 27017
 33 |  *            - host: 192.168.1.12
 34 |  *              port: 27017
 35 |  *     
36 | *

37 | *

38 | */ 39 | public class MongoFactory { 40 | 41 | /** 42 | * List of server addresses 43 | */ 44 | @NotEmpty 45 | private List connections = new ArrayList<>(); 46 | 47 | /** 48 | * Optional name of the database. This property is required to use the dbBuild method. 49 | */ 50 | private String dbName; 51 | 52 | /** 53 | * Optional name of the collection to be set. The property is required to use the collBuild method. 54 | */ 55 | private String collName; 56 | 57 | /** 58 | * The mongo API documentation for 59 | * MongoClient states that there should only be one object per JVM, so this property is only set once. 60 | */ 61 | private MongoClient mongoClient; 62 | 63 | @JsonProperty 64 | public String getCollName() { 65 | return collName; 66 | } 67 | 68 | @JsonProperty 69 | public void setCollName(String collName) { 70 | this.collName = collName; 71 | } 72 | 73 | @JsonProperty 74 | public String getDbName() { 75 | return dbName; 76 | } 77 | 78 | @JsonProperty 79 | public void setDbName(String dbName) { 80 | this.dbName = dbName; 81 | } 82 | 83 | @JsonProperty 84 | public List getConnections() { 85 | return connections; 86 | } 87 | 88 | @JsonProperty 89 | public void setConnections(List connections) { 90 | this.connections = connections; 91 | } 92 | 93 | /** 94 | * Builds the MongoClient from a set of connections specified in the 95 | * configuration file. 96 | * @param env Dropwizard environment. 97 | * @return A Mongo API {@code MongoClient} object. 98 | * @throws {@link UnknownHostException} Thrown if the server can not be found. 99 | */ 100 | public MongoClient buildClient(Environment env) throws UnknownHostException { 101 | 102 | if(this.mongoClient != null) 103 | return mongoClient; 104 | 105 | final MongoClient client = new MongoClient(buildServerAddresses(getConnections(),env)); 106 | 107 | env.lifecycle().manage(new Managed() { 108 | @Override 109 | public void start() throws Exception { 110 | 111 | } 112 | 113 | @Override 114 | public void stop() throws Exception { 115 | client.close(); 116 | } 117 | }); 118 | 119 | this.mongoClient = client; 120 | 121 | return client; 122 | 123 | } 124 | 125 | /** 126 | * Builds a Mongo {@code DB} object from connection and db info set in a configuration file. 127 | * @param env The dropwizard environment. 128 | * @return A Mongo Java API {@code DB} object. 129 | * @throws {@link UnknownHostException} Thrown if the server can not be found. 130 | * @throws {@link com.eeb.dropwizardmongo.exceptions.NullDBNameException} Throw in the db name is null. 131 | */ 132 | public DB buildDB(Environment env) throws UnknownHostException, NullDBNameException { 133 | if(this.dbName == null) 134 | throw new NullDBNameException(); 135 | 136 | final MongoClient client = buildClient(env); 137 | return client.getDB(this.dbName); 138 | } 139 | 140 | /** 141 | * Builds a Mongo {@code DBCollection} object from connection, db, and collection information set in a 142 | * configuration file 143 | * @param env The dropwizard environment. 144 | * @return A Mongo Java API {@code DBCollection} object. 145 | * @throws {@link UnknownHostException} Thrown if the server can not be found. 146 | * @throws {@link com.eeb.dropwizardmongo.exceptions.NullDBNameException} Throw in the db name is null. 147 | * @throws {@link NullCollectionNameException} Thrown if the collection name is null. 148 | */ 149 | public DBCollection buildColl(Environment env) throws UnknownHostException,NullDBNameException, NullCollectionNameException { 150 | if(this.dbName == null) 151 | throw new NullDBNameException(); 152 | 153 | if(this.collName == null) 154 | throw new NullCollectionNameException(); 155 | 156 | final DB db = buildDB(env); 157 | return db.getCollection(this.collName); 158 | 159 | } 160 | 161 | 162 | private List buildServerAddresses(List conns, Environment env) throws UnknownHostException { 163 | final List sal = new ArrayList<>(conns.size()); 164 | for(ServerAddressBuilder factory : conns) { 165 | sal.add(factory.build(env)); 166 | } 167 | 168 | return sal; 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2010-2013 Coda Hale and Yammer, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------