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

openmrs / openmrs-core / 24403205906

14 Apr 2026 01:59PM UTC coverage: 63.88% (+0.04%) from 63.836%
24403205906

push

github

ibacher
Fix compilation issue

0 of 2 new or added lines in 1 file covered. (0.0%)

193 existing lines in 14 files now uncovered.

22202 of 34756 relevant lines covered (63.88%)

0.64 hits per line

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

90.39
/api/src/main/java/org/openmrs/api/db/hibernate/HibernateUserDAO.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.api.db.hibernate;
11

12
import java.util.ArrayList;
13
import java.util.Date;
14
import java.util.HashMap;
15
import java.util.Iterator;
16
import java.util.List;
17
import java.util.Map;
18

19
import org.apache.commons.collections.CollectionUtils;
20
import org.apache.commons.lang3.StringUtils;
21
import org.hibernate.Criteria;
22
import org.hibernate.Query;
23
import org.hibernate.SessionFactory;
24
import org.hibernate.criterion.MatchMode;
25
import org.hibernate.criterion.Order;
26
import org.hibernate.criterion.Restrictions;
27
import org.openmrs.Person;
28
import org.openmrs.Privilege;
29
import org.openmrs.Role;
30
import org.openmrs.User;
31
import org.openmrs.api.context.Context;
32
import org.openmrs.api.context.Daemon;
33
import org.openmrs.api.db.DAOException;
34
import org.openmrs.api.db.LoginCredential;
35
import org.openmrs.api.db.UserDAO;
36
import org.openmrs.patient.impl.LuhnIdentifierValidator;
37
import org.openmrs.util.OpenmrsConstants;
38
import org.openmrs.util.Security;
39
import org.openmrs.util.UserByNameComparator;
40
import org.slf4j.Logger;
41
import org.slf4j.LoggerFactory;
42

43
/**
44
 * Hibernate specific database methods for the UserService
45
 * 
46
 * @see org.openmrs.api.context.Context
47
 * @see org.openmrs.api.db.UserDAO
48
 * @see org.openmrs.api.UserService
49
 */
50
public class HibernateUserDAO implements UserDAO {
1✔
51
        
52
        private static final Logger log = LoggerFactory.getLogger(HibernateUserDAO.class);
1✔
53
        
54
        /**
55
         * Hibernate session factory
56
         */
57
        private SessionFactory sessionFactory;
58
        
59
        /**
60
         * Set session factory
61
         * 
62
         * @param sessionFactory
63
         */
64
        public void setSessionFactory(SessionFactory sessionFactory) {
65
                this.sessionFactory = sessionFactory;
1✔
66
        }
1✔
67
        
68
        /**
69
         * @see org.openmrs.api.UserService#saveUser(org.openmrs.User)
70
         */
71
        @Override
72
        public User saveUser(User user, String password) {
73
                
74
                // only change the user's password when creating a new user
75
                boolean isNewUser = user.getUserId() == null;
1✔
76
                
77
                sessionFactory.getCurrentSession().saveOrUpdate(user);
1✔
78
                
79
                if (isNewUser && password != null) {
1✔
80
                        /* In OpenMRS, we are using generation strategy as native which will convert to IDENTITY 
81
                         for MySQL and SEQUENCE for PostgreSQL. When using IDENTITY strategy, hibernate directly 
82
                         issues insert statements where as with  SEQUENCE strategy hibernate only increments 
83
                         sequences and issues insert on session flush ( batching is possible) . 
84
                         PostgreSQL behaves differently than MySQL because it makes use of SEQUENCE strategy. 
85
                        */
86
                        sessionFactory.getCurrentSession().flush();
1✔
87
                        
88
                        //update the new user with the password
89
                        String salt = Security.getRandomToken();
1✔
90
                        String hashedPassword = Security.encodeString(password + salt);
1✔
91
                        
92
                        updateUserPassword(hashedPassword, salt, Context.getAuthenticatedUser().getUserId(), new Date(), user
1✔
93
                                .getUserId());
1✔
94
                }
95
                
96
                return user;
1✔
97
        }
98
        
99
        /**
100
         * @see org.openmrs.api.UserService#getUserByUsername(java.lang.String)
101
         */
102
        @Override
103
        @SuppressWarnings("unchecked")
104
        public User getUserByUsername(String username) {
105
                Query query = sessionFactory.getCurrentSession().createQuery(
1✔
106
                    "from User u where u.retired = '0' and (u.username = ?0 or u.systemId = ?1)");
107
                query.setString(0, username);
1✔
108
                query.setString(1, username);
1✔
109
                List<User> users = query.list();
1✔
110
                
111
                if (users == null || users.isEmpty()) {
1✔
112
                        log.warn("request for username '" + username + "' not found");
1✔
113
                        return null;
1✔
114
                }
115
                
116
                return users.get(0);
1✔
117
        }
118
        
119
        @Override
120
        @SuppressWarnings("unchecked")
121
        public User getUserByEmail(String email) {
122
                return (User) sessionFactory.getCurrentSession().createCriteria(User.class).add(Restrictions.eq("email", email).ignoreCase()).uniqueResult();        
1✔
123
        }
124
        
125
        /**
126
         * @see org.openmrs.api.db.UserDAO#getLoginCredentialByActivationKey(java.lang.String)
127
         */
128
        @Override
129
        public LoginCredential getLoginCredentialByActivationKey(String activationKey) {
130
                String key = Security.encodeString(activationKey);
1✔
131
                LoginCredential loginCred = (LoginCredential) sessionFactory.getCurrentSession().createCriteria(LoginCredential.class)
1✔
132
                                                                        .add(Restrictions.like("activationKey", key, MatchMode.START)).uniqueResult();        
1✔
133
                if(loginCred != null) {
1✔
134
                        String[] credTokens = loginCred.getActivationKey().split(":");
1✔
135
                        if(credTokens[0].equals(key)){
1✔
136
                                return loginCred;
1✔
137
                        }
138
                }        
139
                return null;
1✔
140
         }
141
        
142
        /**
143
         * @see org.openmrs.api.UserService#hasDuplicateUsername(org.openmrs.User)
144
         */
145
        @Override
146
        public boolean hasDuplicateUsername(String username, String systemId, Integer userId) {
147
                if (username == null || username.length() == 0) {
1✔
148
                        username = "-";
1✔
149
                }
150
                if (systemId == null || systemId.length() == 0) {
1✔
UNCOV
151
                        systemId = "-";
×
152
                }
153
                
154
                if (userId == null) {
1✔
155
                        userId = -1;
1✔
156
                }
157
                
158
                String usernameWithCheckDigit = username;
1✔
159
                try {
160
                        //Hardcoding in Luhn since past user IDs used this validator.
161
                        usernameWithCheckDigit = new LuhnIdentifierValidator().getValidIdentifier(username);
1✔
162
                }
163
                catch (Exception e) {}
1✔
164
                
165
                Query query = sessionFactory
1✔
166
                        .getCurrentSession()
1✔
167
                        .createQuery(
1✔
168
                            "select count(*) from User u where (u.username = :uname1 or u.systemId = :uname2 or u.username = :sysid1 or u.systemId = :sysid2 or u.systemId = :uname3) and u.userId <> :uid");
169
                query.setString("uname1", username);
1✔
170
                query.setString("uname2", username);
1✔
171
                query.setString("sysid1", systemId);
1✔
172
                query.setString("sysid2", systemId);
1✔
173
                query.setString("uname3", usernameWithCheckDigit);
1✔
174
                query.setInteger("uid", userId);
1✔
175
                
176
                Long count = (Long) query.uniqueResult();
1✔
177
                
178
                log.debug("# users found: " + count);
1✔
179
                return (count != null && count != 0);
1✔
180
        }
181
        
182
        /**
183
         * @see org.openmrs.api.UserService#getUser(java.lang.Integer)
184
         */
185
        @Override
186
        public User getUser(Integer userId) {
187

188
                return (User) sessionFactory.getCurrentSession().get(User.class, userId);
1✔
189
        }
190
        
191
        /**
192
         * @see org.openmrs.api.UserService#getAllUsers()
193
         */
194
        @Override
195
        @SuppressWarnings("unchecked")
196
        public List<User> getAllUsers() throws DAOException {
197
                return sessionFactory.getCurrentSession().createQuery("from User where not uuid = :daemonUserUuid order by userId")
1✔
198
                                                                                     .setString("daemonUserUuid", Daemon.getDaemonUserUuid()).list();
1✔
199
                
200
        }
201
        
202
        /**
203
         * @see org.openmrs.api.UserService#purgeUser(org.openmrs.User)
204
         */
205
        @Override
206
        public void deleteUser(User user) {
207
                sessionFactory.getCurrentSession().delete(user);
1✔
208
        }
1✔
209
        
210
        /**
211
         * @see org.openmrs.api.UserService#getUsersByRole(org.openmrs.Role)
212
         */
213
        @SuppressWarnings("unchecked")
214
        public List<User> getUsersByRole(Role role) throws DAOException {
215

UNCOV
216
                return (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class, "u").createCriteria("roles", "r")
×
UNCOV
217
                        .add(Restrictions.like("r.role", role.getRole())).add(Restrictions.ne("u.uuid", Daemon.getDaemonUserUuid())).addOrder(Order.asc("u.username")).list();
×
218
                
219
        }
220
        
221
        /**
222
         * @see org.openmrs.api.UserService#getAllPrivileges()
223
         */
224
        @Override
225
        @SuppressWarnings("unchecked")
226
        public List<Privilege> getAllPrivileges() throws DAOException {
227
                return sessionFactory.getCurrentSession().createQuery("from Privilege p order by p.privilege").list();
1✔
228
        }
229
        
230
        /**
231
         * @see org.openmrs.api.UserService#getPrivilege(String)
232
         */
233
        @Override
234
        public Privilege getPrivilege(String p) throws DAOException {
235
                return (Privilege) sessionFactory.getCurrentSession().get(Privilege.class, p);
1✔
236
        }
237
        
238
        /**
239
         * @see org.openmrs.api.db.UserDAO#deletePrivilege(org.openmrs.Privilege)
240
         */
241
        @Override
242
        public void deletePrivilege(Privilege privilege) throws DAOException {
243
                sessionFactory.getCurrentSession().delete(privilege);
1✔
244
        }
1✔
245
        
246
        /**
247
         * @see org.openmrs.api.db.UserDAO#savePrivilege(org.openmrs.Privilege)
248
         */
249
        @Override
250
        public Privilege savePrivilege(Privilege privilege) throws DAOException {
251
                sessionFactory.getCurrentSession().saveOrUpdate(privilege);
1✔
252
                return privilege;
1✔
253
        }
254
        
255
        /**
256
         * @see org.openmrs.api.UserService#purgeRole(org.openmrs.Role)
257
         */
258
        @Override
259
        public void deleteRole(Role role) throws DAOException {
260
                sessionFactory.getCurrentSession().delete(role);
1✔
261
        }
1✔
262
        
263
        /**
264
         * @see org.openmrs.api.UserService#saveRole(org.openmrs.Role)
265
         */
266
        @Override
267
        public Role saveRole(Role role) throws DAOException {
268
                sessionFactory.getCurrentSession().saveOrUpdate(role);
1✔
269
                return role;
1✔
270
        }
271
        
272
        /**
273
         * @see org.openmrs.api.UserService#getAllRoles()
274
         */
275
        @Override
276
        @SuppressWarnings("unchecked")
277
        public List<Role> getAllRoles() throws DAOException {
278
                return sessionFactory.getCurrentSession().createQuery("from Role r order by r.role").list();
1✔
279
        }
280
        
281
        /**
282
         * @see org.openmrs.api.UserService#getRole(String)
283
         */
284
        @Override
285
        public Role getRole(String r) throws DAOException {
286
                return (Role) sessionFactory.getCurrentSession().get(Role.class, r);
1✔
287
        }
288
        
289
        /**
290
         * @see org.openmrs.api.db.UserDAO#changePassword(org.openmrs.User, java.lang.String)
291
         */
292
        @Override
293
        public void changePassword(User u, String pw) throws DAOException {
294
                User authUser = Context.getAuthenticatedUser();
1✔
295
                
296
                if (authUser == null) {
1✔
UNCOV
297
                        authUser = u;
×
298
                }
299
                
300
                log.debug("updating password");
1✔
301
                String salt = getLoginCredential(u).getSalt();
1✔
302
                if (StringUtils.isBlank(salt)) {
1✔
303
                        salt = Security.getRandomToken();
1✔
304
                }
305
                String newHashedPassword = Security.encodeString(pw + salt);
1✔
306
                
307
                updateUserPassword(newHashedPassword, salt, authUser.getUserId(), new Date(), u.getUserId());
1✔
308
                
309
        }
1✔
310
        
311
        /**
312
         * @see org.openmrs.api.db.UserDAO#changeHashedPassword(User, String, String)
313
         */
314
        @Override
315
        public void changeHashedPassword(User user, String hashedPassword, String salt) throws DAOException {
316
                User authUser = Context.getAuthenticatedUser();
1✔
317
                updateUserPassword(hashedPassword, salt, authUser.getUserId(), new Date(), user.getUserId());
1✔
318
        }
1✔
319
        
320
        /**
321
         * @param newHashedPassword
322
         * @param salt
323
         * @param userId
324
         * @param date
325
         * @param userId2
326
         */
327
        private void updateUserPassword(String newHashedPassword, String salt, Integer changedBy, Date dateChanged,
328
                Integer userIdToChange) {
329
                User changeForUser = getUser(userIdToChange);
1✔
330
                if (changeForUser == null) {
1✔
UNCOV
331
                        throw new DAOException("Couldn't find user to set password for userId=" + userIdToChange);
×
332
                }
333
                User changedByUser = getUser(changedBy);
1✔
334
                LoginCredential credentials = getLoginCredential(changeForUser);
1✔
335
                credentials.setUserId(userIdToChange);
1✔
336
                credentials.setHashedPassword(newHashedPassword);
1✔
337
                credentials.setSalt(salt);
1✔
338
                credentials.setChangedBy(changedByUser);
1✔
339
                credentials.setDateChanged(dateChanged);
1✔
340
                credentials.setUuid(changeForUser.getUuid());
1✔
341
                
342
                sessionFactory.getCurrentSession().merge(credentials);
1✔
343
                
344
                // reset lockout 
345
                changeForUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP, "");
1✔
346
                changeForUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOGIN_ATTEMPTS, "0");
1✔
347
                saveUser(changeForUser, null);
1✔
348
        }
1✔
349
        
350
        /**
351
         * @see org.openmrs.api.UserService#changePassword(java.lang.String, java.lang.String)
352
         */
353
        @Override
354
        public void changePassword(String oldPassword, String newPassword) throws DAOException {
355
                User u = Context.getAuthenticatedUser();
1✔
356
                LoginCredential credentials = getLoginCredential(u);
1✔
357
                if (!credentials.checkPassword(oldPassword)) {
1✔
UNCOV
358
                        log.error("Passwords don't match");
×
UNCOV
359
                        throw new DAOException("Passwords don't match");
×
360
                }
361
                
362
                log.info("updating password for {}", u.getUsername());
1✔
363
                
364
                // update the user with the new password
365
                String salt = credentials.getSalt();
1✔
366
                String newHashedPassword = Security.encodeString(newPassword + salt);
1✔
367
                updateUserPassword(newHashedPassword, salt, u.getUserId(), new Date(), u.getUserId());
1✔
368
        }
1✔
369
        
370
        /**
371
         * @see org.openmrs.api.UserService#changeQuestionAnswer(java.lang.String, java.lang.String,
372
         *      java.lang.String)
373
         */
374
        @Override
375
        public void changeQuestionAnswer(String pw, String question, String answer) throws DAOException {
376
                User u = Context.getAuthenticatedUser();
1✔
377
                
378
                LoginCredential credentials = getLoginCredential(u);
1✔
379
                if (!credentials.checkPassword(pw)) {
1✔
UNCOV
380
                        log.error("Passwords don't match");
×
UNCOV
381
                        throw new DAOException("Passwords don't match");
×
382
                }
383
                
384
                changeQuestionAnswer(u, question, answer);
1✔
385
        }
1✔
386
        
387
        /**
388
         * @see org.openmrs.api.UserService#changeQuestionAnswer(User, String, String)
389
         */
390
        @Override
391
        public void changeQuestionAnswer(User u, String question, String answer) throws DAOException {
392
                log.info("Updating secret question and answer for " + u.getUsername());
1✔
393
                
394
                LoginCredential credentials = getLoginCredential(u);
1✔
395
                credentials.setSecretQuestion(question);
1✔
396
                String hashedAnswer = Security.encodeString(answer.toLowerCase() + credentials.getSalt());
1✔
397
                credentials.setSecretAnswer(hashedAnswer);
1✔
398
                credentials.setDateChanged(new Date());
1✔
399
                credentials.setChangedBy(u);
1✔
400
                
401
                updateLoginCredential(credentials);
1✔
402
        }
1✔
403
        
404
        /**
405
         * @see org.openmrs.api.UserService#isSecretAnswer(User, java.lang.String)
406
         */
407
        @Override
408
        public boolean isSecretAnswer(User u, String answer) throws DAOException {
409
                
410
                if (StringUtils.isEmpty(answer)) {
1✔
UNCOV
411
                        return false;
×
412
                }
413
                
414
                LoginCredential credentials = getLoginCredential(u);
1✔
415
                String answerOnRecord = credentials.getSecretAnswer();
1✔
416
                String hashedAnswer = Security.encodeString(answer.toLowerCase() + credentials.getSalt());
1✔
417
                return (hashedAnswer.equals(answerOnRecord));
1✔
418
        }
419
        
420
        /**
421
         * @see UserDAO#getUsers(String, List, boolean, Integer, Integer)
422
         */
423
        @Override
424
        @SuppressWarnings("unchecked")
425
        public List<User> getUsers(String name, List<Role> roles, boolean includeRetired, Integer start, Integer length) {
426
                
427
                String hqlSelectStart = "select distinct user from User as user inner join user.person.names as name ";
1✔
428
                Query query = createUserSearchQuery(name, roles, includeRetired, hqlSelectStart);
1✔
429
                
430
                if (start != null) {
1✔
UNCOV
431
                        query.setFirstResult(start);
×
432
                }
433
                if (length != null && length > 0) {
1✔
434
                        query.setMaxResults(length);
×
435
                }
436
                
437
                List<User> returnList = query.list();
1✔
438
                
439
                if (!CollectionUtils.isEmpty(returnList)) {
1✔
440
                        returnList.sort(new UserByNameComparator());
1✔
441
                }
442
                
443
                return returnList;
1✔
444
        }
445
        
446
        /**
447
         * @see org.openmrs.api.UserService#generateSystemId()
448
         */
449
        @Override
450
        public Integer generateSystemId() {
451
                
452
                String hql = "select max(userId) from User";
1✔
453
                
454
                Query query = sessionFactory.getCurrentSession().createQuery(hql);
1✔
455
                
456
                Object object = query.uniqueResult();
1✔
457
                
458
                Integer id;
459
                if (object instanceof Number) {
1✔
460
                        id = ((Number) query.uniqueResult()).intValue() + 1;
1✔
461
                } else {
UNCOV
462
                        log.warn("What is being returned here? Definitely nothing expected object value: '" + object + "' of class: "
×
UNCOV
463
                                + object.getClass());
×
UNCOV
464
                        id = 1;
×
465
                }
466
                
467
                return id;
1✔
468
        }
469
        
470
        /**
471
         * @see org.openmrs.api.UserService#getUsersByName(java.lang.String, java.lang.String, boolean)
472
         */
473
        @Override
474
        public List<User> getUsersByName(String givenName, String familyName, boolean includeRetired) {
475
                Criteria crit = sessionFactory.getCurrentSession().createCriteria(User.class);
1✔
476
                crit.createAlias("person", "person");
1✔
477
                crit.createAlias("person.names", "names");
1✔
478
                crit.add(Restrictions.eq("names.givenName", givenName));
1✔
479
                crit.add(Restrictions.eq("names.familyName", familyName));
1✔
480
                crit.add(Restrictions.ne("uuid", Daemon.getDaemonUserUuid()));
1✔
481
                crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
1✔
482
                if (!includeRetired) {
1✔
483
                        crit.add(Restrictions.eq("retired", false));
1✔
484
                }
485
                return new ArrayList<>((List<User>) crit.list());
1✔
486
        }
487
        
488
        /**
489
         * @see org.openmrs.api.db.UserDAO#getPrivilegeByUuid(java.lang.String)
490
         */
491
        @Override
492
        public Privilege getPrivilegeByUuid(String uuid) {
493
                return (Privilege) sessionFactory.getCurrentSession().createQuery("from Privilege p where p.uuid = :uuid")
1✔
494
                        .setString("uuid", uuid).uniqueResult();
1✔
495
        }
496
        
497
        /**
498
         * @see org.openmrs.api.db.UserDAO#getRoleByUuid(java.lang.String)
499
         */
500
        @Override
501
        public Role getRoleByUuid(String uuid) {
502
                return (Role) sessionFactory.getCurrentSession().createQuery("from Role r where r.uuid = :uuid").setString("uuid",
1✔
503
                    uuid).uniqueResult();
1✔
504
        }
505
        
506
        /**
507
         * @see org.openmrs.api.db.UserDAO#getUserByUuid(java.lang.String)
508
         */
509
        @Override
510
        public User getUserByUuid(String uuid) {
511
                User ret = null;
1✔
512
                
513
                if (uuid != null) {
1✔
514
                        uuid = uuid.trim();
1✔
515
                        ret = (User) sessionFactory.getCurrentSession().createQuery("from User u where u.uuid = :uuid").setString(
1✔
516
                            "uuid", uuid).uniqueResult();
1✔
517
                }
518
                
519
                return ret;
1✔
520
        }
521
        
522
        /**
523
         * @see org.openmrs.api.db.UserDAO#getLoginCredential(org.openmrs.User)
524
         */
525
        @Override
526
        public LoginCredential getLoginCredential(User user) {
527
                return (LoginCredential) sessionFactory.getCurrentSession().get(LoginCredential.class, user.getUserId());
1✔
528
        }
529
        
530
        /**
531
         * @see org.openmrs.api.db.UserDAO#getLoginCredential(org.openmrs.User)
532
         */
533
        @Override
534
        public LoginCredential getLoginCredentialByUuid(String uuid) {
UNCOV
535
                if (uuid == null) {
×
UNCOV
536
                        return null;
×
537
                } else {
538
                        return (LoginCredential) sessionFactory.getCurrentSession().createQuery(
×
539
                            "from LoginCredential where uuid = :uuid").setString("uuid", uuid.trim()).uniqueResult();
×
540
                }
541
        }
542
        
543
        /**
544
         * @see org.openmrs.api.db.UserDAO#updateLoginCredential(LoginCredential)
545
         */
546
        @Override
547
        public void updateLoginCredential(LoginCredential credential) {
548
                sessionFactory.getCurrentSession().update(credential);
1✔
549
        }
1✔
550
        
551
        /**
552
         * @see org.openmrs.api.db.UserDAO#getUsersByPerson(org.openmrs.Person, boolean)
553
         */
554
        @Override
555
        @SuppressWarnings("unchecked")
556
        public List<User> getUsersByPerson(Person person, boolean includeRetired) {
557
                Criteria crit = sessionFactory.getCurrentSession().createCriteria(User.class);
1✔
558
                crit.add(Restrictions.ne("uuid", Daemon.getDaemonUserUuid()));
1✔
559
                if (person != null) {
1✔
560
                        crit.add(Restrictions.eq("person", person));
1✔
561
                }
562
                if (!includeRetired) {
1✔
563
                        crit.add(Restrictions.eq("retired", false));
1✔
564
                }
565
                return (List<User>) crit.list();
1✔
566
        }
567
        
568
        /**
569
         * @see org.openmrs.api.db.UserDAO#getCountOfUsers(String, List, boolean)
570
         */
571
        @Override
572
        public Integer getCountOfUsers(String name, List<Role> roles, boolean includeRetired) {
UNCOV
573
                String hqlSelectStart = "select count(distinct user) from User as user inner join user.person.names as name ";
×
UNCOV
574
                Query query = createUserSearchQuery(name, roles, includeRetired, hqlSelectStart);
×
575
                
576
                return ((Long) query.uniqueResult()).intValue();
×
577
        }
578
        
579
        /**
580
         * Utility methods that creates a hibernate query object from the specified arguments
581
         * 
582
         * @param name The name of the user to search against
583
         * @param roles the roles to match against
584
         * @param includeRetired Specifies if retired users should be included or not
585
         * @param hqlSelectStart The starting phrase of the select statement that includes the joined
586
         *            tables
587
         * @return the created hibernate query object
588
         */
589
        private Query createUserSearchQuery(String name, List<Role> roles, boolean includeRetired, String hqlSelectStart) {
590
                
591
                log.debug("name: " + name);
1✔
592
                
593
                name = HibernateUtil.escapeSqlWildcards(name, sessionFactory);
1✔
594
                
595
                // Create an HQL query like this:
596
                // select distinct user
597
                // from User as user inner join user.person.names as name inner join user.roles as role
598
                // where (user.username like :name1 or ...and for systemId givenName familyName familyName2...)
599
                //   and (user.username like :name2 or ...and for systemId givenName familyName familyName2...)
600
                //   ...repeat for all name fragments...
601
                //         and role in :roleList 
602
                //   and user.retired = false
603
                // order by username asc
604
                List<String> criteria = new ArrayList<>();
1✔
605
                int counter = 0;
1✔
606
                Map<String, String> namesMap = new HashMap<>();
1✔
607
                if (name != null) {
1✔
608
                        name = name.replace(", ", " ");
1✔
609
                        String[] names = name.split(" ");
1✔
610
                        for (String n : names) {
1✔
611
                                if (n != null && n.length() > 0) {
1✔
612
                                        // compare each fragment of the query against username, systemId, given, middle, family, and family2
613
                                        String key = "name" + ++counter;
1✔
614
                                        String value = n + "%";
1✔
615
                                        namesMap.put(key, value);
1✔
616
                                        criteria.add("(user.username like :" + key + " or user.systemId like :" + key
1✔
617
                                                + " or name.givenName like :" + key + " or name.middleName like :" + key
618
                                                + " or name.familyName like :" + key + " or name.familyName2 like :" + key + ")");
619
                                }
620
                        }
621
                }
622
                
623
                if (!includeRetired) {
1✔
624
                        criteria.add("user.retired = false");
1✔
625
                }
626
                
627
                // build the hql query
628
                StringBuilder hql = new StringBuilder(hqlSelectStart);
1✔
629
                boolean searchOnRoles = false;
1✔
630
                
631
                if (CollectionUtils.isNotEmpty(roles)) {
1✔
632
                        hql.append("inner join user.roles as role ");
1✔
633
                        searchOnRoles = true;
1✔
634
                }
635
                hql.append("where user.uuid != :DAEMON_USER_UUID ");
1✔
636
                
637
                if (!criteria.isEmpty() || searchOnRoles) {
1✔
638
                        hql.append("and ");
1✔
639
                }
640
                for (Iterator<String> i = criteria.iterator(); i.hasNext();) {
1✔
641
                        hql.append(i.next()).append(" ");
1✔
642
                        if (i.hasNext()) {
1✔
643
                                hql.append("and ");
1✔
644
                        }
645
                }
646
                
647
                //Match against the specified roles
648
                if (searchOnRoles) {
1✔
649
                        if (!criteria.isEmpty()) {
1✔
650
                                hql.append(" and ");
1✔
651
                        }
652
                        hql.append(" role in (:roleList)");
1✔
653
                }
654
                
655
                Query query = sessionFactory.getCurrentSession().createQuery(hql.toString());
1✔
656
                query.setParameter("DAEMON_USER_UUID", Daemon.getDaemonUserUuid());
1✔
657
                for (Map.Entry<String, String> e : namesMap.entrySet()) {
1✔
658
                        query.setString(e.getKey(), e.getValue());
1✔
659
                }
1✔
660
                
661
                if (searchOnRoles) {
1✔
662
                        query.setParameterList("roleList", roles);
1✔
663
                }
664
                
665
                return query;
1✔
666
        }
667
        
668
        /**
669
         * @see org.openmrs.api.db.UserDAO#setUserActivationKey(org.openmrs.api.db.LoginCredential)
670
         */
671
        @Override
672
        public void setUserActivationKey(LoginCredential credentials) {                
673
                        sessionFactory.getCurrentSession().merge(credentials);        
1✔
674
        }
1✔
675
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc