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

openmrs / openmrs-core / 43295168256

12 Nov 2026 03:43PM UTC coverage: 68.956% (+0.02%) from 68.932%
43295168256

push

github

ibacher
Restrict PersonAttribute hydration and type formats to permitted classes (#6799)

19 of 19 new or added lines in 2 files covered. (100.0%)

385 existing lines in 7 files now uncovered.

26426 of 38323 relevant lines covered (68.96%)

0.69 hits per line

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

0.0
/api/src/main/java/org/openmrs/migration/MigrationHelper.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.migration;
11

12
import java.io.IOException;
13
import java.io.StringReader;
14
import java.text.DateFormat;
15
import java.text.ParseException;
16
import java.text.SimpleDateFormat;
17
import java.util.ArrayList;
18
import java.util.Collection;
19
import java.util.Collections;
20
import java.util.Date;
21
import java.util.HashMap;
22
import java.util.List;
23
import java.util.Map;
24
import java.util.Random;
25

26
import javax.xml.parsers.DocumentBuilder;
27
import javax.xml.parsers.DocumentBuilderFactory;
28
import javax.xml.parsers.ParserConfigurationException;
29

30
import org.openmrs.Location;
31
import org.openmrs.Patient;
32
import org.openmrs.PatientIdentifier;
33
import org.openmrs.PatientIdentifierType;
34
import org.openmrs.PatientProgram;
35
import org.openmrs.PatientState;
36
import org.openmrs.Person;
37
import org.openmrs.PersonName;
38
import org.openmrs.Program;
39
import org.openmrs.ProgramWorkflow;
40
import org.openmrs.ProgramWorkflowState;
41
import org.openmrs.Relationship;
42
import org.openmrs.RelationshipType;
43
import org.openmrs.Role;
44
import org.openmrs.User;
45
import org.openmrs.api.LocationService;
46
import org.openmrs.api.PatientService;
47
import org.openmrs.api.PersonService;
48
import org.openmrs.api.ProgramWorkflowService;
49
import org.openmrs.api.UserService;
50
import org.openmrs.api.context.Context;
51
import org.slf4j.Logger;
52
import org.slf4j.LoggerFactory;
53
import org.w3c.dom.Document;
54
import org.w3c.dom.Element;
55
import org.w3c.dom.Node;
56
import org.w3c.dom.NodeList;
57
import org.xml.sax.InputSource;
58
import org.xml.sax.SAXException;
59

60
import static org.openmrs.util.XmlUtils.createDocumentBuilder;
61

62
/**
63
 * The MigrationHelper will be removed from openmrs-core. If you need the code migrate it to your code base.
64
 * 
65
 * @deprecated since 2.2.0
66
 */
67
@Deprecated
68
public class MigrationHelper {
69

70
        private MigrationHelper() {
71
        }
72
        
73
        private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
74

75
        private static final Logger log = LoggerFactory.getLogger(MigrationHelper.class);
×
76
        
UNCOV
77
        static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
×
78

79
        /**
80
         * @deprecated since 2.2.0 migrate the method to your code base if needed
81
         */
82
        @Deprecated
83
        public static Date parseDate(String s) throws ParseException {
UNCOV
84
                if (s == null || s.length() == 0) {
×
85
                        return null;
×
86
                } else {
UNCOV
87
                        if (s.length() == 10) {
×
88
                                s += " 00:00:00";
×
89
                        }
UNCOV
90
                        DateFormat df = new SimpleDateFormat(DATE_TIME_PATTERN);
×
UNCOV
91
                        return df.parse(s);
×
92
                }
93
        }
94

95
        /**
96
         * @deprecated since 2.2.0 migrate the method to your code base if needed
97
         */
98
        @Deprecated
99
        public static Document parseXml(String xml) throws ParserConfigurationException {
UNCOV
100
                DocumentBuilder builder = createDocumentBuilder();
×
101
                try {
UNCOV
102
                        return builder.parse(new InputSource(new StringReader(xml)));
×
103
                }
UNCOV
104
                catch (IOException | SAXException ex) {
×
105
                        return null;
×
106
                }
107
        }
108
        
109
        private static void findNodesNamed(Node node, String lookForName, Collection<Node> ret) {
UNCOV
110
                if (node.getNodeName().equals(lookForName)) {
×
111
                        ret.add(node);
×
112
                } else {
UNCOV
113
                        NodeList list = node.getChildNodes();
×
114
                        for (int i = 0; i < list.getLength(); ++i) {
×
115
                                findNodesNamed(list.item(i), lookForName, ret);
×
116
                        }
117
                }
UNCOV
118
        }
×
119
        
120
        /**
121
         * Takes XML like: &lt;something&gt; &lt;user date_changed="2001-03-06 08:46:53.0"
122
         * date_created="2001-03-06 08:46:53.0" username="hamish@mit.edu" first_name="Hamish"
123
         * last_name="Fraser" user_id="2001"/&gt; &lt;/something&gt; Returns the number of users added
124
         * 
125
         * @deprecated since 2.2.0 migrate the method to your code base if needed
126
         */
127
        @Deprecated
128
        public static int importUsers(Document document) throws ParseException {
UNCOV
129
                int ret = 0;
×
130
                Random rand = new Random();
×
131
                UserService us = Context.getUserService();
×
132
                
UNCOV
133
                List<Node> toAdd = new ArrayList<>();
×
134
                findNodesNamed(document, "user", toAdd);
×
135
                for (Node node : toAdd) {
×
136
                        Element e = (Element) node;
×
137
                        String username = e.getAttribute("username");
×
138
                        if (username == null || username.length() == 0) {
×
139
                                throw new IllegalArgumentException("each <user /> element must define a user_name attribute");
×
140
                        }
UNCOV
141
                        if (us.getUserByUsername(username) != null) {
×
142
                                continue;
×
143
                        }
UNCOV
144
                        User user = new User();
×
145
                        user.setPerson(new Person());
×
146
                        PersonName pn = new PersonName(e.getAttribute("first_name"), "", e.getAttribute("last_name"));
×
147
                        user.addName(pn);
×
148
                        user.setUsername(username);
×
149
                        user.setDateCreated(parseDate(e.getAttribute("date_created")));
×
150
                        user.setDateChanged(parseDate(e.getAttribute("date_changed")));
×
151
                        
152
                        // Generate a temporary password: 8-12 random characters
153
                        String pass;
154
                        {
UNCOV
155
                                int length = rand.nextInt(4) + 8;
×
156
                                char[] password = new char[length];
×
157
                                for (int x = 0; x < length; x++) {
×
158
                                        int randDecimalAsciiVal = rand.nextInt(93) + 33;
×
159
                                        password[x] = (char) randDecimalAsciiVal;
×
160
                                }
UNCOV
161
                                pass = new String(password);
×
162
                        }
UNCOV
163
                        us.createUser(user, pass);
×
164
                        ++ret;
×
165
                }
×
166
                return ret;
×
167
        }
168
        
169
        /**
170
         * Takes XML like: &lt;something&gt; &lt;location name="Cerca-la-Source"/&gt; &lt;/something&gt; returns the
171
         * number of locations added
172
         * 
173
         * @deprecated since 2.2.0 migrate the method to your code base if needed
174
         */
175
        @Deprecated
176
        public static int importLocations(Document document) {
UNCOV
177
                int ret = 0;
×
178
                LocationService ls = Context.getLocationService();
×
179
                List<Node> toAdd = new ArrayList<>();
×
180
                findNodesNamed(document, "location", toAdd);
×
181
                for (Node node : toAdd) {
×
182
                        Element e = (Element) node;
×
183
                        String name = e.getAttribute("name");
×
184
                        if (name == null || name.length() == 0) {
×
185
                                throw new IllegalArgumentException("each <location /> element must define a name attribute");
×
186
                        }
UNCOV
187
                        if (ls.getLocation(name) != null) {
×
188
                                continue;
×
189
                        }
UNCOV
190
                        Location location = new Location();
×
191
                        location.setName(name);
×
192
                        
UNCOV
193
                        ls.saveLocation(location);
×
194
                        ++ret;
×
195
                }
×
196
                return ret;
×
197
        }
198
        
199
        /**
200
         * Takes a list of Strings of the format RELATIONSHIP:&lt;user last name&gt;,&lt;user first
201
         * name&gt;,&lt;relationship type name&gt;,&lt;patient identifier type name&gt;,&lt;identifier&gt; so if user hfraser
202
         * if the cardiologist of the patient with patient_id 8039 in PIH's old emr, then:
203
         * RELATIONSHIP:hfraser,Cardiologist,HIV-EMRV1,8039 (the "RELATIONSHIP:" is not actually
204
         * necessary. Anything before and including the first : will be dropped If autoCreateUsers is
205
         * true, and no user exists with the given username, one will be created. If autoAddRole is
206
         * true, then whenever a user is auto-created, if a role exists with the same name as
207
         * relationshipType.name, then the user will be added to that role
208
         * 
209
         * @deprecated since 2.2.0 migrate the method to your code base if needed
210
         */
211
        @Deprecated
212
        public static int importRelationships(Collection<String> relationships, boolean autoCreateUsers, boolean autoAddRole) {
UNCOV
213
                PatientService ps = Context.getPatientService();
×
214
                UserService us = Context.getUserService();
×
215
                PersonService personService = Context.getPersonService();
×
216
                List<Relationship> relsToAdd = new ArrayList<>();
×
217
                Random rand = new Random();
×
218
                for (String s : relationships) {
×
219
                        if (s.contains(":")) {
×
220
                                s = s.substring(s.indexOf(":") + 1);
×
221
                        }
UNCOV
222
                        String[] ss = s.split(",");
×
223
                        if (ss.length < 5) {
×
224
                                throw new IllegalArgumentException("The line '" + s + "' is in the wrong format");
×
225
                        }
UNCOV
226
                        String userLastName = ss[0];
×
227
                        String userFirstName = ss[1];
×
228
                        String username = (userFirstName + userLastName).replaceAll(" ", "");
×
229
                        String relationshipType = ss[2];
×
230
                        String identifierType = ss[3];
×
231
                        String identifier = ss[4];
×
232
                        User user = null;
×
233
                        { // first try looking for non-voided users
UNCOV
234
                                List<User> users = us.getUsersByName(userFirstName, userLastName, false);
×
235
                                if (users.size() == 1) {
×
236
                                        user = users.get(0);
×
237
                                } else if (users.size() > 1) {
×
238
                                        throw new IllegalArgumentException("Found " + users.size() + " users named '" + userLastName + ", "
×
239
                                                + userFirstName + "'");
240
                                }
241
                        }
UNCOV
242
                        if (user == null) {
×
243
                                // next try looking for voided users
UNCOV
244
                                List<User> users = us.getUsersByName(userFirstName, userLastName, false);
×
245
                                if (users.size() == 1) {
×
246
                                        user = users.get(0);
×
247
                                } else if (users.size() > 1) {
×
248
                                        throw new IllegalArgumentException("Found " + users.size() + " voided users named '" + userLastName
×
249
                                                + ", " + userFirstName + "'");
250
                                }
251
                        }
UNCOV
252
                        if (user == null && autoCreateUsers) {
×
253
                                user = new User();
×
254
                                user.setPerson(new Person());
×
255
                                PersonName pn = new PersonName(userFirstName, "", userLastName);
×
256
                                user.addName(pn);
×
257
                                user.setUsername(username);
×
258
                                // Generate a temporary password: 8-12 random characters
259
                                String pass;
260
                                {
UNCOV
261
                                        int length = rand.nextInt(4) + 8;
×
262
                                        char[] password = new char[length];
×
263
                                        for (int x = 0; x < length; x++) {
×
264
                                                int randDecimalAsciiVal = rand.nextInt(93) + 33;
×
265
                                                password[x] = (char) randDecimalAsciiVal;
×
266
                                        }
UNCOV
267
                                        pass = new String(password);
×
268
                                }
UNCOV
269
                                if (autoAddRole) {
×
270
                                        Role role = us.getRole(relationshipType);
×
271
                                        if (role != null) {
×
272
                                                user.addRole(role);
×
273
                                        }
274
                                }
UNCOV
275
                                us.createUser(user, pass);
×
276
                        }
UNCOV
277
                        if (user == null) {
×
278
                                throw new IllegalArgumentException("Can't find user '" + userLastName + ", " + userFirstName + "'");
×
279
                        }
UNCOV
280
                        Person person = personService.getPerson(user.getUserId());
×
281
                        
UNCOV
282
                        RelationshipType relationship = personService.getRelationshipTypeByName(relationshipType);
×
283
                        PatientIdentifierType pit = ps.getPatientIdentifierTypeByName(identifierType);
×
284
                        List<PatientIdentifier> found = ps.getPatientIdentifiers(identifier, Collections.singletonList(pit), null, null,
×
285
                            null);
UNCOV
286
                        if (found.size() != 1) {
×
287
                                throw new IllegalArgumentException("Found " + found.size() + " patients with identifier '" + identifier
×
288
                                        + "' of type " + identifierType);
289
                        }
UNCOV
290
                        Person relative = personService.getPerson(found.get(0).getPatient().getPatientId());
×
291
                        Relationship rel = new Relationship();
×
292
                        rel.setPersonA(person);
×
293
                        rel.setRelationshipType(relationship);
×
294
                        rel.setPersonB(relative);
×
295
                        relsToAdd.add(rel);
×
296
                }
×
297
                int addedSoFar = 0;
×
298
                for (Relationship rel : relsToAdd) {
×
299
                        personService.saveRelationship(rel);
×
300
                        ++addedSoFar;
×
301
                }
×
302
                return addedSoFar;
×
303
        }
304

305
        /**
306
         * @deprecated since 2.2.0 migrate the method to your code base if needed
307
         */
308
        @Deprecated
309
        public static int importProgramsAndStatuses(List<String> programWorkflow) throws ParseException {
UNCOV
310
                ProgramWorkflowService pws = Context.getProgramWorkflowService();
×
311
                PatientService ps = Context.getPatientService();
×
312
                List<PatientProgram> patientPrograms = new ArrayList<>();
×
313
                Map<String, PatientProgram> knownPatientPrograms = new HashMap<>();
×
314
                Map<String, Program> programsByName = new HashMap<>();
×
315
                for (Program program : pws.getAllPrograms()) {
×
316
                        programsByName.put(program.getConcept().getName(Context.getLocale(), false).getName(), program);
×
317
                }
×
318
                for (String s : programWorkflow) {
×
319
                        // ENROLLMENT:HIVEMR-V1,9266,IMB HIV PROGRAM,2005-08-25,
UNCOV
320
                        log.debug(s);
×
321
                        if (s.startsWith("ENROLLMENT:")) {
×
322
                                s = s.substring(s.indexOf(":") + 1);
×
323
                                String[] temp = s.split(",");
×
324
                                PatientIdentifierType pit = ps.getPatientIdentifierTypeByName(temp[0]);
×
325
                                String identifier = temp[1];
×
326
                                List<PatientIdentifier> pis = ps.getPatientIdentifiers(identifier, Collections.singletonList(pit), null,
×
327
                                    null, null);
UNCOV
328
                                if (pis.size() != 1) {
×
329
                                        throw new IllegalArgumentException("Found " + pis.size() + " instances of identifier " + identifier
×
330
                                                + " of type " + pit);
331
                                }
UNCOV
332
                                Patient p = pis.get(0).getPatient();
×
333
                                Program program = programsByName.get(temp[2]);
×
334
                                if (program == null) {
×
335
                                        throw new RuntimeException("Couldn't find program \"" + temp[2] + "\" in " + programsByName);
×
336
                                }
UNCOV
337
                                Date enrollmentDate = temp.length < 4 ? null : parseDate(temp[3]);
×
338
                                Date completionDate = temp.length < 5 ? null : parseDate(temp[4]);
×
339
                                PatientProgram pp = new PatientProgram();
×
340
                                pp.setPatient(p);
×
341
                                pp.setProgram(program);
×
342
                                pp.setDateEnrolled(enrollmentDate);
×
343
                                pp.setDateCompleted(completionDate);
×
344
                                patientPrograms.add(pp);
×
345
                                knownPatientPrograms.put(temp[0] + "," + temp[1] + "," + temp[2], pp); // "HIVEMR-V1,9266,IMB HIV PROGRAM"
×
346
                        } else if (s.startsWith("STATUS:")) {
×
347
                                // STATUS:HIVEMR-V1,9266,IMB HIV PROGRAM,TREATMENT STATUS,ACTIVE,2005-08-25,,
UNCOV
348
                                s = s.substring(s.indexOf(":") + 1);
×
349
                                String[] temp = s.split(",");
×
350
                                Program program = programsByName.get(temp[2]);
×
351
                                if (program == null) {
×
352
                                        throw new RuntimeException("Couldn't find program \"" + temp[2] + "\" in " + programsByName);
×
353
                                }
UNCOV
354
                                ProgramWorkflow wf = program.getWorkflowByName(temp[3]);
×
355
                                if (wf == null) {
×
356
                                        throw new RuntimeException("Couldn't find workflow \"" + temp[3] + "\" for program " + program + " (in "
×
357
                                                + program.getAllWorkflows() + ")");
×
358
                                }
UNCOV
359
                                ProgramWorkflowState st = wf.getStateByName(temp[4]);
×
360
                                if (st == null) {
×
361
                                        throw new RuntimeException("Couldn't find state \"" + temp[4] + "\" for workflow " + wf + " (in "
×
362
                                                + wf.getStates() + ")");
×
363
                                }
UNCOV
364
                                Date startDate = temp.length < 6 ? null : parseDate(temp[5]);
×
365
                                Date endDate = temp.length < 7 ? null : parseDate(temp[6]);
×
366
                                PatientState state = new PatientState();
×
367
                                PatientProgram pp = knownPatientPrograms.get(temp[0] + "," + temp[1] + "," + temp[2]);
×
368
                                state.setPatientProgram(pp);
×
369
                                state.setState(st);
×
370
                                state.setStartDate(startDate);
×
371
                                state.setEndDate(endDate);
×
372
                                pp.getStates().add(state);
×
373
                        }
UNCOV
374
                }
×
375
                int numAdded = 0;
×
376
                
UNCOV
377
                for (PatientProgram pp : knownPatientPrograms.values()) {
×
378
                        pws.savePatientProgram(pp);
×
379
                        ++numAdded;
×
380
                }
×
381
                return numAdded;
×
382
        }
383
        
384
}
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