Instantly share code, notes, and snippets.

What would you like to do?
package jmodern;
import com.codahale.metrics.*;
import com.codahale.metrics.annotation.*;
import com.fasterxml.jackson.annotation.*;
import dagger.Module;
import dagger.ObjectGraph;
import dagger.Provides;
import io.dropwizard.Application;
import io.dropwizard.*;
import io.dropwizard.db.*;
import io.dropwizard.setup.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import javax.inject.Inject;
import javax.inject.Named;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.*;
public class Main extends Application<Main.JModernConfiguration> {
public static void main(String[] args) throws Exception {
new Main().run(new String[]{"server", System.getProperty("dropwizard.config")});
public void initialize(Bootstrap<JModernConfiguration> bootstrap) {
public void run(JModernConfiguration cfg, Environment env) throws ClassNotFoundException {
JmxReporter.forRegistry(env.metrics()).build().start(); // Manually add JMX reporting (Dropwizard regression)
ObjectGraph objectGraph = ObjectGraph.create(new ModernModule(cfg));
// YAML Configuration
public static class JModernConfiguration extends Configuration {
@JsonProperty private @NotEmpty String template;
@JsonProperty private @NotEmpty String defaultName;
@Valid @NotNull @JsonProperty private DataSourceFactory database = new DataSourceFactory();
public DataSourceFactory getDataSourceFactory() { return database; }
public String getTemplate() { return template; }
public String getDefaultName() { return defaultName; }
@Module(injects = HelloWorldResource.class)
class ModernModule {
private final JModernConfiguration cfg;
public ModernModule(JModernConfiguration cfg) {
this.cfg = cfg;
@Provides @Named("template") String provideTemplate() {
return cfg.getTemplate();
@Provides @Named("defaultName") String provideDefaultName() {
return cfg.getDefaultName();
public static class HelloWorldResource {
private final AtomicLong counter = new AtomicLong();
@Inject @Named("template") String template;
@Inject @Named("defaultName") String defaultName;
HelloWorldResource() {
@Timed // monitor timing of this service with Metrics
public Saying sayHello(@QueryParam("name") Optional<String> name) throws InterruptedException {
final String value = String.format(template, name.or(defaultName));
Thread.sleep(ThreadLocalRandom.current().nextInt(10, 500));
return new Saying(counter.incrementAndGet(), value);
// JSON (immutable!) payload
public static class Saying {
private long id;
private @Length(max = 10) String content;
public Saying(long id, String content) { = id;
this.content = content;
public Saying() {} // required for deserialization
@JsonProperty public long getId() { return id; }
@JsonProperty public String getContent() { return content; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment