Skip to content

Commit d4637b9

Browse files
committed
various improvements
1 parent 542ed59 commit d4637b9

File tree

6 files changed

+131
-959
lines changed

6 files changed

+131
-959
lines changed

Diff for: mock_data.sql

+1-851
Large diffs are not rendered by default.

Diff for: src/main/java/com/example/App.java

+13-9
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,27 @@
77
import com.example.bean.EmployeeBean;
88
import com.google.gson.Gson;
99

10+
import spark.Service.StaticFiles;
11+
1012
/**
1113
* Main application class
1214
*/
1315
public final class App {
14-
private static Gson gson = new Gson();
15-
private static RestService service;
16+
private static final RestService service;
17+
18+
private static final Gson gson = new Gson();
1619

1720
static {
1821
try {
19-
DatabaseUtil.initDatabase();
20-
21-
// Replace this with yout own implementation of RestService.
22-
service = new MyRestService();
22+
DatabaseProvider.initDatabase();
2323
} catch (SQLException e) {
24-
e.printStackTrace();
24+
System.err.println("Error setting up database: " + e.getMessage());
25+
System.err.println("Exiting...");
26+
System.exit(1);
2527
}
28+
29+
// Replace this with yout own implementation of RestService.
30+
service = new MyRestService();
2631
}
2732

2833
/**
@@ -32,7 +37,6 @@ public final class App {
3237
* @throws Exception
3338
*/
3439
public static void main(String[] args) throws Exception {
35-
3640
// returns a list of all employees
3741
get("/users", (request, response) -> service.getEmployees(), gson::toJson);
3842

@@ -52,7 +56,7 @@ public static void main(String[] args) throws Exception {
5256
(request, response) -> service.updateEmployee(gson.fromJson(request.body(), EmployeeBean.class)),
5357
gson::toJson);
5458

55-
// set default content-type to json for all endpoints
59+
// set default content-type to json for response from all endpoints.
5660
after((request, response) -> response.header("Content-type", "application/json"));
5761
}
5862
}

Diff for: src/main/java/com/example/DatabaseProvider.java

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.example;
2+
3+
import java.io.IOException;
4+
import java.nio.file.Files;
5+
import java.nio.file.Paths;
6+
import java.sql.Connection;
7+
import java.sql.SQLException;
8+
import java.sql.Statement;
9+
import java.util.Objects;
10+
11+
import org.h2.jdbcx.JdbcDataSource;
12+
import org.h2.tools.Server;
13+
14+
/**
15+
* Implementation encapsulates an H2 in-memmory database.
16+
*/
17+
public class DatabaseProvider {
18+
private static Server db;
19+
private static JdbcDataSource ds = new JdbcDataSource();
20+
21+
private static final Object lock = new Object();
22+
23+
private DatabaseProvider() {
24+
}
25+
26+
public static void initDatabase() throws SQLException {
27+
if (Objects.isNull(db)) {
28+
synchronized (lock) {
29+
if (Objects.isNull(db)) {
30+
db = Server.createTcpServer().start();
31+
32+
ds.setURL("jdbc:h2:mem:mockdb;DB_CLOSE_DELAY=-1");
33+
// ds.setUser("user");
34+
// ds.setPassword("password");
35+
36+
try (Connection conn = ds.getConnection(); Statement stmt = conn.createStatement()) {
37+
38+
Files.lines(Paths.get("mock_data.sql")).filter(line -> !line.isEmpty()).forEach(line -> {
39+
try {
40+
stmt.executeUpdate(line);
41+
} catch (SQLException e) {
42+
System.err.println("Error setting up database: " + e.getMessage());
43+
System.err.println("Exiting...");
44+
System.exit(1);
45+
}
46+
});
47+
} catch (IOException e) {
48+
System.err.println("Unable to read SQL file: " + e.getMessage());
49+
System.err.println("Make sure it is placedin the same directory as the JAR file!");
50+
System.err.println("Exiting...");
51+
System.exit(1);
52+
}
53+
}
54+
}
55+
}
56+
}
57+
58+
public static Connection getConnection() throws SQLException {
59+
if (Objects.isNull(db)) {
60+
initDatabase();
61+
}
62+
63+
return ds.getConnection();
64+
}
65+
}

Diff for: src/main/java/com/example/DatabaseUtil.java

-54
This file was deleted.

Diff for: src/main/java/com/example/ResponseMessage.java

+12-4
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
package com.example;
22

3-
import java.time.LocalDateTime;
43
import java.util.Collection;
54

65
public class ResponseMessage <T> {
76
private String status;
8-
private LocalDateTime timeStamp;
7+
private String timeStamp;
8+
private Integer count;
99
private Collection<T> msg;
1010

1111
public String getStatus() {
@@ -16,14 +16,22 @@ public void setStatus(String status) {
1616
this.status = status;
1717
}
1818

19-
public LocalDateTime getTimeStamp() {
19+
public String getTimeStamp() {
2020
return timeStamp;
2121
}
2222

23-
public void setTimeStamp(LocalDateTime timeStamp) {
23+
public void setTimeStamp(String timeStamp) {
2424
this.timeStamp = timeStamp;
2525
}
2626

27+
public Integer getCount() {
28+
return count;
29+
}
30+
31+
public void setCount(Integer count) {
32+
this.count = count;
33+
}
34+
2735
public Collection<T> getMsg() {
2836
return msg;
2937
}

Diff for: src/main/java/com/example/RestService.java

+40-41
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,28 @@
77
import java.sql.Statement;
88
import java.time.LocalDateTime;
99
import java.util.ArrayList;
10+
import java.util.List;
1011

1112
import com.example.bean.EmployeeBean;
1213

1314
public interface RestService {
1415
public default ResponseMessage<EmployeeBean> getEmployees() {
1516
ResponseMessage<EmployeeBean> message = new ResponseMessage<>();
1617

17-
try (Connection conn = DatabaseUtil.getConnection();
18-
Statement stmt = conn.createStatement();
19-
ResultSet res = stmt.executeQuery("select * from employees;")) {
18+
try (Connection conn = DatabaseProvider.getConnection();
19+
Statement stmt = conn.createStatement();
20+
ResultSet res = stmt.executeQuery("select * from employees;")) {
2021

21-
message.setTimeStamp(LocalDateTime.now());
22-
message.setStatus("SUCCESS");
23-
message.setMsg(EmployeeBean.ofResultSet(res));
22+
message.setTimeStamp(LocalDateTime.now().toString());
23+
message.setStatus("Ok");
24+
List<EmployeeBean> tmp = EmployeeBean.ofResultSet(res);
25+
message.setCount(tmp.size());
26+
message.setMsg(tmp);
2427
} catch (SQLException e) {
2528
e.printStackTrace();
2629

27-
message.setTimeStamp(LocalDateTime.now());
28-
message.setStatus("ERROR");
30+
message.setTimeStamp(LocalDateTime.now().toString());
31+
message.setStatus("Error");
2932
message.setMsg(new ArrayList<>());
3033
}
3134

@@ -36,23 +39,28 @@ public default ResponseMessage<EmployeeBean> getEmployeeById(Integer id) {
3639
ResponseMessage<EmployeeBean> message = new ResponseMessage<>();
3740
String sql = "select * from employees where id=?;";
3841

39-
try (Connection conn = DatabaseUtil.getConnection();
40-
PreparedStatement stmt = conn.prepareStatement(sql)) {
41-
42+
try (Connection conn = DatabaseProvider.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) {
43+
4244
stmt.setInt(1, id);
4345
ResultSet res = stmt.executeQuery();
4446

47+
EmployeeBean e = EmployeeBean.ofSingleResult(res);
48+
4549
ArrayList<EmployeeBean> tmp = new ArrayList<>();
46-
tmp.add(EmployeeBean.ofSingleResult(res));
4750

48-
message.setTimeStamp(LocalDateTime.now());
49-
message.setStatus("OK");
51+
if (e.getId() != -1) {
52+
tmp.add(e);
53+
}
54+
55+
message.setTimeStamp(LocalDateTime.now().toString());
56+
message.setStatus("Ok");
5057
message.setMsg(tmp);
58+
message.setCount(tmp.size());
5159
} catch (SQLException e) {
5260
e.printStackTrace();
5361

54-
message.setTimeStamp(LocalDateTime.now());
55-
message.setStatus("ERROR");
62+
message.setTimeStamp(LocalDateTime.now().toString());
63+
message.setStatus("Error");
5664
message.setMsg(new ArrayList<>());
5765
}
5866

@@ -63,19 +71,18 @@ public default ResponseMessage<EmployeeBean> deleteEmployee(Integer id) {
6371
ResponseMessage<EmployeeBean> message = new ResponseMessage<>();
6472
String sql = "delete from employees where id=?;";
6573

66-
try (Connection conn = DatabaseUtil.getConnection();
67-
PreparedStatement stmt = conn.prepareStatement(sql)) {
74+
try (Connection conn = DatabaseProvider.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) {
6875
stmt.setInt(1, id);
6976
stmt.executeUpdate();
7077

71-
message.setTimeStamp(LocalDateTime.now());
72-
message.setStatus("deleted");
78+
message.setTimeStamp(LocalDateTime.now().toString());
79+
message.setStatus("Ok");
7380
message.setMsg(new ArrayList<>());
7481
} catch (SQLException e) {
7582
e.printStackTrace();
7683

77-
message.setTimeStamp(LocalDateTime.now());
78-
message.setStatus("error");
84+
message.setTimeStamp(LocalDateTime.now().toString());
85+
message.setStatus("Error");
7986
message.setMsg(new ArrayList<>());
8087
}
8188

@@ -85,33 +92,24 @@ public default ResponseMessage<EmployeeBean> deleteEmployee(Integer id) {
8592
public default ResponseMessage<EmployeeBean> updateEmployee(EmployeeBean employee) {
8693
ResponseMessage<EmployeeBean> message = new ResponseMessage<>();
8794
EmployeeBean current = new EmployeeBean();
88-
95+
8996
String sql1 = "select * from employees where id=?;";
90-
try (Connection conn = DatabaseUtil.getConnection();
91-
PreparedStatement stmt = conn.prepareStatement(sql1)) {
92-
97+
try (Connection conn = DatabaseProvider.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql1)) {
98+
9399
stmt.setInt(1, employee.getId());
94100
ResultSet res = stmt.executeQuery();
95101

96102
current = EmployeeBean.ofSingleResult(res);
97103
} catch (SQLException e) {
98104
e.printStackTrace();
99105
}
100-
106+
101107
current.update(employee);
102-
103-
String sql2 = "update employees set firstName=?,"
104-
+ "lastName=?,"
105-
+ "birthDate=?,"
106-
+ "gender=?,"
107-
+ "company=?,"
108-
+ "department=?,"
109-
+ "employerId=?,"
110-
+ "email=? "
111-
+ "where id=?;";
112-
113-
try (Connection conn = DatabaseUtil.getConnection();
114-
PreparedStatement stmt = conn.prepareStatement(sql2)) {
108+
109+
String sql2 = "update employees set firstName=?," + "lastName=?," + "birthDate=?," + "gender=?," + "company=?,"
110+
+ "department=?," + "employerId=?," + "email=? " + "where id=?;";
111+
112+
try (Connection conn = DatabaseProvider.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql2)) {
115113

116114
stmt.setString(1, current.getFirstName());
117115
stmt.setString(2, current.getLastName());
@@ -125,12 +123,13 @@ public default ResponseMessage<EmployeeBean> updateEmployee(EmployeeBean employe
125123

126124
stmt.executeUpdate();
127125

128-
message.setTimeStamp(LocalDateTime.now());
126+
message.setTimeStamp(LocalDateTime.now().toString());
129127
message.setStatus("Ok");
130128

131129
ArrayList<EmployeeBean> tmp = new ArrayList<>();
132130
tmp.add(current);
133131
message.setMsg(tmp);
132+
message.setCount(tmp.size());
134133
} catch (SQLException e) {
135134
e.printStackTrace();
136135
}

0 commit comments

Comments
 (0)