-
Notifications
You must be signed in to change notification settings - Fork 225
/
HtmlFormEntryUtil.java
2319 lines (2057 loc) · 74.3 KB
/
HtmlFormEntryUtil.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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.openmrs.module.htmlformentry;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.ConceptDatatype;
import org.openmrs.ConceptName;
import org.openmrs.Drug;
import org.openmrs.Encounter;
import org.openmrs.EncounterRole;
import org.openmrs.EncounterType;
import org.openmrs.FormField;
import org.openmrs.Location;
import org.openmrs.LocationTag;
import org.openmrs.Obs;
import org.openmrs.OpenmrsMetadata;
import org.openmrs.Order;
import org.openmrs.Patient;
import org.openmrs.PatientIdentifier;
import org.openmrs.PatientIdentifierType;
import org.openmrs.PatientProgram;
import org.openmrs.PatientState;
import org.openmrs.Person;
import org.openmrs.PersonAddress;
import org.openmrs.PersonAttribute;
import org.openmrs.PersonAttributeType;
import org.openmrs.PersonName;
import org.openmrs.Program;
import org.openmrs.ProgramWorkflow;
import org.openmrs.ProgramWorkflowState;
import org.openmrs.Provider;
import org.openmrs.User;
import org.openmrs.api.APIException;
import org.openmrs.api.context.Context;
import org.openmrs.messagesource.MessageSourceService;
import org.openmrs.module.htmlformentry.FormEntryContext.Mode;
import org.openmrs.module.htmlformentry.action.FormSubmissionControllerAction;
import org.openmrs.module.htmlformentry.action.ObsGroupAction;
import org.openmrs.module.htmlformentry.compatibility.EncounterCompatibility;
import org.openmrs.module.htmlformentry.element.GettingExistingOrder;
import org.openmrs.module.htmlformentry.element.ObsSubmissionElement;
import org.openmrs.module.htmlformentry.element.ProviderStub;
import org.openmrs.module.htmlformentry.schema.HtmlFormSchema;
import org.openmrs.module.htmlformentry.util.MatchMode;
import org.openmrs.module.htmlformentry.util.Predicate;
import org.openmrs.module.htmlformentry.util.ProviderTransformer;
import org.openmrs.module.providermanagement.ProviderRole;
import org.openmrs.module.providermanagement.api.ProviderManagementService;
import org.openmrs.obs.ComplexData;
import org.openmrs.propertyeditor.ConceptEditor;
import org.openmrs.propertyeditor.DrugEditor;
import org.openmrs.propertyeditor.EncounterTypeEditor;
import org.openmrs.propertyeditor.LocationEditor;
import org.openmrs.propertyeditor.PatientEditor;
import org.openmrs.propertyeditor.PersonEditor;
import org.openmrs.propertyeditor.UserEditor;
import org.openmrs.util.OpenmrsUtil;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* HTML Form Entry utility methods
*/
public class HtmlFormEntryUtil {
public static Log log = LogFactory.getLog(HtmlFormEntryUtil.class);
private static MetadataMappingResolver getMetadaMappingResolver() {
return Context.getRegisteredComponent("metadataMappingResolver", MetadataMappingResolver.class);
}
/**
* Returns the HTML Form Entry service from the Context
*
* @return HTML Form Entry service
*/
public static HtmlFormEntryService getService() {
return Context.getService(HtmlFormEntryService.class);
}
private static <T extends OpenmrsMetadata> T getMetadataByMapping(Class<T> type, String identifier) {
MetadataMappingResolver metadataMappingResolver = getMetadaMappingResolver();
if (metadataMappingResolver != null) {
return metadataMappingResolver.getMetadataItem(type, identifier);
}
return null;
}
/**
* Fetches a http request parameter from an http request and returns it as a specific type
*
* @param request an http servlet request
* @param name the name of the parameter to retrieve
* @param clazz the type to convert the parameter to
* @return parameter, converted to appropriate type
*/
public static Object getParameterAsType(HttpServletRequest request, String name, Class<?> clazz) {
if (ComplexData.class.isAssignableFrom(clazz) && request instanceof MultipartHttpServletRequest) {
return convertToComplexData(request, name);
} else {
String val = request.getParameter(name);
return convertToType(val, clazz);
}
}
public static ComplexData convertToComplexData(HttpServletRequest request, String name) {
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
MultipartFile file = mRequest.getFile(name);
if (file != null && file.getSize() > 0) {
try {
byte[] bytes = IOUtils.toByteArray(file.getInputStream());
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
return new ComplexData(file.getOriginalFilename(), is);
}
catch (IOException e) {
throw new IllegalArgumentException(e);
}
} else {
return null;
}
}
/**
* Converts a string to specified type
*
* @param val the string to convert
* @param clazz the type to convert to
* @return an instance of the specified type, with it's value set to val
*/
public static Object convertToType(String val, Class<?> clazz) {
if (val == null)
return null;
if ("".equals(val) && !String.class.equals(clazz))
return null;
if (Location.class.isAssignableFrom(clazz)) {
LocationEditor ed = new LocationEditor();
ed.setAsText(val);
return ed.getValue();
} else if (User.class.isAssignableFrom(clazz)) {
UserEditor ed = new UserEditor();
ed.setAsText(val);
return ed.getValue();
} else if (Date.class.isAssignableFrom(clazz)) {
// all HTML Form Entry dates should be submitted as yyyy-mm-dd
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);
return df.parse(val);
}
catch (ParseException e) {
throw new IllegalArgumentException(e);
}
} else if (Double.class.isAssignableFrom(clazz)) {
return Double.valueOf(val);
} else if (Integer.class.isAssignableFrom(clazz)) {
return Integer.valueOf(val);
} else if (Concept.class.isAssignableFrom(clazz)) {
ConceptEditor ed = new ConceptEditor();
ed.setAsText(val);
return ed.getValue();
} else if (Drug.class.isAssignableFrom(clazz)) {
DrugEditor ed = new DrugEditor();
ed.setAsText(val);
return ed.getValue();
} else if (Patient.class.isAssignableFrom(clazz)) {
PatientEditor ed = new PatientEditor();
ed.setAsText(val);
return ed.getValue();
} else if (Person.class.isAssignableFrom(clazz)) {
PersonEditor ed = new PersonEditor();
ed.setAsText(val);
return ed.getValue();
} else if (EncounterType.class.isAssignableFrom(clazz)) {
EncounterTypeEditor ed = new EncounterTypeEditor();
ed.setAsText(val);
return ed.getValue();
} else {
return val;
}
}
/**
* Creaets an OpenMRS Obs instance
*
* @param formField the form field that specifies the concept associated with the Obs
* @param value value associated with the Obs
* @param datetime date/time associated with the Obs (may be null)
* @param accessionNumber accession number associatd with the Obs (may be null)
* @return the created Obs instance
*/
public static Obs createObs(FormField formField, Object value, Date datetime, String accessionNumber) {
Concept concept = formField.getField().getConcept();
if (concept == null)
throw new FormEntryException("Can't create an Obs for a formField that doesn't represent a Concept");
return createObs(concept, value, datetime, accessionNumber);
}
/**
* Creates an OpenMRS Obs instance
*
* @param concept concept associated with the Obs
* @param value value associated with the Obs
* @param datetime date/time associated with the Obs (may be null)
* @param accessionNumber accession number associated with the Obs (may be null)
* @return the created Obs instance
*/
public static Obs createObs(Concept concept, Object value, Date datetime, String accessionNumber) {
Obs obs = new Obs();
obs.setConcept(concept);
ConceptDatatype dt = obs.getConcept().getDatatype();
if (dt.isNumeric()) {
obs.setValueNumeric(Double.parseDouble(value.toString()));
} else if (HtmlFormEntryConstants.COMPLEX_UUID.equals(dt.getUuid())) {
obs.setComplexData((ComplexData) value);
obs.setValueComplex(obs.getComplexData().getTitle());
} else if (dt.isText()) {
if (value instanceof Location) {
Location location = (Location) value;
obs.setValueText(location.getId().toString() + " - " + location.getName());
} else if (value instanceof Person) {
Person person = (Person) value;
obs.setValueText(person.getId().toString() + " - " + person.getPersonName().toString());
} else {
obs.setValueText(value.toString());
}
} else if (dt.isCoded()) {
if (value instanceof Drug) {
obs.setValueDrug((Drug) value);
obs.setValueCoded(((Drug) value).getConcept());
} else if (value instanceof ConceptName) {
obs.setValueCodedName((ConceptName) value);
obs.setValueCoded(obs.getValueCodedName().getConcept());
} else if (value instanceof Concept) {
obs.setValueCoded((Concept) value);
} else {
obs.setValueCoded((Concept) convertToType(value.toString(), Concept.class));
}
} else if (dt.isBoolean()) {
if (value != null) {
try {
obs.setValueAsString(value.toString());
}
catch (ParseException e) {
throw new IllegalArgumentException("Unable to convert " + value + " to a Boolean Obs value", e);
}
}
} else if (ConceptDatatype.DATE.equals(dt.getHl7Abbreviation())
|| ConceptDatatype.TIME.equals(dt.getHl7Abbreviation())
|| ConceptDatatype.DATETIME.equals(dt.getHl7Abbreviation())) {
Date date = (Date) value;
obs.setValueDatetime(date);
} else if ("ZZ".equals(dt.getHl7Abbreviation())) {
// don't set a value
} else {
throw new IllegalArgumentException("concept datatype not yet implemented: " + dt.getName()
+ " with Hl7 Abbreviation: " + dt.getHl7Abbreviation());
}
if (datetime != null)
obs.setObsDatetime(datetime);
if (accessionNumber != null)
obs.setAccessionNumber(accessionNumber);
return obs;
}
/**
* Converts an xml string to a Document object
*
* @param xml the xml string to convert
* @return the resulting Document object
* @throws Exception
*/
public static Document stringToDocument(String xml) throws Exception {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// Disable XXE: security measure to prevent DOS, arbitrary-file-read, and possibly RCE
dbf.setExpandEntityReferences(false);
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new InputSource(new StringReader(xml)));
return document;
}
catch (Exception e) {
log.error("Error converting String to Document:\n" + xml);
throw e;
}
}
/**
* Converts a Document object to an xml string
*
* @param document the Document instance to convert
* @return the resulting xml string
* @throws Exception
*/
public static String documentToString(Document document) throws Exception {
//set up a transformer
Transformer trans = null;
TransformerFactory transfac = TransformerFactory.newInstance();
try {
trans = transfac.newTransformer();
}
catch (TransformerException te) {
System.out.println(HtmlFormEntryConstants.ERROR_TRANSFORMER_1 + te);
}
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, HtmlFormEntryConstants.CONSTANT_YES);
trans.setOutputProperty(OutputKeys.INDENT, HtmlFormEntryConstants.CONSTANT_YES);
trans.setOutputProperty(OutputKeys.METHOD, HtmlFormEntryConstants.CONSTANT_XML);
trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(document);
try {
trans.transform(source, result);
}
catch (TransformerException te) {
System.out.println(HtmlFormEntryConstants.ERROR_TRANSFORMER_2 + te);
}
String xmlString = sw.toString();
return xmlString;
}
/**
* Retrieves a child Node by name
*
* @param content the parent Node
* @param name the name of the child Node
* @return the child Node with the specified name
*/
public static Node findChild(Node content, String name) {
if (content == null)
return null;
NodeList children = content.getChildNodes();
for (int i = 0; i < children.getLength(); ++i) {
Node node = children.item(i);
if (name.equals(node.getNodeName()))
return node;
}
return null;
}
/**
* Finds the first descendant of this node with the given tag name
*
* @param node
* @param tagName
* @return
*/
public static Node findDescendant(Node node, String tagName) {
if (node == null)
return null;
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); ++i) {
Node child = children.item(i);
if (tagName.equals(node.getNodeName()))
return node;
Node matchingDescendant = findDescendant(child, tagName);
if (matchingDescendant != null) {
return matchingDescendant;
}
}
return null;
}
/**
* Returns all the attributes associated with a Node
*
* @param node the Node to retrieve attributes from
* @return a Map containing all the attributes of the Node
*/
public static Map<String, String> getNodeAttributes(Node node) {
Map<String, String> ret = new HashMap<String, String>();
NamedNodeMap atts = node.getAttributes();
for (int i = 0; i < atts.getLength(); i++) {
Node attribute = atts.item(i);
ret.put(attribute.getNodeName(), attribute.getNodeValue());
}
return ret;
}
/**
* Returns a specific attribute of a Node
*
* @param node the Node to retrieve the attribute from
* @param attributeName the name of the attribute to return
* @param defaultVal a default value to return if the attribute is not specified for the selected
* Node
* @return
*/
public static String getNodeAttribute(Node node, String attributeName, String defaultVal) {
String ret = getNodeAttributes(node).get(attributeName);
return (ret == null ? defaultVal : ret);
}
/**
* @param node
* @return the contents of node as a String
*/
public static String getNodeContentsAsString(Node node) {
StringWriter sw = new StringWriter();
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
}
catch (TransformerException ex) {
throw new RuntimeException("Error transforming node", ex);
}
return sw.toString();
}
/**
* Creates a non-persistent "Fake" Person (used when previewing or validating an HTML Form)
*
* @return the "fake" person
*/
public static Patient getFakePerson() {
Patient demo = new Patient(12345);
demo.addName(new PersonName("Demo", "The", "Person"));
Location l = Context.getLocationService().getAllLocations().iterator().next();
for (PatientIdentifierType pit : Context.getPatientService().getAllPatientIdentifierTypes()) {
if (StringUtils.isEmpty(pit.getValidator())) {
demo.addIdentifier(new PatientIdentifier("Testing" + pit.getName() + "123", pit, l));
}
}
demo.setGender("F");
demo.setUuid("testing-html-form-entry");
{
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -31);
demo.setBirthdate(cal.getTime());
}
for (PersonAttributeType type : Context.getPersonService().getAllPersonAttributeTypes()) {
if (type.getFormat() != null && type.getFormat().equals("java.lang.String")) {
demo.addAttribute(new PersonAttribute(type, "Test " + type.getName() + " Attribute"));
}
}
PersonAddress addr = new PersonAddress();
addr.setCityVillage("Rwinkwavu");
addr.setCountyDistrict("Kayonza District");
addr.setStateProvince("Eastern Province");
addr.setCountry("Rwanda");
demo.addAddress(addr);
return demo;
}
public static HtmlFormSchema getHtmlFormSchema(HtmlForm htmlForm, FormEntryContext.Mode mode) {
try {
Patient patient = HtmlFormEntryUtil.getFakePerson();
FormEntrySession fes = new FormEntrySession(patient, null, mode, htmlForm, null);
fes.getHtmlToDisplay();
return fes.getContext().getSchema();
}
catch (Exception e) {
throw new IllegalStateException("Unable to load html form schema for htmlform: " + htmlForm, e);
}
}
/**
* Combines a Date object that contains only a date component (day, month, year) with a Date object
* that contains only a time component (hour, minute, second) into a single Date object
*
* @param date the Date object that contains date information
* @param time the Date object that contains time information
* @return a Date object with the combined date/time
*/
public static Date combineDateAndTime(Date date, Date time) {
if (date == null)
return null;
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if (time != null) {
Calendar temp = Calendar.getInstance();
temp.setTime(time);
cal.set(Calendar.HOUR_OF_DAY, temp.get(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, temp.get(Calendar.MINUTE));
cal.set(Calendar.SECOND, temp.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, temp.get(Calendar.MILLISECOND));
}
return cal.getTime();
}
/**
* Find Drug by UUID
*
* @param uuid
* @return
*/
public static Drug getDrug(String uuid) {
Drug drug = null;
if (StringUtils.isNotBlank(uuid)) {
try {
drug = Context.getConceptService().getDrugByUuid(uuid);
}
catch (Exception e) {
log.error("Failed to find drug: ", e);
}
}
return drug;
}
/**
* Get the concept by id where the id can either be: 1) an integer id like 5090 2) a mapping type id
* like "XYZ:HT" 3) a uuid like "a3e12268-74bf-11df-9768-17cfc9833272" 4) the fully qualified name
* of a Java constant that contains one of above
*
* @param id the concept identifier
* @return the concept if exist, else null <strong>Should</strong> find a concept by its conceptId
* <strong>Should</strong> find a concept by its mapping <strong>Should</strong> find a
* concept by its uuid <strong>Should</strong> find a concept by static constant
* <strong>Should</strong> return null otherwise <strong>Should</strong> find a concept by
* its mapping with a space in between
*/
public static Concept getConcept(String id) {
Concept cpt = null;
if (id != null) {
id = id.trim();
// see if this is a parseable int; if so, try looking up concept by id
try { //handle integer: id
int conceptId = Integer.parseInt(id);
cpt = Context.getConceptService().getConcept(conceptId);
if (cpt != null) {
return cpt;
}
}
catch (Exception ex) {
//do nothing
}
// handle mapping id: xyz:ht
int index = id.indexOf(":");
if (index != -1) {
cpt = Context.getService(HtmlFormEntryService.class).getConceptByMapping(id);
if (cpt != null) {
return cpt;
}
}
// handle uuid id: "a3e1302b-74bf-11df-9768-17cfc9833272", if the id matches a uuid format
if (isValidUuidFormat(id)) {
cpt = Context.getConceptService().getConceptByUuid(id);
}
// finally, if input contains at least one period handle recursively as a code constant
else if (id.contains(".")) {
return getConcept(evaluateStaticConstant(id));
}
}
return cpt;
}
/**
* Gets a concept by id, mapping, or uuid. (See #getConcept(String) for precise details.) If no
* concept is found, throws an IllegalArgumentException with the given message.
*
* @param id
* @param errorMessageIfNotFound
* @return
* @throws IllegalArgumentException
*/
public static Concept getConcept(String id, String errorMessageIfNotFound) throws IllegalArgumentException {
Concept c = null;
try {
c = getConcept(id);
}
catch (Exception ex) {
throw new IllegalArgumentException(errorMessageIfNotFound, ex);
}
if (c == null)
throw new IllegalArgumentException(errorMessageIfNotFound);
return c;
}
/**
* This method doesn't support "SessionAttribute:", but is otherwise like the similarly-named
* method.
*
* @see #getLocation(String, FormEntryContext)
*/
public static Location getLocation(String id) {
return getLocation(id, null);
}
/**
* Get the location by:
* <ol>
* <li>an integer id like 5090</li>
* <li>a uuid like "a3e12268-74bf-11df-9768-17cfc9833272"</li>
* <li>a name like "Boston"</li>
* <li>an id/name pair like "501 - Boston" (this format is used when saving a location on a obs as a
* value text)</li>
* <li>"GlobalProperty:property.name"</li>
* <li>"UserProperty:propertyName"</li>
* <li>"SessionAttribute:attributeName"</li>
* </ol>
*
* @param id
* @param context
* @return the location if exist, else null <strong>Should</strong> find a location by its
* locationId <strong>Should</strong> find a location by name <strong>Should</strong> find a
* location by its uuid <strong>Should</strong> find a location by global property
* <strong>Should</strong> find a location by user property <strong>Should</strong> find a
* location by session attribute <strong>Should</strong> not fail if trying to find a
* location by session attribute and we have no session <strong>Should</strong> return null
* otherwise
*/
public static Location getLocation(String id, FormEntryContext context) {
Location location = null;
if (id != null) {
id = id.trim();
// handle "SystemDefault" setting
if (id.equals(HtmlFormEntryConstants.SYSTEM_DEFAULT)) {
location = Context.getLocationService().getDefaultLocation();
if (location != null) {
return location;
}
}
// handle GlobalProperty:property.name
if (id.startsWith("GlobalProperty:")) {
String gpName = id.substring("GlobalProperty:".length());
String gpValue = Context.getAdministrationService().getGlobalProperty(gpName);
if (StringUtils.isNotEmpty(gpValue)) {
return getLocation(gpValue, context);
}
}
// handle UserProperty:propName
if (id.startsWith("UserProperty:")) {
String upName = id.substring("UserProperty:".length());
String upValue = Context.getAuthenticatedUser().getUserProperty(upName);
if (StringUtils.isNotEmpty(upValue)) {
return getLocation(upValue, context);
}
}
// handle SessionAttribute:attributeName
if (id.startsWith("SessionAttribute:")) {
if (context.getHttpSession() == null) {
// if we don't have access to a session, e.g. when validating a form, we can't do anything
return null;
}
String saName = id.substring("SessionAttribute:".length());
Object saValue = context.getHttpSession().getAttribute(saName);
if (saValue == null) {
return null;
} else if (saValue instanceof Location) {
return (Location) saValue;
} else if (saValue instanceof String) {
return getLocation((String) saValue, context);
} else {
return getLocation(saValue.toString(), context);
}
}
// see if this is parseable int; if so, try looking up by id
try { //handle integer: id
int locationId = Integer.parseInt(id);
location = Context.getLocationService().getLocation(locationId);
if (location != null) {
return location;
}
}
catch (Exception ex) {
//do nothing
}
// handle uuid id: "a3e1302b-74bf-11df-9768-17cfc9833272" if id matches a uuid format
if (isValidUuidFormat(id)) {
location = Context.getLocationService().getLocationByUuid(id);
if (location != null) {
return location;
}
}
//get by mapping "source:code"
location = getMetadataByMapping(Location.class, id);
if (location != null) {
return location;
}
// if it's neither a uuid or id, try location name
location = Context.getLocationService().getLocation(id);
if (location != null) {
return location;
}
// try the "101 - Cange" case
if (id.contains(" ")) {
String[] values = id.split(" ");
try {
int locationId = Integer.parseInt(values[0]);
location = Context.getLocationService().getLocation(locationId);
if (location != null) {
return location;
}
}
catch (Exception ex) {
//do nothing
}
}
}
// no match found, so return null
return null;
}
/***
* Get the program by: 1)an integer id like 5090 or 2) uuid like
* "a3e12268-74bf-11df-9768-17cfc9833272" or 3) name of *associated concept* (not name of program),
* like "MDR-TB Program"
*
* @param id
* @return the program if exist, else null <strong>Should</strong> find a program by its id
* <strong>Should</strong> find a program by name of associated concept
* <strong>Should</strong> find a program by its uuid <strong>Should</strong> return null
* otherwise
*/
public static Program getProgram(String id) {
Program program = null;
if (id != null) {
id = id.trim();
// see if this is parseable int; if so, try looking up by id
try {//handle integer: id
int programId = Integer.parseInt(id);
program = Context.getProgramWorkflowService().getProgram(programId);
if (program != null) {
return program;
}
}
catch (Exception ex) {
//do nothing
}
//get Program by mapping
program = getMetadataByMapping(Program.class, id);
if (program != null) {
return program;
}
//handle uuid id: "a3e1302b-74bf-11df-9768-17cfc9833272", if id matches uuid format
if (isValidUuidFormat(id)) {
program = Context.getProgramWorkflowService().getProgramByUuid(id);
if (program != null) {
return program;
}
} else {
// if it's neither a uuid or id, try program name
// (note that this API method actually checks based on name of the associated concept, not the name of the program itself)
program = Context.getProgramWorkflowService().getProgramByName(id);
}
}
return program;
}
/***
* Get the person by: 1)an integer id like 5090 or 2) uuid like
* "a3e12268-74bf-11df-9768-17cfc9833272" or 3) a username like "mgoodrich" or 4) an id/name pair
* like "5090 - Bob Jones" (this format is used when saving a person on a obs as a value text)
*
* @param id
* @return the person if exist, else null <strong>Should</strong> find a person by its id
* <strong>Should</strong> find a person by its uuid <strong>Should</strong> find a person
* by username of corresponding user <strong>Should</strong> return null otherwise
*/
public static Person getPerson(String id) {
Person person = null;
if (id != null) {
id = id.trim();
// see if this is parseable int; if so, try looking up by id
try { //handle integer: id
int personId = Integer.parseInt(id);
person = Context.getPersonService().getPerson(personId);
if (person != null) {
return person;
}
}
catch (Exception ex) {
//do nothing
}
// handle uuid id: "a3e1302b-74bf-11df-9768-17cfc9833272", if id matches uuid format
if (isValidUuidFormat(id)) {
person = Context.getPersonService().getPersonByUuid(id);
if (person != null) {
return person;
}
}
// handle username
User personByUsername = Context.getUserService().getUserByUsername(id);
if (personByUsername != null) {
return personByUsername.getPerson();
}
// try the "5090 - Bob Jones" case
if (id.contains(" ")) {
String[] values = id.split(" ");
try {
int personId = Integer.parseInt(values[0]);
person = Context.getPersonService().getPerson(personId);
if (person != null) {
return person;
}
}
catch (Exception ex) {
//do nothing
}
}
}
// no match found, so return null
return null;
}
/***
* Get the patient identifier type by: 1)an integer id like 5090 or 2) uuid like
* "a3e12268-74bf-11df-9768-17cfc9833272" or 3) a name like "Temporary Identifier"
*
* @param id
* @return the identifier type if exist, else null <strong>Should</strong> find an identifier type
* by its id <strong>Should</strong> find an identifier type by its uuid
* <strong>Should</strong> find an identifier type by its name <strong>Should</strong>
* return null otherwise
*/
public static PatientIdentifierType getPatientIdentifierType(String id) {
PatientIdentifierType identifierType = null;
if (id != null) {
id = id.trim();
// see if this is parseable int; if so, try looking up by id
try { //handle integer: id
int identifierTypeId = Integer.parseInt(id);
identifierType = Context.getPatientService().getPatientIdentifierType(identifierTypeId);
if (identifierType != null) {
return identifierType;
}
}
catch (Exception ex) {
//do nothing
}
//get PatientIdentifierType by mapping
identifierType = getMetadataByMapping(PatientIdentifierType.class, id);
if (identifierType != null) {
return identifierType;
}
//handle uuid id: "a3e1302b-74bf-11df-9768-17cfc9833272", if id matches uuid format
if (isValidUuidFormat(id)) {
identifierType = Context.getPatientService().getPatientIdentifierTypeByUuid(id);
if (identifierType != null) {
return identifierType;
}
}
// handle name
else {
// if it's neither a uuid or id, try identifier type name
identifierType = Context.getPatientService().getPatientIdentifierTypeByName(id);
}
}
return identifierType;
}
public static ProgramWorkflow getWorkflow(Integer id) {
for (Program p : Context.getProgramWorkflowService().getAllPrograms()) {
for (ProgramWorkflow w : p.getAllWorkflows()) {
if (w.getProgramWorkflowId().equals(id)) {
return w;
}
}
}
return null;
}
/**
* Looks up a {@link ProgramWorkflow} by id, uuid or by concept map of the underlying concept
*/
@SuppressWarnings("deprecation")
public static ProgramWorkflow getWorkflow(String identifier) {
ProgramWorkflow workflow = null;
if (identifier != null) {
identifier = identifier.trim();
// first try to fetch by id
try {
Integer id = Integer.valueOf(identifier);
workflow = getWorkflow(id);
if (workflow != null) {
return workflow;
}
}
catch (NumberFormatException e) {}
// if not, try to fetch by uuid
if (isValidUuidFormat(identifier)) {
workflow = Context.getProgramWorkflowService().getWorkflowByUuid(identifier);
if (workflow != null) {
return workflow;
}
}
// finally, try to fetch by concept map
// handle mapping id: xyz:ht
int index = identifier.indexOf(":");
if (index != -1) {
Concept concept = getConcept(identifier);
// iterate through workflows until we see if we find a match
if (concept != null) {