-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathEligibilityCheckResource.java
More file actions
398 lines (329 loc) · 15.8 KB
/
EligibilityCheckResource.java
File metadata and controls
398 lines (329 loc) · 15.8 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
package org.acme.controller;
import io.quarkus.logging.Log;
import io.quarkus.security.identity.SecurityIdentity;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import com.fasterxml.jackson.databind.JsonNode;
import org.acme.auth.AuthUtils;
import org.acme.constants.CheckStatus;
import org.acme.model.domain.EligibilityCheck;
import org.acme.model.dto.CreateCheckRequest;
import org.acme.model.dto.EligibilityCheck.CheckDmnRequest;
import org.acme.model.dto.EligibilityCheck.EditCheckRequest;
import org.acme.persistence.EligibilityCheckRepository;
import org.acme.persistence.StorageService;
import org.acme.service.DmnService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Path("/api/custom-checks")
public class EligibilityCheckResource {
@Inject
EligibilityCheckRepository eligibilityCheckRepository;
@Inject
StorageService storageService;
@Inject
DmnService dmnService;
// ========== Collection Endpoints ==========
// By default, returns the most recent versions of all published checks owned by the calling user
// If the query parameter 'working' is set to true,
// then all the working check objects owned by the user are returned
@GET
public Response getCustomChecks(
@Context SecurityIdentity identity,
@QueryParam("working") Boolean working
) {
String userId = AuthUtils.getUserId(identity);
if (userId == null) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
List<EligibilityCheck> checks;
if (working != null && working){
Log.info("Fetching all working custom checks. User: " + userId);
checks = eligibilityCheckRepository.getWorkingCustomChecks(userId);
} else {
Log.info("Fetching all published custom checks. User: " + userId);
checks = eligibilityCheckRepository.getLatestVersionPublishedCustomChecks(userId);
}
return Response.ok(checks, MediaType.APPLICATION_JSON).build();
}
@POST
public Response createCustomCheck(@Context SecurityIdentity identity,
CreateCheckRequest request) {
String userId = AuthUtils.getUserId(identity);
// Build EligibilityCheck from allowed fields only
EligibilityCheck newCheck = new EligibilityCheck(
request.name,
request.module,
request.description,
request.parameterDefinitions,
userId
);
try {
eligibilityCheckRepository.saveNewWorkingCustomCheck(newCheck);
return Response.ok(newCheck, MediaType.APPLICATION_JSON).build();
} catch (Exception e){
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "Could not save Check"))
.build();
}
}
// ========== Single Resource Endpoints ==========
@GET
@Path("/{checkId}")
public Response getCustomCheck(@Context SecurityIdentity identity, @PathParam("checkId") String checkId) {
String userId = AuthUtils.getUserId(identity);
if (userId == null) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
char statusIndicator = (checkId != null && !checkId.isEmpty())
? checkId.charAt(0)
: '\0';
Optional<EligibilityCheck> checkOpt;
if (statusIndicator == CheckStatus.WORKING.getCode()){
Log.info("Fetching working custom check: " + checkId + " User: " + userId);
checkOpt = eligibilityCheckRepository.getWorkingCustomCheck(userId, checkId);
} else {
Log.info("Fetching published custom check: " + checkId + " User: " + userId);
checkOpt = eligibilityCheckRepository.getPublishedCustomCheck(userId, checkId);
}
if (checkOpt.isEmpty()){
return Response.status(Response.Status.NOT_FOUND).build();
}
EligibilityCheck check = checkOpt.get();
if (!check.getOwnerId().equals(userId)){
return Response.status(Response.Status.UNAUTHORIZED).build();
}
return Response.ok(check, MediaType.APPLICATION_JSON).build();
}
@PATCH
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{checkId}")
public Response updateCustomCheck(@Context SecurityIdentity identity,
@PathParam("checkId") String checkId,
@Valid EditCheckRequest request){
String userId = AuthUtils.getUserId(identity);
// Check if the check exists and is not archived
Optional<EligibilityCheck> existingCheckOpt = eligibilityCheckRepository.getWorkingCustomCheck(userId, checkId);
if (existingCheckOpt.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
EligibilityCheck existingCheck = existingCheckOpt.get();
// Authorization: verify ownership using existing record (not from request)
if (!userId.equals(existingCheck.getOwnerId())){
return Response.status(Response.Status.UNAUTHORIZED).build();
}
// Partial update: only update fields that are provided (non-null)
if (request.description() != null) {
existingCheck.setDescription(request.description());
}
if (request.parameterDefinitions() != null) {
existingCheck.setParameterDefinitions(request.parameterDefinitions());
}
try {
eligibilityCheckRepository.updateWorkingCustomCheck(existingCheck);
return Response.ok().entity(existingCheck).build();
} catch (Exception e){
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "could not update Check"))
.build();
}
}
// ========== Sub-Resource Endpoints: DMN ==========
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{checkId}/dmn")
public Response saveCheckDmn(@Context SecurityIdentity identity,
@PathParam("checkId") String checkId,
@Valid CheckDmnRequest saveDmnRequest){
String dmnModel = saveDmnRequest.dmnModel();
String userId = AuthUtils.getUserId(identity);
Optional<EligibilityCheck> checkOpt = eligibilityCheckRepository.getWorkingCustomCheck(userId, checkId);
if (checkOpt.isEmpty()){
return Response.status(Response.Status.NOT_FOUND).build();
}
EligibilityCheck check = checkOpt.get();
if (!check.getOwnerId().equals(userId)){
return Response.status(Response.Status.UNAUTHORIZED).build();
}
try {
String filePath = storageService.getCheckDmnModelPath(checkId);
storageService.writeStringToStorage(filePath, dmnModel, "application/xml");
Log.info("Saved DMN model of check " + checkId + " to storage");
// TODO: Need to figure out if we are allowing DMN versions to be mutable. If so, we need to update a
// last_saved field so that we know the check was updated and needs to be recompiled on evaluation
return Response.ok().build();
} catch (Exception e){
Log.info(("Failed to save DMN model for check " + checkId));
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{checkId}/dmn/validate")
public Response validateCheckDmn(@Context SecurityIdentity identity,
@PathParam("checkId") String checkId,
@Valid CheckDmnRequest validateDmnRequest){
String dmnModel = validateDmnRequest.dmnModel();
String userId = AuthUtils.getUserId(identity);
Optional<EligibilityCheck> checkOpt = eligibilityCheckRepository.getWorkingCustomCheck(userId, checkId);
if (checkOpt.isEmpty()){
return Response.status(Response.Status.NOT_FOUND).build();
}
EligibilityCheck check = checkOpt.get();
if (!check.getOwnerId().equals(userId)){
return Response.status(Response.Status.UNAUTHORIZED).build();
}
if (dmnModel == null || dmnModel.isBlank()){
return Response.ok(Map.of("errors", List.of("DMN Definition cannot be empty"))).build();
}
try {
HashMap<String, String> dmnDependenciesMap = new HashMap<String, String>();
List<String> validationErrors = dmnService.validateDmnXml(dmnModel, dmnDependenciesMap, check.getName(), check.getName());
if (!validationErrors.isEmpty()) {
validationErrors = validationErrors.stream()
.map(error -> error.replaceAll("\\(.*?\\)", ""))
.collect(java.util.stream.Collectors.toList());
return Response.ok(Map.of("errors", validationErrors)).build();
}
return Response.ok(Map.of("errors", List.of())).build();
} catch (Exception e){
Log.info(("Failed to validate DMN model for check " + checkId));
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
// ========== Sub-Resource Endpoints: Actions ==========
@POST
@Path("/{checkId}/publish")
public Response publishCustomCheck(@Context SecurityIdentity identity, @PathParam("checkId") String checkId){
String userId = AuthUtils.getUserId(identity);
Optional<EligibilityCheck> checkOpt = eligibilityCheckRepository.getWorkingCustomCheck(userId, checkId);
if (checkOpt.isEmpty()){
return Response.status(Response.Status.NOT_FOUND).build();
}
EligibilityCheck check = checkOpt.get();
// Authorization
if (!userId.equals(check.getOwnerId())){
return Response.status(Response.Status.UNAUTHORIZED).build();
}
// Retrieve DMN Path before incrementing version
Optional<String> workingDmnOpt = storageService.getStringFromStorage(storageService.getCheckDmnModelPath(check.getId()));
if (!workingDmnOpt.isPresent()) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "could not find DMN file for working Check"))
.build();
}
// Extract input schema from DMN
try {
String workingDmn = workingDmnOpt.get();
HashMap<String, String> dmnDependenciesMap = new HashMap<String, String>();
JsonNode inputSchema = dmnService.extractInputSchema(workingDmn, dmnDependenciesMap, check.getName());
check.setInputDefinition(inputSchema);
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "Failed to extract input schema for check " + check.getId()))
.build();
}
// Update workingCheck so that the incremented version number is saved
check.setVersion(incrementMajorVersion(check.getVersion()));
try {
eligibilityCheckRepository.updateWorkingCustomCheck(check);
} catch (Exception e){
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "could not update working Check, published check version was not created"))
.build();
}
// Create new published custom check
try {
// save published check meta data document
String publishedCheckId = eligibilityCheckRepository.saveNewPublishedCustomCheck(check);
// save published check DMN to storage
if (workingDmnOpt.isPresent()){
String workingDmn = workingDmnOpt.get();
storageService.writeStringToStorage(storageService.getCheckDmnModelPath(publishedCheckId), workingDmn, "application/xml");
} else {
Log.warn("Could not find working DMN model for check " + check.getId() + ", published check created without DMN model");
}
} catch (Exception e){
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "could not create new published custom check version"))
.build();
}
return Response.ok(check, MediaType.APPLICATION_JSON).build();
}
@POST
@Path("/{checkId}/archive")
public Response archiveCustomCheck(@Context SecurityIdentity identity, @PathParam("checkId") String checkId) {
String userId = AuthUtils.getUserId(identity);
if (userId == null) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
Optional<EligibilityCheck> checkOpt = eligibilityCheckRepository.getWorkingCustomCheck(userId, checkId, true);
if (checkOpt.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
EligibilityCheck check = checkOpt.get();
if (!check.getOwnerId().equals(userId)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
if (check.getIsArchived()) {
return Response.status(Response.Status.BAD_REQUEST)
.entity(Map.of("error", "Check is already archived"))
.build();
}
check.setIsArchived(true);
try {
eligibilityCheckRepository.updateWorkingCustomCheck(check);
return Response.ok().build();
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "Could not archive check"))
.build();
}
}
// ========== Sub-Resource Endpoints: Related Resources ==========
/* Endpoint for returning all Published Check Versions related to a given Working Eligibility Check */
@GET
@Path("/{checkId}/versions")
public Response getPublishedVersionsOfWorkingCheck(@Context SecurityIdentity identity, @PathParam("checkId") String checkId){
String userId = AuthUtils.getUserId(identity);
Optional<EligibilityCheck> checkOpt = eligibilityCheckRepository.getWorkingCustomCheck(userId, checkId);
if (checkOpt.isEmpty()){
return Response.status(Response.Status.NOT_FOUND).build();
}
EligibilityCheck check = checkOpt.get();
// Authorization
if (!userId.equals(check.getOwnerId())){
return Response.status(Response.Status.UNAUTHORIZED).build();
}
try {
List<EligibilityCheck> publishedChecks = eligibilityCheckRepository.getPublishedCheckVersions(check);
return Response.ok(publishedChecks, MediaType.APPLICATION_JSON).build();
} catch (Exception e){
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(Map.of("error", "could not update working Check, published check version was not created"))
.build();
}
}
// ========== Private Helper Methods ==========
private String incrementMajorVersion(String version) {
int[] v = normalize(version);
v[0]++; // increment major
v[1] = 0; // reset minor
v[2] = 0; // reset patch
return v[0] + "." + v[1] + "." + v[2];
}
private int[] normalize(String version) {
String[] parts = version.split("\\.");
int[] nums = new int[]{0, 0, 0};
for (int i = 0; i < parts.length && i < 3; i++) {
nums[i] = Integer.parseInt(parts[i]);
}
return nums;
}
}