/
CohortBuilderController.java
688 lines (592 loc) · 21.7 KB
/
CohortBuilderController.java
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.controller.analysis;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.WeakHashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.NullComparator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Cohort;
import org.openmrs.Concept;
import org.openmrs.ConceptAnswer;
import org.openmrs.ConceptName;
import org.openmrs.Drug;
import org.openmrs.User;
import org.openmrs.api.APIAuthenticationException;
import org.openmrs.api.ConceptService;
import org.openmrs.api.context.Context;
import org.openmrs.cohort.CohortSearchHistory;
import org.openmrs.module.reportingcompatibility.CohortBuilderLinkProvider;
import org.openmrs.reporting.PatientFilter;
import org.openmrs.reporting.PatientSearch;
import org.openmrs.reporting.PatientSearchReportObject;
import org.openmrs.reporting.ReportObjectService;
import org.openmrs.util.HandlerUtil;
import org.openmrs.web.WebConstants;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.RedirectView;
public class CohortBuilderController implements Controller {
protected final Log log = LogFactory.getLog(getClass());
private String formView;
private String successView;
private static Map<User, Map<String, Object>> volatileUserData = new WeakHashMap<User, Map<String, Object>>();
public CohortBuilderController() {
}
public String getFormView() {
return formView;
}
public void setFormView(String formView) {
this.formView = formView;
}
public String getSuccessView() {
return successView;
}
public void setSuccessView(String successView) {
this.successView = successView;
}
public List<String> getLinks() {
List<String> ret = new ArrayList<String>();
for (CohortBuilderLinkProvider p : HandlerUtil.getHandlersForType(CohortBuilderLinkProvider.class, null)) {
List<String> links = p.getLinkSpecifications();
if (links != null)
ret.addAll(links);
}
return ret;
}
public static Object getVolatileUserData(String key) {
User u = Context.getAuthenticatedUser();
if (u == null) {
throw new APIAuthenticationException();
}
Map<String, Object> myData = volatileUserData.get(u);
if (myData == null) {
return null;
} else {
return myData.get(key);
}
}
public static void setVolatileUserData(String key, Object value) {
User u = Context.getAuthenticatedUser();
if (u == null) {
throw new APIAuthenticationException();
}
Map<String, Object> myData = volatileUserData.get(u);
if (myData == null) {
myData = new HashMap<String, Object>();
volatileUserData.put(u, myData);
}
myData.put(key, value);
}
private void setMySearchHistory(HttpServletRequest request, CohortSearchHistory history) {
setVolatileUserData("CohortBuilderSearchHistory", history);
}
private CohortSearchHistory getMySearchHistory(HttpServletRequest request) {
try {
Object searchHistoryObj = getVolatileUserData("CohortBuilderSearchHistory");
return (CohortSearchHistory) searchHistoryObj;
}
catch (Exception e) {
log.debug("An error occurred while trying to retrieve search history for user.", e);
}
return null;
}
private ModelAndView handleMethod(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ModelAndView modelAndView = null;
String method = request.getParameter("method");
if ("addFilter".equals(method)) {
modelAndView = addFilter(request, response);
}
else if ("addDynamicFilter".equals(method)) {
try {
modelAndView = addDynamicFilter(request, response);
}
catch (ClassNotFoundException ex) {
throw new IllegalArgumentException(ex);
}
}
else if ("saveHistory".equals(method)) {
modelAndView = saveHistory(request, response);
}
else if ("clearHistory".equals(method)) {
modelAndView = clearHistory(request, response);
}
else if ("removeFilter".equals(method)) {
modelAndView = removeFilter(request, response);
}
return modelAndView;
}
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
ModelAndView modelAndView = handleMethod(request, response);
if (modelAndView != null) {
return modelAndView;
}
Map<String, Object> model = new HashMap<String, Object>();
if (Context.isAuthenticated()) {
CohortSearchHistory history = getMySearchHistory(request);
if (history == null) {
history = new CohortSearchHistory();
setMySearchHistory(request, history);
}
List<Shortcut> shortcuts = new ArrayList<Shortcut>();
String shortcutProperty = Context.getAdministrationService().getGlobalProperty("cohort.cohortBuilder.shortcuts");
if (shortcutProperty != null && shortcutProperty.length() > 0) {
String[] shortcutSpecs = shortcutProperty.split(";");
for (int i = 0; i < shortcutSpecs.length; ++i) {
try {
shortcuts.add(new Shortcut(shortcutSpecs[i]));
}
catch (Exception ex) {
log.error("Exception trying to create filter from shortcut", ex);
}
}
}
ConceptService cs = Context.getConceptService();
// TODO: generalize this beyond PIH data model
List<Concept> orderStopReasons = new ArrayList<Concept>();
{
Concept c = cs.getConceptByName("REASON ORDER STOPPED");
if (c != null)
orderStopReasons.addAll(cs.getConceptsByConceptSet(c));
if (c != null && c.getAnswers() != null)
for (ConceptAnswer ca : c.getAnswers())
orderStopReasons.add(ca.getAnswerConcept());
}
List<Concept> genericDrugs = Context.getConceptService().getConceptsWithDrugsInFormulary();
Collections.sort(genericDrugs, new Comparator<Concept>() {
private NullComparator nullComparator = new NullComparator(false);
public int compare(Concept left, Concept right) {
ConceptName leftName = left.getName();
ConceptName rightName = right.getName();
if (leftName == null || rightName == null) {
return nullComparator.compare(leftName, rightName);
} else {
return nullComparator.compare(leftName.getName(), rightName.getName());
}
}
});
List<Concept> drugSets = new ArrayList<Concept>();
{
String temp = Context.getAdministrationService().getGlobalProperty("cohortBuilder.drugSets");
if (StringUtils.hasText(temp)) {
String[] drugSetNames = temp.split(",");
for (String setName : drugSetNames) {
Concept c = Context.getConceptService().getConcept(setName);
if (c != null)
drugSets.add(c);
}
}
}
List<Drug> allDrugs = Context.getConceptService().getAllDrugs();
Collections.sort(allDrugs, new BeanComparator("displayName"));
model.put("searchHistory", history);
model.put("links", linkHelper());
model.put("programs", Context.getProgramWorkflowService().getAllPrograms());
model.put("encounterTypes", Context.getEncounterService().getAllEncounterTypes());
model.put("locations", Context.getLocationService().getAllLocations());
model.put("forms", Context.getFormService().getAllForms());
model.put("drugs", allDrugs);
model.put("drugConcepts", genericDrugs);
model.put("drugSets", drugSets);
model.put("orderStopReasons", orderStopReasons);
model.put("personAttributeTypes", Context.getPersonService().getAllPersonAttributeTypes());
model.put("shortcuts", shortcuts);
}
return new ModelAndView(formView, "model", model);
}
public class Shortcut {
private String label;
private PatientFilter patientFilter;
private String className;
private List<ArgHolder> args;
private Boolean hasPromptArgs;
private String vars;
public Shortcut() {
}
public Shortcut(String spec) {
// possible formats:
// (1) just the name of a saved filter
// (2) a label, then a colon, then the name of a saved filter
// (3) a label, then a colon, then @className(argname=argvalue#argClassName,...)
// (e.g. male:@org.openmrs.reporting.PatientCharacteristicFilter(gender=m#java.lang.String)
String label = null;
if (spec.indexOf(":") > 0) {
label = spec.substring(0, spec.indexOf(":"));
spec = spec.substring(spec.indexOf(":") + 1);
}
if (spec.startsWith("@")) {
// could be "@org.openmrs.reporting.ArvTreatmentGroupFilter(group#java.lang.String)"
// could be "@org.openmrs.reporting.PatientCharacteristicFilter(gender=m#java.lang.String)"
List<ArgHolder> temp = new ArrayList<ArgHolder>();
if (spec.indexOf('(') <= 0 || spec.indexOf(')') <= 0)
log.error("this line is missing a ( or a ): " + spec);
setClassName(spec.substring(1, spec.indexOf('(')));
String s = spec.substring(spec.indexOf('(') + 1, spec.lastIndexOf(')'));
String[] t = s.split(",");
for (String arg : t) {
if (arg.trim().length() == 0)
continue;
if (arg.startsWith("\'") && arg.endsWith("\'")) {
temp.add(new ArgHolder(null, arg.substring(1, arg.length() - 1), null));
} else {
String[] u = arg.split("#");
if (u.length != 2) {
throw new IllegalArgumentException("Shortcut arguments must be name#Type. arg = " + arg);
}
Class clz;
try {
clz = Class.forName(u[1]);
}
catch (ClassNotFoundException ex) {
throw new IllegalArgumentException(ex);
}
if (u[0].indexOf('=') > 0) {
String[] v = u[0].split("=");
if (v.length != 2) {
throw new IllegalArgumentException("shortcut arguments can have only one equal sign");
}
/*
String hidden = "<input type=hidden name=\"" + v[0] + "\" value=\"" + v[1] + "\"/>";
tempHidden.add(hidden);
tempHiddenNames.add(v[0]);
log.debug("hidden arg " + v[0] + " -> " + v[1]);
*/
temp.add(new ArgHolder(clz, v[0], v[1]));
} else {
String name = u[0];
setHasPromptArgs(true);
temp.add(new ArgHolder(clz, name, null));
}
}
}
if (temp.size() > 0) {
setArgs(temp);
StringBuilder sb = new StringBuilder();
for (ArgHolder arg : temp)
if (arg.getArgClass() != null) {
if (sb.length() > 0)
sb.append(",");
sb.append(arg.getArgName() + "#" + arg.getArgClass().getName());
}
setVars(sb.toString());
}
} else {
ReportObjectService rs = Context.getService(ReportObjectService.class);
PatientFilter pf = rs.getPatientFilterByName(spec);
if (label == null)
label = pf.getName();
if (pf != null)
setPatientFilter(pf);
else
throw new IllegalArgumentException("Couldn't find a patient filter called: " + spec);
}
setLabel(label);
}
public boolean isConcrete() {
return patientFilter != null;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public PatientFilter getPatientFilter() {
return patientFilter;
}
public void setPatientFilter(PatientFilter patientFilter) {
this.patientFilter = patientFilter;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public List<ArgHolder> getArgs() {
return args;
}
public void setArgs(List<ArgHolder> args) {
this.args = args;
}
public Boolean getHasPromptArgs() {
return hasPromptArgs;
}
public void setHasPromptArgs(Boolean hasPromptArgs) {
this.hasPromptArgs = hasPromptArgs;
}
public String getVars() {
return vars;
}
public void setVars(String vars) {
this.vars = vars;
}
}
public ModelAndView clearHistory(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
if (Context.isAuthenticated()) {
setMySearchHistory(request, null);
}
return new ModelAndView(new RedirectView(getSuccessView()));
}
public ModelAndView addFilter(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
if (Context.isAuthenticated()) {
ReportObjectService rs = Context.getService(ReportObjectService.class);
CohortSearchHistory history = getMySearchHistory(request);
String temp = request.getParameter("filter_id");
if (temp != null) {
Integer filterId = new Integer(temp);
PatientFilter pf = rs.getPatientFilterById(filterId);
if (pf != null)
history.addSearchItem(PatientSearch.createSavedFilterReference(filterId));
else
log.warn("addFilter(id) didn't find " + filterId);
}
temp = request.getParameter("search_id");
if (temp != null) {
Integer searchId = new Integer(temp);
PatientSearchReportObject ro = (PatientSearchReportObject) rs.getReportObject(searchId);
if (ro != null)
history.addSearchItem(PatientSearch.createSavedSearchReference(searchId));
else
log.warn("addSearch(id) didn't find " + searchId);
}
temp = request.getParameter("cohort_id");
if (temp != null) {
Integer cohortId = new Integer(temp);
Cohort c = Context.getCohortService().getCohort(cohortId);
if (c != null) {
history.addSearchItem(PatientSearch.createSavedCohortReference(cohortId));
} else
log.warn("addCohort(id) didn't find " + cohortId);
}
temp = request.getParameter("composition");
if (temp != null) {
PatientSearch ps = history.createCompositionFilter(temp);
if (ps != null)
history.addSearchItem(ps);
else
request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Error building composition filter");
}
}
return new ModelAndView(new RedirectView(getSuccessView()));
}
public ModelAndView removeFilter(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
if (Context.isAuthenticated()) {
CohortSearchHistory history = getMySearchHistory(request);
String temp = request.getParameter("index");
if (temp != null) {
Integer index = new Integer(temp);
history.removeSearchItem(index);
}
}
return new ModelAndView(new RedirectView(getSuccessView()));
}
public class ArgHolder {
private Class argClass;
private String argName;
private Object argValue;
public ArgHolder() {
}
public ArgHolder(Class argClass, String argName, Object argValue) {
this.argClass = argClass;
this.argName = argName;
this.argValue = argValue;
}
public Class getArgClass() {
return argClass;
}
public void setArgClass(Class argClass) {
this.argClass = argClass;
}
public String getArgName() {
return argName;
}
public void setArgName(String argName) {
this.argName = argName;
}
public Object getArgValue() {
return argValue;
}
public void setArgValue(Object argValue) {
this.argValue = argValue;
}
public boolean hasValue() {
return argValue != null
&& ((argValue instanceof String && ((String) argValue).length() > 0) || (argValue instanceof String[] && ((String[]) argValue).length > 0));
}
@Override
public String toString() {
return "(" + argClass + ") " + argName + " = " + argValue;
}
}
private boolean checkClassHelper(Class checkFor, Class checkFirst, Class checkNext) {
return checkFor.equals(checkFirst)
|| ((checkFirst.equals(Object.class) || checkFirst.equals(List.class)) && checkFor.equals(checkNext));
}
public ModelAndView addDynamicFilter(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException,
ClassNotFoundException {
if (Context.isAuthenticated()) {
String filterClassName = request.getParameter("filterClass");
String temp = request.getParameter("vars");
String[] args = temp.split(",");
log.debug(args.length + " args: vars=" + temp);
List<ArgHolder> argValues = new ArrayList<ArgHolder>();
for (String arg : args) {
log.debug("looking at: " + arg);
if (arg.trim().length() == 0)
continue;
String[] u = arg.split("#");
if (u.length != 2) {
StringBuilder msg = new StringBuilder();
msg.append(arg);
msg.append(" -> ");
for (String str : u) {
msg.append(str).append(" , ");
}
throw new IllegalArgumentException("shortcut option arguments must be label#Type. " + msg);
}
String name = u[0];
Class c;
boolean isList = false;
if (u[1].startsWith("*")) {
u[1] = u[1].substring(1);
isList = true;
}
try {
c = Class.forName(u[1]);
}
catch (ClassNotFoundException ex) {
throw new IllegalArgumentException(ex);
}
argValues
.add(new ArgHolder(c, name, isList ? request.getParameterValues(name) : request.getParameter(name)));
}
log.debug("argValues has size " + argValues.size());
// Refactoring to create a PatientSearch instead of a PatientFilter
PatientSearch search = new PatientSearch();
search.setFilterClass(Class.forName(filterClassName));
for (ArgHolder arg : argValues) {
Object val = arg.getArgValue();
if (val instanceof String[]) {
String[] valArray = (String[]) val;
for (int i = 0; i < valArray.length; ++i)
if (StringUtils.hasText(valArray[i]))
search.addArgument(arg.getArgName(), valArray[i], arg.getArgClass());
} else {
if (StringUtils.hasText((String) val))
search.addArgument(arg.getArgName(), (String) val, arg.getArgClass());
}
}
log.debug("Created PatientSearch: " + search);
if (search != null) {
CohortSearchHistory history = getMySearchHistory(request);
if (history != null)
history.addSearchItem(search);
}
}
return new ModelAndView(new RedirectView(getSuccessView()));
}
public ModelAndView saveHistory(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// TODO: fix this!
if (Context.isAuthenticated()) {
String name = request.getParameter("name");
String description = request.getParameter("description");
if ((name == null || "".equals(name)) && (description == null || "".equals(description))) {
throw new RuntimeException("Name and Description are required");
}
CohortSearchHistory history = getMySearchHistory(request);
if (history.getReportObjectId() != null)
throw new RuntimeException("Re-saving histories is not yet implemented");
history.setName(name);
history.setDescription(description);
ReportObjectService rs = Context.getService(ReportObjectService.class);
rs.saveSearchHistory(history);
}
return new ModelAndView(new RedirectView(getSuccessView()));
}
private List<LinkSpec> linkHelper() {
List<LinkSpec> ret = new ArrayList<LinkSpec>();
for (String spec : getLinks()) {
ret.add(new LinkSpec(spec));
}
return ret;
}
public class LinkArg {
String name;
String value;
public LinkArg() {
}
public LinkArg(String name, String value) {
this.name = name;
this.value = value;
}
public LinkArg(String nameEqualsValue) {
int i = nameEqualsValue.indexOf('=');
name = nameEqualsValue.substring(0, i);
value = nameEqualsValue.substring(i + 1);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public class LinkSpec {
String label;
String url;
List<LinkArg> arguments = new ArrayList<LinkArg>();
public LinkSpec(String spec) {
StringTokenizer st = new StringTokenizer(spec, ":");
url = st.nextToken();
label = st.nextToken();
while (st.hasMoreTokens()) {
arguments.add(new LinkArg(st.nextToken()));
}
}
public List<LinkArg> getArguments() {
return arguments;
}
public String getLabel() {
return label;
}
public String getUrl() {
return url;
}
}
}