Skip to content

Instantly share code, notes, and snippets.

@mariagomez
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mariagomez/a0e1011bfb8b0cca0c9d to your computer and use it in GitHub Desktop.
Save mariagomez/a0e1011bfb8b0cca0c9d to your computer and use it in GitHub Desktop.
Dropwizard + Flyway using its API
package com.example.helloworld.core;
import org.hibernate.annotations.*;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.List;
@Entity
@Table(name = "companies")
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "name", nullable = false)
private String name;
@OneToMany
@JoinColumn(name = "company_id")
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
private List<Person> employees;
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setId(long id) {
this.id = id;
}
public List<Person> getEmployees() {
return employees;
}
public void setEmployees(List<Person> employees) {
this.employees = employees;
}
}
package com.example.helloworld.dao;
import com.example.helloworld.core.Company;
import io.dropwizard.hibernate.AbstractDAO;
import org.hibernate.SessionFactory;
public class CompanyDAO extends AbstractDAO<Company> {
public CompanyDAO(SessionFactory sessionFactory) {
super(sessionFactory);
}
public Company create(Company company) {
return persist(company);
}
}
package com.example.helloworld.resources;
import com.example.helloworld.core.Company;
import com.example.helloworld.dao.CompanyDAO;
import io.dropwizard.hibernate.UnitOfWork;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/company")
@Produces(MediaType.APPLICATION_JSON)
public class CompanyResource {
private CompanyDAO companyDAO;
public CompanyResource(CompanyDAO companyDAO) {
this.companyDAO = companyDAO;
}
@POST
@UnitOfWork
public Response create(Company company) {
Company newCompany = companyDAO.create(company);
return Response.status(Response.Status.CREATED).entity(newCompany).build();
}
}
package com.example.helloworld.resources;
import com.example.helloworld.HelloWorldApplication;
import com.example.helloworld.HelloWorldConfiguration;
import com.example.helloworld.core.Company;
import com.google.common.io.Resources;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.junit.ClassRule;
import org.junit.Test;
import java.io.File;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class CompanyResourceTest {
@ClassRule
public static final DropwizardAppRule<HelloWorldConfiguration> RULE = new DropwizardAppRule<>(HelloWorldApplication.class, resourceFilePath("hello-world.yml"));
private static final String COMPANY_REQUEST = "{\"name\":\"test company\", \"employees\":[{\"name\": \"test founder\"}]}";
@Test
public void shouldCreateANewCompanyWithFounder() {
Client client = new Client();
ClientResponse response = client.resource(String.format("http://localhost:%d/company", RULE.getLocalPort()))
.header("Content-Type", "application/json")
.post(ClientResponse.class, COMPANY_REQUEST);
assertThat(response.getStatus(), is(201));
Company newCompany = response.getEntity(Company.class);
assertThat(newCompany.getId(), is(not(0l)));
assertThat(newCompany.getEmployees().get(0).getId(), is(not(0l)));
}
public static String resourceFilePath(String resourceClassPathLocation) {
try {
return new File(Resources.getResource(resourceClassPathLocation).toURI()).getAbsolutePath();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
template: Hello, %s!
defaultName: Stranger
database:
# the name of your JDBC driver
driverClass: org.postgresql.Driver
# the username
user: testowner
# the password
password: password
# the JDBC URL
url: jdbc:postgresql://localhost/mycompany
# any properties specific to your JDBC driver:
properties:
charSet: UTF-8
hibernate.dialect: org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql: true
# the maximum amount of time to wait on an empty pool before throwing an exception
maxWaitForConnection: 1s
# the SQL query to run when validating a connection's liveness
validationQuery: "/* Servicio Usuario Health Check */ SELECT 1"
# the minimum number of connections to keep open
minSize: 8
# the maximum number of connections to keep open
maxSize: 32
# whether or not idle connections should be validated
checkConnectionWhileIdle: false
package com.example.helloworld;
import com.example.helloworld.core.Company;
import com.example.helloworld.core.Person;
import com.example.helloworld.dao.CompanyDAO;
import com.example.helloworld.health.TemplateHealthCheck;
import com.example.helloworld.resources.CompanyResource;
import com.example.helloworld.resources.HelloWorldResource;
import io.dropwizard.Application;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.hibernate.HibernateBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
public class HelloWorldApplication extends Application<HelloWorldConfiguration> {
private final HibernateBundle<HelloWorldConfiguration> hibernate = new HibernateBundle<HelloWorldConfiguration>(Company.class, Person.class) {
@Override
public DataSourceFactory getDataSourceFactory(HelloWorldConfiguration configuration) {
return configuration.getDataSourceFactory();
}
};
public static void main(String[] args) throws Exception {
new HelloWorldApplication().run(args);
}
@Override
public String getName() {
return "hello-world";
}
@Override
public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {
bootstrap.addBundle(hibernate);
}
@Override
public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {
final HelloWorldResource resource = new HelloWorldResource(
configuration.getTemplate(),
configuration.getDefaultName()
);
CompanyResource companyResource = new CompanyResource(new CompanyDAO(hibernate.getSessionFactory()));
final TemplateHealthCheck healthCheck =
new TemplateHealthCheck(configuration.getTemplate());
environment.healthChecks().register("template", healthCheck);
environment.jersey().register(resource);
environment.jersey().register(companyResource);
}
}
package com.example.helloworld;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import io.dropwizard.db.DataSourceFactory;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
public class HelloWorldConfiguration extends Configuration {
@NotEmpty
private String template;
@NotEmpty
private String defaultName = "Stranger";
@Valid
@NotNull
private DataSourceFactory database = new DataSourceFactory();
@JsonProperty
public String getTemplate() {
return template;
}
@JsonProperty
public void setTemplate(String template) {
this.template = template;
}
@JsonProperty
public String getDefaultName() {
return defaultName;
}
@JsonProperty
public void setDefaultName(String name) {
this.defaultName = name;
}
@JsonProperty("database")
public DataSourceFactory getDataSourceFactory() {
return database;
}
@JsonProperty("database")
public void setDataSourceFactory(DataSourceFactory dataSourceFactory) {
this.database = dataSourceFactory;
}
}
CREATE TABLE companies (id serial primary key,name text);
ALTER TABLE companies OWNER TO testowner;
CREATE TABLE people (id serial primary key,name text, company_id integer NOT NULL references companies(id));
ALTER TABLE people OWNER TO testowner;
package com.example.helloworld.core;
import javax.persistence.*;
@Entity
@Table(name = "people")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "name", nullable = false)
private String name;
@ManyToOne(optional = false)
private Company company;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment