-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathScreenerResource.java
More file actions
531 lines (455 loc) · 18.9 KB
/
ScreenerResource.java
File metadata and controls
531 lines (455 loc) · 18.9 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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
package org.acme.controller;
import io.quarkus.logging.Log;
import io.quarkus.security.identity.SecurityIdentity;
import jakarta.annotation.security.PermitAll;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.validation.Validator;
import jakarta.validation.constraints.NotBlank;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.acme.auth.AuthUtils;
import org.acme.model.domain.*;
import org.acme.model.dto.FormPathsResponse;
import org.acme.model.dto.PublishScreenerRequest;
import org.acme.model.dto.SaveSchemaRequest;
import org.acme.persistence.EligibilityCheckRepository;
import org.acme.persistence.ScreenerRepository;
import org.acme.persistence.PublishedScreenerRepository;
import org.acme.persistence.StorageService;
import org.acme.service.DmnService;
import org.acme.service.InputSchemaService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.acme.model.dto.Screener.CreateScreenerRequest;
import org.acme.model.dto.Screener.EditScreenerRequest;
@Path("/api")
public class ScreenerResource {
@Inject Validator validator;
@Inject ScreenerRepository screenerRepository;
@Inject PublishedScreenerRepository publishedScreenerRepository;
@Inject EligibilityCheckRepository eligibilityCheckRepository;
@Inject StorageService storageService;
@Inject DmnService dmnService;
@Inject
InputSchemaService inputSchemaService;
@GET
@Path("/screeners")
public Response getScreeners(@Context SecurityIdentity identity) {
String userId = AuthUtils.getUserId(identity);
if (userId == null){
return Response.status(Response.Status.UNAUTHORIZED).build();
}
Log.info("Fetching screeners for user: " + userId);
List<Screener> screeners = screenerRepository.getWorkingScreeners(userId);
return Response.ok(screeners, MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/screener/{screenerId}")
public Response getScreener(
@Context SecurityIdentity identity, @PathParam("screenerId") String screenerId) {
String userId = AuthUtils.getUserId(identity);
Log.info("Fetching screener " + screenerId + " for user " + userId);
Optional<Screener> screenerOptional = screenerRepository.getWorkingScreener(screenerId);
if (screenerOptional.isEmpty()) {
throw new NotFoundException();
}
Screener screener = screenerOptional.get();
if (!isUserAuthorizedToAccessScreenerByScreener(userId, screener)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
return Response.ok(screener, MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/published/screener/{screenerId}")
@PermitAll // This endpoint is accessible without authentication
public Response getPublishedScreener(@PathParam("screenerId") String screenerId) {
Optional<Screener> screenerOptional = publishedScreenerRepository.getScreener(screenerId);
if (screenerOptional.isEmpty()) {
throw new NotFoundException();
}
return Response.ok(screenerOptional.get(), MediaType.APPLICATION_JSON).build();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/screener")
public Response postScreener(
@Context SecurityIdentity identity, @Valid CreateScreenerRequest request) {
String userId = AuthUtils.getUserId(identity);
Screener newScreener = Screener.create(userId, request.screenerName(), request.description());
try {
String screenerId = screenerRepository.saveNewWorkingScreener(newScreener);
newScreener.setId(screenerId);
return Response.ok(newScreener, MediaType.APPLICATION_JSON).build();
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "Could not save Screener"))
.build();
}
}
@PATCH
@Consumes(MediaType.APPLICATION_JSON)
@Path("/screener/{screenerId}")
public Response updateScreener(
@Context SecurityIdentity identity,
@PathParam("screenerId") String screenerId,
@Valid EditScreenerRequest request) {
String userId = AuthUtils.getUserId(identity);
// Fetch Screener record and confirm user is authorized
Optional<Screener> maybeScreener = screenerRepository.getWorkingScreener(screenerId);
if (maybeScreener.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
Screener screener = maybeScreener.get();
if (!isUserAuthorizedToAccessScreenerByScreener(userId, screener)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
Log.info(request.toString());
// Update Screener fields from request
if (request.screenerName() != null) {
screener.setScreenerName(request.screenerName());
}
try {
screenerRepository.updateWorkingScreener(screener);
return Response.ok(screener, MediaType.APPLICATION_JSON).build();
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "Could not update Screener"))
.build();
}
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/save-form-schema")
public Response saveFormSchema(
@Context SecurityIdentity identity,
@QueryParam("screenerId") @NotBlank(message = "Must provide screenerId") String screenerId,
@Valid SaveSchemaRequest request) {
Log.info(
"schema node = "
+ (request == null
? "request=null"
: request.schema() == null
? "schema=null"
: request.schema().getNodeType() + " : " + request.schema().toString()));
var violations = validator.validate(request);
if (!violations.isEmpty()) {
return Response.status(400).entity(violations.toString()).build();
}
String userId = AuthUtils.getUserId(identity);
// Fetch Screener record and confirm user is authorized
Optional<Screener> maybeScreener = screenerRepository.getWorkingScreener(screenerId);
if (maybeScreener.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND)
.entity(Map.of("error", true, "message", "Screener " + screenerId + " cannot be found."))
.build();
}
Screener screener = maybeScreener.get();
if (!isUserAuthorizedToAccessScreenerByScreener(userId, screener)) {
return Response.status(Response.Status.UNAUTHORIZED)
.entity(Map.of("error", true, "message", "Unauthorized access to the screener."))
.build();
}
try {
String filePath = storageService.getScreenerWorkingFormSchemaPath(screenerId);
storageService.writeJsonToStorage(filePath, request.schema());
return Response.ok().build();
} catch (Exception e) {
Log.info(("Failed to save form for screener " + screenerId));
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/publish")
public Response publishScreener(
@Context SecurityIdentity identity, PublishScreenerRequest publishScreenerRequest) {
String screenerId = publishScreenerRequest.screenerId;
if (screenerId == null || screenerId.isBlank()) {
return Response.status(Response.Status.BAD_REQUEST)
.entity("Error: Missing required query parameter: screenerId")
.build();
}
String userId = AuthUtils.getUserId(identity);
if (!isUserAuthorizedToAccessScreener(userId, screenerId))
return Response.status(Response.Status.UNAUTHORIZED).build();
try {
Optional<Screener> screenerOpt = screenerRepository.getWorkingScreener(screenerId);
if (screenerOpt.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
Screener screener = screenerOpt.get();
screenerRepository.publishScreener(screener);
return Response.ok().build();
} catch (Exception e) {
Log.error("Error: Error updating screener to published. Screener: " + screenerId);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@DELETE
@Path("/screener/delete")
public Response deleteScreener(
@Context SecurityIdentity identity, @QueryParam("screenerId") String screenerId) {
if (screenerId == null || screenerId.isBlank()) {
return Response.status(Response.Status.BAD_REQUEST)
.entity("Error: Missing required query parameter: screenerId")
.build();
}
String userId = AuthUtils.getUserId(identity);
if (!isUserAuthorizedToAccessScreener(userId, screenerId))
return Response.status(Response.Status.UNAUTHORIZED).build();
try {
screenerRepository.deleteWorkingScreener(screenerId);
return Response.ok().build();
} catch (Exception e) {
Log.error("Error: error deleting screener " + screenerId);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
/**
* Returns the list of unique input paths required by all checks in a screener.
* This endpoint transforms inputDefinition schemas and extracts paths,
* replacing the frontend's transformInputDefinitionSchema and extractJsonSchemaPaths logic.
*/
@GET
@Path("/screener/{screenerId}/form-paths")
public Response getScreenerFormPaths(@Context SecurityIdentity identity,
@PathParam("screenerId") String screenerId) {
String userId = AuthUtils.getUserId(identity);
Optional<Screener> screenerOpt = screenerRepository.getWorkingScreener(screenerId);
if (screenerOpt.isEmpty()) {
throw new NotFoundException();
}
Screener screener = screenerOpt.get();
if (!isUserAuthorizedToAccessScreenerByScreener(userId, screener)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
try {
List<Benefit> benefits = screenerRepository.getBenefitsInScreener(screener);
List<FormPath> paths = new ArrayList<>(inputSchemaService.extractUniqueInputPaths(benefits));
Collections.sort(paths, new Comparator<FormPath>() {
public int compare(FormPath fp1, FormPath fp2) {
// compare two instance of `Score` and return `int` as result.
return fp1.getPath().compareTo(fp2.getPath());
}
});
return Response.ok().entity(new FormPathsResponse(paths)).build();
} catch (Exception e) {
Log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "Could not extract form paths"))
.build();
}
}
private boolean isUserAuthorizedToAccessScreener(String userId, String screenerId) {
Optional<Screener> screenerOptional =
screenerRepository.getWorkingScreenerMetaDataOnly(screenerId);
if (screenerOptional.isEmpty()) {
return false;
}
Screener screener = screenerOptional.get();
return isUserAuthorizedToAccessScreenerByScreener(userId, screener);
}
private boolean isUserAuthorizedToAccessScreenerByScreener(String userId, Screener screener) {
return userId.equals(screener.getOwnerId());
}
@GET
@Path("/screener/{screenerId}/benefit")
public Response getScreenerBenefits(
@Context SecurityIdentity identity, @PathParam("screenerId") String screenerId) {
String userId = AuthUtils.getUserId(identity);
Optional<Screener> screenerOpt = screenerRepository.getWorkingScreener(screenerId);
if (screenerOpt.isEmpty()) {
throw new NotFoundException();
}
Screener screener = screenerOpt.get();
if (!isUserAuthorizedToAccessScreenerByScreener(userId, screener)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
try {
List<Benefit> benefits = screenerRepository.getBenefitsInScreener(screener);
return Response.ok().entity(benefits).build();
} catch (Exception e) {
Log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "Could not fetch benefits"))
.build();
}
}
@GET
@Path("/screener/{screenerId}/benefit/{benefitId}")
public Response getScreenerBenefit(
@Context SecurityIdentity identity,
@PathParam("screenerId") String screenerId,
@PathParam("benefitId") String benefitId) {
String userId = AuthUtils.getUserId(identity);
if (!isUserAuthorizedToAccessScreener(userId, screenerId)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
try {
Optional<Benefit> benefitOpt = screenerRepository.getCustomBenefit(screenerId, benefitId);
if (benefitOpt.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok().entity(benefitOpt.get()).build();
} catch (Exception e) {
Log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "Could not fetch benefit"))
.build();
}
}
@GET
@Path("/screener/{screenerId}/benefit/{benefitId}/check")
public Response getScreenerCustomBenefitChecks(
@Context SecurityIdentity identity,
@PathParam("screenerId") String screenerId,
@PathParam("benefitId") String benefitId) {
try {
String userId = AuthUtils.getUserId(identity);
Optional<Screener> screenerOpt = screenerRepository.getWorkingScreener(screenerId);
if (screenerOpt.isEmpty()) {
throw new NotFoundException();
}
Screener screener = screenerOpt.get();
if (!isUserAuthorizedToAccessScreenerByScreener(userId, screener)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
Optional<Benefit> benefitOpt = screenerRepository.getCustomBenefit(screenerId, benefitId);
if (benefitOpt.isEmpty()) {
throw new NotFoundException();
}
List<EligibilityCheck> checks =
eligibilityCheckRepository.getChecksInBenefit(benefitOpt.get());
return Response.ok().entity(checks).build();
} catch (Exception e) {
Log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "Could not fetch checks"))
.build();
}
}
@POST
@Path("/screener/{screenerId}/benefit")
public Response addCustomBenefit(
@Context SecurityIdentity identity,
@PathParam("screenerId") String screenerId,
Benefit newBenefit) {
String userId = AuthUtils.getUserId(identity);
newBenefit.setOwnerId(userId);
newBenefit.setChecks(Collections.emptyList());
BenefitDetail benefitDetail = new BenefitDetail();
benefitDetail.setId(newBenefit.getId());
benefitDetail.setName(newBenefit.getName());
benefitDetail.setDescription(newBenefit.getDescription());
benefitDetail.setPublic(newBenefit.getPublic());
try {
// Check to make sure not introducing duplicates
Optional<Screener> screenerOpt = screenerRepository.getWorkingScreener(screenerId);
if (screenerOpt.isEmpty()) {
Log.error("Screener not found. Screener ID:" + screenerId);
throw new NotFoundException();
}
Screener screener = screenerOpt.get();
// Authorise action
if (userId != null && !isUserAuthorizedToAccessScreenerByScreener(userId, screener)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
List<BenefitDetail> benefits = screenerOpt.get().getBenefits();
if (benefits == null) {
benefits = Collections.emptyList();
}
Boolean benefitIdExists =
!benefits.stream()
.filter(benefit -> benefit.getId().equals(benefitDetail.getId()))
.toList()
.isEmpty();
if (benefitIdExists) {
return Response.status(
Response.Status.CONFLICT.getStatusCode(),
"Benefit with provided ID already exists on screener.")
.build();
}
String benefitId = screenerRepository.saveNewCustomBenefit(screenerId, newBenefit);
screenerRepository.addBenefitDetailToWorkingScreener(screenerId, benefitDetail);
newBenefit.setId(benefitId);
return Response.ok(newBenefit, MediaType.APPLICATION_JSON).build();
} catch (Exception e) {
Log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "Could not save benefit"))
.build();
}
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("/screener/{screenerId}/benefit")
public Response updateCustomBenefit(
@Context SecurityIdentity identity,
@PathParam("screenerId") String screenerId,
Benefit updatedBenefit) {
String userId = AuthUtils.getUserId(identity);
// TODO: Add validations for user provided data
if (!isUserAuthorizedToAccessScreener(userId, screenerId)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
try {
Optional<Benefit> benefitOpt =
screenerRepository.getCustomBenefit(screenerId, updatedBenefit.getId());
if (benefitOpt.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
screenerRepository.updateCustomBenefit(screenerId, updatedBenefit);
return Response.ok(updatedBenefit, MediaType.APPLICATION_JSON).build();
} catch (Exception e) {
Log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "Could not update custom benefit"))
.build();
}
}
@DELETE
@Path("/screener/{screenerId}/benefit/{benefitId}")
public Response deleteCustomBenefit(
@Context SecurityIdentity identity,
@PathParam("screenerId") String screenerId,
@PathParam("benefitId") String benefitId) {
try {
// Check if Screener and Benefit exist
Optional<Screener> screenerOpt = screenerRepository.getWorkingScreener(screenerId);
Optional<Benefit> benefitOpt = screenerRepository.getCustomBenefit(screenerId, benefitId);
if (screenerOpt.isEmpty()) {
throw new NotFoundException();
}
if (benefitOpt.isEmpty()) {
throw new NotFoundException();
}
// Confirm user is authorized to make the change
String userId = AuthUtils.getUserId(identity);
Screener screener = screenerOpt.get();
if (!isUserAuthorizedToAccessScreenerByScreener(userId, screener)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
// Delete the benefit and remove the benefitDetail from the screener
screenerRepository.deleteCustomBenefit(screenerId, benefitId);
List<BenefitDetail> updatedBenefits =
screener.getBenefits().stream()
.filter(benefitDetail -> !benefitDetail.getId().equals(benefitId))
.toList();
screener.setBenefits(updatedBenefits);
screenerRepository.updateWorkingScreener(screener);
return Response.ok().build();
} catch (Exception e) {
Log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "Could not delete custom benefit"))
.build();
}
}
}