Skip to content

Commit 8aacfca

Browse files
committed
Set up REST API to conform to test harness conventions
1 parent 1c5725d commit 8aacfca

File tree

12 files changed

+460
-47
lines changed

12 files changed

+460
-47
lines changed

java/hibernate/Makefile

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@
1515
#
1616
# Author: Nathan VanBenschoten ([email protected])
1717

18+
ifneq ($(ADDR),)
19+
ADDRFLAG = -PappArgs="['-addr', '$(ADDR)']"
20+
endif
21+
1822
.PHONY: start
1923
start:
20-
@gradle run
24+
@gradle run $(ADDRFLAG)

java/hibernate/build.gradle

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,27 @@ apply plugin: 'java'
55
apply plugin: 'application'
66

77
mainClassName = 'com.cockroachlabs.Application'
8-
sourceCompatibility = 1.7
98

109
repositories {
1110
mavenCentral()
1211
}
1312

1413
dependencies {
14+
// Necessary for Hibernate.
1515
compile 'org.hibernate:hibernate-core:5.2.4.Final'
1616
compile 'org.postgresql:postgresql:9.4.1208'
1717

18+
// Necessary for web application.
19+
compile 'org.glassfish.jersey.core:jersey-server:2.25'
20+
compile 'org.glassfish.jersey.containers:jersey-container-netty-http:2.25'
21+
compile 'com.fasterxml.jackson.core:jackson-databind:2.8.5'
22+
compile 'com.beust:jcommander:1.7'
23+
1824
testCompile group: 'junit', name: 'junit', version: '4.11'
1925
}
26+
27+
run {
28+
if (project.hasProperty("appArgs")) {
29+
args Eval.me(appArgs)
30+
}
31+
}
Lines changed: 34 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,47 @@
11
package com.cockroachlabs;
22

3-
import com.cockroachlabs.model.Customer;
4-
import com.cockroachlabs.model.Order;
5-
import com.cockroachlabs.model.Product;
6-
import org.hibernate.Session;
7-
import org.hibernate.SessionFactory;
8-
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9-
import org.hibernate.cfg.Configuration;
10-
import org.hibernate.service.ServiceRegistry;
11-
12-
import java.math.BigDecimal;
3+
import com.beust.jcommander.JCommander;
4+
import com.beust.jcommander.Parameter;
5+
import com.cockroachlabs.services.CustomerService;
6+
import com.cockroachlabs.services.OrderService;
7+
import com.cockroachlabs.services.PingService;
8+
import com.cockroachlabs.services.ProductService;
9+
import com.cockroachlabs.util.SessionUtil;
10+
import org.glassfish.jersey.netty.httpserver.NettyHttpContainerProvider;
11+
import org.glassfish.jersey.server.ResourceConfig;
12+
13+
import javax.ws.rs.core.UriBuilder;
14+
import java.net.URI;
1315

1416
public class Application {
1517

16-
public static void main(String[] args) {
17-
try (SessionFactory sf = buildSessionFactory()) {
18-
Session session = sf.getCurrentSession();
19-
20-
Customer c = new Customer();
21-
c.setName("joe");
22-
23-
Order o = new Order();
24-
o.setCustomer(c);
25-
o.setSubtotal(new BigDecimal(100));
18+
@Parameter(names = "-addr", description = "the address of the database")
19+
private String dbAddr;
2620

27-
session.beginTransaction();
28-
session.save(c);
29-
session.save(o);
30-
session.getTransaction().commit();
31-
}
21+
public static void main(String[] args) {
22+
Application app = new Application();
23+
new JCommander(app, args);
24+
app.run();
3225
}
3326

34-
private static SessionFactory buildSessionFactory() {
35-
Configuration configuration = new Configuration();
36-
configuration.configure("hibernate.cfg.xml");
37-
configuration.addAnnotatedClass(Customer.class);
38-
configuration.addAnnotatedClass(Order.class);
39-
configuration.addAnnotatedClass(Product.class);
27+
private void run() {
28+
initHibernate();
29+
initHTTPServer();
30+
}
4031

41-
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
42-
.applySettings(configuration.getProperties())
43-
.build();
32+
private void initHibernate() {
33+
SessionUtil.init(dbAddr);
34+
}
4435

45-
return configuration.buildSessionFactory(serviceRegistry);
36+
private void initHTTPServer() {
37+
URI baseUri = UriBuilder.fromUri("http://localhost/").port(6543).build();
38+
ResourceConfig resourceConfig = new ResourceConfig(
39+
PingService.class,
40+
CustomerService.class,
41+
ProductService.class,
42+
OrderService.class
43+
);
44+
NettyHttpContainerProvider.createServer(baseUri, resourceConfig, true);
4645
}
4746

4847
}

java/hibernate/src/main/java/com/cockroachlabs/model/Order.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public class Order {
2121
private Customer customer;
2222

2323
@ManyToMany()
24-
@JoinTable(name="product_orders",
24+
@JoinTable(name="order_products",
2525
joinColumns=@JoinColumn(name="order_id"),
2626
inverseJoinColumns=@JoinColumn(name="product_id"))
2727
private Set<Product> products;

java/hibernate/src/main/java/com/cockroachlabs/model/Product.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ public class Product {
1616
@Column(name="name")
1717
private String name;
1818

19-
@Column(name="product", precision=18, scale=2)
20-
private BigDecimal product;
19+
@Column(name="price", precision=18, scale=2)
20+
private BigDecimal price;
2121

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

41-
public BigDecimal getProduct() {
42-
return product;
41+
public BigDecimal getPrice() {
42+
return price;
4343
}
4444

45-
public void setProduct(BigDecimal product) {
46-
this.product = product;
45+
public void setPrice(BigDecimal price) {
46+
this.price = price;
4747
}
4848

4949
public Set<Order> getOrders() {
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
package com.cockroachlabs.services;
2+
3+
import com.cockroachlabs.model.Customer;
4+
import com.cockroachlabs.util.SessionUtil;
5+
import com.fasterxml.jackson.core.JsonProcessingException;
6+
import com.fasterxml.jackson.databind.ObjectMapper;
7+
import org.hibernate.Session;
8+
import org.hibernate.Transaction;
9+
import org.hibernate.query.Query;
10+
11+
import javax.ws.rs.*;
12+
import java.io.IOException;
13+
import java.util.List;
14+
15+
@Path("/customer")
16+
public class CustomerService {
17+
18+
private final ObjectMapper mapper = new ObjectMapper();
19+
20+
@GET
21+
@Produces("application/json")
22+
public String getCustomers() {
23+
try (Session session = SessionUtil.getSession()) {
24+
Query query = session.createQuery("from Customer");
25+
List customers = query.list();
26+
return mapper.writeValueAsString(customers);
27+
} catch (JsonProcessingException e) {
28+
return e.toString();
29+
}
30+
}
31+
32+
@POST
33+
@Produces("application/json")
34+
public String createCustomer(String body) {
35+
try (Session session = SessionUtil.getSession()) {
36+
Customer newCustomer = mapper.readValue(body, Customer.class);
37+
session.save(newCustomer);
38+
39+
return mapper.writeValueAsString(newCustomer);
40+
} catch (IOException e) {
41+
return e.toString();
42+
}
43+
}
44+
45+
@GET
46+
@Path("/{customerID}")
47+
@Produces("application/json")
48+
public String getCustomer(@PathParam("customerID") long customerID) {
49+
try (Session session = SessionUtil.getSession()) {
50+
Customer customer = session.get(Customer.class, customerID);
51+
if (customer == null) {
52+
throw new NotFoundException();
53+
}
54+
55+
return mapper.writeValueAsString(customer);
56+
} catch (JsonProcessingException e) {
57+
return e.toString();
58+
}
59+
}
60+
61+
@PUT
62+
@Path("/{customerID}")
63+
@Produces("application/json")
64+
public String updateCustomer(@PathParam("customerID") long customerID, String body) {
65+
try (Session session = SessionUtil.getSession()) {
66+
Customer updateInfo = mapper.readValue(body, Customer.class);
67+
updateInfo.setId(customerID);
68+
69+
Customer updatedCustomer = (Customer) session.merge(updateInfo);
70+
return mapper.writeValueAsString(updatedCustomer);
71+
} catch (IOException e) {
72+
return e.toString();
73+
}
74+
}
75+
76+
@DELETE
77+
@Path("/{customerID}")
78+
@Produces("text/plain")
79+
public String deleteCustomer(@PathParam("customerID") long customerID) {
80+
try (Session session = SessionUtil.getSession()) {
81+
Transaction tx = session.beginTransaction();
82+
83+
Query deleteReferencing = session.createQuery("delete from Order where customer_id = :id");
84+
deleteReferencing.setParameter("id", customerID);
85+
deleteReferencing.executeUpdate();
86+
87+
Query deleteCustomer = session.createQuery("delete from Customer where id = :id");
88+
deleteCustomer.setParameter("id", customerID);
89+
90+
int rowCount = deleteCustomer.executeUpdate();
91+
if (rowCount == 0) {
92+
tx.rollback();
93+
throw new NotFoundException();
94+
}
95+
tx.commit();
96+
return "ok";
97+
}
98+
}
99+
100+
}
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
package com.cockroachlabs.services;
2+
3+
import com.cockroachlabs.model.Order;
4+
import com.cockroachlabs.util.SessionUtil;
5+
import com.fasterxml.jackson.core.JsonProcessingException;
6+
import com.fasterxml.jackson.databind.ObjectMapper;
7+
import org.hibernate.Session;
8+
import org.hibernate.Transaction;
9+
import org.hibernate.query.Query;
10+
11+
import javax.ws.rs.*;
12+
import java.io.IOException;
13+
import java.util.List;
14+
15+
@Path("/order")
16+
public class OrderService {
17+
18+
private final ObjectMapper mapper = new ObjectMapper();
19+
20+
@GET
21+
@Produces("application/json")
22+
public String getOrders() {
23+
try (Session session = SessionUtil.getSession()) {
24+
Query query = session.createQuery("from Order");
25+
List orders = query.list();
26+
return mapper.writeValueAsString(orders);
27+
} catch (JsonProcessingException e) {
28+
return e.toString();
29+
}
30+
}
31+
32+
@POST
33+
@Produces("application/json")
34+
public String createOrder(String body) {
35+
try (Session session = SessionUtil.getSession()) {
36+
Order newOrder = mapper.readValue(body, Order.class);
37+
session.save(newOrder);
38+
39+
return mapper.writeValueAsString(newOrder);
40+
} catch (IOException e) {
41+
return e.toString();
42+
}
43+
}
44+
45+
@GET
46+
@Path("/{orderID}")
47+
@Produces("application/json")
48+
public String getOrder(@PathParam("orderID") long orderID) {
49+
try (Session session = SessionUtil.getSession()) {
50+
Order order = session.get(Order.class, orderID);
51+
if (order == null) {
52+
throw new NotFoundException();
53+
}
54+
55+
return mapper.writeValueAsString(order);
56+
} catch (JsonProcessingException e) {
57+
return e.toString();
58+
}
59+
}
60+
61+
@PUT
62+
@Path("/{orderID}")
63+
@Produces("application/json")
64+
public String updateOrder(@PathParam("orderID") long orderID, String body) {
65+
try (Session session = SessionUtil.getSession()) {
66+
Order updateInfo = mapper.readValue(body, Order.class);
67+
updateInfo.setId(orderID);
68+
69+
Order updatedOrder = (Order) session.merge(updateInfo);
70+
return mapper.writeValueAsString(updatedOrder);
71+
} catch (IOException e) {
72+
return e.toString();
73+
}
74+
}
75+
76+
@DELETE
77+
@Path("/{orderID}")
78+
@Produces("text/plain")
79+
public String deleteOrder(@PathParam("orderID") long orderID) {
80+
try (Session session = SessionUtil.getSession()) {
81+
Transaction tx = session.beginTransaction();
82+
83+
Query deleteReferencing = session.createQuery("delete from Order where order_id = :id");
84+
deleteReferencing.setParameter("id", orderID);
85+
deleteReferencing.executeUpdate();
86+
87+
Query deleteOrder = session.createQuery("delete from Order where id = :id");
88+
deleteOrder.setParameter("id", orderID);
89+
90+
int rowCount = deleteOrder.executeUpdate();
91+
if (rowCount == 0) {
92+
tx.rollback();
93+
throw new NotFoundException();
94+
}
95+
tx.commit();
96+
return "ok";
97+
}
98+
}
99+
100+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.cockroachlabs.services;
2+
3+
import javax.ws.rs.GET;
4+
import javax.ws.rs.Path;
5+
import javax.ws.rs.Produces;
6+
7+
@Path("/ping")
8+
public class PingService {
9+
10+
@GET
11+
@Produces("text/plain")
12+
public String ping() {
13+
return "pong";
14+
}
15+
16+
}

0 commit comments

Comments
 (0)