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

openmrs / openmrs-core / 43293528472

12 Nov 2026 05:19PM UTC coverage: 66.969% (+0.2%) from 66.721%
43293528472

push

github

ibacher
Validate module ids and contain module paths (#6813)

38 of 42 new or added lines in 4 files covered. (90.48%)

391 existing lines in 8 files now uncovered.

26387 of 39402 relevant lines covered (66.97%)

0.67 hits per line

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

88.68
/api/src/main/java/org/openmrs/PersonAttribute.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 javax.persistence.Cacheable;
13
import java.io.Serializable;
14
import java.lang.reflect.InvocationTargetException;
15
import java.lang.reflect.Method;
16
import java.util.Arrays;
17
import java.util.Collections;
18
import java.util.Comparator;
19
import java.util.Date;
20
import java.util.HashSet;
21
import java.util.Set;
22

23
import org.apache.commons.lang3.StringUtils;
24
import org.hibernate.annotations.Cache;
25
import org.hibernate.annotations.CacheConcurrencyStrategy;
26
import org.hibernate.envers.Audited;
27
import org.hibernate.search.mapper.pojo.automaticindexing.ReindexOnUpdate;
28
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.AssociationInverseSide;
29
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.DocumentId;
30
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
31
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;
32
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IndexedEmbedded;
33
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IndexingDependency;
34
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ObjectPath;
35
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.PropertyValue;
36
import org.openmrs.api.context.Context;
37
import org.openmrs.api.db.hibernate.search.SearchAnalysis;
38
import org.openmrs.util.OpenmrsClassLoader;
39
import org.openmrs.util.OpenmrsUtil;
40
import org.slf4j.Logger;
41
import org.slf4j.LoggerFactory;
42

43
/**
44
 * A PersonAttribute is meant as way for implementations to add arbitrary information about a
45
 * user/patient to their database. PersonAttributes are essentially just key-value pairs. However,
46
 * the PersonAttributeType can be defined in such a way that the value portion of this
47
 * PersonAttribute is a foreign key to another database table (like to the location table, or
48
 * concept table). This gives a PersonAttribute the ability to link to any other part of the
49
 * database A Person can have zero to n PersonAttribute(s).
50
 * 
51
 * @see org.openmrs.PersonAttributeType
52
 * @see org.openmrs.Attributable
53
 */
54
@Indexed
55
@Audited
56
@Cacheable
57
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
58
public class PersonAttribute extends BaseChangeableOpenmrsData implements java.io.Serializable, Comparable<PersonAttribute> {
59
        
60
        public static final long serialVersionUID = 11231211232111L;
61
        
62
        private static final Logger log = LoggerFactory.getLogger(PersonAttribute.class);
1 ✔
63
        
64
        // Fields
65
        @DocumentId
66
        private Integer personAttributeId;
67

68
        @IndexedEmbedded(includeEmbeddedObjectId = true)
69
        @AssociationInverseSide(inversePath = @ObjectPath({
70
                @PropertyValue(propertyName = "attributes")
71
        }))
72
        private Person person;
73

74
        @IndexedEmbedded
75
        @IndexingDependency(reindexOnUpdate = ReindexOnUpdate.SHALLOW)
76
        private PersonAttributeType attributeType;
77
        
78
        @FullTextField(name="valuePhrase", analyzer = SearchAnalysis.PHRASE_ANALYZER)
79
        @FullTextField(name = "valueExact", analyzer = SearchAnalysis.EXACT_ANALYZER)
80
        @FullTextField(name = "valueStart", analyzer = SearchAnalysis.START_ANALYZER, searchAnalyzer = SearchAnalysis.EXACT_ANALYZER)
81
        @FullTextField(name = "valueAnywhere", analyzer = SearchAnalysis.ANYWHERE_ANALYZER, searchAnalyzer = SearchAnalysis.EXACT_ANALYZER)
82
        private String value;
83
        
84
        private static final Set<Class<?>> VALUE_TYPES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
1 ✔
85
            String.class, Integer.class, Long.class, Double.class, Float.class, Boolean.class, Date.class)));
86
        
87
        /** default constructor */
88
        public PersonAttribute() {
1 ✔
89
        }
1 ✔
90
        
91
        public PersonAttribute(Integer personAttributeId) {
1 ✔
92
                this.personAttributeId = personAttributeId;
1 ✔
93
        }
1 ✔
94
        
95
        /**
96
         * Constructor for creating a basic attribute
97
         * 
98
         * @param type PersonAttributeType
99
         * @param value String
100
         */
101
        public PersonAttribute(PersonAttributeType type, String value) {
1 ✔
102
                this.attributeType = type;
1 ✔
103
                this.value = value;
1 ✔
104
        }
1 ✔
105
        
106
        /**
107
         * Shallow copy of this PersonAttribute. Does NOT copy personAttributeId
108
         * 
109
         * @return a shallows copy of <code>this</code>
110
         */
111
        public PersonAttribute copy() {
112
                return copyHelper(new PersonAttribute());
1 ✔
113
        }
114
        
115
        /**
116
         * The purpose of this method is to allow subclasses of PersonAttribute to delegate a portion of
117
         * their copy() method back to the superclass, in case the base class implementation changes.
118
         * 
119
         * @param target a PersonAttribute that will have the state of <code>this</code> copied into it
120
         * @return Returns the PersonAttribute that was passed in, with state copied into it
121
         */
122
        protected PersonAttribute copyHelper(PersonAttribute target) {
123
                target.setPerson(getPerson());
1 ✔
124
                target.setAttributeType(getAttributeType());
1 ✔
125
                target.setValue(getValue());
1 ✔
126
                target.setCreator(getCreator());
1 ✔
127
                target.setDateCreated(getDateCreated());
1 ✔
128
                target.setChangedBy(getChangedBy());
1 ✔
129
                target.setDateChanged(getDateChanged());
1 ✔
130
                target.setVoidedBy(getVoidedBy());
1 ✔
131
                target.setVoided(getVoided());
1 ✔
132
                target.setDateVoided(getDateVoided());
1 ✔
133
                target.setVoidReason(getVoidReason());
1 ✔
134
                return target;
1 ✔
135
        }
136
        
137
        /**
138
         * Compares this PersonAttribute object to the given otherAttribute. This method differs from
139
         * {@link #equals(Object)} in that this method compares the inner fields of each attribute for
140
         * equality. Note: Null/empty fields on <code>otherAttribute</code> /will not/ cause a false
141
         * value to be returned
142
         * 
143
         * @param otherAttribute PersonAttribute with which to compare
144
         * @return boolean true/false whether or not they are the same attributes
145
         * <strong>Should</strong> return true if attributeType value and void status are the same
146
         */
147
        @SuppressWarnings("unchecked")
148
        public boolean equalsContent(PersonAttribute otherAttribute) {
149
                boolean returnValue = true;
1 ✔
150
                
151
                // these are the methods to compare.
152
                String[] methods = { "getAttributeType", "getValue", "getVoided" };
1 ✔
153
                
154
                Class attributeClass = this.getClass();
1 ✔
155
                
156
                // loop over all of the selected methods and compare this and other
157
                for (String methodAttribute : methods) {
1 ✔
158
                        try {
159
                                Method method = attributeClass.getMethod(methodAttribute);
1 ✔
160
                                
161
                                Object thisValue = method.invoke(this);
1 ✔
162
                                Object otherValue = method.invoke(otherAttribute);
1 ✔
163
                                
164
                                if (otherValue != null) {
1 ✔
165
                                        returnValue &= otherValue.equals(thisValue);
1 ✔
166
                                }
167
                                
168
                        }
UNCOV
169
                        catch (NoSuchMethodException e) {
×
UNCOV
170
                                log.warn("No such method for comparison " + methodAttribute, e);
×
171
                        }
UNCOV
172
                        catch (IllegalAccessException | InvocationTargetException e) {
×
UNCOV
173
                                log.error("Error while comparing attributes", e);
×
174
                        }
1 ✔
175

176
                }
177
                
178
                return returnValue;
1 ✔
179
        }
180
        
181
        // property accessors
182
        
183
        /**
184
         * @return Returns the person.
185
         */
186
        public Person getPerson() {
187
                return person;
1 ✔
188
        }
189
        
190
        /**
191
         * @param person The person to set.
192
         */
193
        public void setPerson(Person person) {
194
                this.person = person;
1 ✔
195
        }
1 ✔
196
        
197
        /**
198
         * @return the attributeType
199
         */
200
        public PersonAttributeType getAttributeType() {
201
                return attributeType;
1 ✔
202
        }
203
        
204
        /**
205
         * @param attributeType the attributeType to set
206
         */
207
        public void setAttributeType(PersonAttributeType attributeType) {
208
                this.attributeType = attributeType;
1 ✔
209
        }
1 ✔
210
        
211
        /**
212
         * @return the value
213
         */
214
        public String getValue() {
215
                return value;
1 ✔
216
        }
217
        
218
        /**
219
         * @param value the value to set
220
         */
221
        public void setValue(String value) {
222
                this.value = value;
1 ✔
223
        }
1 ✔
224
        
225
        /**
226
         * @see java.lang.Object#toString()
227
         * <strong>Should</strong> return toString of hydrated value
228
         */
229
        @Override
230
        public String toString() {
231
                Object o = getHydratedObject();
1 ✔
232
                if (o instanceof Attributable) {
1 ✔
233
                        return ((Attributable) o).getDisplayString();
1 ✔
234
                } else if (o != null) {
1 ✔
235
                        return o.toString();
1 ✔
236
                }
237
                
238
                return this.value;
1 ✔
239
        }
240
        
241
        /**
242
         * @return the personAttributeId
243
         */
244
        public Integer getPersonAttributeId() {
245
                return personAttributeId;
1 ✔
246
        }
247
        
248
        /**
249
         * @param personAttributeId the personAttributeId to set
250
         */
251
        public void setPersonAttributeId(Integer personAttributeId) {
252
                this.personAttributeId = personAttributeId;
1 ✔
253
        }
1 ✔
254
        
255
        /**
256
         * Will try to create an object of class 'PersonAttributeType.format'. If that implements
257
         * <code>Attributable</code>, hydrate(value) is called. Defaults to just returning getValue()
258
         * 
259
         * @return hydrated object or getValue()
260
         * <strong>Should</strong> load class in format property
261
         * <strong>Should</strong> still load class in format property if not Attributable
262
         * <strong>Should</strong> not call no arg constructor of class that is not permitted
263
         */
264
        @SuppressWarnings("unchecked")
265
        public Object getHydratedObject() {
266
                
267
                if (getValue() == null) {
1 ✔
UNCOV
268
                        return null;
×
269
                }
270
                
271
                try {
272
                        Class c = OpenmrsClassLoader.getInstance().loadClass(getAttributeType().getFormat());
1 ✔
273

274
                        if (!Attributable.class.isAssignableFrom(c) && !VALUE_TYPES.contains(c)) {
1 ✔
275
                                if (!isPermittedClass(c)) {
1 ✔
276
                                        log.warn("Refusing to hydrate PersonAttributeType '{}': format '{}' is not a permitted class",
1 ✔
277
                                            getAttributeType().getName(), getAttributeType().getFormat());
1 ✔
278
                                }
279
                                return getValue();
1 ✔
280
                        }
281
                        try {
282
                                Object o = c.newInstance();
1 ✔
283
                                if (o instanceof Attributable) {
1 ✔
284
                                        Attributable attr = (Attributable) o;
1 ✔
285
                                        return attr.hydrate(getValue());
1 ✔
286
                                }
287
                        }
288
                        catch (InstantiationException e) {
1 ✔
289
                                if (!VALUE_TYPES.contains(c)) {
1 ✔
290
                                        log.warn(
1 ✔
291
                                            "Unable to hydrate PersonAttributeType '{}': Attributable format '{}' has no no-arg constructor",
292
                                            getAttributeType().getName(), getAttributeType().getFormat());
1 ✔
293
                                        return getValue();
1 ✔
294
                                }
295
                                // try to hydrate the object with the String constructor
296
                                log.trace("Unable to call no-arg constructor for class: " + c.getName());
1 ✔
297
                                return c.getConstructor(String.class).newInstance(getValue());
1 ✔
298
                        }
1 ✔
299
                }
UNCOV
300
                catch (Exception e) {
×
301
                        
302
                        // No need to warn if the input was blank
UNCOV
303
                        if (StringUtils.isBlank(getValue())) {
×
UNCOV
304
                                return null;
×
305
                        }
306
                        
UNCOV
307
                        log.warn("Unable to hydrate value: " + getValue() + " for type: " + getAttributeType(), e);
×
308
                }
1 ✔
309
                
310
                log.debug("Returning value: '" + getValue() + "'");
1 ✔
311
                return getValue();
1 ✔
312
        }
313
        
314
        /**
315
         * Convenience method for voiding this attribute
316
         * 
317
         * @param reason
318
         * <strong>Should</strong> set voided bit to true
319
         */
320
        public void voidAttribute(String reason) {
321
                setVoided(true);
1 ✔
322
                setVoidedBy(Context.getAuthenticatedUser());
1 ✔
323
                setVoidReason(reason);
1 ✔
324
                setDateVoided(new Date());
1 ✔
325
        }
1 ✔
326
        
327
        /**
328
         * @see java.lang.Comparable#compareTo(java.lang.Object)
329
         * <strong>Should</strong> return negative if other attribute is voided
330
         * <strong>Should</strong> return negative if other attribute has earlier date created
331
         * <strong>Should</strong> return negative if this attribute has lower attribute type than argument
332
         * <strong>Should</strong> return negative if other attribute has lower value
333
         * <strong>Should</strong> return negative if this attribute has lower attribute id than argument
334
         * <strong>Should</strong> not throw exception if attribute type is null
335
         * Note: this comparator imposes orderings that are inconsistent with equals
336
         */
337
        @Override
338
        public int compareTo(PersonAttribute other) {
339
                DefaultComparator paDComparator = new DefaultComparator();
1 ✔
340
                return paDComparator.compare(this, other);
1 ✔
341
        }
342
        
343
        /**
344
         * @since 1.5
345
         * @see org.openmrs.OpenmrsObject#getId()
346
         */
347
        @Override
348
        public Integer getId() {
349
                
350
                return getPersonAttributeId();
1 ✔
351
        }
352
        
353
        /**
354
         * @since 1.5
355
         * @see org.openmrs.OpenmrsObject#setId(java.lang.Integer)
356
         */
357
        @Override
358
        public void setId(Integer id) {
UNCOV
359
                setPersonAttributeId(id);
×
360
                
361
        }
×
362
        
363
        /**
364
         Provides a default comparator.
365
         @since 1.12
366
         **/
367
        public static class DefaultComparator implements Comparator<PersonAttribute>, Serializable {
1 ✔
368

369
                private static final long serialVersionUID = 1L;
370
                
371
                @Override
372
                public int compare(PersonAttribute pa1, PersonAttribute pa2) {
373
                        int retValue;
374
                        if ((retValue = OpenmrsUtil.compareWithNullAsGreatest(pa1.getAttributeType(), pa2.getAttributeType())) != 0) {
1 ✔
375
                                return retValue;
1 ✔
376
                        }
377
                        
378
                        if ((retValue = pa1.getVoided().compareTo(pa2.getVoided())) != 0) {
1 ✔
379
                                return retValue;
1 ✔
380
                        }
381
                        
382
                        if ((retValue = OpenmrsUtil.compareWithNullAsLatest(pa1.getDateCreated(), pa2.getDateCreated())) != 0) {
1 ✔
UNCOV
383
                                return retValue;
×
384
                        }
385
                        
386
                        if ((retValue = OpenmrsUtil.compareWithNullAsGreatest(pa1.getValue(), pa2.getValue())) != 0) {
1 ✔
387
                                return retValue;
1 ✔
388
                        }
389
                        
390
                        return OpenmrsUtil.compareWithNullAsGreatest(pa1.getPersonAttributeId(), pa2.getPersonAttributeId());
1 ✔
391
                }
392
        }
393

394
        /**
395
         * Whether a class may be used as a {@link PersonAttributeType#getFormat()}: an {@link Attributable}
396
         * implementation, one of a fixed set of value types, an {@link OpenmrsObject} or {@link Character}.
397
         * Only the first two are ever instantiated by {@link #getHydratedObject()}; the others are accepted
398
         * so that existing types referencing domain objects remain valid.
399
         * <p>
400
         * <strong>Should</strong> return true for attributable class<br/>
401
         * <strong>Should</strong> return true for permitted value type<br/>
402
         * <strong>Should</strong> return true for openmrs object class<br/>
403
         * <strong>Should</strong> return true for character<br/>
404
         * <strong>Should</strong> return false for class outside permitted set
405
         *
406
         * @param c the class named by a person attribute type format
407
         * @return true if a type with that format passes validation
408
         */
409
        public static boolean isPermittedClass(Class<?> c) {
410
                return Attributable.class.isAssignableFrom(c) || VALUE_TYPES.contains(c) || OpenmrsObject.class.isAssignableFrom(c)
1 ✔
411
                        || Character.class.equals(c);
1 ✔
412
        }
413

414
}
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