-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHistoryService.java
More file actions
80 lines (68 loc) · 2.85 KB
/
HistoryService.java
File metadata and controls
80 lines (68 loc) · 2.85 KB
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
78
79
80
package beans;
import javax.annotation.PostConstruct;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class HistoryService {
private Connection connection;
public HistoryService() {}
@PostConstruct
private void initConnection() {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Can't find driver!!!", e);
}
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
String jdbcProtocolName = context.getInitParameter("jdbc-protocol-name");
String jdbcHost = context.getInitParameter("jdbc-host");
String jdbcPort = context.getInitParameter("jdbc-port");
String jdbcDatabase = context.getInitParameter("jdbc-database");
String jdbcUser = context.getInitParameter("jdbc-user");
String jdbcPassword = context.getInitParameter("jdbc-password");
try {
connection = DriverManager.getConnection(
"jdbc:" + jdbcProtocolName + "://" + jdbcHost + ":" + jdbcPort + "/" + jdbcDatabase,
jdbcUser, jdbcPassword
);
connection.createStatement().execute(
"create table if not exists results (" +
"x text, y text, r text, result boolean)"
);
} catch (SQLException e) {
throw new IllegalStateException("Could not create connection!!!", e);
}
}
public void addResult(HistoryBean.Query result) throws SQLException {
if (connection == null)
initConnection();
PreparedStatement s = connection.prepareStatement(
"insert into results (x, y, r, result) values (?, ?, ?, ?)"
);
s.setString(1, result.getX());
s.setString(2, result.getY());
s.setString(3, result.getR());
s.setBoolean(4, result.isResult());
s.execute();
}
public LinkedList<HistoryBean.Query> getResults() {
if (connection == null)
initConnection();
LinkedList<HistoryBean.Query> result = new LinkedList<>();
try{
ResultSet rs = connection.createStatement().executeQuery("select * from results");
while (rs.next()) {
HistoryBean.Query current = new HistoryBean.Query(
(rs.getString("x")),
(rs.getString("y")),
(rs.getString("r")),
(rs.getBoolean("result")));
result.add(current);
}}
catch (SQLException ignored){}
return result;
}
}