- Notifications
You must be signed in to change notification settings - Fork 7.2k
/
Copy pathApp.java
executable file
·78 lines (64 loc) · 2.42 KB
/
App.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
importcom.google.gson.Gson;
importcom.mysql.cj.jdbc.exceptions.CommunicationsException;
importstaticspark.Spark.*;
importjava.nio.file.Files;
importjava.nio.file.Paths;
importjava.sql.*;
importjava.util.ArrayList;
importjava.util.List;
publicclassApp {
publicstaticvoidmain(String[] args) throwsException {
Class.forName("com.mysql.cj.jdbc.Driver");
prepare();
port(8080);
get("/", (req, res) -> newGson().toJson(titles()));
}
privatestaticList<String> titles() {
try (Connectionconn = connect()) {
List<String> titles = newArrayList<>();
try (Statementstmt = conn.createStatement()) {
try (ResultSetrs = stmt.executeQuery("SELECT title FROM blog")) {
while (rs.next()) {
titles.add(rs.getString("title"));
}
}
}
returntitles;
} catch (Exceptionex) {
returnnewArrayList<>();
}
}
publicstaticvoidprepare() throwsException {
try (Connectionconn = connect()) {
recreateTable(conn);
insertData(conn);
}
}
privatestaticvoidinsertData(Connectionconn) throwsSQLException {
for (inti = 0; i < 5; i++) {
try (PreparedStatementstmt = conn.prepareStatement("INSERT INTO blog (title) VALUES (?);")) {
stmt.setString(1, "Blog post #" + i);
stmt.execute();
}
}
}
privatestaticvoidrecreateTable(Connectionconn) throwsSQLException {
try (Statementstmt = conn.createStatement()) {
stmt.execute("DROP TABLE IF EXISTS blog");
stmt.execute("CREATE TABLE IF NOT EXISTS blog (id int NOT NULL AUTO_INCREMENT, title varchar(255), PRIMARY KEY (id))");
}
}
privatestaticConnectionconnect() throwsException {
for (inti = 0; i < 60; i++) {
try {
returnDriverManager.getConnection("jdbc:mysql://db/example?allowPublicKeyRetrieval=true&useSSL=false", "root", Files.lines(Paths.get("/run/secrets/db-password")).findFirst().get());
} catch (CommunicationsExceptionex) {
Thread.sleep(1000L);
continue;
} catch (Exceptionex) {
throwex;
}
}
thrownewRuntimeException("Unable to connect to MySQL");
}
}