• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

openmrs / openmrs-core / 41717832711

30 Oct 2026 04:16PM UTC coverage: 66.75% (+0.003%) from 66.747%
41717832711

push

github

ibacher
TRUNK-6863: Remove the generation token before clearing a node's cache locally (#6791)

1 of 1 new or added line in 1 file covered. (100.0%)

419 existing lines in 31 files now uncovered.

26279 of 39369 relevant lines covered (66.75%)

0.67 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

85.93
/api/src/main/java/org/openmrs/Obs.java
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
3
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
4
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
5
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
6
 *
7
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
8
 * graphic logo is a trademark of OpenMRS Inc.
9
 */
10
package org.openmrs;
11

12
import java.text.DateFormat;
13
import java.text.DecimalFormat;
14
import java.text.NumberFormat;
15
import java.text.ParseException;
16
import java.text.ParsePosition;
17
import java.text.SimpleDateFormat;
18
import java.time.DateTimeException;
19
import java.time.Instant;
20
import java.time.LocalDateTime;
21
import java.time.OffsetDateTime;
22
import java.time.ZoneId;
23
import java.time.format.DateTimeFormatter;
24
import java.time.format.DateTimeFormatterBuilder;
25
import java.time.format.ResolverStyle;
26
import java.time.temporal.ChronoField;
27
import java.time.temporal.TemporalAccessor;
28
import java.util.Date;
29
import java.util.HashSet;
30
import java.util.LinkedHashSet;
31
import java.util.Locale;
32
import java.util.Set;
33

34
import org.apache.commons.lang3.StringUtils;
35
import org.hibernate.envers.Audited;
36
import org.openmrs.annotation.AllowDirectAccess;
37
import org.openmrs.api.APIException;
38
import org.openmrs.api.context.Context;
39
import org.openmrs.api.db.hibernate.HibernateUtil;
40
import org.openmrs.obs.ComplexData;
41
import org.openmrs.obs.ComplexObsHandler;
42
import org.openmrs.util.CollectionUtil;
43
import org.openmrs.util.DateUtil;
44
import org.openmrs.util.Format;
45
import org.openmrs.util.Format.FORMAT_TYPE;
46
import org.openmrs.util.OpenmrsUtil;
47
import org.slf4j.Logger;
48
import org.slf4j.LoggerFactory;
49

50
/**
51
 * An observation is a single unit of clinical information. <br>
52
 * <br>
53
 * Observations are collected and grouped together into one Encounter (one visit). Obs can be
54
 * grouped in a hierarchical fashion. <br>
55
 * <br>
56
 * <p>
57
 * The {@link #getObsGroup()} method returns an optional parent. That parent object is also an Obs.
58
 * The parent Obs object knows about its child objects through the {@link #getGroupMembers()}
59
 * method.
60
 * </p>
61
 * <p>
62
 * (Multi-level hierarchies are achieved by an Obs parent object being a member of another Obs
63
 * (grand)parent object) Read up on the obs table: http://openmrs.org/wiki/Obs_Table_Primer In an
64
 * OpenMRS installation, there may be an occasion need to change an Obs.
65
 * </p>
66
 * <p>
67
 * For example, a site may decide to replace a concept in the dictionary with a more specific set of
68
 * concepts. An observation is part of the official record of an encounter. There may be legal,
69
 * ethical, and auditing consequences from altering a record. It is recommended that you create a
70
 * new Obs and void the old one:
71
 * </p>
72
 * Obs newObs = Obs.newInstance(oldObs); //copies values from oldObs
73
 * newObs.setPreviousVersion(oldObs);
74
 * Context.getObsService().saveObs(newObs,"Your reason for the change here");
75
 * Context.getObsService().voidObs(oldObs, "Your reason for the change here");
76
 * 
77
 * @see Encounter
78
 */
79
@Audited
80
public class Obs extends BaseFormRecordableOpenmrsData {
81
        
82
        /**
83
         * @since 2.1.0
84
         */
85
        public enum Interpretation {
1 ✔
86
                NORMAL, ABNORMAL, CRITICALLY_ABNORMAL, NEGATIVE, POSITIVE, CRITICALLY_LOW, LOW, HIGH, CRITICALLY_HIGH, VERY_SUSCEPTIBLE, SUSCEPTIBLE, INTERMEDIATE, RESISTANT, SIGNIFICANT_CHANGE_DOWN, SIGNIFICANT_CHANGE_UP, OFF_SCALE_LOW, OFF_SCALE_HIGH
1 ✔
87
        }
88
        
89
        /**
90
         * @since 2.1.0
91
         */
92
        public enum Status {
1 ✔
93
                PRELIMINARY, FINAL, AMENDED
1 ✔
94
        }
95
        
96
        private static final String TIME_PATTERN = "HH:mm";
97
        
98
        private static final String TIME_PATTERN_WITH_SECONDS = "HH:mm:ss";
99
        
100
        private static final String DATE_PATTERN = "yyyy-MM-dd";
101
        
102
        public static final long serialVersionUID = 112342333L;
103
        
104
        private static final Logger log = LoggerFactory.getLogger(Obs.class);
1 ✔
105
        
106
        protected Integer obsId;
107
        
108
        protected Concept concept;
109
        
110
        protected Date obsDatetime;
111
        
112
        protected String accessionNumber;
113
        
114
        /**
115
         * The "parent" of this obs. It is the grouping that brings other obs together. note:
116
         * obsGroup.getConcept().isSet() should be true This will be non-null if this obs is a member of
117
         * another groupedObs
118
         * 
119
         * @see #isObsGrouping() (??)
120
         */
121
        protected Obs obsGroup;
122
        
123
        /**
124
         * The list of obs grouped under this obs.
125
         */
126
        @AllowDirectAccess
127
        protected Set<Obs> groupMembers;
128
        
129
        protected Concept valueCoded;
130
        
131
        protected ConceptName valueCodedName;
132
        
133
        protected Drug valueDrug;
134
        
135
        protected Integer valueGroupId;
136
        
137
        protected Date valueDatetime;
138
        
139
        protected Double valueNumeric;
140
        
141
        protected String valueModifier;
142
        
143
        protected String valueText;
144
        
145
        protected String valueComplex;
146
        
147
        // ComplexData is not persisted in the database.
148
        protected transient ComplexData complexData;
149
        
150
        protected String comment;
151
        
152
        protected transient Integer personId;
153
        
154
        protected Person person;
155
        
156
        protected Order order;
157
        
158
        protected Location location;
159
        
160
        protected Encounter encounter;
161
        
162
        private Obs previousVersion;
163
        
164
        private Boolean dirty = Boolean.FALSE;
1 ✔
165
        
166
        private Interpretation interpretation;
167
        
168
        private Status status = Status.FINAL;
1 ✔
169

170
        private ObsReferenceRange referenceRange;
171

172
        /** default constructor */
173
        public Obs() {
1 ✔
174
        }
1 ✔
175
        
176
        /**
177
         * Required parameters constructor A value is also required, but that can be one of: valueCoded,
178
         * valueDrug, valueNumeric, or valueText
179
         * 
180
         * @param person The Person this obs is acting on
181
         * @param question The question concept this obs is related to
182
         * @param obsDatetime The time this obs took place
183
         * @param location The location this obs took place
184
         */
185
        public Obs(Person person, Concept question, Date obsDatetime, Location location) {
1 ✔
186
                this.person = person;
1 ✔
187
                if (person != null) {
1 ✔
188
                        this.personId = person.getPersonId();
1 ✔
189
                }
190
                this.concept = question;
1 ✔
191
                this.obsDatetime = obsDatetime;
1 ✔
192
                this.location = location;
1 ✔
193
        }
1 ✔
194
        
195
        /** constructor with id */
196
        public Obs(Integer obsId) {
1 ✔
197
                this.obsId = obsId;
1 ✔
198
        }
1 ✔
199
        
200
        /**
201
         * This is an equivalent to a copy constructor. Creates a new copy of the given
202
         * <code>obsToCopy</code> with a null obs id
203
         * 
204
         * @param obsToCopy The Obs that is going to be copied
205
         * @return a new Obs object with all the same attributes as the given obs
206
         */
207
        public static Obs newInstance(Obs obsToCopy) {
208
                Obs newObs = new Obs(obsToCopy.getPerson(), obsToCopy.getConcept(), obsToCopy.getObsDatetime(),
1 ✔
209
                        obsToCopy.getLocation());
1 ✔
210
                
211
                newObs.setObsGroup(obsToCopy.getObsGroup());
1 ✔
212
                newObs.setAccessionNumber(obsToCopy.getAccessionNumber());
1 ✔
213
                newObs.setValueCoded(obsToCopy.getValueCoded());
1 ✔
214
                newObs.setValueDrug(obsToCopy.getValueDrug());
1 ✔
215
                newObs.setValueGroupId(obsToCopy.getValueGroupId());
1 ✔
216
                newObs.setValueDatetime(obsToCopy.getValueDatetime());
1 ✔
217
                newObs.setValueNumeric(obsToCopy.getValueNumeric());
1 ✔
218
                newObs.setValueModifier(obsToCopy.getValueModifier());
1 ✔
219
                newObs.setValueText(obsToCopy.getValueText());
1 ✔
220
                newObs.setComment(obsToCopy.getComment());
1 ✔
221
                newObs.setEncounter(obsToCopy.getEncounter());
1 ✔
222
                newObs.setCreator(obsToCopy.getCreator());
1 ✔
223
                newObs.setDateCreated(obsToCopy.getDateCreated());
1 ✔
224
                newObs.setVoided(obsToCopy.getVoided());
1 ✔
225
                newObs.setVoidedBy(obsToCopy.getVoidedBy());
1 ✔
226
                newObs.setDateVoided(obsToCopy.getDateVoided());
1 ✔
227
                newObs.setVoidReason(obsToCopy.getVoidReason());
1 ✔
228
                newObs.setStatus(obsToCopy.getStatus());
1 ✔
229
                newObs.setInterpretation(obsToCopy.getInterpretation());
1 ✔
230
                newObs.setOrder(obsToCopy.getOrder());
1 ✔
231
                
232
                newObs.setValueComplex(obsToCopy.getValueComplex());
1 ✔
233
                newObs.setComplexData(obsToCopy.getComplexData());
1 ✔
234
                newObs.setFormField(obsToCopy.getFormFieldNamespace(), obsToCopy.getFormFieldPath());
1 ✔
235
                
236
                if (obsToCopy.getReferenceRange() != null) {
1 ✔
237
                        ObsReferenceRange newRange = new ObsReferenceRange();
1 ✔
238
                        ObsReferenceRange srcRange = obsToCopy.getReferenceRange();
1 ✔
239
                        newRange.setHiAbsolute(srcRange.getHiAbsolute());
1 ✔
240
                        newRange.setHiCritical(srcRange.getHiCritical());
1 ✔
241
                        newRange.setHiNormal(srcRange.getHiNormal());
1 ✔
242
                        newRange.setLowAbsolute(srcRange.getLowAbsolute());
1 ✔
243
                        newRange.setLowCritical(srcRange.getLowCritical());
1 ✔
244
                        newRange.setLowNormal(srcRange.getLowNormal());
1 ✔
245
                        newRange.setObs(newObs);
1 ✔
246
                        newObs.setReferenceRange(newRange);
1 ✔
247
                }
248
                
249
                // Copy list of all members, including voided, and put them in respective groups
250
                if (obsToCopy.hasGroupMembers(true)) {
1 ✔
251
                        for (Obs member : obsToCopy.getGroupMembers(true)) {
1 ✔
252
                                // if the obs hasn't been saved yet, no need to duplicate it
253
                                if (member.getObsId() == null) {
1 ✔
254
                                        newObs.addGroupMember(member);
1 ✔
255
                                } else {
256
                                        Obs newMember = Obs.newInstance(member);
1 ✔
257
                                        newMember.setPreviousVersion(member);
1 ✔
258
                                        newObs.addGroupMember(newMember);
1 ✔
259
                                }
260
                        }
1 ✔
261
                }
262
                
263
                return newObs;
1 ✔
264
        }
265
        
266
        // Property accessors
267
        
268
        /**
269
         * @return Returns the comment.
270
         */
271
        public String getComment() {
272
                return comment;
1 ✔
273
        }
274
        
275
        /**
276
         * @param comment The comment to set.
277
         */
278
        public void setComment(String comment) {
279
                markAsDirty(this.comment, comment);
1 ✔
280
                this.comment = comment;
1 ✔
281
        }
1 ✔
282
        
283
        /**
284
         * @return Returns the concept.
285
         */
286
        public Concept getConcept() {
287
                return concept;
1 ✔
288
        }
289
        
290
        /**
291
         * @param concept The concept to set.
292
         */
293
        public void setConcept(Concept concept) {
294
                markAsDirty(this.concept, concept);
1 ✔
295
                this.concept = concept;
1 ✔
296
        }
1 ✔
297
        
298
        /**
299
         * Get the concept description that is tied to the concept name that was used when making this
300
         * observation
301
         * 
302
         * @return ConceptDescription the description used
303
         */
304
        public ConceptDescription getConceptDescription() {
305
                // if we don't have a question for this concept,
306
                // then don't bother looking for a description
307
                if (getConcept() == null) {
×
UNCOV
308
                        return null;
×
309
                }
310
                
311
                // ABKTOD: description in which locale?
UNCOV
312
                return concept.getDescription();
×
313
        }
314
        
315
        /**
316
         * @return Returns the encounter.
317
         */
318
        public Encounter getEncounter() {
319
                return encounter;
1 ✔
320
        }
321
        
322
        /**
323
         * @param encounter The encounter to set.
324
         */
325
        public void setEncounter(Encounter encounter) {
326
                markAsDirty(this.encounter, encounter);
1 ✔
327
                this.encounter = encounter;
1 ✔
328
        }
1 ✔
329
        
330
        /**
331
         * @return Returns the location.
332
         */
333
        public Location getLocation() {
334
                return location;
1 ✔
335
        }
336
        
337
        /**
338
         * @param location The location to set.
339
         */
340
        public void setLocation(Location location) {
341
                markAsDirty(this.location, location);
1 ✔
342
                this.location = location;
1 ✔
343
        }
1 ✔
344
        
345
        /**
346
         * @return Returns the obsDatetime.
347
         */
348
        public Date getObsDatetime() {
349
                return obsDatetime;
1 ✔
350
        }
351
        
352
        /**
353
         * @param obsDatetime The obsDatetime to set.
354
         */
355
        public void setObsDatetime(Date obsDatetime) {
356
                markAsDirty(this.obsDatetime, obsDatetime);
1 ✔
357
                this.obsDatetime = obsDatetime;
1 ✔
358
        }
1 ✔
359
        
360
        /**
361
         * An obs grouping occurs when the question (#getConcept()) is a set. (@link
362
         * org.openmrs.Concept#isSet()) If this is non-null, it means the current Obs is in the list
363
         * returned by <code>obsGroup</code>.{@link #getGroupMembers()}
364
         * 
365
         * @return the Obs that is the grouping factor
366
         */
367
        public Obs getObsGroup() {
368
                return obsGroup;
1 ✔
369
        }
370
        
371
        /**
372
         * This method does NOT add this current obs to the list of obs in obsGroup.getGroupMembers().
373
         * That must be done (and should be done) manually. (I am not doing it here for fear of screwing
374
         * up the normal loading and creation of this object via hibernate/spring)
375
         * 
376
         * @param obsGroup the obsGroup to set
377
         */
378
        public void setObsGroup(Obs obsGroup) {
379
                markAsDirty(this.obsGroup, obsGroup);
1 ✔
380
                this.obsGroup = obsGroup;
1 ✔
381
        }
1 ✔
382
        
383
        /**
384
         * Convenience method that checks for if this obs has 1 or more group members (either voided or
385
         * non-voided) Note this method differs from hasGroupMembers(), as that method excludes voided
386
         * obs; logic is that while a obs that has only voided group members should be seen as
387
         * "having no group members" it still should be considered an "obs grouping"
388
         * <p>
389
         * NOTE: This method could also be called "isObsGroup" for a little less confusion on names.
390
         * However, jstl in a web layer (or any psuedo-getter) access isn't good with both an
391
         * "isObsGroup" method and a "getObsGroup" method. Which one should be returned with a
392
         * simplified jstl call like ${obs.obsGroup} ? With this setup, ${obs.obsGrouping} returns a
393
         * boolean of whether this obs is a parent and has members. ${obs.obsGroup} returns the parent
394
         * object to this obs if this obs is a group member of some other group.
395
         * 
396
         * @return true if this is the parent group of other obs
397
         */
398
        public boolean isObsGrouping() {
399
                return hasGroupMembers(true);
1 ✔
400
        }
401
        
402
        /**
403
         * A convenience method to check for nullity and length to determine if this obs has group
404
         * members. By default, this ignores voided-objects. To include voided, use
405
         * {@link #hasGroupMembers(boolean)} with value true.
406
         * 
407
         * @return true if this is the parent group of other obs
408
         * <strong>Should</strong> not include voided obs
409
         */
410
        public boolean hasGroupMembers() {
411
                return hasGroupMembers(false);
1 ✔
412
        }
413
        
414
        /**
415
         * Convenience method that checks for nullity and length to determine if this obs has group
416
         * members. The parameter specifies if this method whether or not voided obs should be
417
         * considered.
418
         * 
419
         * @param includeVoided determines if Voided members should be considered as group members.
420
         * @return true if this is the parent group of other Obs
421
         * <strong>Should</strong> return true if this obs has group members based on parameter
422
         */
423
        public boolean hasGroupMembers(boolean includeVoided) {
424
                // ! symbol used because if it's not empty, we want true
425
                return !org.springframework.util.CollectionUtils.isEmpty(getGroupMembers(includeVoided));
1 ✔
426
        }
427
        
428
        /**
429
         * Get the non-voided members of the obs group, if this obs is a group. By default this method
430
         * only returns non-voided group members. To get all group members, use
431
         * {@link #getGroupMembers(boolean)} with value true.
432
         * <p>
433
         * If it's not a group (i.e. {@link #getConcept()}.{@link org.openmrs.Concept#getSet()} is not
434
         * true, then this returns null.
435
         * 
436
         * @return a Set&lt;Obs&gt; of the members of this group.
437
         * @see #addGroupMember(Obs)
438
         * @see #hasGroupMembers()
439
         */
440
        public Set<Obs> getGroupMembers() {
441
                //same as just returning groupMembers
442
                return getGroupMembers(false);
1 ✔
443
        }
444
        
445
        /**
446
         * Get the group members of this obs group, if this obs is a group. This method will either
447
         * return all group members, or only non-voided group members, depending on if the argument is
448
         * set to be true or false respectively.
449
         * 
450
         * @param includeVoided
451
         * @return the set of group members in this obs group
452
         * <strong>Should</strong> Get all group members if passed true, and non-voided if passed false
453
         */
454
        public Set<Obs> getGroupMembers(boolean includeVoided) {
455
                if (includeVoided) {
1 ✔
456
                        //just return all group members
457
                        return groupMembers;
1 ✔
458
                }
459
                if (groupMembers == null) {
1 ✔
460
                        //Empty set so return null
461
                        return null;
1 ✔
462
                }
463
                Set<Obs> nonVoided = new LinkedHashSet<>(groupMembers);
1 ✔
464
                nonVoided.removeIf(BaseOpenmrsData::getVoided);
1 ✔
465
                return nonVoided;
1 ✔
466
        }
467
        
468
        /**
469
         * Set the members of the obs group, if this obs is a group.
470
         * <p>
471
         * If it's not a group (i.e. {@link #getConcept()}.{@link org.openmrs.Concept#getSet()} is not
472
         * true, then this returns null.
473
         * 
474
         * @param groupMembers the groupedObs to set
475
         * @see #addGroupMember(Obs)
476
         * @see #hasGroupMembers()
477
         * <strong>Should</strong> mark the obs as dirty when the set is changed from null to a non empty one
478
         * <strong>Should</strong> not mark the obs as dirty when the set is changed from null to an empty one
479
         * <strong>Should</strong> mark the obs as dirty when the set is replaced with another with different members
480
         * <strong>Should</strong> not mark the obs as dirty when the set is replaced with another with same members
481
         */
482
        public void setGroupMembers(Set<Obs> groupMembers) {
483
                //Copy over the entire list
484
                this.groupMembers = CollectionUtil.setCollection(this.groupMembers, groupMembers);
1 ✔
485
                
486
        }
1 ✔
487
        
488
        /**
489
         * Convenience method to add the given <code>obs</code> to this grouping. Will implicitly make
490
         * this obs an ObsGroup.
491
         * 
492
         * @param member Obs to add to this group
493
         * @see #setGroupMembers(Set)
494
         * @see #getGroupMembers()
495
         * <strong>Should</strong> return true when a new obs is added as a member
496
         * <strong>Should</strong> return false when a duplicate obs is added as a member
497
         */
498
        public void addGroupMember(Obs member) {
499
                if (member == null) {
1 ✔
UNCOV
500
                        return;
×
501
                }
502
                
503
                if (getGroupMembers() == null) {
1 ✔
504
                        groupMembers = new HashSet<>();
1 ✔
505
                }
506
                
507
                // a quick sanity check to make sure someone isn't adding
508
                // itself to the group
509
                if (member.equals(this)) {
1 ✔
510
                        throw new APIException("Obs.error.groupCannotHaveItselfAsAMentor", new Object[] { this, member });
1 ✔
511
                }
512
                
513
                member.setObsGroup(this);
1 ✔
514
                groupMembers.add(member);
1 ✔
515
        }
1 ✔
516
        
517
        /**
518
         * Convenience method to remove an Obs from this grouping This also removes the link in the
519
         * given <code>obs</code>object to this obs grouper
520
         * 
521
         * @param member Obs to remove from this group
522
         * @see #setGroupMembers(Set)
523
         * @see #getGroupMembers()
524
         * <strong>Should</strong> return true when an obs is removed
525
         * <strong>Should</strong> return false when a non existent obs is removed
526
         */
527
        public void removeGroupMember(Obs member) {
528
                if (member == null || getGroupMembers() == null) {
1 ✔
529
                        return;
1 ✔
530
                }
531
                
532
                if (groupMembers.remove(member)) {
1 ✔
533
                        member.setObsGroup(null);
1 ✔
534
                }
535
        }
1 ✔
536
        
537
        /**
538
         * Convenience method that returns related Obs If the Obs argument is not an ObsGroup: a
539
         * Set&lt;Obs&gt; will be returned containing all of the children of this Obs' parent that are
540
         * not ObsGroups themselves. This will include this Obs by default, unless getObsGroup() returns
541
         * null, in which case an empty set is returned. If the Obs argument is an ObsGroup: a
542
         * Set&lt;Obs&gt; will be returned containing 1. all of this Obs' group members, and 2. all
543
         * ancestor Obs that are not themselves obsGroups.
544
         * 
545
         * @return Set&lt;Obs&gt;
546
         */
547
        public Set<Obs> getRelatedObservations() {
548
                Set<Obs> ret = new HashSet<>();
1 ✔
549
                if (this.isObsGrouping()) {
1 ✔
550
                        ret.addAll(this.getGroupMembers());
1 ✔
551
                        Obs parentObs = this;
1 ✔
552
                        while (parentObs.getObsGroup() != null) {
1 ✔
553
                                for (Obs obsSibling : parentObs.getObsGroup().getGroupMembers()) {
1 ✔
554
                                        if (!obsSibling.isObsGrouping()) {
1 ✔
555
                                                ret.add(obsSibling);
1 ✔
556
                                        }
557
                                }
1 ✔
558
                                parentObs = parentObs.getObsGroup();
1 ✔
559
                        }
560
                } else if (this.getObsGroup() != null) {
1 ✔
561
                        for (Obs obsSibling : this.getObsGroup().getGroupMembers()) {
1 ✔
562
                                if (!obsSibling.isObsGrouping()) {
1 ✔
563
                                        ret.add(obsSibling);
1 ✔
564
                                }
565
                        }
1 ✔
566
                }
567
                return ret;
1 ✔
568
        }
569
        
570
        /**
571
         * @return Returns the obsId.
572
         */
573
        public Integer getObsId() {
574
                return obsId;
1 ✔
575
        }
576
        
577
        /**
578
         * @param obsId The obsId to set.
579
         */
580
        public void setObsId(Integer obsId) {
581
                this.obsId = obsId;
1 ✔
582
        }
1 ✔
583
        
584
        /**
585
         * @return Returns the order.
586
         */
587
        public Order getOrder() {
588
                return order;
1 ✔
589
        }
590
        
591
        /**
592
         * @param order The order to set.
593
         */
594
        public void setOrder(Order order) {
595
                markAsDirty(this.order, order);
1 ✔
596
                this.order = order;
1 ✔
597
        }
1 ✔
598
        
599
        /**
600
         * The person id of the person on this object. This should be the same as
601
         * <code>{@link #getPerson()}.getPersonId()</code>. It is duplicated here for speed and
602
         * simplicity reasons
603
         * 
604
         * @return the integer person id of the person this obs is acting on
605
         */
606
        public Integer getPersonId() {
607
                return personId;
1 ✔
608
        }
609
        
610
        /**
611
         * Set the person id on this obs object. This method is here for convenience, but really the
612
         * {@link #setPerson(Person)} method should be used like
613
         * <code>setPerson(new Person(personId))</code>
614
         * 
615
         * @see #setPerson(Person)
616
         * @param personId
617
         */
618
        protected void setPersonId(Integer personId) {
619
                markAsDirty(this.personId, personId);
1 ✔
620
                this.personId = personId;
1 ✔
621
        }
1 ✔
622
        
623
        /**
624
         * Get the person object that this obs is acting on.
625
         * 
626
         * @see #getPersonId()
627
         * @return the person object
628
         */
629
        public Person getPerson() {
630
                return person;
1 ✔
631
        }
632
        
633
        /**
634
         * Set the person object to this obs object. This will also set the personId on this obs object
635
         * 
636
         * @see #setPersonId(Integer)
637
         * @param person the Patient/Person object that this obs is acting on
638
         */
639
        public void setPerson(Person person) {
640
                markAsDirty(this.person, person);
1 ✔
641
                this.person = person;
1 ✔
642
                if (person != null) {
1 ✔
643
                        setPersonId(person.getPersonId());
1 ✔
644
                }
645
        }
1 ✔
646
        
647
        /**
648
         * Sets the value of this obs to the specified valueBoolean if this obs has a boolean concept.
649
         * 
650
         * @param valueBoolean the boolean value matching the boolean coded concept to set to
651
         */
652
        public void setValueBoolean(Boolean valueBoolean) {
653
                if (getConcept() != null && getConcept().getDatatype() != null && getConcept().getDatatype().isBoolean()) {
1 ✔
654
                        if (valueBoolean != null) {
1 ✔
655
                                setValueCoded(valueBoolean ? Context.getConceptService().getTrueConcept() : Context.getConceptService()
1 ✔
656
                                        .getFalseConcept());
1 ✔
657
                        } else {
UNCOV
658
                                setValueCoded(null);
×
659
                        }
660
                }
661
        }
1 ✔
662
        
663
        /**
664
         * Coerces a value to a Boolean representation
665
         * 
666
         * @return Boolean representation of the obs value
667
         * <strong>Should</strong> return true for value_numeric concepts if value is 1
668
         * <strong>Should</strong> return false for value_numeric concepts if value is 0
669
         * <strong>Should</strong> return null for value_numeric concepts if value is neither 1 nor 0
670
         */
671
        public Boolean getValueAsBoolean() {
672
                
673
                if (getValueCoded() != null) {
1 ✔
674
                        if (getValueCoded().equals(Context.getConceptService().getTrueConcept())) {
×
675
                                return Boolean.TRUE;
×
676
                        } else if (getValueCoded().equals(Context.getConceptService().getFalseConcept())) {
×
UNCOV
677
                                return Boolean.FALSE;
×
678
                        }
679
                } else if (getValueNumeric() != null) {
1 ✔
680
                        if (getValueNumeric() == 1) {
1 ✔
681
                                return Boolean.TRUE;
1 ✔
682
                        } else if (getValueNumeric() == 0) {
1 ✔
683
                                return Boolean.FALSE;
1 ✔
684
                        }
685
                }
686
                //returning null is preferred to defaulting to false to support validation of user input is from a form
687
                return null;
1 ✔
688
        }
689
        
690
        /**
691
         * Returns the boolean value if the concept of this obs is of boolean datatype
692
         * 
693
         * @return true or false if value is set otherwise null
694
         * <strong>Should</strong> return true if value coded answer concept is true concept
695
         * <strong>Should</strong> return false if value coded answer concept is false concept
696
         */
697
        public Boolean getValueBoolean() {
698
                if (getConcept() != null && valueCoded != null && getConcept().getDatatype().isBoolean()) {
1 ✔
699
                        Concept trueConcept = Context.getConceptService().getTrueConcept();
1 ✔
700
                        return trueConcept != null && valueCoded.getId().equals(trueConcept.getId());
1 ✔
701
                }
702
                
703
                return null;
1 ✔
704
        }
705
        
706
        /**
707
         * @return Returns the valueCoded.
708
         */
709
        
710
        public Concept getValueCoded() {
711
                return valueCoded;
1 ✔
712
        }
713
        
714
        /**
715
         * @param valueCoded The valueCoded to set.
716
         */
717
        public void setValueCoded(Concept valueCoded) {
718
                markAsDirty(this.valueCoded, valueCoded);
1 ✔
719
                this.valueCoded = valueCoded;
1 ✔
720
        }
1 ✔
721
        
722
        /**
723
         * Gets the specific name used for the coded value.
724
         * 
725
         * @return the name of the coded value
726
         */
727
        public ConceptName getValueCodedName() {
728
                return valueCodedName;
1 ✔
729
        }
730
        
731
        /**
732
         * Sets the specific name used for the coded value.
733
         * 
734
         * @param valueCodedName the name of the coded value
735
         */
736
        public void setValueCodedName(ConceptName valueCodedName) {
737
                markAsDirty(this.valueCodedName, valueCodedName);
1 ✔
738
                this.valueCodedName = valueCodedName;
1 ✔
739
        }
1 ✔
740
        
741
        /**
742
         * @return Returns the valueDrug
743
         */
744
        public Drug getValueDrug() {
745
                return valueDrug;
1 ✔
746
        }
747
        
748
        /**
749
         * @param valueDrug The valueDrug to set.
750
         */
751
        public void setValueDrug(Drug valueDrug) {
752
                markAsDirty(this.valueDrug, valueDrug);
1 ✔
753
                this.valueDrug = valueDrug;
1 ✔
754
        }
1 ✔
755
        
756
        /**
757
         * @return Returns the valueDatetime.
758
         */
759
        public Date getValueDatetime() {
760
                return valueDatetime;
1 ✔
761
        }
762
        
763
        /**
764
         * @param valueDatetime The valueDatetime to set.
765
         */
766
        public void setValueDatetime(Date valueDatetime) {
767
                markAsDirty(this.valueDatetime, valueDatetime);
1 ✔
768
                this.valueDatetime = valueDatetime;
1 ✔
769
        }
1 ✔
770
        
771
        /**
772
         * @return the value of this obs as a Date. Note that this uses a java.util.Date, so it includes
773
         *         a time component, that should be ignored.
774
         * @since 1.9
775
         */
776
        public Date getValueDate() {
777
                return valueDatetime;
1 ✔
778
        }
779
        
780
        /**
781
         * @param valueDate The date value to set.
782
         * @since 1.9
783
         */
784
        public void setValueDate(Date valueDate) {
785
                markAsDirty(this.valueDatetime, valueDate);
1 ✔
786
                this.valueDatetime = valueDate;
1 ✔
787
        }
1 ✔
788
        
789
        /**
790
         * @return the time value of this obs. Note that this uses a java.util.Date, so it includes a
791
         *         date component, that should be ignored.
792
         * @since 1.9
793
         */
794
        public Date getValueTime() {
795
                return valueDatetime;
1 ✔
796
        }
797
        
798
        /**
799
         * @param valueTime the time value to set
800
         * @since 1.9
801
         */
802
        public void setValueTime(Date valueTime) {
803
                markAsDirty(this.valueDatetime, valueTime);
1 ✔
804
                this.valueDatetime = valueTime;
1 ✔
805
        }
1 ✔
806
        
807
        /**
808
         * @return Returns the valueGroupId.
809
         */
810
        public Integer getValueGroupId() {
811
                return valueGroupId;
1 ✔
812
        }
813
        
814
        /**
815
         * @param valueGroupId The valueGroupId to set.
816
         */
817
        public void setValueGroupId(Integer valueGroupId) {
818
                markAsDirty(this.valueGroupId, valueGroupId);
1 ✔
819
                this.valueGroupId = valueGroupId;
1 ✔
820
        }
1 ✔
821
        
822
        /**
823
         * @return Returns the valueModifier.
824
         */
825
        public String getValueModifier() {
826
                return valueModifier;
1 ✔
827
        }
828
        
829
        /**
830
         * @param valueModifier The valueModifier to set.
831
         */
832
        public void setValueModifier(String valueModifier) {
833
                markAsDirty(this.valueModifier, valueModifier);
1 ✔
834
                this.valueModifier = valueModifier;
1 ✔
835
        }
1 ✔
836
        
837
        /**
838
         * @return Returns the valueNumeric.
839
         */
840
        public Double getValueNumeric() {
841
                return valueNumeric;
1 ✔
842
        }
843
        
844
        /**
845
         * @param valueNumeric The valueNumeric to set.
846
         */
847
        public void setValueNumeric(Double valueNumeric) {
848
                markAsDirty(this.valueNumeric, valueNumeric);
1 ✔
849
                this.valueNumeric = valueNumeric;
1 ✔
850
        }
1 ✔
851
        
852
        /**
853
         * @return Returns the valueText.
854
         */
855
        public String getValueText() {
856
                return valueText;
1 ✔
857
        }
858
        
859
        /**
860
         * @param valueText The valueText to set.
861
         */
862
        public void setValueText(String valueText) {
863
                markAsDirty(this.valueText, valueText);
1 ✔
864
                this.valueText = valueText;
1 ✔
865
        }
1 ✔
866
        
867
        /**
868
         * @return Returns true if this Obs is complex.
869
         * @since 1.5
870
         * <strong>Should</strong> return true if the concept is complex
871
         */
872
        public boolean isComplex() {
873
                if (getConcept() != null) {
1 ✔
874
                        return getConcept().isComplex();
1 ✔
875
                }
876
                
877
                return false;
1 ✔
878
        }
879
        
880
        /**
881
         * Get the value for the ComplexData. This method is used by the ComplexObsHandler. The
882
         * valueComplex has two parts separated by a bar '|' character: part A) the title; and part B)
883
         * the URI. The title is the readable description of the valueComplex that is returned by
884
         * {@link Obs#getValueAsString(java.util.Locale)}. The URI is the location where the ComplexData is stored.
885
         * 
886
         * @return readable title and URI for the location of the ComplexData binary object.
887
         * @since 1.5
888
         */
889
        public String getValueComplex() {
890
                return this.valueComplex;
1 ✔
891
        }
892
        
893
        /**
894
         * Set the value for the ComplexData. This method is used by the ComplexObsHandler. The
895
         * valueComplex has two parts separated by a bar '|' character: part A) the title; and part B)
896
         * the URI. The title is the readable description of the valueComplex that is returned by
897
         * {@link Obs#getValueAsString(java.util.Locale)}. The URI is the location where the ComplexData is stored.
898
         * 
899
         * @param valueComplex readable title and URI for the location of the ComplexData binary object.
900
         * @since 1.5
901
         */
902
        public void setValueComplex(String valueComplex) {
903
                markAsDirty(this.valueComplex, valueComplex);
1 ✔
904
                this.valueComplex = valueComplex;
1 ✔
905
        }
1 ✔
906
        
907
        /**
908
         * Set the ComplexData for this Obs. The ComplexData is stored in the file system or elsewhere,
909
         * but is not persisted to the database. <br>
910
         * <br>
911
         * {@link ComplexObsHandler}s that are registered to {@link ConceptComplex}s will persist the
912
         * {@link ComplexData#getData()} object to the correct place for the given concept.
913
         * 
914
         * @param complexData
915
         * @since 1.5
916
         */
917
        public void setComplexData(ComplexData complexData) {
918
                markAsDirty(this.complexData, complexData);
1 ✔
919
                this.complexData = complexData;
1 ✔
920
        }
1 ✔
921
        
922
        /**
923
         * Get the ComplexData. This is retrieved by the {@link ComplexObsHandler} from the file system
924
         * or another location, not from the database. <br>
925
         * <br>
926
         * This will be null unless you call:
927
         * 
928
         * <pre>
929
         * Obs obsWithComplexData =
930
         * Context.getObsService().getComplexObs(obsId, OpenmrsConstants.RAW_VIEW);
931
         * 
932
         * <pre/>
933
         *
934
         * @return the complex data for this obs (if its a complex obs)
935
         * @since 1.5
936
         */
937
        public ComplexData getComplexData() {
938
                return this.complexData;
1 ✔
939
        }
940
        
941
        /**
942
         * @return Returns the accessionNumber.
943
         */
944
        public String getAccessionNumber() {
945
                return accessionNumber;
1 ✔
946
        }
947
        
948
        /**
949
         * @param accessionNumber The accessionNumber to set.
950
         */
951
        public void setAccessionNumber(String accessionNumber) {
952
                markAsDirty(this.accessionNumber, accessionNumber);
1 ✔
953
                this.accessionNumber = accessionNumber;
1 ✔
954
        }
1 ✔
955
        
956
        /***************************************************************************
957
         * Convenience methods
958
         **************************************************************************/
959
        
960
        /**
961
         * Convenience method for obtaining the observation's value as a string If the Obs is complex,
962
         * returns the title of the complexData denoted by the section of getValueComplex() before the
963
         * first bar '|' character; or returns the entire getValueComplex() if the bar '|' character is
964
         * missing.
965
         *
966
         * @param locale locale for locale-specific depictions of value
967
         * <strong>Should</strong> return first part of valueComplex for complex obs
968
         * <strong>Should</strong> return first part of valueComplex for non null valueComplexes
969
         * <strong>Should</strong> return non precise values for NumericConcepts
970
         * <strong>Should</strong> return date in correct format
971
         * <strong>Should</strong> not return long decimal numbers as scientific notation
972
         * <strong>Should</strong> use commas or decimal places depending on locale
973
         * <strong>Should</strong> not use thousand separator
974
         * <strong>Should</strong> return regular number for size of zero to or greater than ten digits
975
         * <strong>Should</strong> return regular number if decimal places are as high as six
976
         */
977
        public String getValueAsString(Locale locale) {
978
                // formatting for the return of numbers of type double
979
                NumberFormat nf = NumberFormat.getNumberInstance(locale);
1 ✔
980
                DecimalFormat df = (DecimalFormat) nf;
1 ✔
981
                // formatting style up to 6 digits
982
                df.applyPattern("#0.0#####");
1 ✔
983
                //branch on hl7 abbreviations
984
                if (getConcept() != null) {
1 ✔
985
                        String abbrev = getConcept().getDatatype().getHl7Abbreviation();
1 ✔
986
                        if ("BIT".equals(abbrev)) {
1 ✔
UNCOV
987
                                return getValueAsBoolean() == null ? "" : getValueAsBoolean().toString();
×
988
                        } else if ("CWE".equals(abbrev)) {
1 ✔
989
                                if (getValueCoded() == null) {
1 ✔
UNCOV
990
                                        return "";
×
991
                                }
992
                                if (getValueDrug() != null) {
1 ✔
UNCOV
993
                                        return getValueDrug().getFullName(locale);
×
994
                                } else {
995
                                        ConceptName codedName = getValueCodedName();
1 ✔
996
                                        if (codedName != null) {
1 ✔
997
                                                return getValueCoded().getName(locale, false).getName();
1 ✔
998
                                        } else {
999
                                                ConceptName fallbackName = getValueCoded().getName();
×
1000
                                                if (fallbackName != null) {
×
UNCOV
1001
                                                        return fallbackName.getName();
×
1002
                                                } else {
UNCOV
1003
                                                        return "";
×
1004
                                                }
1005
                                                
1006
                                        }
1007
                                }
1008
                        } else if ("NM".equals(abbrev) || "SN".equals(abbrev)) {
1 ✔
1009
                                if (getValueNumeric() == null) {
1 ✔
UNCOV
1010
                                        return "";
×
1011
                                } else {
1012
                                        Concept deproxiedConcept = HibernateUtil.getRealObjectFromProxy(getConcept());
1 ✔
1013
                                        if (deproxiedConcept instanceof ConceptNumeric) {
1 ✔
1014
                                                ConceptNumeric cn = (ConceptNumeric) deproxiedConcept;
1 ✔
1015
                                                if (!cn.getAllowDecimal()) {
1 ✔
1016
                                                        double d = getValueNumeric();
1 ✔
1017
                                                        int i = (int) d;
1 ✔
1018
                                                        return Integer.toString(i);
1 ✔
1019
                                                } else {
UNCOV
1020
                                                        df.format(getValueNumeric());
×
1021
                                                }
1022
                                        }
UNCOV
1023
                                }
×
1024
                        } else if ("DT".equals(abbrev)) {
1 ✔
1025
                                DateFormat dateFormat = new SimpleDateFormat(DATE_PATTERN);
1 ✔
1026
                                return (getValueDatetime() == null ? "" : dateFormat.format(getValueDatetime()));
1 ✔
1027
                        } else if ("TM".equals(abbrev)) {
1 ✔
UNCOV
1028
                                return (getValueDatetime() == null ? "" : Format.format(getValueDatetime(), locale, FORMAT_TYPE.TIME));
×
1029
                        } else if ("TS".equals(abbrev)) {
1 ✔
UNCOV
1030
                                return (getValueDatetime() == null ? "" : Format.format(getValueDatetime(), locale, FORMAT_TYPE.TIMESTAMP));
×
1031
                        } else if ("ST".equals(abbrev)) {
1 ✔
UNCOV
1032
                                return getValueText();
×
1033
                        } else if ("ED".equals(abbrev) && getValueComplex() != null) {
1 ✔
1034
                                String[] valuesComplex = getValueComplex().split("\\|");
×
1035
                                for (String value : valuesComplex) {
×
1036
                                        if (StringUtils.isNotEmpty(value)) {
×
UNCOV
1037
                                                return value.trim();
×
1038
                                        }
1039
                                }
1040
                        }
1041
                }
1042
                
1043
                // if the datatype is 'unknown', default to just returning what is not null
1044
                if (getValueNumeric() != null) {
1 ✔
1045
                        return df.format(getValueNumeric());
1 ✔
1046
                } else if (getValueCoded() != null) {
×
1047
                        if (getValueDrug() != null) {
×
UNCOV
1048
                                return getValueDrug().getFullName(locale);
×
1049
                        } else {
1050
                                ConceptName valudeCodedName = getValueCodedName();
×
1051
                                if (valudeCodedName != null) {
×
UNCOV
1052
                                        return valudeCodedName.getName();
×
1053
                                } else {
UNCOV
1054
                                        return "";
×
1055
                                }
1056
                        }
1057
                } else if (getValueDatetime() != null) {
×
1058
                        return Format.format(getValueDatetime(), locale, FORMAT_TYPE.DATE);
×
1059
                } else if (getValueText() != null) {
×
1060
                        return getValueText();
×
UNCOV
1061
                } else if (hasGroupMembers()) {
×
1062
                        // all of the values are null and we're an obs group...so loop
1063
                        // over the members and just do a getValueAsString on those
1064
                        // this could potentially cause an infinite loop if an obs group
1065
                        // is a member of its own group at some point in the hierarchy
1066
                        StringBuilder sb = new StringBuilder();
×
1067
                        for (Obs groupMember : getGroupMembers()) {
×
1068
                                if (sb.length() > 0) {
×
UNCOV
1069
                                        sb.append(", ");
×
1070
                                }
1071
                                sb.append(groupMember.getValueAsString(locale));
×
1072
                        }
×
UNCOV
1073
                        return sb.toString();
×
1074
                }
1075
                
1076
                // returns the title portion of the valueComplex
1077
                // which is everything before the first bar '|' character.
1078
                if (getValueComplex() != null) {
×
1079
                        String[] valuesComplex = getValueComplex().split("\\|");
×
1080
                        for (String value : valuesComplex) {
×
1081
                                if (StringUtils.isNotEmpty(value)) {
×
UNCOV
1082
                                        return value.trim();
×
1083
                                }
1084
                        }
1085
                }
1086
                
UNCOV
1087
                return "";
×
1088
        }
1089
        
1090
        /**
1091
         * Sets the value for the obs from a string depending on the datatype of the question concept
1092
         *
1093
         * @param s the string to coerce to a boolean
1094
         * <strong>Should</strong> set value as boolean if the datatype of the question concept is boolean
1095
         * <strong>Should</strong> fail if the value of the string is null
1096
         * <strong>Should</strong> fail if the value of the string is empty
1097
         */
1098
        public void setValueAsString(String s) throws ParseException {
1099
                log.debug("getConcept() == {}", getConcept());
1 ✔
1100

1101
                if (getConcept() != null && s != null) {
1 ✔
1102
                        String abbrev = getConcept().getDatatype().getHl7Abbreviation();
1 ✔
1103
                        if ("ST".equals(abbrev)) {
1 ✔
1104
                                if (!StringUtils.isEmpty(s)) {
1 ✔
1105
                                        setValueText(s);
1 ✔
1106
                                }
1107
                                else {
1108
                                        throw new RuntimeException("Cannot set value to a empty string for concept: " + getConcept().getDisplayString());
1 ✔
1109
                                }
1110
                        } else if (!StringUtils.isBlank(s)) {
1 ✔
1111
                                s = s.trim();
1 ✔
1112
                                if ("BIT".equals(abbrev)) {
1 ✔
UNCOV
1113
                                        setValueBoolean(Boolean.valueOf(s));
×
1114
                                } else if ("CWE".equals(abbrev)) {
1 ✔
UNCOV
1115
                                        throw new RuntimeException("Not Yet Implemented");
×
1116
                                } else if ("NM".equals(abbrev) || "SN".equals(abbrev)) {
1 ✔
UNCOV
1117
                                        setValueNumeric(Double.valueOf(s));
×
1118
                                } else if ("DT".equals(abbrev)) {
1 ✔
1119
                                        DateFormat dateFormat = new SimpleDateFormat(DATE_PATTERN);
1 ✔
1120
                                        dateFormat.setLenient(false);
1 ✔
1121
                                        // ParsePosition tracks how much of the string was consumed, so trailing characters
1122
                                        // are rejected instead of ignored, and its index locates the failure in the exception.
1123
                                        ParsePosition position = new ParsePosition(0);
1 ✔
1124
                                        Date parsedDate = dateFormat.parse(s, position);
1 ✔
1125
                                        if (parsedDate == null || position.getIndex() != s.length()) {
1 ✔
1126
                                                // Some clients post a full ISO 8601 datetime for a date obs (the O3
1127
                                                // registration form posts a JavaScript Date, for example), so accept
1128
                                                // that form too, parsed strictly so invalid dates are still rejected.
1129
                                                Date isoDate = parseIsoDatetime(s);
1 ✔
1130
                                                if (isoDate == null) {
1 ✔
1131
                                                        int errorOffset = parsedDate == null ? position.getErrorIndex() : position.getIndex();
1 ✔
1132
                                                        throw new ParseException("Unable to parse date: " + s, errorOffset);
1 ✔
1133
                                                }
1134
                                                parsedDate = isoDate;
1 ✔
1135
                                        }
1136
                                        setValueDatetime(parsedDate);
1 ✔
1137
                                } else if ("TM".equals(abbrev)) {
1 ✔
1138
                                        DateFormat timeFormat = new SimpleDateFormat(TIME_PATTERN);
1 ✔
1139
                                        timeFormat.setLenient(false);
1 ✔
1140
                                        ParsePosition position = new ParsePosition(0);
1 ✔
1141
                                        Date parsedTime = timeFormat.parse(s, position);
1 ✔
1142
                                        if (parsedTime == null || position.getIndex() != s.length()) {
1 ✔
1143
                                                // Times may also carry seconds (HH:mm:ss), the usual ISO 8601 and FHIR form.
1144
                                                DateFormat secondsFormat = new SimpleDateFormat(TIME_PATTERN_WITH_SECONDS);
1 ✔
1145
                                                secondsFormat.setLenient(false);
1 ✔
1146
                                                ParsePosition secondsPosition = new ParsePosition(0);
1 ✔
1147
                                                Date parsedTimeWithSeconds = secondsFormat.parse(s, secondsPosition);
1 ✔
1148
                                                if (parsedTimeWithSeconds == null || secondsPosition.getIndex() != s.length()) {
1 ✔
1149
                                                        int errorOffset = parsedTime == null ? position.getErrorIndex() : position.getIndex();
1 ✔
1150
                                                        throw new ParseException("Unable to parse time: " + s, errorOffset);
1 ✔
1151
                                                }
1152
                                                parsedTime = parsedTimeWithSeconds;
1 ✔
1153
                                        }
1154
                                        setValueDatetime(parsedTime);
1 ✔
1155
                                } else if ("TS".equals(abbrev)) {
1 ✔
1156
                                        setValueDatetime(DateUtil.parseDatetimeString(s));
1 ✔
1157
                                }  else {
UNCOV
1158
                                        throw new RuntimeException("Don't know how to handle " + abbrev + " for concept: " + getConcept().getDisplayString());
×
1159
                                }
1160
                        } else {
1161
                                throw new RuntimeException("Cannot set value to a blank string for concept: " + getConcept().getDisplayString());
1 ✔
1162
                        }
1163
                } else {
1 ✔
1164
                        if (s == null) {
1 ✔
1165
                                throw new RuntimeException("cannot set value to null via setValueAsString()");
1 ✔
1166
                        } else {
UNCOV
1167
                                throw new RuntimeException("concept is null for " + this);
×
1168
                        }
1169
                }
1170
        }
1 ✔
1171
        
1172
        /**
1173
         * Parses an ISO 8601 datetime string, with or without a timezone offset, using strict resolution so
1174
         * that invalid values such as February 30 are rejected instead of being rolled over to a different
1175
         * day. Uses the same formatter shape as {@link DateUtil#parseDatetimeString(String)}, whose default
1176
         * resolution is not strict.
1177
         *
1178
         * @param s the string to parse
1179
         * @return the parsed date, or null if the string is not a valid ISO 8601 datetime
1180
         */
1181
        private static Date parseIsoDatetime(String s) {
1182
                if (!s.contains("T")) {
1 ✔
1183
                        return null;
1 ✔
1184
                }
1185
                DateTimeFormatter isoFormatter = new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
1 ✔
1186
                        .optionalStart().appendPattern("XXX").optionalEnd().optionalStart().appendPattern("XX").optionalEnd()
1 ✔
1187
                        .optionalStart().appendPattern("X").optionalEnd().toFormatter().withResolverStyle(ResolverStyle.STRICT);
1 ✔
1188
                try {
1189
                        TemporalAccessor parsed = isoFormatter.parse(s);
1 ✔
1190
                        Instant instant = parsed.isSupported(ChronoField.OFFSET_SECONDS) ? OffsetDateTime.from(parsed).toInstant()
1 ✔
1191
                                : LocalDateTime.from(parsed).atZone(ZoneId.systemDefault()).toInstant();
1 ✔
1192
                        return Date.from(instant);
1 ✔
1193
                } catch (DateTimeException e) {
1 ✔
1194
                        return null;
1 ✔
1195
                }
1196
        }
1197

1198
        /**
1199
         * @see java.lang.Object#toString()
1200
         */
1201
        @Override
1202
        public String toString() {
1203
                if (obsId == null) {
1 ✔
1204
                        return "obs id is null";
1 ✔
1205
                }
1206
                
1207
                return "Obs #" + obsId.toString();
1 ✔
1208
        }
1209
        
1210
        /**
1211
         * @since 1.5
1212
         * @see org.openmrs.OpenmrsObject#getId()
1213
         */
1214
        @Override
1215
        public Integer getId() {
1216
                return getObsId();
1 ✔
1217
                
1218
        }
1219
        
1220
        /**
1221
         * @since 1.5
1222
         * @see org.openmrs.OpenmrsObject#setId(java.lang.Integer)
1223
         */
1224
        @Override
1225
        public void setId(Integer id) {
1226
                setObsId(id);
1 ✔
1227
                
1228
        }
1 ✔
1229
        
1230
        /**
1231
         * When ObsService updates an obs, it voids the old version, creates a new Obs with the updates,
1232
         * and adds a reference to the previousVersion in the new Obs. getPreviousVersion returns the
1233
         * last version of this Obs.
1234
         */
1235
        public Obs getPreviousVersion() {
1236
                return previousVersion;
1 ✔
1237
        }
1238
        
1239
        /**
1240
         * A previousVersion indicates that this Obs replaces an earlier one.
1241
         *
1242
         * @param previousVersion the Obs that this Obs superceeds
1243
         */
1244
        public void setPreviousVersion(Obs previousVersion) {
1245
                markAsDirty(this.previousVersion, previousVersion);
1 ✔
1246
                this.previousVersion = previousVersion;
1 ✔
1247
        }
1 ✔
1248
        
1249
        public Boolean hasPreviousVersion() {
1250
                return getPreviousVersion() != null;
1 ✔
1251
        }
1252
        
1253
        /**
1254
         * @param creator
1255
         * @see Auditable#setCreator(User)
1256
         */
1257
        @Override
1258
        public void setCreator(User creator) {
1259
                markAsDirty(getCreator(), creator);
1 ✔
1260
                super.setCreator(creator);
1 ✔
1261
        }
1 ✔
1262
        
1263
        /**
1264
         * @param dateCreated
1265
         * @see Auditable#setDateCreated(Date)
1266
         */
1267
        @Override
1268
        public void setDateCreated(Date dateCreated) {
1269
                markAsDirty(getDateCreated(), dateCreated);
1 ✔
1270
                super.setDateCreated(dateCreated);
1 ✔
1271
        }
1 ✔
1272
        
1273
        /**
1274
         * @see org.openmrs.FormRecordable#setFormField(String,String)
1275
         */
1276
        @Override
1277
        public void setFormField(String namespace, String formFieldPath) {
1278
                String oldValue = formNamespaceAndPath;
1 ✔
1279
                super.setFormField(namespace, formFieldPath);
1 ✔
1280
                markAsDirty(oldValue, formNamespaceAndPath);
1 ✔
1281
        }
1 ✔
1282
        
1283
        /**
1284
         * Returns true if any change has been made to an Obs instance. In general, the only time
1285
         * isDirty() is going to return false is when a new Obs has just been instantiated or loaded
1286
         * from the database and no method that modifies it internally has been invoked.
1287
         *
1288
         * @return true if not changed otherwise false
1289
         * @since 2.0
1290
         * <strong>Should</strong> return false when no change has been made
1291
         * <strong>Should</strong> return true when any immutable field has been changed
1292
         * <strong>Should</strong> return false when only mutable fields are changed
1293
         * <strong>Should</strong> return true when an immutable field is changed from a null to a non null value
1294
         * <strong>Should</strong> return true when an immutable field is changed from a non null to a null value
1295
         */
1296
        public boolean isDirty() {
1297
                return dirty;
1 ✔
1298
        }
1299
        
1300
        protected void markAsDirty(Object oldValue, Object newValue) {
1301
                //Should we ignore the case for Strings?
1302
                if (!isDirty() && obsId != null && !OpenmrsUtil.nullSafeEquals(oldValue, newValue)) {
1 ✔
1303
                        dirty = true;
1 ✔
1304
                }
1305
        }
1 ✔
1306
        
1307
        /**
1308
         * Similar to FHIR's Observation.interpretation. Supports a subset of FHIR's Observation
1309
         * Interpretation Codes. See https://www.hl7.org/fhir/valueset-observation-interpretation.html
1310
         * 
1311
         * @since 2.1.0
1312
         */
1313
        public Interpretation getInterpretation() {
1314
                return interpretation;
1 ✔
1315
        }
1316
        
1317
        /**
1318
         * @since 2.1.0
1319
         */
1320
        public void setInterpretation(Interpretation interpretation) {
1321
                markAsDirty(this.interpretation, interpretation);
1 ✔
1322
                this.interpretation = interpretation;
1 ✔
1323
        }
1 ✔
1324
        
1325
        /**
1326
         * Similar to FHIR's Observation.status. Supports a subset of FHIR's ObservationStatus values.
1327
         * At present OpenMRS does not support FHIR's REGISTERED and CANCELLED statuses, because we
1328
         * don't support obs with null values. See:
1329
         * https://www.hl7.org/fhir/valueset-observation-status.html
1330
         * 
1331
         * @since 2.1.0
1332
         */
1333
        public Status getStatus() {
1334
                return status;
1 ✔
1335
        }
1336
        
1337
        /**
1338
         * @since 2.1.0
1339
         */
1340
        public void setStatus(Status status) {
1341
                markAsDirty(this.status, status);
1 ✔
1342
                this.status = status;
1 ✔
1343
        }
1 ✔
1344

1345
        /**
1346
         * Returns the ObsReferenceRange
1347
         * @return obsReferenceRange.
1348
         * 
1349
         * @since 2.7.0
1350
         */
1351
        public ObsReferenceRange getReferenceRange() {
1352
                return referenceRange;
1 ✔
1353
        }
1354
        
1355
        /**
1356
         * Sets ObsReferenceRange
1357
         * 
1358
         * @param referenceRange ObsReferenceRange to set.
1359
         *               
1360
         * @since 2.7.0
1361
         */
1362
        public void setReferenceRange(ObsReferenceRange referenceRange) {
1363
                this.referenceRange = referenceRange;
1 ✔
1364
        }
1 ✔
1365
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc