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

openmrs / openmrs-core / 39827418952

22 Oct 2026 05:58PM UTC coverage: 68.744% (+0.09%) from 68.654%
39827418952

push

github

ibacher
Restrict reference range criteria to read-only calls and validate on save (#6721)

109 of 116 new or added lines in 5 files covered. (93.97%)

49 existing lines in 7 files now uncovered.

26263 of 38204 relevant lines covered (68.74%)

0.69 hits per line

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

90.75
/api/src/main/java/org/openmrs/util/ConceptReferenceRangeUtility.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.util;
11

12
import java.lang.reflect.Method;
13
import java.lang.reflect.Modifier;
14
import java.time.LocalDate;
15
import java.time.ZoneId;
16
import java.time.temporal.ChronoUnit;
17
import java.util.ArrayList;
18
import java.util.Collections;
19
import java.util.Date;
20
import java.util.HashMap;
21
import java.util.List;
22
import java.util.Locale;
23
import java.util.Map;
24
import java.util.concurrent.TimeUnit;
25
import java.util.regex.Pattern;
26

27
import org.apache.commons.lang3.StringUtils;
28
import org.hibernate.collection.spi.PersistentCollection;
29
import org.joda.time.LocalTime;
30
import org.jspecify.annotations.NonNull;
31
import org.jspecify.annotations.Nullable;
32
import org.openmrs.Concept;
33
import org.openmrs.ConceptReferenceRangeContext;
34
import org.openmrs.Obs;
35
import org.openmrs.Patient;
36
import org.openmrs.PatientProgram;
37
import org.openmrs.PatientState;
38
import org.openmrs.Person;
39
import org.openmrs.api.APIException;
40
import org.openmrs.api.context.Context;
41
import org.openmrs.api.db.hibernate.HibernateUtil;
42
import org.springframework.core.convert.TypeDescriptor;
43
import org.springframework.expression.AccessException;
44
import org.springframework.expression.EvaluationContext;
45
import org.springframework.expression.Expression;
46
import org.springframework.expression.ExpressionParser;
47
import org.springframework.expression.MethodExecutor;
48
import org.springframework.expression.MethodResolver;
49
import org.springframework.expression.ParseException;
50
import org.springframework.expression.PropertyAccessor;
51
import org.springframework.expression.TypedValue;
52
import org.springframework.expression.spel.SpelEvaluationException;
53
import org.springframework.expression.spel.SpelMessage;
54
import org.springframework.expression.spel.SpelNode;
55
import org.springframework.expression.spel.ast.Assign;
56
import org.springframework.expression.spel.ast.BeanReference;
57
import org.springframework.expression.spel.ast.CompoundExpression;
58
import org.springframework.expression.spel.ast.ConstructorReference;
59
import org.springframework.expression.spel.ast.MethodReference;
60
import org.springframework.expression.spel.ast.OpDec;
61
import org.springframework.expression.spel.ast.OpInc;
62
import org.springframework.expression.spel.ast.PropertyOrFieldReference;
63
import org.springframework.expression.spel.ast.TypeReference;
64
import org.springframework.expression.spel.standard.SpelExpression;
65
import org.springframework.expression.spel.standard.SpelExpressionParser;
66
import org.springframework.expression.spel.support.DataBindingMethodResolver;
67
import org.springframework.expression.spel.support.DataBindingPropertyAccessor;
68
import org.springframework.expression.spel.support.ReflectiveMethodResolver;
69
import org.springframework.context.expression.MapAccessor;
70
import org.springframework.expression.spel.support.SimpleEvaluationContext;
71

72
import com.github.benmanes.caffeine.cache.Cache;
73
import com.github.benmanes.caffeine.cache.Caffeine;
74

75
/**
76
 * A utility class that evaluates the concept ranges.
77
 * <p>
78
 * Criteria are SpEL expressions authored by users with the Manage Concepts privilege and evaluated
79
 * inside the transaction of whoever saves an obs. To keep them read-only, expressions are evaluated
80
 * in a restricted context: assignment is disabled, the only methods that may be invoked are
81
 * <ul>
82
 * <li>{@code get*}, {@code is*} and {@code has*} methods on any object, and</li>
83
 * <li>any method on the {@code $fn} helper ({@link CriteriaFunctions}),</li>
84
 * </ul>
85
 * and no Hibernate internal object (session, proxy initializer and the like) may be read, whether
86
 * through a method call or a property. Everything else, including {@code set*}, {@code add},
87
 * {@code clear} and {@code remove}, fails to resolve and the evaluation throws an
88
 * {@link APIException}.
89
 *
90
 * @since 2.7.0
91
 */
92
public class ConceptReferenceRangeUtility {
93

94
        /**
95
         * A local-only cache for expressions, which should alleviate parsing overhead in hot loops, i.e.,
96
         * if the same expressions are evaluated multiple times within a relatively short succession.
97
         * Expires each element 5 minutes after its last access.
98
         */
99
        private static final Cache<String, Expression> EXPRESSION_CACHE = Caffeine.newBuilder().maximumSize(20000)
1 ✔
100
                .expireAfterAccess(5, TimeUnit.MINUTES).build();
1 ✔
101

102
        /**
103
         * {@link ExpressionParser} instance used by the {@link ConceptReferenceRangeUtility} to parse
104
         * expressions
105
         */
106
        private static final ExpressionParser PARSER = new SpelExpressionParser();
1 ✔
107

108
        private static final Pattern ACCESSOR_NAME = Pattern.compile("^(get|is|has)[A-Z]\\w*$");
1 ✔
109

110
        /**
111
         * Static {@link org.springframework.expression.EvaluationContext} which is used to run evaluations.
112
         * This class is thread-safe, so shareable.
113
         * <p>
114
         * Assignment is disabled explicitly: the SpEL indexer writes to maps and lists directly without
115
         * consulting property accessors or method resolvers, so a read-only property accessor alone would
116
         * still let {@code $encounter.creator.userProperties['x'] = 'y'} through.
117
         */
118
        private static final SimpleEvaluationContext EVAL_CONTEXT = SimpleEvaluationContext
1 ✔
119
                .forPropertyAccessors(new MapAccessor(), new RestrictedPropertyAccessor())
1 ✔
120
                .withMethodResolvers(new RestrictedMethodResolver()).withAssignmentDisabled().build();
1 ✔
121

122
        private final CriteriaFunctions functions = new CriteriaFunctions();
1 ✔
123

124
        public ConceptReferenceRangeUtility() {
1 ✔
125
        }
1 ✔
126

127
        /**
128
         * This method evaluates the given criteria against the provided {@link Obs}.
129
         *
130
         * @param criteria the criteria string to evaluate e.g. "$patient.getAge() > 1"
131
         * @param obs The observation (Obs) object containing the values to be used in the criteria
132
         *            evaluation.
133
         * @return true if the criteria evaluates to true, false otherwise
134
         */
135
        public boolean evaluateCriteria(String criteria, Obs obs) {
136
                if (obs == null) {
1 ✔
137
                        throw new IllegalArgumentException("Failed to evaluate criteria with reason: Obs is null");
1 ✔
138
                }
139

140
                if (obs.getPerson() == null) {
1 ✔
141
                        throw new IllegalArgumentException("Failed to evaluate criteria with reason: patient is null");
×
142
                }
143

144
                if (StringUtils.isBlank(criteria)) {
1 ✔
145
                        throw new IllegalArgumentException("Failed to evaluate criteria with reason: criteria is empty");
1 ✔
146
                }
147

148
                return evaluateCriteria(criteria, new ConceptReferenceRangeContext(obs));
1 ✔
149
        }
150

151
        /**
152
         * Evaluates criteria against a {@link ConceptReferenceRangeContext}. When the context was
153
         * constructed from an Obs, {@code $obs} is available in the expression; otherwise only
154
         * {@code $patient}, {@code $fn}, {@code $context}, {@code $date}, and {@code $encounter} are
155
         * available.
156
         *
157
         * @param criteria the criteria string to evaluate
158
         * @param context the evaluation context
159
         * @return true if the criteria evaluates to true, false otherwise
160
         * @since 3.0.0, 2.9.0, 2.8.5, 2.7.9
161
         */
162
        public boolean evaluateCriteria(String criteria, ConceptReferenceRangeContext context) {
163
                if (context == null) {
1 ✔
164
                        throw new IllegalArgumentException("Failed to evaluate criteria with reason: context is null");
×
165
                }
166

167
                if (context.getPerson() == null) {
1 ✔
168
                        throw new IllegalArgumentException("Failed to evaluate criteria with reason: patient is null");
×
169
                }
170

171
                if (StringUtils.isBlank(criteria)) {
1 ✔
172
                        throw new IllegalArgumentException("Failed to evaluate criteria with reason: criteria is empty");
×
173
                }
174

175
                Map<String, Object> root = new HashMap<>();
1 ✔
176
                root.put("$fn", functions);
1 ✔
177
                root.put("$patient", HibernateUtil.getRealObjectFromProxy(context.getPerson()));
1 ✔
178
                root.put("$context", context);
1 ✔
179
                root.put("$obs", context.getObs());
1 ✔
180
                root.put("$encounter", context.getEncounter());
1 ✔
181
                root.put("$date", context.getDate());
1 ✔
182

183
                try {
184
                        Expression expression = EXPRESSION_CACHE.get(criteria, PARSER::parseExpression);
1 ✔
185
                        Boolean result = expression.getValue(EVAL_CONTEXT, root, Boolean.class);
1 ✔
186
                        return result != null && result;
1 ✔
187
                } catch (SpelEvaluationException e) {
1 ✔
188
                        SpelMessage msg = e.getMessageCode();
1 ✔
189
                        if (msg == SpelMessage.METHOD_CALL_ON_NULL_OBJECT_NOT_ALLOWED
1 ✔
190
                                || msg == SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL) {
191
                                return false;
1 ✔
192
                        }
193
                        throw new APIException("An error occurred while evaluating criteria: " + criteria, e);
1 ✔
194
                } catch (Exception e) {
×
195
                        throw new APIException("An error occurred while evaluating criteria: " + criteria, e);
×
196
                }
197
        }
198

199
        /**
200
         * Finds everything in a criteria expression that the evaluation context refuses, so that criteria
201
         * can be checked before they are stored. Reported are method calls outside the resolver's rule (any
202
         * method may be called on {@code $fn}; only {@code get*}, {@code is*} and {@code has*} methods may
203
         * be called on anything else), assignments, increments and decrements, type references, constructor
204
         * calls and bean references. Method calls are judged by name, so a call that passes here can still
205
         * fail at evaluation time if the method does not exist on the actual target or returns a Hibernate
206
         * internal object.
207
         *
208
         * @param criteria the criteria expression, already HTML-unescaped
209
         * @return the disallowed constructs rendered from the parsed expression, in source order
210
         * @throws ParseException if the criteria is not a valid expression
211
         * @since 2.8.11
212
         */
213
        public static List<String> findDisallowedConstructs(String criteria) throws ParseException {
214
                SpelNode ast;
215
                try {
216
                        ast = ((SpelExpression) PARSER.parseExpression(criteria)).getAST();
1 ✔
217
                } catch (SpelEvaluationException e) {
1 ✔
218
                        throw new ParseException(e.getPosition(), e.getSimpleMessage(), e);
1 ✔
219
                }
1 ✔
220
                List<String> disallowed = new ArrayList<>();
1 ✔
221
                collectDisallowedConstructs(ast, false, disallowed);
1 ✔
222
                return disallowed;
1 ✔
223
        }
224

225
        private static void collectDisallowedConstructs(SpelNode node, boolean onFunctions, List<String> disallowed) {
226
                if (node instanceof MethodReference) {
1 ✔
227
                        MethodReference method = (MethodReference) node;
1 ✔
228
                        if (isDisallowedMethodCall(method.getName(), onFunctions)) {
1 ✔
229
                                disallowed.add(method.toStringAST());
1 ✔
230
                        }
231
                } else if (node instanceof Assign || node instanceof OpInc || node instanceof OpDec || node instanceof TypeReference
1 ✔
232
                        || node instanceof ConstructorReference || node instanceof BeanReference) {
233
                        disallowed.add(node.toStringAST());
1 ✔
234
                }
235
                for (int i = 0; i < node.getChildCount(); i++) {
1 ✔
236
                        boolean childOnFunctions = i == 1 && node instanceof CompoundExpression
1 ✔
237
                                && node.getChild(0) instanceof PropertyOrFieldReference
1 ✔
238
                                && "$fn".equals(((PropertyOrFieldReference) node.getChild(0)).getName());
1 ✔
239
                        collectDisallowedConstructs(node.getChild(i), childOnFunctions, disallowed);
1 ✔
240
                }
241
        }
1 ✔
242

243
        private static boolean isDisallowedMethodCall(String name, boolean onFunctions) {
244
                return !onFunctions && !ACCESSOR_NAME.matcher(name).matches();
1 ✔
245
        }
246

247
        private static TypedValue refuseHibernateInternals(TypedValue value) throws AccessException {
248
                Object object = value.getValue();
1 ✔
249
                if (object != null && object.getClass().getName().startsWith("org.hibernate.")
1 ✔
250
                        && !(object instanceof PersistentCollection)) {
251
                        throw new AccessException("Hibernate internals may not be accessed in criteria");
1 ✔
252
                }
253
                return value;
1 ✔
254
        }
255

256
        /**
257
         * {@link MethodResolver} that restricts which methods a criteria expression may invoke. A method
258
         * call resolves only when the target is the {@code $fn} helper ({@link CriteriaFunctions}) or the
259
         * method is named {@code get*}, {@code is*} or {@code has*}, and its result is refused if it is a
260
         * Hibernate internal object such as a session or a proxy initializer. Like
261
         * {@link DataBindingMethodResolver}, it also refuses static methods, methods declared on
262
         * {@link Object} and {@link Class}, and {@link Class} or {@link ClassLoader} targets. It extends
263
         * {@link ReflectiveMethodResolver} so that SpEL can cache resolved methods between evaluations; the
264
         * returned executor therefore re-applies the checks that must hold on every call.
265
         */
266
        private static final class RestrictedMethodResolver extends ReflectiveMethodResolver {
267

268
                @Override
269
                protected boolean isCandidateForInvocation(Method method, Class<?> targetClass) {
270
                        Class<?> declaringClass = method.getDeclaringClass();
1 ✔
271
                        return !Modifier.isStatic(method.getModifiers()) && declaringClass != Object.class
1 ✔
272
                                && declaringClass != Class.class && !ClassLoader.class.isAssignableFrom(targetClass);
1 ✔
273
                }
274

275
                @Override
276
                public @Nullable MethodExecutor resolve(@NonNull EvaluationContext context, @NonNull Object targetObject,
277
                        @NonNull String name, @NonNull List<TypeDescriptor> argumentTypes) throws AccessException {
278
                        if (isDisallowedMethodCall(name, targetObject instanceof CriteriaFunctions)) {
1 ✔
279
                                throw new AccessException("Method '" + name + "' is not allowed in criteria; only get*, is* and has* "
1 ✔
280
                                        + "methods and $fn helper methods may be called");
281
                        }
282
                        if (targetObject instanceof Class) {
1 ✔
NEW
283
                                throw new AccessException("Class targets are not supported in criteria");
×
284
                        }
285

286
                        MethodExecutor executor = super.resolve(context, targetObject, name, argumentTypes);
1 ✔
287
                        if (executor == null) {
1 ✔
288
                                return null;
1 ✔
289
                        }
290
                        return (evaluationContext, target, arguments) -> {
1 ✔
291
                                if (target instanceof Class || target instanceof ClassLoader) {
1 ✔
NEW
292
                                        throw new AccessException("Class targets are not supported in criteria");
×
293
                                }
294
                                return refuseHibernateInternals(executor.execute(evaluationContext, target, arguments));
1 ✔
295
                        };
296
                }
297
        }
298

299
        /**
300
         * Read-only {@link PropertyAccessor} that refuses Hibernate internal objects, so that a proxy
301
         * initializer or a session cannot be reached as a property when the method form is refused.
302
         */
303
        private static final class RestrictedPropertyAccessor implements PropertyAccessor {
1 ✔
304

305
                private final PropertyAccessor delegate = DataBindingPropertyAccessor.forReadOnlyAccess();
1 ✔
306

307
                @Override
308
                public Class<?>[] getSpecificTargetClasses() {
309
                        return delegate.getSpecificTargetClasses();
1 ✔
310
                }
311

312
                @Override
313
                public boolean canRead(@NonNull EvaluationContext context, @Nullable Object target, @NonNull String name)
314
                        throws AccessException {
315
                        return delegate.canRead(context, target, name);
1 ✔
316
                }
317

318
                @Override
319
                public TypedValue read(@NonNull EvaluationContext context, @Nullable Object target, @NonNull String name)
320
                        throws AccessException {
321
                        return refuseHibernateInternals(delegate.read(context, target, name));
1 ✔
322
                }
323

324
                @Override
325
                public boolean canWrite(@NonNull EvaluationContext context, @Nullable Object target, @NonNull String name) {
NEW
326
                        return false;
×
327
                }
328

329
                @Override
330
                public void write(@NonNull EvaluationContext context, @Nullable Object target, @NonNull String name,
331
                        @Nullable Object newValue) throws AccessException {
NEW
332
                        throw new AccessException("Criteria may not assign values");
×
333
                }
334
        }
335

336
        /**
337
         * Helper functions available as {@code $fn} in concept reference range criteria expressions.
338
         * <p>
339
         * This class is intentionally separate from the outer class so that {@code evaluateCriteria} is not
340
         * callable from within expressions.
341
         *
342
         * @since 2.7.9, 2.8.6, 2.9.0, 3.0.0
343
         */
344
        static class CriteriaFunctions {
1 ✔
345

346
                private final long NULL_DATE_RETURN_VALUE = -1;
1 ✔
347

348
                /**
349
                 * Gets the latest Obs by concept.
350
                 *
351
                 * @param conceptRef can be either concept uuid or conceptMap's code and sourceName e.g
352
                 *            "bac25fd5-c143-4e43-bffe-4eb1e7efb6ce" or "CIEL:1434"
353
                 * @param person person to get obs for
354
                 * @return Obs latest Obs
355
                 */
356
                public Obs getLatestObs(String conceptRef, Person person) {
357
                        if (person == null) {
1 ✔
358
                                return null;
×
359
                        }
360
                        Concept concept = Context.getConceptService().getConceptByReference(conceptRef);
1 ✔
361

362
                        if (concept != null) {
1 ✔
363
                                List<Obs> observations = Context.getObsService().getObservations(Collections.singletonList(person), null,
1 ✔
364
                                    Collections.singletonList(concept), null, null, null, Collections.singletonList("dateCreated"), 1, null,
1 ✔
365
                                    null, null, false);
366

367
                                return observations.isEmpty() ? null : observations.get(0);
1 ✔
368
                        }
369

370
                        return null;
1 ✔
371
                }
372

373
                /**
374
                 * Gets the time of the day in hours.
375
                 *
376
                 * @return the hour of the day in 24hr format (e.g. 14 to mean 2pm)
377
                 */
378
                public int getCurrentHour() {
379
                        return LocalTime.now().getHourOfDay();
1 ✔
380
                }
381

382
                /**
383
                 * Retrieves the most relevant Obs for the given current Obs and conceptRef. If the current Obs
384
                 * contains a valid value (coded, numeric, date, text etc.) and the concept in Obs is the same as
385
                 * the supplied concept, the method returns the current Obs. Otherwise, it fetches the latest Obs
386
                 * for the supplied concept and patient.
387
                 *
388
                 * @param conceptRef can be either concept uuid or conceptMap's code and sourceName
389
                 * @param currentObs the current Obs being evaluated
390
                 * @return the most relevant Obs based on the current Obs, or the latest Obs if the current one has
391
                 *         no valid value
392
                 */
393
                public Obs getCurrentObs(String conceptRef, Obs currentObs) {
394
                        Concept concept = Context.getConceptService().getConceptByReference(conceptRef);
1 ✔
395

396
                        if (concept != null && concept.equals(currentObs.getConcept())
1 ✔
397
                                && !currentObs.getValueAsString(Locale.ENGLISH).isEmpty()) {
1 ✔
398
                                return currentObs;
1 ✔
399
                        } else {
400
                                return getLatestObs(conceptRef, currentObs.getPerson());
1 ✔
401
                        }
402
                }
403

404
                /**
405
                 * Gets the person's latest observation date for a given concept
406
                 *
407
                 * @param conceptRef can be either concept uuid or conceptMap's code and sourceName e.g
408
                 *            "bac25fd5-c143-4e43-bffe-4eb1e7efb6ce" or "CIEL:1434"
409
                 * @param person the person
410
                 * @return the observation date
411
                 * @since 2.7.0
412
                 */
413
                public Date getLatestObsDate(String conceptRef, Person person) {
414
                        Obs obs = getLatestObs(conceptRef, person);
1 ✔
415
                        if (obs == null) {
1 ✔
416
                                return null;
1 ✔
417
                        }
418

419
                        Date date = obs.getValueDate();
1 ✔
420
                        if (date == null) {
1 ✔
421
                                date = obs.getValueDatetime();
1 ✔
422
                        }
423

424
                        return date;
1 ✔
425
                }
426

427
                /**
428
                 * Checks if an observation's value coded answer is equal to a given concept
429
                 *
430
                 * @param conceptRef can be either concept uuid or conceptMap's code and sourceName e.g
431
                 *            "bac25fd5-c143-4e43-bffe-4eb1e7efb6ce" or "CIEL:1434" for the observation's question
432
                 * @param person the person
433
                 * @param answerConceptRef can be either concept uuid or conceptMap's code and sourceName for the
434
                 *            observation's coded answer
435
                 * @return true if the given concept is equal to the observation's value coded answer
436
                 * @since 2.7.0
437
                 */
438
                public boolean isObsValueCodedAnswer(String conceptRef, Person person, String answerConceptRef) {
439
                        Obs obs = getLatestObs(conceptRef, person);
1 ✔
440
                        if (obs == null) {
1 ✔
441
                                return false;
1 ✔
442
                        }
443

444
                        Concept valueCoded = obs.getValueCoded();
1 ✔
445
                        if (valueCoded == null) {
1 ✔
446
                                return false;
×
447
                        }
448

449
                        Concept answerConcept = Context.getConceptService().getConceptByReference(answerConceptRef);
1 ✔
450
                        if (answerConcept == null) {
1 ✔
451
                                return false;
×
452
                        }
453

454
                        return valueCoded.equals(answerConcept);
1 ✔
455
                }
456

457
                /**
458
                 * Gets the number of days from the person's latest observation date value for a given concept to
459
                 * the current date
460
                 *
461
                 * @param conceptRef concept uuid or conceptMap code and sourceName
462
                 * @param person the person
463
                 * @return the number of days
464
                 * @since 2.7.0
465
                 */
466
                public long getObsDays(String conceptRef, Person person) {
467
                        Date date = getLatestObsDate(conceptRef, person);
1 ✔
468
                        if (date == null) {
1 ✔
469
                                return NULL_DATE_RETURN_VALUE;
1 ✔
470
                        }
471
                        return getDays(date);
1 ✔
472
                }
473

474
                /**
475
                 * Gets the number of weeks from the person's latest observation date value for a given concept to
476
                 * the current date
477
                 *
478
                 * @param conceptRef concept uuid or conceptMap code and sourceName
479
                 * @param person the person
480
                 * @return the number of weeks
481
                 * @since 2.7.0
482
                 */
483
                public long getObsWeeks(String conceptRef, Person person) {
484
                        Date date = getLatestObsDate(conceptRef, person);
1 ✔
485
                        if (date == null) {
1 ✔
486
                                return NULL_DATE_RETURN_VALUE;
1 ✔
487
                        }
488
                        return getWeeks(date);
1 ✔
489
                }
490

491
                /**
492
                 * Gets the number of months from the person's latest observation date value for a given concept to
493
                 * the current date
494
                 *
495
                 * @param conceptRef concept uuid or conceptMap code and sourceName
496
                 * @param person the person
497
                 * @return the number of months
498
                 * @since 2.7.0
499
                 */
500
                public long getObsMonths(String conceptRef, Person person) {
501
                        Date date = getLatestObsDate(conceptRef, person);
1 ✔
502
                        if (date == null) {
1 ✔
503
                                return NULL_DATE_RETURN_VALUE;
1 ✔
504
                        }
505
                        return getMonths(date);
1 ✔
506
                }
507

508
                /**
509
                 * Gets the number of years from the person's latest observation date value for a given concept to
510
                 * the current date
511
                 *
512
                 * @param conceptRef concept uuid or conceptMap code and sourceName
513
                 * @param person the person
514
                 * @return the number of years
515
                 * @since 2.7.0
516
                 */
517
                public long getObsYears(String conceptRef, Person person) {
518
                        Date date = getLatestObsDate(conceptRef, person);
1 ✔
519
                        if (date == null) {
1 ✔
520
                                return NULL_DATE_RETURN_VALUE;
1 ✔
521
                        }
522
                        return getYears(date);
1 ✔
523
                }
524

525
                /**
526
                 * Gets the number of days between two given dates
527
                 *
528
                 * @param fromDate the date from which to start counting
529
                 * @param toDate the date up to which to stop counting
530
                 * @return the number of days between
531
                 * @since 2.7.0
532
                 */
533
                public long getDaysBetween(Date fromDate, Date toDate) {
534
                        if (fromDate == null || toDate == null) {
1 ✔
535
                                return NULL_DATE_RETURN_VALUE;
1 ✔
536
                        }
537
                        return ChronoUnit.DAYS.between(toLocalDate(fromDate), toLocalDate(toDate));
1 ✔
538
                }
539

540
                /**
541
                 * Gets the number of weeks between two given dates
542
                 *
543
                 * @param fromDate the date from which to start counting
544
                 * @param toDate the date up to which to stop counting
545
                 * @return the number of weeks between
546
                 * @since 2.7.0
547
                 */
548
                public long getWeeksBetween(Date fromDate, Date toDate) {
549
                        if (fromDate == null || toDate == null) {
1 ✔
550
                                return NULL_DATE_RETURN_VALUE;
1 ✔
551
                        }
552
                        return ChronoUnit.WEEKS.between(toLocalDate(fromDate), toLocalDate(toDate));
1 ✔
553
                }
554

555
                /**
556
                 * Gets the number of months between two given dates
557
                 *
558
                 * @param fromDate the date from which to start counting
559
                 * @param toDate the date up to which to stop counting
560
                 * @return the number of months between
561
                 * @since 2.7.0
562
                 */
563
                public long getMonthsBetween(Date fromDate, Date toDate) {
564
                        if (fromDate == null || toDate == null) {
1 ✔
565
                                return NULL_DATE_RETURN_VALUE;
1 ✔
566
                        }
567
                        return ChronoUnit.MONTHS.between(toLocalDate(fromDate), toLocalDate(toDate));
1 ✔
568
                }
569

570
                /**
571
                 * Gets the number of years between two given dates
572
                 *
573
                 * @param fromDate the date from which to start counting
574
                 * @param toDate the date up to which to stop counting
575
                 * @return the number of years between
576
                 * @since 2.7.0
577
                 */
578
                public long getYearsBetween(Date fromDate, Date toDate) {
579
                        if (fromDate == null || toDate == null) {
1 ✔
580
                                return NULL_DATE_RETURN_VALUE;
1 ✔
581
                        }
582
                        return ChronoUnit.YEARS.between(toLocalDate(fromDate), toLocalDate(toDate));
1 ✔
583
                }
584

585
                /**
586
                 * Gets the number of days from a given date up to the current date.
587
                 *
588
                 * @param fromDate the date from which to start counting
589
                 * @return the number of days
590
                 * @since 2.7.0
591
                 */
592
                public long getDays(Date fromDate) {
593
                        return getDaysBetween(fromDate, new Date());
1 ✔
594
                }
595

596
                /**
597
                 * Gets the number of weeks from a given date up to the current date.
598
                 *
599
                 * @param fromDate the date from which to start counting
600
                 * @return the number of weeks
601
                 * @since 2.7.0
602
                 */
603
                public long getWeeks(Date fromDate) {
604
                        return getWeeksBetween(fromDate, new Date());
1 ✔
605
                }
606

607
                /**
608
                 * Gets the number of months from a given date up to the current date.
609
                 *
610
                 * @param fromDate the date from which to start counting
611
                 * @return the number of months
612
                 * @since 2.7.0
613
                 */
614
                public long getMonths(Date fromDate) {
615
                        return getMonthsBetween(fromDate, new Date());
1 ✔
616
                }
617

618
                /**
619
                 * Gets the number of years from a given date up to the current date.
620
                 *
621
                 * @param fromDate the date from which to start counting
622
                 * @return the number of years
623
                 * @since 2.7.0
624
                 */
625
                public long getYears(Date fromDate) {
626
                        return getYearsBetween(fromDate, new Date());
1 ✔
627
                }
628

629
                /**
630
                 * Returns whether the patient is the specified program on the specified date
631
                 *
632
                 * @param uuid of program
633
                 * @param person the patient to test
634
                 * @param onDate the date to test whether the patient is in the program
635
                 * @return true if the patient is in the program on the specified date, false otherwise
636
                 * @since 2.7.0
637
                 */
638
                public boolean isEnrolledInProgram(String uuid, Person person, Date onDate) {
639
                        if (person == null) {
1 ✔
640
                                return false;
×
641
                        }
642
                        if (!(person.getIsPatient())) {
1 ✔
643
                                return false;
1 ✔
644
                        }
645
                        return getPatientPrograms((Patient) person, onDate).stream()
1 ✔
646
                                .anyMatch(pp -> pp.getProgram().getUuid().equals(uuid));
1 ✔
647
                }
648

649
                /**
650
                 * Returns whether the patient is the specified program state on the specified date
651
                 *
652
                 * @param uuid of program state
653
                 * @param person the patient to test
654
                 * @param onDate the date to test whether the patient is in the program state
655
                 * @return true if the patient is in the program state on the specified date, false otherwise
656
                 * @since 2.7.0
657
                 */
658
                public boolean isInProgramState(String uuid, Person person, Date onDate) {
659
                        if (person == null) {
1 ✔
660
                                return false;
×
661
                        }
662
                        if (!(person.getIsPatient())) {
1 ✔
663
                                return false;
1 ✔
664
                        }
665

666
                        List<PatientProgram> patientPrograms = getPatientPrograms((Patient) person, onDate);
1 ✔
667
                        List<PatientState> patientStates = new ArrayList<>();
1 ✔
668

669
                        for (PatientProgram pp : patientPrograms) {
1 ✔
670
                                for (PatientState state : pp.getStates()) {
1 ✔
671
                                        if (state.getActive(onDate)) {
1 ✔
672
                                                patientStates.add(state);
1 ✔
673
                                        }
674
                                }
1 ✔
675
                        }
1 ✔
676

677
                        return patientStates.stream().anyMatch(ps -> ps.getState().getUuid().equals(uuid));
1 ✔
678
                }
679

680
                private LocalDate toLocalDate(Date date) {
681
                        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
1 ✔
682
                }
683

684
                private List<PatientProgram> getPatientPrograms(Patient patient, Date onDate) {
685
                        if (onDate == null) {
1 ✔
686
                                onDate = new Date();
×
687
                        }
688
                        return Context.getProgramWorkflowService().getPatientPrograms(patient, null, null, onDate, onDate, null, false);
1 ✔
689
                }
690
        }
691
}
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