Skip to content

Commit

Permalink
Set up REST API to conform to test harness conventions
Browse files Browse the repository at this point in the history
  • Loading branch information
nvanbenschoten committed Jan 27, 2017
1 parent 1c5725d commit 8aacfca
Show file tree
Hide file tree
Showing 12 changed files with 460 additions and 47 deletions.
6 changes: 5 additions & 1 deletion java/hibernate/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
#
# Author: Nathan VanBenschoten ([email protected])

ifneq ($(ADDR),)
ADDRFLAG = -PappArgs="['-addr', '$(ADDR)']"
endif

.PHONY: start
start:
@gradle run
@gradle run $(ADDRFLAG)
14 changes: 13 additions & 1 deletion java/hibernate/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,27 @@ apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'com.cockroachlabs.Application'
sourceCompatibility = 1.7

repositories {
mavenCentral()
}

dependencies {
// Necessary for Hibernate.
compile 'org.hibernate:hibernate-core:5.2.4.Final'
compile 'org.postgresql:postgresql:9.4.1208'

// Necessary for web application.
compile 'org.glassfish.jersey.core:jersey-server:2.25'
compile 'org.glassfish.jersey.containers:jersey-container-netty-http:2.25'
compile 'com.fasterxml.jackson.core:jackson-databind:2.8.5'
compile 'com.beust:jcommander:1.7'

testCompile group: 'junit', name: 'junit', version: '4.11'
}

run {
if (project.hasProperty("appArgs")) {
args Eval.me(appArgs)
}
}
69 changes: 34 additions & 35 deletions java/hibernate/src/main/java/com/cockroachlabs/Application.java
Original file line number Diff line number Diff line change
@@ -1,48 +1,47 @@
package com.cockroachlabs;

import com.cockroachlabs.model.Customer;
import com.cockroachlabs.model.Order;
import com.cockroachlabs.model.Product;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import java.math.BigDecimal;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.cockroachlabs.services.CustomerService;
import com.cockroachlabs.services.OrderService;
import com.cockroachlabs.services.PingService;
import com.cockroachlabs.services.ProductService;
import com.cockroachlabs.util.SessionUtil;
import org.glassfish.jersey.netty.httpserver.NettyHttpContainerProvider;
import org.glassfish.jersey.server.ResourceConfig;

import javax.ws.rs.core.UriBuilder;
import java.net.URI;

public class Application {

public static void main(String[] args) {
try (SessionFactory sf = buildSessionFactory()) {
Session session = sf.getCurrentSession();

Customer c = new Customer();
c.setName("joe");

Order o = new Order();
o.setCustomer(c);
o.setSubtotal(new BigDecimal(100));
@Parameter(names = "-addr", description = "the address of the database")
private String dbAddr;

session.beginTransaction();
session.save(c);
session.save(o);
session.getTransaction().commit();
}
public static void main(String[] args) {
Application app = new Application();
new JCommander(app, args);
app.run();
}

private static SessionFactory buildSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
configuration.addAnnotatedClass(Customer.class);
configuration.addAnnotatedClass(Order.class);
configuration.addAnnotatedClass(Product.class);
private void run() {
initHibernate();
initHTTPServer();
}

ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
private void initHibernate() {
SessionUtil.init(dbAddr);
}

return configuration.buildSessionFactory(serviceRegistry);
private void initHTTPServer() {
URI baseUri = UriBuilder.fromUri("http://localhost/").port(6543).build();
ResourceConfig resourceConfig = new ResourceConfig(
PingService.class,
CustomerService.class,
ProductService.class,
OrderService.class
);
NettyHttpContainerProvider.createServer(baseUri, resourceConfig, true);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class Order {
private Customer customer;

@ManyToMany()
@JoinTable(name="product_orders",
@JoinTable(name="order_products",
joinColumns=@JoinColumn(name="order_id"),
inverseJoinColumns=@JoinColumn(name="product_id"))
private Set<Product> products;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ public class Product {
@Column(name="name")
private String name;

@Column(name="product", precision=18, scale=2)
private BigDecimal product;
@Column(name="price", precision=18, scale=2)
private BigDecimal price;

@ManyToMany(cascade=CascadeType.ALL, mappedBy="products")
private Set<Order> orders;
Expand All @@ -38,12 +38,12 @@ public void setName(String name) {
this.name = name;
}

public BigDecimal getProduct() {
return product;
public BigDecimal getPrice() {
return price;
}

public void setProduct(BigDecimal product) {
this.product = product;
public void setPrice(BigDecimal price) {
this.price = price;
}

public Set<Order> getOrders() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package com.cockroachlabs.services;

import com.cockroachlabs.model.Customer;
import com.cockroachlabs.util.SessionUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import javax.ws.rs.*;
import java.io.IOException;
import java.util.List;

@Path("/customer")
public class CustomerService {

private final ObjectMapper mapper = new ObjectMapper();

@GET
@Produces("application/json")
public String getCustomers() {
try (Session session = SessionUtil.getSession()) {
Query query = session.createQuery("from Customer");
List customers = query.list();
return mapper.writeValueAsString(customers);
} catch (JsonProcessingException e) {
return e.toString();
}
}

@POST
@Produces("application/json")
public String createCustomer(String body) {
try (Session session = SessionUtil.getSession()) {
Customer newCustomer = mapper.readValue(body, Customer.class);
session.save(newCustomer);

return mapper.writeValueAsString(newCustomer);
} catch (IOException e) {
return e.toString();
}
}

@GET
@Path("/{customerID}")
@Produces("application/json")
public String getCustomer(@PathParam("customerID") long customerID) {
try (Session session = SessionUtil.getSession()) {
Customer customer = session.get(Customer.class, customerID);
if (customer == null) {
throw new NotFoundException();
}

return mapper.writeValueAsString(customer);
} catch (JsonProcessingException e) {
return e.toString();
}
}

@PUT
@Path("/{customerID}")
@Produces("application/json")
public String updateCustomer(@PathParam("customerID") long customerID, String body) {
try (Session session = SessionUtil.getSession()) {
Customer updateInfo = mapper.readValue(body, Customer.class);
updateInfo.setId(customerID);

Customer updatedCustomer = (Customer) session.merge(updateInfo);
return mapper.writeValueAsString(updatedCustomer);
} catch (IOException e) {
return e.toString();
}
}

@DELETE
@Path("/{customerID}")
@Produces("text/plain")
public String deleteCustomer(@PathParam("customerID") long customerID) {
try (Session session = SessionUtil.getSession()) {
Transaction tx = session.beginTransaction();

Query deleteReferencing = session.createQuery("delete from Order where customer_id = :id");
deleteReferencing.setParameter("id", customerID);
deleteReferencing.executeUpdate();

Query deleteCustomer = session.createQuery("delete from Customer where id = :id");
deleteCustomer.setParameter("id", customerID);

int rowCount = deleteCustomer.executeUpdate();
if (rowCount == 0) {
tx.rollback();
throw new NotFoundException();
}
tx.commit();
return "ok";
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package com.cockroachlabs.services;

import com.cockroachlabs.model.Order;
import com.cockroachlabs.util.SessionUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import javax.ws.rs.*;
import java.io.IOException;
import java.util.List;

@Path("/order")
public class OrderService {

private final ObjectMapper mapper = new ObjectMapper();

@GET
@Produces("application/json")
public String getOrders() {
try (Session session = SessionUtil.getSession()) {
Query query = session.createQuery("from Order");
List orders = query.list();
return mapper.writeValueAsString(orders);
} catch (JsonProcessingException e) {
return e.toString();
}
}

@POST
@Produces("application/json")
public String createOrder(String body) {
try (Session session = SessionUtil.getSession()) {
Order newOrder = mapper.readValue(body, Order.class);
session.save(newOrder);

return mapper.writeValueAsString(newOrder);
} catch (IOException e) {
return e.toString();
}
}

@GET
@Path("/{orderID}")
@Produces("application/json")
public String getOrder(@PathParam("orderID") long orderID) {
try (Session session = SessionUtil.getSession()) {
Order order = session.get(Order.class, orderID);
if (order == null) {
throw new NotFoundException();
}

return mapper.writeValueAsString(order);
} catch (JsonProcessingException e) {
return e.toString();
}
}

@PUT
@Path("/{orderID}")
@Produces("application/json")
public String updateOrder(@PathParam("orderID") long orderID, String body) {
try (Session session = SessionUtil.getSession()) {
Order updateInfo = mapper.readValue(body, Order.class);
updateInfo.setId(orderID);

Order updatedOrder = (Order) session.merge(updateInfo);
return mapper.writeValueAsString(updatedOrder);
} catch (IOException e) {
return e.toString();
}
}

@DELETE
@Path("/{orderID}")
@Produces("text/plain")
public String deleteOrder(@PathParam("orderID") long orderID) {
try (Session session = SessionUtil.getSession()) {
Transaction tx = session.beginTransaction();

Query deleteReferencing = session.createQuery("delete from Order where order_id = :id");
deleteReferencing.setParameter("id", orderID);
deleteReferencing.executeUpdate();

Query deleteOrder = session.createQuery("delete from Order where id = :id");
deleteOrder.setParameter("id", orderID);

int rowCount = deleteOrder.executeUpdate();
if (rowCount == 0) {
tx.rollback();
throw new NotFoundException();
}
tx.commit();
return "ok";
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.cockroachlabs.services;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/ping")
public class PingService {

@GET
@Produces("text/plain")
public String ping() {
return "pong";
}

}
Loading

0 comments on commit 8aacfca

Please sign in to comment.