-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskApiHandler.java
More file actions
476 lines (431 loc) · 22.4 KB
/
Copy pathTaskApiHandler.java
File metadata and controls
476 lines (431 loc) · 22.4 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package com.strms.web;
import com.strms.controller.TaskManager;
import com.strms.enums.PriorityLevel;
import com.strms.enums.TaskCategory;
import com.strms.exceptions.DuplicateTaskException;
import com.strms.exceptions.InvalidRoleException;
import com.strms.exceptions.InvalidTaskStateException;
import com.strms.exceptions.TaskNotFoundException;
import com.strms.model.Admin;
import com.strms.model.Engineer;
import com.strms.model.Manager;
import com.strms.model.Task;
import com.strms.model.User;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Handles all /api/* requests for the STRMS web interface.
* Returns JSON responses, accepts JSON POST bodies.
*/
public class TaskApiHandler implements HttpHandler {
private static final User WEB_ADMIN = new Admin("WEB", "Web User", "web@strms.local");
private final TaskManager taskManager;
public TaskApiHandler(TaskManager taskManager) {
this.taskManager = taskManager;
}
@Override
public void handle(HttpExchange exchange) throws IOException {
String path = exchange.getRequestURI().getPath();
String method = exchange.getRequestMethod();
addCorsHeaders(exchange);
if ("OPTIONS".equals(method)) {
sendResponse(exchange, 204, "");
return;
}
try {
if (path.equals("/api/stats") && "GET".equals(method)) {
handleGetStats(exchange);
} else if (path.equals("/api/users") && "GET".equals(method)) {
handleGetUsers(exchange);
} else if (path.equals("/api/tasks") && "GET".equals(method)) {
handleGetTasks(exchange);
} else if (path.equals("/api/tasks") && "POST".equals(method)) {
handleCreateTask(exchange);
} else if (path.equals("/api/tasks/assign") && "POST".equals(method)) {
handleAssignTask(exchange);
} else if (path.equals("/api/tasks/start") && "POST".equals(method)) {
handleStartTask(exchange);
} else if (path.equals("/api/tasks/complete") && "POST".equals(method)) {
handleCompleteTask(exchange);
} else if (path.equals("/api/tasks/delete") && "POST".equals(method)) {
handleDeleteTask(exchange);
} else if (path.equals("/api/users") && "POST".equals(method)) {
handleCreateUser(exchange);
} else if (path.equals("/api/users/delete") && "POST".equals(method)) {
handleDeleteUser(exchange);
} else if (path.equals("/api/auth/login") && "POST".equals(method)) {
handleLogin(exchange);
} else if (path.equals("/api/tasks/update") && "POST".equals(method)) {
handleUpdateTask(exchange);
} else if (path.equals("/api/tasks/dependency/add") && "POST".equals(method)) {
handleAddDependency(exchange);
} else if (path.equals("/api/tasks/dependency/remove") && "POST".equals(method)) {
handleRemoveDependency(exchange);
} else {
sendResponse(exchange, 404, "{\"error\":\"Route non trouvee\"}");
}
} catch (Exception e) {
sendResponse(exchange, 500, "{\"error\":\"" + escape(e.getMessage()) + "\"}");
}
}
// ── GET /api/tasks ────────────────────────────────────────────────────────
private void handleGetTasks(HttpExchange exchange) throws IOException {
Collection<Task> tasks = taskManager.getAllTasks();
StringBuilder sb = new StringBuilder("[");
boolean first = true;
for (Task t : tasks) {
if (!first) sb.append(",");
first = false;
sb.append(taskToJson(t));
}
sb.append("]");
sendJson(exchange, 200, sb.toString());
}
// ── GET /api/stats ────────────────────────────────────────────────────────
private void handleGetStats(HttpExchange exchange) throws IOException {
Collection<Task> tasks = taskManager.getAllTasks();
int total = tasks.size();
int done = 0, inProgress = 0, todo = 0, blocked = 0, overdue = 0;
for (Task t : tasks) {
switch (t.getStatus()) {
case DONE -> done++;
case IN_PROGRESS -> inProgress++;
case TODO -> todo++;
case BLOCKED -> blocked++;
}
if (t.isOverdue()) overdue++;
}
int pct = total == 0 ? 0 : (done * 100 / total);
String json = "{"
+ "\"total\":" + total + ","
+ "\"done\":" + done + ","
+ "\"inProgress\":" + inProgress + ","
+ "\"todo\":" + todo + ","
+ "\"blocked\":" + blocked + ","
+ "\"overdue\":" + overdue + ","
+ "\"completion\":" + pct
+ "}";
sendJson(exchange, 200, json);
}
// ── GET /api/users ────────────────────────────────────────────────────────
private void handleGetUsers(HttpExchange exchange) throws IOException {
Collection<User> users = taskManager.getAllUsers();
StringBuilder sb = new StringBuilder("[");
boolean first = true;
for (User u : users) {
if (!first) sb.append(",");
first = false;
sb.append("{\"id\":\"").append(escape(u.getId())).append("\",")
.append("\"name\":\"").append(escape(u.getName())).append("\",")
.append("\"role\":\"").append(escape(u.getRole())).append("\"}");
}
sb.append("]");
sendJson(exchange, 200, sb.toString());
}
// ── POST /api/tasks ───────────────────────────────────────────────────────
private void handleCreateTask(HttpExchange exchange) throws IOException {
Map<String, String> body = parseBody(exchange);
String id = body.getOrDefault("id", "");
String title = body.getOrDefault("title", "");
String desc = body.getOrDefault("description", "");
String pl = body.getOrDefault("priority", "MEDIUM");
String cat = body.getOrDefault("category", "FEATURE");
String dl = body.getOrDefault("deadline", "");
if (id.isBlank() || title.isBlank()) {
sendJson(exchange, 400, "{\"error\":\"id et title sont obligatoires\"}");
return;
}
LocalDate deadline = dl.isBlank() ? null : LocalDate.parse(dl);
Task task = new Task(id, title, desc,
PriorityLevel.valueOf(pl),
TaskCategory.valueOf(cat),
deadline);
try {
taskManager.addTask(task, WEB_ADMIN);
sendJson(exchange, 201, "{\"message\":\"Tache creee\",\"id\":\"" + escape(id) + "\"}");
} catch (InvalidRoleException | DuplicateTaskException e) {
sendJson(exchange, 400, "{\"error\":\"" + escape(e.getMessage()) + "\"}");
}
}
// ── POST /api/tasks/assign ────────────────────────────────────────────────
private void handleAssignTask(HttpExchange exchange) throws IOException {
Map<String, String> body = parseBody(exchange);
String taskId = body.getOrDefault("taskId", "");
String userId = body.getOrDefault("userId", "");
try {
taskManager.assignTask(taskId, userId, WEB_ADMIN);
sendJson(exchange, 200, "{\"message\":\"Tache assignee\"}");
} catch (InvalidRoleException | TaskNotFoundException e) {
sendJson(exchange, 400, "{\"error\":\"" + escape(e.getMessage()) + "\"}");
}
}
// ── POST /api/tasks/start ─────────────────────────────────────────────────
private void handleStartTask(HttpExchange exchange) throws IOException {
Map<String, String> body = parseBody(exchange);
String taskId = body.getOrDefault("taskId", "");
try {
taskManager.startTask(taskId, WEB_ADMIN);
sendJson(exchange, 200, "{\"message\":\"Tache demarree\"}");
} catch (Exception e) {
sendJson(exchange, 400, "{\"error\":\"" + escape(e.getMessage()) + "\"}");
}
}
// ── POST /api/tasks/complete ──────────────────────────────────────────────
private void handleCompleteTask(HttpExchange exchange) throws IOException {
Map<String, String> body = parseBody(exchange);
String taskId = body.getOrDefault("taskId", "");
try {
taskManager.completeTask(taskId, WEB_ADMIN);
sendJson(exchange, 200, "{\"message\":\"Tache terminee\"}");
} catch (TaskNotFoundException | InvalidTaskStateException e) {
sendJson(exchange, 400, "{\"error\":\"" + escape(e.getMessage()) + "\"}");
}
}
// ── POST /api/tasks/delete ────────────────────────────────────────────────
private void handleDeleteTask(HttpExchange exchange) throws IOException {
Map<String, String> body = parseBody(exchange);
String taskId = body.getOrDefault("taskId", "");
try {
taskManager.deleteTask(taskId, WEB_ADMIN);
sendJson(exchange, 200, "{\"message\":\"Tache supprimee\"}");
} catch (Exception e) {
sendJson(exchange, 400, "{\"error\":\"" + escape(e.getMessage()) + "\"}");
}
}
// ── POST /api/users ───────────────────────────────────────────────────────
private void handleCreateUser(HttpExchange exchange) throws IOException {
Map<String, String> body = parseBody(exchange);
String id = body.getOrDefault("id", "").trim();
String name = body.getOrDefault("name", "").trim();
String email = body.getOrDefault("email", "").trim();
String role = body.getOrDefault("role", "Engineer").trim();
String pass = body.getOrDefault("password", "").trim();
if (id.isBlank() || name.isBlank() || email.isBlank()) {
sendJson(exchange, 400, "{\"error\":\"id, name et email sont obligatoires\"}");
return;
}
if (taskManager.getAllUsers().stream().anyMatch(u -> u.getId().equals(id))) {
sendJson(exchange, 400, "{\"error\":\"Un utilisateur avec cet ID existe deja\"}");
return;
}
User user = switch (role) {
case "Admin" -> new Admin(id, name, email);
case "Manager" -> new Manager(id, name, email);
default -> new Engineer(id, name, email);
};
if (!pass.isBlank()) user.setPassword(pass);
taskManager.addUser(user);
try { taskManager.saveUsersToFile("strms_users.csv"); } catch (Exception ignored) {}
sendJson(exchange, 201, "{\"message\":\"Utilisateur cree\",\"id\":\"" + escape(id) + "\"}");
}
// ── POST /api/users/delete ────────────────────────────────────────────────
private void handleDeleteUser(HttpExchange exchange) throws IOException {
Map<String, String> body = parseBody(exchange);
String id = body.getOrDefault("id", "").trim();
if (id.isBlank()) {
sendJson(exchange, 400, "{\"error\":\"id est obligatoire\"}");
return;
}
boolean removed = taskManager.removeUser(id);
if (!removed) {
sendJson(exchange, 404, "{\"error\":\"Utilisateur introuvable\"}");
return;
}
try { taskManager.saveUsersToFile("strms_users.csv"); } catch (Exception ignored) {}
sendJson(exchange, 200, "{\"message\":\"Utilisateur supprime\"}");
}
// ── POST /api/auth/login ──────────────────────────────────────────────────
private void handleLogin(HttpExchange exchange) throws IOException {
Map<String, String> body = parseBody(exchange);
String name = body.getOrDefault("name", "").trim();
String pass = body.getOrDefault("password", "").trim();
if (name.isBlank() || pass.isBlank()) {
sendJson(exchange, 400, "{\"error\":\"name et password sont obligatoires\"}");
return;
}
User found = taskManager.getAllUsers().stream()
.filter(u -> u.getName().equalsIgnoreCase(name))
.findFirst().orElse(null);
if (found == null) {
sendJson(exchange, 401, "{\"error\":\"Utilisateur introuvable\"}");
return;
}
if (!found.checkPassword(pass)) {
sendJson(exchange, 401, "{\"error\":\"Mot de passe incorrect\"}");
return;
}
sendJson(exchange, 200,
"{\"name\":\"" + escape(found.getName()) + "\"," +
"\"role\":\"" + escape(found.getRole()) + "\"," +
"\"id\":\"" + escape(found.getId()) + "\"}");
}
// ── POST /api/tasks/update ────────────────────────────────────────────────
private void handleUpdateTask(HttpExchange exchange) throws IOException {
Map<String, String> body = parseBody(exchange);
String taskId = body.getOrDefault("taskId", "").trim();
if (taskId.isBlank()) {
sendJson(exchange, 400, "{\"error\":\"taskId est obligatoire\"}");
return;
}
try {
// Validation explicite demandee : ID inconnu => 404, pas 400/500.
taskManager.findTask(taskId);
} catch (TaskNotFoundException e) {
sendJson(exchange, 404, "{\"error\":\"Task not found\"}");
return;
}
String title = body.getOrDefault("title", "").trim();
String desc = body.getOrDefault("description", "").trim();
String pl = body.getOrDefault("priority", "").trim();
String cat = body.getOrDefault("category", "").trim();
String dl = body.getOrDefault("deadline", "").trim();
PriorityLevel priority;
TaskCategory category;
LocalDate deadline;
try {
priority = pl.isBlank() ? null : PriorityLevel.valueOf(pl);
category = cat.isBlank() ? null : TaskCategory.valueOf(cat);
deadline = dl.isBlank() ? null : LocalDate.parse(dl);
} catch (Exception e) {
sendJson(exchange, 400, "{\"error\":\"Invalid input value\"}");
return;
}
try {
taskManager.updateTask(taskId,
title.isBlank() ? null : title,
desc.isBlank() ? null : desc,
priority, category, deadline, WEB_ADMIN);
sendJson(exchange, 200, "{\"message\":\"Tache mise a jour\"}");
} catch (TaskNotFoundException e) {
sendJson(exchange, 404, "{\"error\":\"Task not found\"}");
} catch (InvalidRoleException e) {
sendJson(exchange, 400, "{\"error\":\"" + escape(e.getMessage()) + "\"}");
}
}
// ── POST /api/tasks/dependency/add ────────────────────────────────────────
private void handleAddDependency(HttpExchange exchange) throws IOException {
Map<String, String> body = parseBody(exchange);
String taskId = body.getOrDefault("taskId", "").trim();
String depId = body.getOrDefault("depId", "").trim();
if (taskId.isBlank() || depId.isBlank()) {
sendJson(exchange, 400, "{\"error\":\"taskId et depId sont obligatoires\"}");
return;
}
try {
// Validation explicite : verifier les deux IDs avant modification.
taskManager.findTask(taskId);
taskManager.findTask(depId);
taskManager.addDependency(taskId, depId);
sendJson(exchange, 200, "{\"message\":\"Dependance ajoutee\"}");
} catch (TaskNotFoundException e) {
sendJson(exchange, 404, "{\"error\":\"Task not found\"}");
} catch (Exception e) {
sendJson(exchange, 400, "{\"error\":\"" + escape(e.getMessage()) + "\"}");
}
}
// ── POST /api/tasks/dependency/remove ─────────────────────────────────────
private void handleRemoveDependency(HttpExchange exchange) throws IOException {
Map<String, String> body = parseBody(exchange);
String taskId = body.getOrDefault("taskId", "").trim();
String depId = body.getOrDefault("depId", "").trim();
if (taskId.isBlank() || depId.isBlank()) {
sendJson(exchange, 400, "{\"error\":\"taskId et depId sont obligatoires\"}");
return;
}
try {
// Validation explicite : verifier les deux IDs avant modification.
taskManager.findTask(taskId);
taskManager.findTask(depId);
taskManager.removeDependency(taskId, depId);
sendJson(exchange, 200, "{\"message\":\"Dependance supprimee\"}");
} catch (TaskNotFoundException e) {
sendJson(exchange, 404, "{\"error\":\"Task not found\"}");
} catch (Exception e) {
sendJson(exchange, 400, "{\"error\":\"" + escape(e.getMessage()) + "\"}");
}
}
// ── Helpers ───────────────────────────────────────────────────────────────
private String taskToJson(Task t) {
String assignee = t.getAssignedTo() != null ? t.getAssignedTo().getName() : "";
String assigneeId = t.getAssignedTo() != null ? t.getAssignedTo().getId() : "";
String deadline = t.getDeadline() != null ? t.getDeadline().toString() : "";
String dependencies = dependenciesToJson(t);
return "{"
+ "\"id\":\"" + escape(t.getId()) + "\","
+ "\"title\":\"" + escape(t.getTitle()) + "\","
+ "\"description\":\"" + escape(t.getDescription()) + "\","
+ "\"status\":\"" + t.getStatus().name() + "\","
+ "\"priority\":\"" + t.getPriorityLevel().name() + "\","
+ "\"category\":\"" + t.getCategory().name() + "\","
+ "\"deadline\":\"" + deadline + "\","
+ "\"assignedTo\":\"" + escape(assignee) + "\","
+ "\"assignedToId\":\"" + escape(assigneeId) + "\","
+ "\"dependencies\":" + dependencies + ","
+ "\"isBlocked\":" + t.isBlocked() + ","
+ "\"isOverdue\":" + t.isOverdue()
+ "}";
}
private String dependenciesToJson(Task t) {
StringBuilder sb = new StringBuilder("[");
boolean first = true;
for (Task dep : t.getDependencies()) {
if (!first) sb.append(",");
first = false;
sb.append("\"").append(escape(dep.getId())).append("\"");
}
sb.append("]");
return sb.toString();
}
private Map<String, String> parseBody(HttpExchange exchange) throws IOException {
Map<String, String> map = new HashMap<>();
try (InputStream is = exchange.getRequestBody()) {
String body = new String(is.readAllBytes(), StandardCharsets.UTF_8).trim();
// Robust JSON parser: extract "key":"value" pairs (handles spaces in values)
java.util.regex.Matcher m = java.util.regex.Pattern
.compile("\"([^\"]+)\"\\s*:\\s*\"([^\"]*)\"")
.matcher(body);
while (m.find()) {
map.put(m.group(1), m.group(2));
}
// Also handle "key":true/false/number (unquoted values)
java.util.regex.Matcher m2 = java.util.regex.Pattern
.compile("\"([^\"]+)\"\\s*:\\s*([^,}\"\\s]+)")
.matcher(body);
while (m2.find()) {
map.putIfAbsent(m2.group(1), m2.group(2));
}
}
return map;
}
private void addCorsHeaders(HttpExchange exchange) {
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
exchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type");
}
private void sendJson(HttpExchange exchange, int code, String json) throws IOException {
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=UTF-8");
sendResponse(exchange, code, json);
}
private void sendResponse(HttpExchange exchange, int code, String body) throws IOException {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(code, bytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(bytes);
}
}
private String escape(String s) {
if (s == null) return "";
return s.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r");
}
}