· 6 years ago · Nov 05, 2019, 05:24 PM
1import com.datastax.driver.core.*;
2import com.datastax.driver.core.utils.UUIDs;
3import org.springframework.web.bind.annotation.*;
4
5import java.util.ArrayList;
6import java.util.List;
7
8//TODO: vurder å ha tilgangskontroll. Sjekke om den brukeren har tilgang til det den skal se.
9//For now we choose to make the history/all registered forms available for all users to see.
10//In the future we might make it so that a user only can see what they have registered themselves,
11//because it can lead to unwanted consequences like security threats, GDPR and might scare users from registering incidents
12
13//TODO: REMEMBER: All communication must use:: content-type: application/json
14//All communication will be through json and Spring. We do not know all of the things Spring does
15//for us, but we appreciate the magic it does.
16//We would like to have a control to ensure that only the approved users get access to there data as well as adding data.
17
18@RestController
19public class FormController {
20 private Cluster cluster;
21 private Session session;
22 private PreparedStatement putStmt;
23 private PreparedStatement fetchStmtFormFromUuid;
24 private PreparedStatement fetchStmtCommentFromUuid;
25 private PreparedStatement fetchStmtPersonList;
26 private PreparedStatement fetchStmtPersonFromUuid;
27 private PreparedStatement fetchStmtUserHistoryList;
28 private PreparedStatement fetchStmtUserHistoryFromUuid;
29 private PreparedStatement fetchStmtAll;
30 private PreparedStatement deleteStmt;
31 private PreparedStatement insertStmtForm;
32 private PreparedStatement insertStmtComment;
33
34 public FormController() {
35 cluster = Cluster.builder()
36 .addContactPoint("diazepam.local")
37 .addContactPoint("epinephrine.local")
38 .addContactPoint("fluoxetine.local")
39 .withQueryOptions(new QueryOptions()
40 .setConsistencyLevel(ConsistencyLevel.TWO))
41 .build();
42 ensureDB();
43 session = cluster.connect("storage");
44 setStmt();
45 }
46
47 // Creates keyspace and tables if they do not exist in database
48 private void ensureDB() {
49 Session creatorSession = cluster.newSession();
50 creatorSession.execute
51 ("CREATE KEYSPACE IF NOT EXISTS g2_keyspace " +
52 "WITH replication = {" +
53 " 'class': 'NetworkTopologyStrategy'," +
54 " 'dc1': '3' " +
55 "}");
56 creatorSession.execute
57 ("CREATE TABLE IF NOT EXISTS g2_keyspace.form " +
58 "(uuid text PRIMARY KEY, " +
59 "comment list<text>, " +
60 "datecreated text, " +
61 "dateofincident text, " +
62 "incident text, " +
63 "isdeleted boolean, " +
64 "iserrorincident boolean, " +
65 "location text, " +
66 "people list<text>, " +
67 "severity int, " +
68 "url text)");
69 creatorSession.execute
70 ("CREATE TABLE IF NOT EXISTS g2_keyspace.people " +
71 "(uuid text PRIMARY KEY, " +
72 "involvement text, " +
73 "name text, " +
74 "relevantinfo text)");
75 creatorSession.execute
76 ("CREATE TABLE IF NOT EXISTS g2_keyspace.comment " +
77 "(uuid text PRIMARY KEY, " +
78 "content text)");
79 creatorSession.execute
80 ("CREATE TABLE IF NOT EXISTS g2_keyspace.userhistory " +
81 "(userid text PRIMARY KEY, " +
82 "registeredincidents list<text>)");
83 }
84
85 //This function is expecting a FormId. This Id will be used to identify the desired form to be deleted.
86 //No form will actually be deleted, this to preserve documentation, instead "isDeleted" is set to "true", and wil not be returned when asked for by !admins.
87 @DeleteMapping("/form/{uuid}")
88 public boolean formRemove(@PathVariable String uuid) {
89 try {
90 session.execute(deleteStmt.bind(uuid));
91 return true;
92 } catch (Exception e) {
93 e.printStackTrace();
94 return false;
95 }
96 }
97
98 //This function should return the requested form based on the given Id. As of right now, we only have hardcoded data. Once there is a
99 //database, we will request the form from the database and return it.
100 @GetMapping("/form/{uuid}")
101 public Form formGet(@PathVariable String uuid) {
102 ResultSet rows = session.execute(fetchStmtFormFromUuid.bind(uuid));
103 Form temp = null;
104 for (Row row : rows) {
105 temp = getFormFromRow(row);
106 }
107 assert temp != null;
108 if (temp.isDeleted()) {
109 return null;
110 }
111 return temp;
112 }
113
114 //This function should return a list of all forms based on userId, to ensure that the user only gets the forms the users should have access to.
115 //As of now, we have a simple ArrayList filled with Forms. We are not sure if we will have to implement security on the server, or if it is implemented elsewhere.
116 @GetMapping("/form")
117 public ArrayList<Form> formGetAll() {
118 ArrayList<Form> forms = new ArrayList<>();
119 ResultSet rows = session.execute(fetchStmtAll.bind());
120 for (Row row : rows) {
121 if (!getFormFromRow(row).isDeleted()) {
122 forms.add(getFormFromRow(row));
123 }
124 }
125 return forms;
126 }
127
128 //This function returns a list of all forms in the database, even the deleted ones.
129 @GetMapping("/form/deleted")
130 public ArrayList<Form> formGetAllWithDeleted() {
131 ArrayList<Form> forms = new ArrayList<>();
132 ResultSet rows = session.execute(fetchStmtAll.bind());
133 for (Row row : rows) {
134 forms.add(getFormFromRow(row));
135 }
136 return forms;
137 }
138
139 //This function is expecting a Form object from the application and will one day add this object to a database.
140 //Post is used to avoid caching and to try to hide away information from the URL by sending it in the body.
141 //Takes input like this:
142 //{"uuid":"68","severity":1,"picture":"url-string","comment":"A comment about the incident","location":"Home","incident":"Broken bone","involvedPeople":["'Per Person'","'Bob Bobbers'"],"dateOfIncident":"20.10.19","dateCreated":"22.10.19","deleted":false,"errorIncident":false}
143 @PostMapping("/form")
144 public String formAdd(@RequestBody Form requestForm) {
145 String uuid = (requestForm.getUuid() == null) ? String.valueOf(UUIDs.timeBased()) : requestForm.getUuid();
146 try {
147 session.execute(insertStmtForm.bind(uuid, requestForm.getSeverity(), requestForm.getPicture(), requestForm.getComment(), requestForm.getLocation(), requestForm.getIncident(), requestForm.isErrorIncident(), requestForm.getInvolvedPeople(), requestForm.getDateOfIncident(), requestForm.getDateCreated(), requestForm.isDeleted()));
148 return "Worked!, Uuid: " + uuid;
149 } catch (Exception e) {
150 e.printStackTrace();
151 return "Error, see StackTrace";
152 }
153 }
154
155 //This function is expecting a String, which should contain information about which form to alter and what data needs to be added,
156 //and update the correct form with additional information.
157 @PutMapping("/form/{uuid}")
158 public boolean formPut(@PathVariable("uuid") String uuid, @RequestBody String content) {
159 try {
160 ResultSet rows = session.execute(fetchStmtFormFromUuid.bind(uuid));
161 Form temp = null;
162 List<String> formComment;
163 for (Row row : rows) {
164 temp = getFormFromRow(row);
165 }
166 assert temp != null;
167
168 formComment = temp.getComment();
169 String commentUuid = String.valueOf(UUIDs.timeBased());
170
171 formComment.add(commentUuid);
172 session.execute(insertStmtComment.bind(commentUuid, content));
173 session.execute(putStmt.bind(formComment, uuid));
174
175 return true;
176 } catch (Exception e) {
177 e.printStackTrace();
178 return false;
179 }
180 }
181
182 //Sets prepared statements
183 private void setStmt() {
184 insertStmtComment = session.prepare("INSERT INTO g2_keyspace.comment (uuid, content) VALUES (?, ?)");
185 insertStmtForm = session
186 .prepare("INSERT INTO g2_keyspace.form " +
187 "(uuid, severity, url, comment, location, incident, iserrorincident, people, dateofincident, datecreated, isdeleted) " +
188 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
189 deleteStmt = session.prepare("UPDATE g2_keyspace.form SET isdeleted = TRUE WHERE uuid = ?");
190 putStmt = session.prepare("UPDATE g2_keyspace.form SET comment = ? WHERE uuid = ?");
191 fetchStmtFormFromUuid = session.prepare("SELECT * FROM g2_keyspace.form WHERE uuid = ?");
192 fetchStmtCommentFromUuid = session.prepare("SELECT * FROM g2_keyspace.comment WHERE uuid = ?");
193 fetchStmtPersonFromUuid = session.prepare("SELECT * FROM g2_keyspace.person WHERE uuid = ?");
194 fetchStmtPersonList = session.prepare("SELECT * FROM g2_keyspace.person WHERE uuid IN ?");
195 fetchStmtUserHistoryList = session.prepare("SELECT * FROM g2_keyspace.userhistory WHERE userid IN ? ");
196 fetchStmtUserHistoryFromUuid = session.prepare("SELECT * FROM g2_keyspace.userhistory WHERE userid = ?");
197 fetchStmtAll = session.prepare("SELECT * FROM g2_keyspace.form");
198 }
199
200 //Creates a Form-object rom a row in the database
201 private Form getFormFromRow(Row row) {
202 return new Form(row.getString("uuid"), row.getInt("severity"), row.getString("url"), row.getList("comment", String.class), row.getString("location"), row.getString("incident"), row.getBool("isErrorIncident"), row.getList("people", String.class), row.getString("dateofincident"), row.getString("datecreated"), row.getBool("isdeleted"));
203 }
204}