Skip to content

Commit

Permalink
Merge pull request dropwizard#49 from wolfeidau/master
Browse files Browse the repository at this point in the history
Add JDBI usage to dropwizard-example
  • Loading branch information
codahale committed Mar 12, 2012
2 parents 318a5a5 + 7b0dd6c commit ec419a3
Show file tree
Hide file tree
Showing 12 changed files with 281 additions and 1 deletion.
2 changes: 2 additions & 0 deletions .gitignore
Expand Up @@ -2,3 +2,5 @@
target
atlassian-ide-plugin.xml
logs
*.iml
*.ipr
41 changes: 41 additions & 0 deletions dropwizard-example/README.md
@@ -0,0 +1,41 @@
# Introduction

The drop wizard example application was developed to, as its name implies, provide examples of some of the features
present in drop wizard.

# Overview

Included with this application is an example of the optional db API module. The examples provided illustrate a few of
the features available in (JDBI)[http://jdbi.org], along with demonstrating how these are used from within dropwizard.

This database example is comprised of the following classes.

* The `PersonDAO` illustrates using the [SQL Object Queries](http://jdbi.org/sql_object_api_queries/) and string template
features in JDBI.

* The `PeopleDAO.sql.stg` stores all the SQL statements for use in the `PersonDAO`, note this is located in the
src/resources under the same path as the `PersonDAO` class file.

* The `SetupDatabaseCommand` illustrates building a "setup" command which can create your database prior to running
dropwizard your application for the first time.

* The `PersonResource` and `PeopleResource` are the REST resource which use the PersonDAO to retrieve data from the database, note the injection
of the PersonDAO in their constructors.

As with all the modules the db example is wired up in the `initialize` function of the `HelloWorldService`.

# Running The Application

To test the example application run the following commands.

* To package the example run.

mvn package

* To setup the h2 database run.

java -jar target/dropwizard-example-0.3.0-SNAPSHOT.jar setup example.yml

* To run the server run.

java -jar target/dropwizard-example-0.3.0-SNAPSHOT.jar server example.yml
15 changes: 15 additions & 0 deletions dropwizard-example/example.yml
Expand Up @@ -2,6 +2,21 @@ template: Hello, %s!

defaultName: Stranger

# Database settings.
database:

# the name of your JDBC driver
driverClass: org.h2.Driver

# the username
user: sa

# the password
password: sa

# the JDBC URL
url: jdbc:h2:target/example

# HTTP-specific options.
http:

Expand Down
17 changes: 17 additions & 0 deletions dropwizard-example/pom.xml
Expand Up @@ -25,6 +25,23 @@
<artifactId>dropwizard-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.yammer.dropwizard</groupId>
<artifactId>dropwizard-db</artifactId>
<version>${project.version}</version>
</dependency>
<!-- Required to support string templates in JDBI -->
<dependency>
<groupId>org.antlr</groupId>
<artifactId>stringtemplate</artifactId>
<version>3.2.1</version>
</dependency>
<!-- Small self contained database to illustrate the features of JDBI -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.158</version>
</dependency>
<dependency>
<groupId>com.yammer.dropwizard</groupId>
<artifactId>dropwizard-auth</artifactId>
Expand Down
Expand Up @@ -2,16 +2,27 @@

import com.example.helloworld.core.Template;
import com.yammer.dropwizard.config.Configuration;
import com.yammer.dropwizard.db.DatabaseConfiguration;
import org.codehaus.jackson.annotate.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

@SuppressWarnings("FieldMayBeFinal")
public class HelloWorldConfiguration extends Configuration {

@NotEmpty
private String template;

@NotEmpty
private String defaultName = "Stranger";

@Valid
@NotNull
@JsonProperty
private DatabaseConfiguration database = new DatabaseConfiguration();

public String getTemplate() {
return template;
}
Expand All @@ -23,4 +34,8 @@ public String getDefaultName() {
public Template buildTemplate() {
return new Template(template, defaultName);
}

public DatabaseConfiguration getDatabaseConfiguration() {
return database;
}
}
Expand Up @@ -2,15 +2,21 @@

import com.example.helloworld.auth.ExampleAuthenticator;
import com.example.helloworld.cli.RenderCommand;
import com.example.helloworld.cli.SetupDatabaseCommand;
import com.example.helloworld.core.Template;
import com.example.helloworld.core.User;
import com.example.helloworld.db.PeopleDAO;
import com.example.helloworld.health.TemplateHealthCheck;
import com.example.helloworld.resources.HelloWorldResource;
import com.example.helloworld.resources.PeopleResource;
import com.example.helloworld.resources.PersonResource;
import com.example.helloworld.resources.ProtectedResource;
import com.yammer.dropwizard.Service;
import com.yammer.dropwizard.auth.basic.BasicAuthBundle;
import com.yammer.dropwizard.bundles.AssetsBundle;
import com.yammer.dropwizard.config.Environment;
import com.yammer.dropwizard.db.Database;
import com.yammer.dropwizard.db.DatabaseFactory;

public class HelloWorldService extends Service<HelloWorldConfiguration> {
public static void main(String[] args) throws Exception {
Expand All @@ -20,18 +26,27 @@ public static void main(String[] args) throws Exception {
private HelloWorldService() {
super("hello-world");
addCommand(new RenderCommand());
addCommand(new SetupDatabaseCommand());
addBundle(new AssetsBundle());
addBundle(new BasicAuthBundle<User>(new ExampleAuthenticator(), "SUPER SECRET STUFF"));
}

@Override
protected void initialize(HelloWorldConfiguration configuration,
Environment environment) {
Environment environment) throws ClassNotFoundException{
final Template template = configuration.buildTemplate();

final DatabaseFactory factory = new DatabaseFactory(environment);
final Database db = factory.build(configuration.getDatabaseConfiguration(), "h2");
final PeopleDAO peopleDAO = db.onDemand(PeopleDAO.class);


environment.addHealthCheck(new TemplateHealthCheck(template));
environment.addResource(new HelloWorldResource(template));
environment.addResource(new ProtectedResource());

environment.addResource(new PeopleResource(peopleDAO));
environment.addResource(new PersonResource(peopleDAO));
}

}
@@ -0,0 +1,33 @@
package com.example.helloworld.cli;

import com.example.helloworld.HelloWorldConfiguration;
import com.example.helloworld.db.PeopleDAO;
import com.yammer.dropwizard.AbstractService;
import com.yammer.dropwizard.cli.ConfiguredCommand;
import com.yammer.dropwizard.config.Environment;
import com.yammer.dropwizard.db.Database;
import com.yammer.dropwizard.db.DatabaseFactory;
import com.yammer.dropwizard.logging.Log;
import org.apache.commons.cli.CommandLine;

public class SetupDatabaseCommand extends ConfiguredCommand<HelloWorldConfiguration> {

public SetupDatabaseCommand() {
super("setup", "Setup the database.");
}

@Override
protected void run(AbstractService<HelloWorldConfiguration> service, HelloWorldConfiguration configuration, CommandLine params) throws Exception {

final Log log = Log.forClass(SetupDatabaseCommand.class);
final Environment environment = new Environment(configuration, service);
//service.initializeWithBundles(configuration, environment);
final DatabaseFactory factory = new DatabaseFactory(environment);
final Database db = factory.build(configuration.getDatabaseConfiguration(), "h2");
final PeopleDAO peopleDAO = db.onDemand(PeopleDAO.class);

log.info("creating tables.");
peopleDAO.createPeopleTable();

}
}
@@ -0,0 +1,32 @@
package com.example.helloworld.core;

public class Person {

private long id;
private String fullName;
private String jobTitle;

public long getId() {
return id;
}

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

public String getFullName() {
return fullName;
}

public void setFullName(String fullName) {
this.fullName = fullName;
}

public String getJobTitle() {
return jobTitle;
}

public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
}
@@ -0,0 +1,31 @@
package com.example.helloworld.db;

import com.example.helloworld.core.Person;
import com.google.common.collect.ImmutableList;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.BindBean;
import org.skife.jdbi.v2.sqlobject.GetGeneratedKeys;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapperFactory;
import org.skife.jdbi.v2.sqlobject.stringtemplate.ExternalizedSqlViaStringTemplate3;
import org.skife.jdbi.v2.tweak.BeanMapperFactory;

@ExternalizedSqlViaStringTemplate3
@RegisterMapperFactory(BeanMapperFactory.class)
public interface PeopleDAO {

@SqlUpdate
void createPeopleTable();

@SqlQuery
Person findById(@Bind("id") Long id);

@SqlUpdate
@GetGeneratedKeys
long create(@BindBean Person person);

@SqlQuery
ImmutableList<Person> findAll();

}
@@ -0,0 +1,34 @@
package com.example.helloworld.resources;

import com.example.helloworld.core.Person;
import com.example.helloworld.db.PeopleDAO;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;

@Path("/people")
@Produces(MediaType.APPLICATION_JSON)
public class PeopleResource {

private final PeopleDAO peopleDAO;

public PeopleResource(PeopleDAO peopleDAO) {
this.peopleDAO = peopleDAO;
}

@POST
public Person createPerson(Person person) {
final long personId = peopleDAO.create(person);
return peopleDAO.findById(personId);
}

@GET
public List<Person> listPeople() {
return peopleDAO.findAll();
}

}
@@ -0,0 +1,28 @@
package com.example.helloworld.resources;

import com.example.helloworld.core.Person;
import com.example.helloworld.db.PeopleDAO;
import com.yammer.dropwizard.jersey.params.LongParam;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/person/{personId}")
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource {

private final PeopleDAO peopleDAO;

public PersonResource(PeopleDAO peopleDAO) {
this.peopleDAO = peopleDAO;
}

@GET
public Person getPerson(@PathParam("personId") LongParam personId) {
return peopleDAO.findById(personId.get());
}

}
@@ -0,0 +1,17 @@
group PeopleDAO;

createPeopleTable() ::= <<
create table people (id Serial primary key, fullName varchar(255), jobTitle varchar(100))
>>

findById(id) ::= <<
select id, fullName, jobTitle from people where id = :id
>>

create() ::= <<
insert into people (fullName, jobTitle) values (:fullName, :jobTitle)
>>

findAll() ::= <<
select id, fullName, jobTitle from people
>>

0 comments on commit ec419a3

Please sign in to comment.