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

openmrs / openmrs-core / 43516285745

13 Nov 2026 10:04PM UTC coverage: 67.351% (-0.03%) from 67.383%
43516285745

push

github

ibacher
TRUNK-6616: Keep contextDAO's transaction proxy when RolePrivilegeCache is created early

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

22 existing lines in 9 files now uncovered.

26906 of 39949 relevant lines covered (67.35%)

0.67 hits per line

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

56.23
/api/src/main/java/org/openmrs/api/context/Context.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.context;
11

12
import javax.mail.Authenticator;
13
import javax.mail.PasswordAuthentication;
14
import javax.mail.Session;
15
import java.sql.Connection;
16
import java.text.SimpleDateFormat;
17
import java.util.Arrays;
18
import java.util.HashMap;
19
import java.util.HashSet;
20
import java.util.List;
21
import java.util.Locale;
22
import java.util.Map;
23
import java.util.Properties;
24
import java.util.Set;
25
import java.util.concurrent.Future;
26

27
import org.aopalliance.aop.Advice;
28
import org.apache.commons.lang3.StringUtils;
29
import org.openmrs.Allergen;
30
import org.openmrs.GlobalProperty;
31
import org.openmrs.OpenmrsObject;
32
import org.openmrs.PersonName;
33
import org.openmrs.Privilege;
34
import org.openmrs.Role;
35
import org.openmrs.User;
36
import org.openmrs.api.APIException;
37
import org.openmrs.api.AdministrationService;
38
import org.openmrs.api.CohortService;
39
import org.openmrs.api.ConceptService;
40
import org.openmrs.api.ConditionService;
41
import org.openmrs.api.DatatypeService;
42
import org.openmrs.api.DiagnosisService;
43
import org.openmrs.api.EncounterService;
44
import org.openmrs.api.FormService;
45
import org.openmrs.api.LocationService;
46
import org.openmrs.api.MedicationDispenseService;
47
import org.openmrs.api.ObsService;
48
import org.openmrs.api.OpenmrsService;
49
import org.openmrs.api.OrderService;
50
import org.openmrs.api.OrderSetService;
51
import org.openmrs.api.PatientService;
52
import org.openmrs.api.PersonService;
53
import org.openmrs.api.ProgramWorkflowService;
54
import org.openmrs.api.ProviderService;
55
import org.openmrs.api.SerializationService;
56
import org.openmrs.api.UserService;
57
import org.openmrs.api.VisitService;
58
import org.openmrs.api.db.ContextDAO;
59
import org.openmrs.hl7.HL7Service;
60
import org.openmrs.logic.LogicService;
61
import org.openmrs.messagesource.MessageSourceService;
62
import org.openmrs.module.ModuleMustStartException;
63
import org.openmrs.module.ModuleUtil;
64
import org.openmrs.notification.AlertService;
65
import org.openmrs.notification.MessageException;
66
import org.openmrs.notification.MessagePreparator;
67
import org.openmrs.notification.MessageSender;
68
import org.openmrs.notification.MessageService;
69
import org.openmrs.notification.mail.MailMessageSender;
70
import org.openmrs.notification.mail.velocity.VelocityMessagePreparator;
71
import org.openmrs.scheduler.SchedulerService;
72
import org.openmrs.util.ConfigUtil;
73
import org.openmrs.util.DatabaseUpdateException;
74
import org.openmrs.util.DatabaseUpdater;
75
import org.openmrs.util.InputRequiredException;
76
import org.openmrs.util.LocaleUtility;
77
import org.openmrs.util.OpenmrsClassLoader;
78
import org.openmrs.util.OpenmrsConstants;
79
import org.openmrs.util.OpenmrsUtil;
80
import org.openmrs.util.PrivilegeConstants;
81
import org.openmrs.validator.ValidateUtil;
82
import org.slf4j.Logger;
83
import org.slf4j.LoggerFactory;
84
import org.springframework.aop.Advisor;
85
import org.springframework.beans.BeansException;
86
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
87
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
88

89
/**
90
 * Represents an OpenMRS <code>Context</code>, which may be used to authenticate to the database and
91
 * obtain services in order to interact with the system.<br>
92
 * <br>
93
 * The Context is split into a {@link UserContext} and {@link ServiceContext}. The UserContext is
94
 * lightweight and there is an instance for every user logged into the system. The ServiceContext is
95
 * heavier and it contains each service class. This is more static and there is only one ServiceContext
96
 * per OpenMRS instance. <br>
97
 * <br>
98
 * Both the {@link UserContext} and the {@link ServiceContext} should not be used directly. This
99
 * context class has methods to pass through to the currently defined UserContext for the thread and
100
 * the currently defined ServiceContext. <br>
101
 * <br>
102
 * To use the OpenMRS api there are four things that have to be done:
103
 * <ol>
104
 * <li>Call {@link Context#startup(String, String, String, Properties)} to let the Context contact
105
 * the database</li>
106
 * <li>Call {@link Context#openSession()} to start a "unit of work".</li>
107
 * <li>Call {@link Context#authenticate(String, String)} to authenticate the current user on the
108
 * current thread</li>
109
 * <li>Call {@link Context#closeSession()} to end your "unit of work" and commit all changes to the
110
 * database.</li>
111
 * </ol>
112
 * <br>
113
 * Example usage:
114
 *
115
 * <pre>
116
 *         public static void main(String[] args) {
117
 *                 Context.startup("jdbc:mysql://localhost:3306/db-name?autoReconnect=true", "openmrs-db-user", "3jknfjkn33ijt", new Properties());
118
 *                 try {
119
 *                         Context.openSession();
120
 *                         Context.authenticate("admin", "test");
121
 *                         List&lt;Patients&gt; patients = Context.getPatientService().getPatientsByName("Fred");
122
 *                         patients.get(0).setBirthdate(new Date());
123
 *                         Context.getPatientService().savePatient(patients.get(0));
124
 *                         ...
125
 *        }
126
 *                 finally {
127
 *                         Context.closeSession();
128
 *        }
129
 *    }
130
 * </pre>
131
 *
132
 * @see org.openmrs.api.context.UserContext
133
 * @see org.openmrs.api.context.ServiceContext
134
 */
135
public class Context {
136

137

138
        // Global resources
139
        private static ContextDAO contextDAO;
140

141
        private static volatile Session mailSession;
142

143
        // Using "wrapper" (Object array) around UserContext to avoid ThreadLocal
144
        // bug in Java 1.5
145
        private static final ThreadLocal<Object[] /* UserContext */> userContextHolder = new ThreadLocal<>();
1 ✔
146

147
        private static volatile ServiceContext serviceContext;
148

149
        private static Properties runtimeProperties = new Properties();
1 ✔
150

151
        private static Properties configProperties = new Properties();
1 ✔
152

153
        private static AuthenticationScheme authenticationScheme;
154

155
        private static final Logger log = LoggerFactory.getLogger(Context.class);
1 ✔
156

157
        /**
158
         * Default public constructor
159
         */
160
        public Context() {
1 ✔
161
        }
1 ✔
162

163
        /**
164
         * Gets the context's data access object
165
         *
166
         * @return ContextDAO
167
         */
168
        static ContextDAO getContextDAO() {
169
                if (contextDAO == null) {
1 ✔
170
                        throw new APIException("error.context.null", (Object[]) null);
×
171
                }
172
                return contextDAO;
1 ✔
173
        }
174

175
        /**
176
         * Used to set the context's DAO for the application.
177
         *
178
         * @param dao ContextDAO to set
179
         */
180
        public void setContextDAO(ContextDAO dao) {
181
                setDAO(dao);
1 ✔
182
        }
1 ✔
183

184
        public static void setDAO(ContextDAO dao) {
185
                contextDAO = dao;
1 ✔
186
        }
1 ✔
187

188
        /**
189
         * Spring init method that sets the authentication scheme.
190
         */
191
        private static void setAuthenticationScheme() {
192

193
                authenticationScheme = new UsernamePasswordAuthenticationScheme();
1 ✔
194

195
                try {
196
                        authenticationScheme = Context.getServiceContext().getApplicationContext().getBean(AuthenticationScheme.class); // manual autowiring (from a module)
×
197
                        log.info("An authentication scheme override was provided. Using this one in place of the OpenMRS default authentication scheme.");
×
198
                }
199
                catch(NoUniqueBeanDefinitionException e) {
×
200
                        log.error("Multiple authentication schemes overrides are being provided, this is currently not supported. Sticking to OpenMRS default authentication scheme.");
×
201
                }
202
                catch(NoSuchBeanDefinitionException e) {
1 ✔
203
                        log.debug("No authentication scheme override was provided. Sticking to OpenMRS default authentication scheme.");
1 ✔
204
                }
205
                catch(BeansException e){
×
206
                        log.error("Fatal error encountered when injecting the authentication scheme override. Sticking to OpenMRS default authentication scheme.");
×
207
                }
1 ✔
208
        }
1 ✔
209

210
        /**
211
         * Loads a class with an instance of the OpenmrsClassLoader. Convenience method equivalent to
212
         * OpenmrsClassLoader.getInstance().loadClass(className);
213
         *
214
         * @param className the class to load
215
         * @return the class that was loaded
216
         * @throws ClassNotFoundException
217
         * <strong>Should</strong> load class with the OpenmrsClassLoader
218
         */
219
        public static Class<?> loadClass(String className) throws ClassNotFoundException {
220
                return OpenmrsClassLoader.getInstance().loadClass(className);
1 ✔
221
        }
222

223
        /**
224
         * Sets the user context on the thread local so that the service layer can perform
225
         * authentication/authorization checks.<br>
226
         * <br>
227
         * This is thread safe since it stores the given user context in ThreadLocal.
228
         *
229
         * @param ctx UserContext to set
230
         */
231
        public static void setUserContext(UserContext ctx) {
232
                log.trace("Setting user context {}", ctx);
1 ✔
233

234
                Object[] arr = new Object[] { ctx };
1 ✔
235
                userContextHolder.set(arr);
1 ✔
236
        }
1 ✔
237

238
        /**
239
         * Clears the user context from the threadlocal.
240
         */
241
        public static void clearUserContext() {
242
                log.trace("Clearing user context {}", Arrays.toString(userContextHolder.get()));
1 ✔
243

244
                userContextHolder.remove();
1 ✔
245
        }
1 ✔
246

247
        /**
248
         * Gets the user context from the thread local. This might be accessed by several threads at the
249
         * same time.
250
         *
251
         * @return The current UserContext for this thread.
252
         * <strong>Should</strong> fail if session hasn't been opened
253
         */
254
        public static UserContext getUserContext() {
255
                Object[] arr = userContextHolder.get();
1 ✔
256
                log.trace("Getting user context {} from userContextHolder {}", Arrays.toString(arr), userContextHolder);
1 ✔
257

258
                if (arr == null) {
1 ✔
259
                        log.trace("userContext is null.");
1 ✔
260
                        throw new APIException(
1 ✔
261
                                        "A user context must first be passed to setUserContext()...use Context.openSession() (and closeSession() to prevent memory leaks!) before using the API");
262
                }
263
                return (UserContext) userContextHolder.get()[0];
1 ✔
264
        }
265

266
        /**
267
         * Gets the currently defined service context. If one is not defined, one will be created and
268
         * then returned.
269
         *
270
         * @return the current ServiceContext
271
         */
272
        static ServiceContext getServiceContext() {
273
                if (serviceContext == null) {
1 ✔
UNCOV
274
                        synchronized (Context.class) {
×
UNCOV
275
                                if (serviceContext == null) {
×
UNCOV
276
                                        serviceContext = ServiceContext.getInstance();
×
277
                                }
UNCOV
278
                        }
×
279
                }
280
                return ServiceContext.getInstance();
1 ✔
281
        }
282

283
        /**
284
         * Sets the service context.
285
         *
286
         * @param ctx
287
         */
288
        public void setServiceContext(ServiceContext ctx) {
289
                setContext(ctx);
1 ✔
290
        }
1 ✔
291

292
        public static void setContext(ServiceContext ctx) {
293
                serviceContext = ctx;
1 ✔
294
        }
1 ✔
295

296
        /**
297
         * OpenMRS provides its default authentication scheme that authenticates via DAO with OpenMRS usernames and passwords.
298
         * 
299
         * Any module can provide an authentication scheme override by Spring wiring a custom implementation of {@link AuthenticationScheme}.
300
         * This method would return Core's default authentication scheme unless a Spring override is provided somewhere else.
301
         * 
302
         * @return The enforced authentication scheme.
303
         */
304
        public static AuthenticationScheme getAuthenticationScheme() {
305
                return authenticationScheme;
1 ✔
306
        }
307

308
        /**
309
         * @deprecated as of 2.3.0, replaced by {@link #authenticate(Credentials)}
310
         * 
311
         * Used to authenticate user within the context
312
         *
313
         * @param username user's identifier token for login
314
         * @param password user's password for authenticating to context
315
         * @throws ContextAuthenticationException
316
         * <strong>Should</strong> not authenticate with null username and password
317
         * <strong>Should</strong> not authenticate with null password
318
         * <strong>Should</strong> not authenticate with null username
319
         * <strong>Should</strong> not authenticate with null password and proper username
320
         * <strong>Should</strong> not authenticate with null password and proper system id
321
         */
322
        @Deprecated
323
        public static void authenticate(String username, String password) throws ContextAuthenticationException {
324
                authenticate(new UsernamePasswordCredentials(username, password));
1 ✔
325
        }
1 ✔
326

327
        /**
328
         * @param credentials
329
         * @throws ContextAuthenticationException
330
         * 
331
         * @since 2.3.0
332
         */
333
        public static Authenticated authenticate(Credentials credentials) throws ContextAuthenticationException {
334

335
                if (Daemon.isDaemonThread()) {
1 ✔
336
                        log.error("Authentication attempted while operating on a "
×
337
                                        + "daemon thread, authenticating is not necessary or allowed");
338
                        return new BasicAuthenticated(Daemon.getDaemonThreadUser(), "No auth scheme used by Context - Daemon user is always authenticated.");
×
339
                }
340

341
                if (credentials == null) {
1 ✔
342
                        throw new ContextAuthenticationException("Context cannot authenticate with null credentials.");
×
343
                }
344

345
                return getUserContext().authenticate(credentials);
1 ✔
346
        }
347

348
        /**
349
         * Refresh the authenticated user object in the current UserContext. This should be used when
350
         * updating information in the database about the current user and it needs to be reflecting in
351
         * the (cached) {@link #getAuthenticatedUser()} User object.
352
         *
353
         * @since 1.5
354
         * <strong>Should</strong> get fresh values from the database
355
         */
356
        public static void refreshAuthenticatedUser() {
357
                if (Daemon.isDaemonThread()) {
1 ✔
358
                        return;
×
359
                }
360
                log.debug("Refreshing authenticated user");
1 ✔
361

362
                getUserContext().refreshAuthenticatedUser();
1 ✔
363
        }
1 ✔
364

365
        /**
366
         * Become a different user. (You should only be able to do this as a superuser.)
367
         *
368
         * @param systemId
369
         * @throws ContextAuthenticationException
370
         * <strong>Should</strong> change locale when become another user
371
         */
372
        public static void becomeUser(String systemId) throws ContextAuthenticationException {
373
                log.info("systemId: {}", systemId);
1 ✔
374

375
                getUserContext().becomeUser(systemId);
1 ✔
376
        }
1 ✔
377

378
        /**
379
         * Get the runtime properties that this OpenMRS instance was started with
380
         *
381
         * @return copy of the runtime properties
382
         */
383
        public static Properties getRuntimeProperties() {
384
                Properties props = new Properties();
1 ✔
385
                if( runtimeProperties != null ) {
1 ✔
386
                        props.putAll(runtimeProperties);
1 ✔
387
                }
388
                return props;
1 ✔
389
        }
390

391
        /**
392
         * Set the runtime properties to be used by this OpenMRS instance
393
         *
394
         * @param props runtime properties
395
         */
396
        public static void setRuntimeProperties(Properties props) {
397
                runtimeProperties = props;
1 ✔
398
        }
1 ✔
399

400
        /**
401
         * @return concept dictionary-related services
402
         */
403
        public static ConceptService getConceptService() {
404
                return getServiceContext().getConceptService();
1 ✔
405
        }
406

407
        /**
408
         * @return encounter-related services
409
         */
410
        public static EncounterService getEncounterService() {
411
                return getServiceContext().getEncounterService();
1 ✔
412
        }
413

414
        /**
415
         * @return location services
416
         */
417
        public static LocationService getLocationService() {
418
                return getServiceContext().getLocationService();
1 ✔
419
        }
420

421
        /**
422
         * @return observation services
423
         */
424
        public static ObsService getObsService() {
425
                return getServiceContext().getObsService();
1 ✔
426
        }
427

428
        /**
429
         * @return patient-related services
430
         */
431
        public static PatientService getPatientService() {
432
                return getServiceContext().getPatientService();
1 ✔
433
        }
434

435
        public static CohortService getCohortService() {
436
                return getServiceContext().getCohortService();
1 ✔
437
        }
438

439
        /**
440
         * @return person-related services
441
         */
442
        public static PersonService getPersonService() {
443
                return getServiceContext().getPersonService();
1 ✔
444
        }
445

446
        /**
447
         * @return condition-related services
448
         * 
449
         * @since 2.2
450
         */
451
        public static ConditionService getConditionService(){
452
                return getServiceContext().getConditionService();
1 ✔
453
        }
454

455
        /**
456
         * @return diagnosis-related services
457
         *
458
         * @since 2.2
459
         */
460
        public static DiagnosisService getDiagnosisService(){
461
                return getServiceContext().getDiagnosisService();
1 ✔
462
        }
463

464
        /**
465
         * @return MedicationDispense-related service
466
         * @since 2.6.0
467
         */
468
        public static MedicationDispenseService getMedicationDispenseService(){
469
                return getServiceContext().getMedicationDispenseService();
1 ✔
470
        }
471

472
        /**
473
         * @return Returns the hl7Service.
474
         */
475
        public static HL7Service getHL7Service() {
476
                return getServiceContext().getHL7Service();
1 ✔
477
        }
478

479
        /**
480
         * @return user-related services
481
         */
482
        public static UserService getUserService() {
483
                return getServiceContext().getUserService();
1 ✔
484
        }
485

486
        /**
487
         * @return order service
488
         */
489
        public static OrderService getOrderService() {
490
                return getServiceContext().getOrderService();
1 ✔
491
        }
492

493
        /**
494
         * @return orderSet service
495
         * @since 1.12
496
         */
497
        public static OrderSetService getOrderSetService() {
498
                return getServiceContext().getOrderSetService();
1 ✔
499
        }
500

501
        /**
502
         * @return form service
503
         */
504
        public static FormService getFormService() {
505
                return getServiceContext().getFormService();
1 ✔
506
        }
507

508
        /**
509
         * @return serialization service
510
         * @since 1.5
511
         */
512
        public static SerializationService getSerializationService() {
513
                return getServiceContext().getSerializationService();
1 ✔
514
        }
515

516
        /**
517
         * @return logic service
518
         */
519
        public static LogicService getLogicService() {
520
                return getServiceContext().getLogicService();
×
521
        }
522

523
        /**
524
         * @return admin-related services
525
         */
526
        public static AdministrationService getAdministrationService() {
527
                return getServiceContext().getAdministrationService();
1 ✔
528
        }
529

530
        /**
531
         * @return MessageSourceService
532
         */
533
        public static MessageSourceService getMessageSourceService() {
534
                return getServiceContext().getMessageSourceService();
1 ✔
535
        }
536

537
        /**
538
         * @return scheduler service
539
         */
540
        public static SchedulerService getSchedulerService() {
541
                return getServiceContext().getSchedulerService();
1 ✔
542
        }
543

544
        /**
545
         * @return alert service
546
         */
547
        public static AlertService getAlertService() {
548
                return getServiceContext().getAlertService();
1 ✔
549
        }
550

551
        /**
552
         * @return program- and workflow-related services
553
         */
554
        public static ProgramWorkflowService getProgramWorkflowService() {
555
                return getServiceContext().getProgramWorkflowService();
1 ✔
556
        }
557
        
558
        /**
559
         * Get the message service.
560
         *
561
         * @return message service
562
         */
563
        public static MessageService getMessageService() {
564
                MessageService ms = getServiceContext().getMessageService();
1 ✔
565
                try {
566
                        // Message service dependencies
567
                        if (ms.getMessagePreparator() == null) {
1 ✔
568
                                ms.setMessagePreparator(getMessagePreparator());
1 ✔
569
                        }
570

571
                        if (ms.getMessageSender() == null) {
1 ✔
572
                                ms.setMessageSender(getMessageSender());
1 ✔
573
                        }
574

575
                }
576
                catch (Exception e) {
×
577
                        log.error("Unable to create message service due", e);
×
578
                }
1 ✔
579
                return ms;
1 ✔
580
        }
581

582
        /**
583
         * @return all of the configured properties that are used to configure the Mail Session in the Message Service
584
         * These properties are defined as all properties that are prefixed with "mail." and this will return all such
585
         * properties as defined in global properties, runtime properties, and/or system properties, with 
586
         * system properties overriding runtime properties overriding global properties.
587
         */
588
        public static Properties getMailProperties() {
589
                Properties p = new Properties();
1 ✔
590
                String prefix = "mail.";
1 ✔
591
                for (GlobalProperty gp : getAdministrationService().getGlobalPropertiesByPrefix(prefix)) {
1 ✔
592
                        // Historically, some mail properties defined with underscores, support these for legacy compatibility
593
                        if (gp.getProperty().equals("mail.transport_protocol")) {
1 ✔
594
                                p.setProperty("mail.transport.protocol", gp.getPropertyValue());
×
595
                        }
596
                        else if (gp.getProperty().equals("mail.smtp_host")) {
1 ✔
597
                                p.setProperty("mail.smtp.host", gp.getPropertyValue());
×
598
                        }
599
                        else if (gp.getProperty().equals("mail.smtp_port")) {
1 ✔
600
                                p.setProperty("mail.smtp.port", gp.getPropertyValue());
×
601
                        }
602
                        else if (gp.getProperty().equals("mail.smtp_auth")) {
1 ✔
603
                                p.setProperty("mail.smtp.auth", gp.getPropertyValue());
×
604
                        }
605
                        else {
606
                                p.setProperty(gp.getProperty(), gp.getPropertyValue());
1 ✔
607
                        }
608
                }
1 ✔
609
                for (String runtimeProperty : runtimeProperties.stringPropertyNames()) {
1 ✔
610
                        if (runtimeProperty.startsWith(prefix)) {
1 ✔
611
                                p.setProperty(runtimeProperty, runtimeProperties.getProperty(runtimeProperty));
×
612
                        }
613
                }
1 ✔
614
                for (String systemProperty : System.getProperties().stringPropertyNames()) {
1 ✔
615
                        if (systemProperty.startsWith(prefix)) {
1 ✔
616
                                p.setProperty(systemProperty, System.getProperty(systemProperty));
×
617
                        }
618
                }
1 ✔
619
                return p;
1 ✔
620
        }
621

622
        /**
623
         * Gets the mail session required by the mail message service. This function forces
624
         * authentication via the getAdministrationService() method call
625
         *
626
         * @return a java mail session
627
         */
628
        private static Session getMailSession() {
629
                if (mailSession == null) {
1 ✔
630
                        synchronized (Context.class) {
1 ✔
631
                                if (mailSession == null) {
1 ✔
632
                                        Authenticator auth = new Authenticator() {
1 ✔
633

634
                                                @Override
635
                                                public PasswordAuthentication getPasswordAuthentication() {
636
                                                        return new PasswordAuthentication(
×
637
                                                                ConfigUtil.getProperty("mail.user"),
×
638
                                                                ConfigUtil.getProperty("mail.password")
×
639
                                                        );
640
                                                }
641
                                        };
642
                                        mailSession = Session.getInstance(getMailProperties(), auth);
1 ✔
643
                                }
644
                        }
1 ✔
645
                }
646
                return mailSession;
1 ✔
647
        }
648

649
        /**
650
         * Convenience method to allow us to change the configuration more easily. TODO Ideally, we
651
         * would be using Spring's method injection to set the dependencies for the message service.
652
         *
653
         * @return the ServiceContext
654
         */
655
        private static MessageSender getMessageSender() {
656
                return new MailMessageSender(getMailSession());
1 ✔
657
        }
658

659
        /**
660
         * Convenience method to allow us to change the configuration more easily. TODO See todo for
661
         * message sender.
662
         *
663
         * @return
664
         */
665
        private static MessagePreparator getMessagePreparator() throws MessageException {
666
                return new VelocityMessagePreparator();
1 ✔
667
        }
668

669
        /**
670
         * @return "active" user who has been authenticated, otherwise <code>null</code>
671
         */
672
        public static User getAuthenticatedUser() {
673
                if (Daemon.isDaemonThread()) {
1 ✔
674
                        return Daemon.getDaemonThreadUser();
1 ✔
675
                }
676

677
                return getUserContext().getAuthenticatedUser();
1 ✔
678
        }
679

680
        /**
681
         * Prefer this to the id on {@link #getAuthenticatedUser()}.
682
         *
683
         * @return the id of the authenticated user as loaded (see
684
         *         {@link UserContext#getAuthenticatedUserId()}), or of the daemon user on a daemon thread;
685
         *         null if no stored user is authenticated
686
         * @since 2.8.11
687
         */
688
        public static Integer getAuthenticatedUserId() {
689
                return getUserContext().getAuthenticatedUserId();
1 ✔
690
        }
691

692
        /**
693
         * @return true if user has been authenticated in this context
694
         */
695
        public static boolean isAuthenticated() {
696
                if (Daemon.isDaemonThread()) {
1 ✔
697
                        return true;
×
698
                } else {
699
                        try {
700
                                return getAuthenticatedUser() != null;
1 ✔
701
                        } catch (APIException e) {
×
702
                                log.info("Could not get authenticated user inside called to isAuthenticated(), assuming no user context has been defined", e);
×
703
                                return false;
×
704
                        }
705
                }
706
        }
707

708
        /**
709
         * Used by {@link org.openmrs.aop.AuthorizationAdvice} to give access for unauthenticated users when
710
         * running initialization code with proxy privileges. See e.g.
711
         * {@link org.openmrs.event.outbox.tasks.OutboxTaskSchedulerInitializer#schedule()}.
712
         *
713
         * @return true if there are any proxy privileges
714
         * @since 2.9.0
715
         */
716
        public static boolean hasProxyPrivileges() {
717
                return getUserContext().hasProxyPrivileges();
1 ✔
718
        }
719

720
        /**
721
         * logs out the "active" (authenticated) user within context
722
         *
723
         * @see #authenticate
724
         * <strong>Should</strong> not fail if session hasn't been opened yet
725
         */
726
        public static void logout() {
727
                if (!isSessionOpen()) {
1 ✔
728
                        return; // fail early if there isn't even a session open
1 ✔
729
                }
730
                log.debug("Logging out : {}", getAuthenticatedUser());
1 ✔
731

732
                getUserContext().logout();
1 ✔
733

734
                // reset the UserContext object (usually cleared out by closeSession()
735
                // soon after this)
736
                setUserContext(new UserContext(getAuthenticationScheme()));
1 ✔
737
        }
1 ✔
738

739
        /**
740
         * Convenience method. Passes through to userContext.getAllRoles(User)
741
         */
742
        public static Set<Role> getAllRoles(User user) throws Exception {
743
                return getUserContext().getAllRoles();
1 ✔
744
        }
745

746
        /**
747
         * Tests whether the currently authenticated user has a particular privilege
748
         */
749
        public static boolean hasPrivilege(String privilege) {
750
                // the daemon threads have access to all things
751
                if (Daemon.isDaemonThread()) {
1 ✔
752
                        return true;
1 ✔
753
                }
754

755
                return getUserContext().hasPrivilege(privilege);
1 ✔
756
        }
757

758
        /**
759
         * Tests whether the currently authenticated user has a particular privilege, optionally excluding
760
         * proxy privileges. Passing <code>false</code> checks only the user's granted roles (and the
761
         * anonymous and authenticated roles), so a proxy privilege added merely to invoke a service method
762
         * cannot satisfy a per-resource access check.
763
         *
764
         * @param privilege the privilege to check
765
         * @param includeProxyPrivileges whether proxy privileges may satisfy the check
766
         * @return true if the current user has the given privilege
767
         * @see UserContext#hasPrivilege(String, boolean)
768
         * @since 3.0.0, 2.9.0, 2.8.9
769
         */
770
        public static boolean hasPrivilege(String privilege, boolean includeProxyPrivileges) {
771
                // the daemon threads have access to all things
772
                if (Daemon.isDaemonThread()) {
1 ✔
773
                        return true;
1 ✔
774
                }
775

776
                return getUserContext().hasPrivilege(privilege, includeProxyPrivileges);
1 ✔
777
        }
778

779
        /**
780
         * Throws an exception if the currently authenticated user does not have the specified
781
         * privilege.
782
         *
783
         * @param privilege
784
         * @throws ContextAuthenticationException
785
         */
786
        public static void requirePrivilege(String privilege) throws ContextAuthenticationException {
787
                if (!hasPrivilege(privilege)) {
1 ✔
788
                        String errorMessage;
789
                        if (StringUtils.isNotBlank(privilege)) {
×
790
                                errorMessage = Context.getMessageSourceService().getMessage("error.privilegesRequired",
×
791
                                                new Object[] { privilege }, null);
792
                        } else {
793
                                //Should we even be here if the privilege is blank?
794
                                errorMessage = Context.getMessageSourceService().getMessage("error.privilegesRequiredNoArgs");
×
795
                        }
796

797
                        throw new ContextAuthenticationException(errorMessage);
×
798
                }
799
        }
1 ✔
800
        
801
        /**
802
         * Adds one or more privileges to the list of privileges that that {@link #hasPrivilege(String)} will
803
         * regard as available regardless of whether the user would otherwise have the privilege.
804
         * <p/>
805
         * This is useful for situations where a system process may need access to some piece of data that the
806
         * user would not otherwise have access to, like a GlobalProperty. <strong>This facility should not be
807
         * used to return data to the user that they otherwise would be unable to see.</strong>
808
         * <p/>
809
         * The expected usage is:
810
         * <p/>
811
         * <pre>{@code
812
         * try {
813
         *   Context.addProxyPrivilege(&quot;AAA&quot;);
814
         *   Context.get*Service().methodRequiringAAAPrivilege();
815
         * }
816
         * finally {
817
         *   Context.removeProxyPrivilege(&quot;AAA&quot;);
818
         * }}
819
         * </pre>
820
         * <p/>
821
         *
822
         * @param privilege privileges to add in string form
823
         * @see #hasPrivilege(String)
824
         * @see #removeProxyPrivilege(String)
825
         */
826
        public static void addProxyPrivilege(String privilege) {
827
                getUserContext().addProxyPrivilege(privilege);
1 ✔
828
        }
1 ✔
829
        
830
        /**
831
         * Adds one or more privileges to the list of privileges that that {@link #hasPrivilege(String)} will
832
         * regard as available regardless of whether the user would otherwise have the privilege.
833
         * <p/>
834
         * This is useful for situations where a system process may need access to some piece of data that the
835
         * user would not otherwise have access to, like a GlobalProperty. <strong>This facility should not be
836
         * used to return data to the user that they otherwise would be unable to see.</strong>
837
         * <p/>
838
         * The expected usage is:
839
         * <p/>
840
         * <pre>{@code
841
         * try {
842
         *   Context.addProxyPrivilege(&quot;AAA&quot;);
843
         *   Context.get*Service().methodRequiringAAAPrivilege();
844
         * }
845
         * finally {
846
         *   Context.removeProxyPrivilege(&quot;AAA&quot;);
847
         * }}
848
         * </pre>
849
         * <p/>
850
         *
851
         * @param privileges privileges to add in string form
852
         * @see #hasPrivilege(String)
853
         * @see #removeProxyPrivilege(String...)
854
         * @since 3.0.0, 2.8.2, 2.7.8
855
         */
856
        public static void addProxyPrivilege(String... privileges) {
857
                getUserContext().addProxyPrivilege(privileges);
1 ✔
858
        }
1 ✔
859

860
        /**
861
         * Removes one or more privileges from the list of privileges that that {@link #hasPrivilege(String)} will
862
         * regard as available regardless of whether the user would otherwise have the privilege.
863
         * <p/>
864
         * This is the compliment for {@link #addProxyPrivilege(String...)} to clean-up the context.
865
         * <p/>
866
         *
867
         * @param privilege privileges to remove in string form
868
         * @see #hasPrivilege(String)
869
         * @see #addProxyPrivilege(String)
870
         */
871
        public static void removeProxyPrivilege(String privilege) {
872
                getUserContext().removeProxyPrivilege(privilege);
1 ✔
873
        }
1 ✔
874

875
        /**
876
         * Removes a privilege from the list of privileges that that {@link #hasPrivilege(String)} will
877
         * regard as available regardless of whether the user would otherwise have the privilege.
878
         * <p/>
879
         * This is the compliment for {@link #addProxyPrivilege(String...)} to clean-up the context.
880
         * <p/>
881
         *
882
         * @param privileges privileges to remove in string form
883
         * @see #hasPrivilege(String)
884
         * @see #addProxyPrivilege(String...)
885
         * * @since 3.0.0, 2.8.2, 2.7.8
886
         */
887
        public static void removeProxyPrivilege(String... privileges) {
888
                getUserContext().removeProxyPrivilege(privileges);
1 ✔
889
        }
1 ✔
890

891
        /**
892
         * Convenience method. Passes through to {@link UserContext#setLocale(Locale)}
893
         */
894
        public static void setLocale(Locale locale) {
895
                getUserContext().setLocale(locale);
1 ✔
896
        }
1 ✔
897

898
        /**
899
         * Convenience method. Passes through to {@link UserContext#getLocale()}
900
         *
901
         * <strong>Should</strong> not fail if session hasn't been opened
902
         */
903
        public static Locale getLocale() {
904
                // if a session hasn't been opened, just fetch the default
905
                if (!isSessionOpen()) {
1 ✔
906
                        return LocaleUtility.getDefaultLocale();
1 ✔
907
                }
908

909
                return getUserContext().getLocale();
1 ✔
910
        }
911

912
        /**
913
         * Used to define a unit of work. All "units of work" should be surrounded by openSession and
914
         * closeSession calls.
915
         */
916
        public static void openSession() {
917
                log.trace("opening session");
1 ✔
918
                setUserContext(new UserContext(getAuthenticationScheme())); // must be cleared out in
1 ✔
919
                // closeSession()
920
                getContextDAO().openSession();
1 ✔
921
        }
1 ✔
922

923
        /**
924
         * Used to define a unit of work. All "units of work" should be surrounded by openSession and
925
         * closeSession calls.
926
         */
927
        public static void closeSession() {
928
                log.trace("closing session");
1 ✔
929
                clearUserContext(); // because we set a UserContext on the current
1 ✔
930
                // thread in openSession()
931
                getContextDAO().closeSession();
1 ✔
932
        }
1 ✔
933

934
        /**
935
         * Used to define a unit of work which does not require clearing out the currently authenticated
936
         * user. Remember to call closeSessionWithCurrentUser in a, preferably, finally block after this
937
         * work.
938
         *
939
         * @since 1.10
940
         */
941
        public static void openSessionWithCurrentUser() {
942
                getContextDAO().openSession();
×
943
        }
×
944

945
        /**
946
         * Used when the a unit of work which started with a call for openSessionWithCurrentUser has
947
         * finished. This should be in a, preferably, finally block.
948
         *
949
         * @since 1.10
950
         */
951
        public static void closeSessionWithCurrentUser() {
952
                getContextDAO().closeSession();
×
953
        }
×
954

955
        /**
956
         * Clears cached changes made so far during this unit of work without writing them to the
957
         * database. If you call this method, and later call closeSession() or flushSession() your
958
         * changes are still lost.
959
         */
960
        public static void clearSession() {
961
                log.trace("clearing session");
1 ✔
962
                getContextDAO().clearSession();
1 ✔
963
        }
1 ✔
964

965
        /**
966
         * Forces any changes made so far in this unit of work to be written to the database
967
         *
968
         * @since 1.6
969
         */
970
        public static void flushSession() {
971
                log.trace("flushing session");
1 ✔
972
                getContextDAO().flushSession();
1 ✔
973
        }
1 ✔
974

975
        /**
976
         * This method tells whether {@link #openSession()} has been called or not already. If it hasn't
977
         * been called, some methods won't work correctly because a {@link UserContext} isn't available.
978
         *
979
         * @return true if {@link #openSession()} has been called already.
980
         * @since 1.5
981
         * <strong>Should</strong> return true if session is closed
982
         */
983
        public static boolean isSessionOpen() {
984
                return userContextHolder.get() != null;
1 ✔
985
        }
986

987
        /**
988
         * Used to re-read the state of the given instance from the underlying database.
989
         * @since 2.0
990
         * @param obj The object to refresh from the database in the session
991
         */
992
        public static void refreshEntity(Object obj) {
993
                log.trace("refreshing object: {}", obj);
1 ✔
994
                getContextDAO().refreshEntity(obj);
1 ✔
995
        }
1 ✔
996

997
        /**
998
         * Used to clear a cached object out of a session in the middle of a unit of work. Future
999
         * updates to this object will not be saved. Future gets of this object will not fetch this
1000
         * cached copy
1001
         *
1002
         * @param obj The object to evict/remove from the session
1003
         */
1004
        public static void evictFromSession(Object obj) {
1005
                log.trace("clearing session");
1 ✔
1006
                getContextDAO().evictFromSession(obj);
1 ✔
1007
        }
1 ✔
1008

1009
        /**
1010
         * Evicts the entity data for a particular entity instance.
1011
         *
1012
         * @param object entity instance to evict from the DB cache
1013
         */
1014
        public static void evictEntity(OpenmrsObject object) {
1015
                log.debug("Clearing DB cache for entity: {} with id: {}", object.getClass(), object.getId());
1 ✔
1016
                getContextDAO().evictEntity(object);
1 ✔
1017
        }
1 ✔
1018
        
1019
        /**
1020
         * Evicts all entity data of a particular class from the given region.
1021
         * 
1022
         * @param entityClass entity class to evict from the DB cache
1023
         */
1024
        public static void evictAllEntities(Class<?> entityClass) {
1025
                log.debug("Clearing DB cache for entities of type: {}", entityClass);
1 ✔
1026
                getContextDAO().evictAllEntities(entityClass);
1 ✔
1027
        }
1 ✔
1028
        
1029
        /**
1030
         * Evicts data from both DB and API cache.
1031
         */
1032
        public static void clearEntireCache() {
1033
                log.debug("Clearing DB cache");
1 ✔
1034
                getContextDAO().clearEntireCache();
1 ✔
1035
                log.debug("Clearing API cache");
1 ✔
1036
                getServiceContext().clearEntireApiCache();
1 ✔
1037
        }
1 ✔
1038
        
1039
        /**
1040
         * Starts the OpenMRS System Should be called prior to any kind of activity
1041
         *
1042
         * @param props Runtime properties to use for startup
1043
         * @throws InputRequiredException if the {@link DatabaseUpdater} has determined that updates
1044
         *             cannot continue without input from the user
1045
         * @throws DatabaseUpdateException if database updates are required, see
1046
         *             {@link DatabaseUpdater#executeChangelog()}
1047
         * @throws ModuleMustStartException if a module that should be started is not able to
1048
         * @see InputRequiredException#getRequiredInput() InputRequiredException#getRequiredInput() for
1049
         *      the required question/datatypes
1050
         */
1051
        public static synchronized void startup(Properties props) throws DatabaseUpdateException, InputRequiredException,
1052
        ModuleMustStartException {
1053
                // do any context database specific startup
1054
                getContextDAO().startup(props);
×
1055

1056
                if (getAdministrationService().isCoreSetupOnVersionChangeNeeded()) {
×
1057
                        log.info("Detected core version change. Running core setup hooks and Liquibase.");
×
1058
                        getAdministrationService().runCoreSetupOnVersionChange();
×
1059
                }
1060

1061
                // this should be first in the startup routines so that the application
1062
                // data directory can be set from the runtime properties
1063
                OpenmrsUtil.startup(props);
×
1064
                
1065
                openSession();
×
1066
                clearSession();
×
1067

1068
                // add any privileges/roles that /must/ exist for openmrs to work
1069
                // correctly.
1070
                checkCoreDataset();
×
1071
                
1072
                getContextDAO().setupSearchIndex();
×
1073

1074
                // Loop over each module and startup each with these custom properties
1075
                ModuleUtil.startup(props);
×
1076
        }
×
1077

1078
        /**
1079
         * Starts the OpenMRS System in a _non-webapp_ environment<br>
1080
         * <br>
1081
         * <b>Note:</b> This method calls {@link Context#openSession()}, so you must call
1082
         * {@link Context#closeSession()} somewhere on the same thread of this application so as to not
1083
         * leak memory.
1084
         *
1085
         * @param url database url like "jdbc:mysql://localhost:3306/openmrs?autoReconnect=true"
1086
         * @param username Connection username
1087
         * @param password Connection password
1088
         * @param properties Other startup properties
1089
         * @throws InputRequiredException if the {@link DatabaseUpdater} has determined that updates
1090
         *             cannot continue without input from the user
1091
         * @throws DatabaseUpdateException if the database must be updated. See {@link DatabaseUpdater}
1092
         * @throws ModuleMustStartException if a module that should start is not able to
1093
         * @see #startup(Properties)
1094
         * @see InputRequiredException#getRequiredInput() InputRequiredException#getRequiredInput() for
1095
         *      the required question/datatypes
1096
         */
1097
        public static synchronized void startup(String url, String username, String password, Properties properties)
1098
                        throws DatabaseUpdateException, InputRequiredException, ModuleMustStartException {
1099
                if (properties == null) {
×
1100
                        properties = new Properties();
×
1101
                }
1102

1103
                properties.put("connection.url", url);
×
1104
                properties.put("connection.username", username);
×
1105
                properties.put("connection.password", password);
×
1106
                setRuntimeProperties(properties);
×
1107

1108
                openSession(); // so that the startup method can use proxyPrivileges
×
1109

1110
                startup(properties);
×
1111
                
1112
                Context.getSchedulerService().onStartup();
×
1113
                
1114
                closeSession();
×
1115
        }
×
1116

1117
        /**
1118
         * Stops the OpenMRS System Should be called after all activity has ended and application is
1119
         * closing
1120
         */
1121
        public static void shutdown() {
1122
                log.debug("Shutting down the scheduler");
1 ✔
1123
                try {
1124
                        SchedulerService schedulerService = null;
1 ✔
1125
                        try {
1126
                                schedulerService = getSchedulerService();
1 ✔
1127
                        }
1128
                        catch (APIException e) {
×
1129
                                // pass
1130
                        }
1 ✔
1131
                        if (schedulerService != null) {
1 ✔
1132
                                // stops running tasks before the modules and the database they use are shut down
1133
                                schedulerService.onShutdown();
1 ✔
1134
                        }
1135
                }
1136
                catch (Exception e) {
×
1137
                        log.warn("Error while shutting down the scheduler", e);
×
1138
                }
1 ✔
1139

1140
                log.debug("Shutting down the modules");
1 ✔
1141
                try {
1142
                        ModuleUtil.shutdown();
1 ✔
1143
                }
1144
                catch (Exception e) {
×
1145
                        log.warn("Error while shutting down module system", e);
×
1146
                }
1 ✔
1147

1148
                log.debug("Shutting down the context");
1 ✔
1149
                try {
1150
                        ContextDAO dao = null;
1 ✔
1151
                        try {
1152
                                dao = getContextDAO();
1 ✔
1153
                        }
1154
                        catch (APIException e) {
×
1155
                                // pass
1156
                        }
1 ✔
1157
                        if (dao != null) {
1 ✔
1158
                                dao.shutdown();
1 ✔
1159
                        }
1160
                }
1161
                catch (Exception e) {
×
1162
                        log.warn("Error while shutting down context dao", e);
×
1163
                }
1 ✔
1164
        }
1 ✔
1165

1166
        /**
1167
         * Used for getting services not in the previous get*Service() calls
1168
         *
1169
         * @param cls The Class of the service to get
1170
         * @return The requested Service
1171
         * <strong>Should</strong> return the same object when called multiple times for the same class
1172
         */
1173
        public static <T> T getService(Class<? extends T> cls) {
1174
                return getServiceContext().getService(cls);
1 ✔
1175
        }
1176

1177
        /**
1178
         * Adds an AOP advisor around the given Class <code>cls</code>
1179
         * <p>
1180
         * Advisors can wrap around a method and effect the method before or after
1181
         *
1182
         * @param cls
1183
         * @param advisor
1184
         */
1185
        public static void addAdvisor(Class cls, Advisor advisor) {
1186
                getServiceContext().addAdvisor(cls, advisor);
×
1187
        }
×
1188

1189
        /**
1190
         * Adds an AOP advice object around the given Class <code>cls</code>
1191
         * <p>
1192
         * Advice comes in the form of before or afterReturning methods
1193
         *
1194
         * @param cls
1195
         * @param advice
1196
         */
1197
        public static void addAdvice(Class cls, Advice advice) {
1198
                getServiceContext().addAdvice(cls, advice);
×
1199
        }
×
1200

1201
        /**
1202
         * Removes the given AOP advisor from Class <code>cls</code>
1203
         *
1204
         * @param cls
1205
         * @param advisor
1206
         */
1207
        public static void removeAdvisor(Class cls, Advisor advisor) {
1208
                getServiceContext().removeAdvisor(cls, advisor);
×
1209
        }
×
1210

1211
        /**
1212
         * Removes the given AOP advice object from Class <code>cls</code>
1213
         *
1214
         * @param cls
1215
         * @param advice
1216
         */
1217
        public static void removeAdvice(Class cls, Advice advice) {
1218
                getServiceContext().removeAdvice(cls, advice);
×
1219
        }
×
1220

1221
        /**
1222
         * Runs through the core data (e.g. privileges, roles, and global properties) and adds them if
1223
         * necessary.
1224
         */
1225
        public static void checkCoreDataset() {
1226
                // setting core roles
1227
                try {
1228
                        Context.addProxyPrivilege(PrivilegeConstants.MANAGE_ROLES);
×
1229
                        Set<String> currentRoleNames = new HashSet<>();
×
1230
                        for (Role role : Context.getUserService().getAllRoles()) {
×
1231
                                currentRoleNames.add(role.getRole().toUpperCase());
×
1232
                        }
×
1233
                        Map<String, String> map = OpenmrsUtil.getCoreRoles();
×
1234
                        for (Map.Entry<String, String> entry : map.entrySet()) {
×
1235
                                String roleName = entry.getKey();
×
1236
                                if (!currentRoleNames.contains(roleName.toUpperCase())) {
×
1237
                                        Role role = new Role();
×
1238
                                        role.setRole(roleName);
×
1239
                                        role.setDescription(entry.getValue());
×
1240
                                        Context.getUserService().saveRole(role);
×
1241
                                }
1242
                        }
×
1243
                }
1244
                catch (Exception e) {
×
1245
                        log.error("Error while setting core roles for openmrs system", e);
×
1246
                }
1247
                finally {
1248
                        Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_ROLES);
×
1249
                }
1250

1251
                // setting core privileges
1252
                try {
1253
                        Context.addProxyPrivilege(PrivilegeConstants.MANAGE_PRIVILEGES);
×
1254
                        Set<String> currentPrivilegeNames = new HashSet<>();
×
1255
                        for (Privilege privilege : Context.getUserService().getAllPrivileges()) {
×
1256
                                currentPrivilegeNames.add(privilege.getPrivilege().toUpperCase());
×
1257
                        }
×
1258
                        Map<String, String> map = OpenmrsUtil.getCorePrivileges();
×
1259
                        for (Map.Entry<String, String> entry : map.entrySet()) {
×
1260
                                String privilegeName = entry.getKey();
×
1261
                                if (!currentPrivilegeNames.contains(privilegeName.toUpperCase())) {
×
1262
                                        Privilege p = new Privilege();
×
1263
                                        p.setPrivilege(privilegeName);
×
1264
                                        p.setDescription(entry.getValue());
×
1265
                                        Context.getUserService().savePrivilege(p);
×
1266
                                }
1267
                        }
×
1268
                }
1269
                catch (Exception e) {
×
1270
                        log.error("Error while setting core privileges", e);
×
1271
                }
1272
                finally {
1273
                        Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_PRIVILEGES);
×
1274
                }
1275

1276
                // setting core global properties
1277
                try {
1278
                        Context.addProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
×
1279
                        Context.addProxyPrivilege(PrivilegeConstants.GET_GLOBAL_PROPERTIES);
×
1280
                        Set<String> currentPropNames = new HashSet<>();
×
1281
                        Map<String, GlobalProperty> propsMissingDescription = new HashMap<>();
×
1282
                        Map<String, GlobalProperty> propsMissingDatatype = new HashMap<>();
×
1283
                        for (GlobalProperty prop : Context.getAdministrationService().getAllGlobalProperties()) {
×
1284
                                currentPropNames.add(prop.getProperty().toUpperCase());
×
1285
                                if (prop.getDescription() == null) {
×
1286
                                        propsMissingDescription.put(prop.getProperty().toUpperCase(), prop);
×
1287
                                }
1288
                                if (prop.getDatatypeClassname() == null) {
×
1289
                                        propsMissingDatatype.put(prop.getProperty().toUpperCase(), prop);
×
1290
                                }
1291
                        }
×
1292

1293
                        for (GlobalProperty coreProp : OpenmrsConstants.CORE_GLOBAL_PROPERTIES()) {
×
1294
                                String corePropName = coreProp.getProperty().toUpperCase();
×
1295
                                // if the prop doesn't exist, save it
1296
                                if (!currentPropNames.contains(corePropName)) {
×
1297
                                        Context.getAdministrationService().saveGlobalProperty(coreProp);
×
1298
                                        currentPropNames.add(corePropName); // add to list in case
×
1299
                                        // of duplicates
1300
                                } else {
1301
                                        // if the prop is missing its description, update it
1302
                                        GlobalProperty propToUpdate = propsMissingDescription.get(corePropName);
×
1303
                                        if (propToUpdate != null) {
×
1304
                                                propToUpdate.setDescription(coreProp.getDescription());
×
1305
                                                Context.getAdministrationService().saveGlobalProperty(propToUpdate);
×
1306
                                        }
1307
                                        // set missing datatypes
1308
                                        propToUpdate = propsMissingDatatype.get(corePropName);
×
1309
                                        if (propToUpdate != null && coreProp.getDatatypeClassname() != null) {
×
1310
                                                propToUpdate.setDatatypeClassname(coreProp.getDatatypeClassname());
×
1311
                                                propToUpdate.setDatatypeConfig(coreProp.getDatatypeConfig());
×
1312
                                                propToUpdate.setPreferredHandlerClassname(coreProp.getPreferredHandlerClassname());
×
1313
                                                propToUpdate.setHandlerConfig(coreProp.getHandlerConfig());
×
1314
                                                Context.getAdministrationService().saveGlobalProperty(propToUpdate);
×
1315
                                        }
1316
                                }
1317
                        }
×
1318
                }
1319
                catch (Exception e) {
×
1320
                        log.error("Error while setting core global properties", e);
×
1321
                }
1322
                finally {
1323
                        Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
×
1324
                        Context.removeProxyPrivilege(PrivilegeConstants.GET_GLOBAL_PROPERTIES);
×
1325
                }
1326

1327
                // setting default validation rule
1328
                AdministrationService as = Context.getAdministrationService();
×
1329
                Boolean disableValidation = Boolean.valueOf(as.getGlobalProperty(OpenmrsConstants.GP_DISABLE_VALIDATION, "false"));
×
1330
                ValidateUtil.setDisableValidation(disableValidation);
×
1331

1332
                PersonName.setFormat(Context.getAdministrationService().getGlobalProperty(
×
1333
                                OpenmrsConstants.GLOBAL_PROPERTY_LAYOUT_NAME_FORMAT));
1334

1335
                Allergen.setOtherNonCodedConceptUuid(Context.getAdministrationService().getGlobalProperty(
×
1336
                                OpenmrsConstants.GP_ALLERGEN_OTHER_NON_CODED_UUID));
1337
        }
×
1338

1339
        /**
1340
         * Updates the openmrs database to the latest. This is only needed if using the API alone. <br>
1341
         * <br>
1342
         * The typical use-case would be: Try to {@link #startup(String, String, String, Properties)},
1343
         * if that fails, call this method to get the database up to speed.
1344
         *
1345
         * @param userInput (can be null) responses from the user about needed input
1346
         * @throws DatabaseUpdateException if an error occurred while updating
1347
         * @since 1.5
1348
         * @deprecated as of 2.4
1349
         * 
1350
         */
1351
        @Deprecated
1352
        public static void updateDatabase(Map<String, Object> userInput) throws DatabaseUpdateException {
1353
                throw new UnsupportedOperationException("As of 2.4, this method is not longer implemented");
×
1354
        }
1355

1356
        /**
1357
         * Gets the simple date format for the current user's locale. The format will be similar in size
1358
         * to mm/dd/yyyy
1359
         *
1360
         * @return SimpleDateFormat for the user's current locale
1361
         * @see org.openmrs.util.OpenmrsUtil#getDateFormat(Locale)
1362
         * <strong>Should</strong> return a pattern with four y characters in it
1363
         */
1364
        public static SimpleDateFormat getDateFormat() {
1365
                return OpenmrsUtil.getDateFormat(getLocale());
1 ✔
1366
        }
1367

1368
        /**
1369
         * Gets the simple time format for the current user's locale. The format will be similar to
1370
         * hh:mm a
1371
         *
1372
         * @return SimpleDateFormat for the user's current locale
1373
         * @see org.openmrs.util.OpenmrsUtil#getTimeFormat(Locale)
1374
         * <strong>Should</strong> return a pattern with two h characters in it
1375
         */
1376
        public static SimpleDateFormat getTimeFormat() {
1377
                return OpenmrsUtil.getTimeFormat(getLocale());
×
1378
        }
1379

1380
        /**
1381
         * Gets the simple datetime format for the current user's locale. The format will be similar to
1382
         * mm/dd/yyyy hh:mm a
1383
         *
1384
         * @return SimpleDateFormat for the user's current locale
1385
         * @see org.openmrs.util.OpenmrsUtil#getDateTimeFormat(Locale)
1386
         * <strong>Should</strong> return a pattern with four y characters and two h characters in it
1387
         */
1388
        public static SimpleDateFormat getDateTimeFormat() {
1389
                return OpenmrsUtil.getDateTimeFormat(getLocale());
1 ✔
1390
        }
1391

1392
        /**
1393
         * @return true/false whether the service context is currently being refreshed
1394
         * @see org.openmrs.api.context.ServiceContext#isRefreshingContext()
1395
         */
1396
        public static boolean isRefreshingContext() {
1397
                return getServiceContext().isRefreshingContext();
1 ✔
1398
        }
1399

1400
        /**
1401
         * @since 1.5
1402
         * @see ServiceContext#getRegisteredComponents(Class)
1403
         */
1404
        public static <T> List<T> getRegisteredComponents(Class<T> type) {
1405
                return getServiceContext().getRegisteredComponents(type);
1 ✔
1406
        }
1407

1408
        /**
1409
         * @see ServiceContext#getRegisteredComponent(String, Class)
1410
         * @since 1.9.4
1411
         */
1412
        public static <T> T getRegisteredComponent(String beanName, Class<T> type) throws APIException {
1413
                return getServiceContext().getRegisteredComponent(beanName, type);
1 ✔
1414
        }
1415

1416
        /**
1417
         * @see ServiceContext#getModuleOpenmrsServices(String)
1418
         * @since 1.9
1419
         */
1420
        public static List<OpenmrsService> getModuleOpenmrsServices(String modulePackage) {
1421
                return getServiceContext().getModuleOpenmrsServices(modulePackage);
1 ✔
1422
        }
1423

1424
        /**
1425
         * @since 1.9
1426
         * @see ServiceContext#getVisitService()
1427
         */
1428
        public static VisitService getVisitService() {
1429
                return getServiceContext().getVisitService();
1 ✔
1430
        }
1431

1432
        /**
1433
         * @since 1.9
1434
         * @see ServiceContext#getProviderService()
1435
         */
1436
        public static ProviderService getProviderService() {
1437
                return getServiceContext().getProviderService();
1 ✔
1438
        }
1439

1440
        /**
1441
         * @since 1.9
1442
         * @see ServiceContext#getDatatypeService()
1443
         */
1444
        public static DatatypeService getDatatypeService() {
1445
                return getServiceContext().getDatatypeService();
1 ✔
1446
        }
1447

1448
        /**
1449
         * Add or replace a property in the config properties list
1450
         *
1451
         * @param key name of the property
1452
         * @param value value of the property
1453
         * @since 1.9
1454
         */
1455
        public static void addConfigProperty(Object key, Object value) {
1456
                configProperties.put(key, value);
×
1457
        }
×
1458

1459
        /**
1460
         * Remove a property from the list of config properties
1461
         *
1462
         * @param key name of the property
1463
         * @since 1.9
1464
         */
1465
        public static void removeConfigProperty(Object key) {
1466
                configProperties.remove(key);
×
1467
        }
×
1468

1469
        /**
1470
         * Get the config properties that have been added to this OpenMRS instance
1471
         *
1472
         * @return copy of the module properties
1473
         * @since 1.9
1474
         */
1475
        public static Properties getConfigProperties() {
1476
                Properties props = new Properties();
1 ✔
1477
                props.putAll(configProperties);
1 ✔
1478
                return props;
1 ✔
1479
        }
1480

1481
        /**
1482
         * Updates the search index. It is a blocking operation, which may take even a few minutes
1483
         * depending on the index size.
1484
         * <p>
1485
         * There is no need to call this method in normal usage since the index is automatically updated
1486
         * whenever DB transactions are committed.
1487
         * <p>
1488
         * The method is designated to be used in tests, which rollback transactions. Note that if the
1489
         * transaction is rolled back, changes to the index will not be reverted.
1490
         *
1491
         * @since 1.11
1492
         */
1493
        public static void updateSearchIndex() {
1494
                getContextDAO().updateSearchIndex();
×
1495
        }
×
1496

1497
        /**
1498
         * Updates the search index. It is an asynchronous operation.
1499
         * <p>
1500
         * There is no need to call this method in normal usage since the index is automatically updated
1501
         * whenever DB transactions are committed.
1502
         * <p>
1503
         *
1504
         * @return object representing the result of the started asynchronous operation
1505
         */
1506
        public static Future<?> updateSearchIndexAsync() {
1507
                return getContextDAO().updateSearchIndexAsync();
×
1508
        }
1509

1510
        /**
1511
         * It should be used <b>IN TESTS ONLY</b>. See {@link #updateSearchIndex(Class[])} for normal use.
1512
         * <p>
1513
         * Updates the search index for objects of the given type.
1514
         *
1515
         * @see #updateSearchIndex()
1516
         * @see #updateSearchIndex(Class[]) 
1517
         * @param type
1518
         * @since 1.11
1519
         */
1520
        public static void updateSearchIndexForType(Class<?> type) {
1521
                getContextDAO().updateSearchIndexForType(type);
1 ✔
1522
        }
1 ✔
1523

1524
        /**
1525
         * Updates the search index for objects of the given types using mass indexer.
1526
         * 
1527
         * @see #updateSearchIndex() 
1528
         * @param types
1529
         * @since 2.8.0
1530
         */
1531
        public static void updateSearchIndex(Class<?>... types) {
1532
                getContextDAO().updateSearchIndex(types);
×
1533
        }
×
1534

1535
        /**
1536
         * Updates the search index for the given object.
1537
         *
1538
         * @see #updateSearchIndex()
1539
         * @param object
1540
         * @since 1.11
1541
         */
1542
        public static void updateSearchIndexForObject(Object object) {
1543
                getContextDAO().updateSearchIndexForObject(object);
×
1544
        }
×
1545

1546
        /**
1547
         * @see org.openmrs.api.context.ServiceContext#setUseSystemClassLoader(boolean)
1548
         * @since 1.10
1549
         */
1550
        public static void setUseSystemClassLoader(boolean useSystemClassLoader) {
1551
                getServiceContext().setUseSystemClassLoader(useSystemClassLoader);
1 ✔
1552
        }
1 ✔
1553

1554
        /**
1555
         * @see org.openmrs.api.context.ServiceContext#isUseSystemClassLoader()
1556
         * @since 1.10
1557
         */
1558
        public static boolean isUseSystemClassLoader() {
1559
                return getServiceContext().isUseSystemClassLoader();
×
1560
        }
1561

1562
        /**
1563
         * @return a Connection from the OpenMRS database connection pool
1564
         * @since 2.5.7
1565
         */
1566
        public static Connection getDatabaseConnection() {
1567
                return getContextDAO().getDatabaseConnection();
×
1568
        }
1569

1570
        /**
1571
         * It is used to shorten startup time by e.g. not running Liquibase checks, if versions did not change or 
1572
         * re-using expanded jars between restarts. If you want to force a standard startup
1573
         * procedure without optimization, please set the <code>optimized.startup</code> runtime property to <code>false</code>.
1574
         * (<code>true</code> by default) 
1575
         * <p>
1576
         * See <a href="https://issues.openmrs.org/browse/TRUNK-6417">TRUNK-6417</a>
1577
         * 
1578
         * @return <code>true</code> (default) or <code>false</code>
1579
         * @since 2.9.0
1580
         */
1581
        public static boolean isOptimizedStartup() {
1582
                return Boolean.parseBoolean(Context.getRuntimeProperties().getProperty("optimized.startup", "true"));
1 ✔
1583
        }
1584
}
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