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

openmrs / openmrs-core / 44343436915

18 Nov 2026 04:06PM UTC coverage: 69.09% (-0.2%) from 69.299%
44343436915

Pull #5431

github

web-flow
Merge f7f17eb23 into 57615988d
Pull Request #5431: TRUNK-6456 - Add inheritance strategy to ProviderRole jpa mappings

26809 of 38803 relevant lines covered (69.09%)

0.69 hits per line

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

51.06
/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 org.aopalliance.aop.Advice;
13
import org.apache.commons.lang3.StringUtils;
14
import org.openmrs.Allergen;
15
import org.openmrs.GlobalProperty;
16
import org.openmrs.OpenmrsObject;
17
import org.openmrs.PersonName;
18
import org.openmrs.Privilege;
19
import org.openmrs.Role;
20
import org.openmrs.User;
21
import org.openmrs.api.APIException;
22
import org.openmrs.api.AdministrationService;
23
import org.openmrs.api.CohortService;
24
import org.openmrs.api.ConceptService;
25
import org.openmrs.api.ConditionService;
26
import org.openmrs.api.DatatypeService;
27
import org.openmrs.api.DiagnosisService;
28
import org.openmrs.api.EncounterService;
29
import org.openmrs.api.FormService;
30
import org.openmrs.api.LocationService;
31
import org.openmrs.api.MedicationDispenseService;
32
import org.openmrs.api.ObsService;
33
import org.openmrs.api.OpenmrsService;
34
import org.openmrs.api.OrderService;
35
import org.openmrs.api.OrderSetService;
36
import org.openmrs.api.PatientService;
37
import org.openmrs.api.PersonService;
38
import org.openmrs.api.ProgramWorkflowService;
39
import org.openmrs.api.ProviderService;
40
import org.openmrs.api.SerializationService;
41
import org.openmrs.api.UserService;
42
import org.openmrs.api.VisitService;
43
import org.openmrs.api.db.ContextDAO;
44
import org.openmrs.hl7.HL7Service;
45
import org.openmrs.logic.LogicService;
46
import org.openmrs.messagesource.MessageSourceService;
47
import org.openmrs.module.ModuleMustStartException;
48
import org.openmrs.module.ModuleUtil;
49
import org.openmrs.notification.AlertService;
50
import org.openmrs.notification.MessageException;
51
import org.openmrs.notification.MessagePreparator;
52
import org.openmrs.notification.MessageSender;
53
import org.openmrs.notification.MessageService;
54
import org.openmrs.notification.mail.MailMessageSender;
55
import org.openmrs.notification.mail.velocity.VelocityMessagePreparator;
56
import org.openmrs.scheduler.SchedulerService;
57
import org.openmrs.scheduler.SchedulerUtil;
58
import org.openmrs.util.ConfigUtil;
59
import org.openmrs.util.DatabaseUpdateException;
60
import org.openmrs.util.DatabaseUpdater;
61
import org.openmrs.util.InputRequiredException;
62
import org.openmrs.util.LocaleUtility;
63
import org.openmrs.util.OpenmrsClassLoader;
64
import org.openmrs.util.OpenmrsConstants;
65
import org.openmrs.util.OpenmrsUtil;
66
import org.openmrs.util.PrivilegeConstants;
67
import org.openmrs.validator.ValidateUtil;
68
import org.slf4j.Logger;
69
import org.slf4j.LoggerFactory;
70
import org.springframework.aop.Advisor;
71
import org.springframework.beans.BeansException;
72
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
73
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
74

75
import javax.mail.Authenticator;
76
import javax.mail.PasswordAuthentication;
77
import javax.mail.Session;
78
import java.sql.Connection;
79
import java.text.SimpleDateFormat;
80
import java.util.Arrays;
81
import java.util.HashMap;
82
import java.util.HashSet;
83
import java.util.List;
84
import java.util.Locale;
85
import java.util.Map;
86
import java.util.Properties;
87
import java.util.Set;
88
import java.util.concurrent.Future;
89

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

138

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

142
        private static volatile Session mailSession;
143

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

148
        private static volatile ServiceContext serviceContext;
149

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

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

154
        private static AuthenticationScheme authenticationScheme;
155

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

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

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

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

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

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

194
                authenticationScheme = new UsernamePasswordAuthenticationScheme();
1 ✔
195

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

709
        /**
710
         * logs out the "active" (authenticated) user within context
711
         *
712
         * @see #authenticate
713
         * <strong>Should</strong> not fail if session hasn't been opened yet
714
         */
715
        public static void logout() {
716
                if (!isSessionOpen()) {
1 ✔
717
                        return; // fail early if there isn't even a session open
1 ✔
718
                }
719
                log.debug("Logging out : {}", getAuthenticatedUser());
1 ✔
720

721
                getUserContext().logout();
1 ✔
722

723
                // reset the UserContext object (usually cleared out by closeSession()
724
                // soon after this)
725
                setUserContext(new UserContext(getAuthenticationScheme()));
1 ✔
726
        }
1 ✔
727

728
        /**
729
         * Convenience method. Passes through to userContext.getAllRoles(User)
730
         */
731
        public static Set<Role> getAllRoles(User user) throws Exception {
732
                return getUserContext().getAllRoles();
1 ✔
733
        }
734

735
        /**
736
         * Tests whether the currently authenticated user has a particular privilege
737
         */
738
        public static boolean hasPrivilege(String privilege) {
739
                // the daemon threads have access to all things
740
                if (Daemon.isDaemonThread()) {
1 ✔
741
                        return true;
1 ✔
742
                }
743

744
                return getUserContext().hasPrivilege(privilege);
1 ✔
745
        }
746

747
        /**
748
         * Tests whether the currently authenticated user has a particular privilege, optionally excluding
749
         * proxy privileges. Passing <code>false</code> checks only the user's granted roles (and the
750
         * anonymous and authenticated roles), so a proxy privilege added merely to invoke a service method
751
         * cannot satisfy a per-resource access check.
752
         *
753
         * @param privilege the privilege to check
754
         * @param includeProxyPrivileges whether proxy privileges may satisfy the check
755
         * @return true if the current user has the given privilege
756
         * @see UserContext#hasPrivilege(String, boolean)
757
         * @since 3.0.0, 2.9.0, 2.8.9
758
         */
759
        public static boolean hasPrivilege(String privilege, boolean includeProxyPrivileges) {
760
                // the daemon threads have access to all things
761
                if (Daemon.isDaemonThread()) {
1 ✔
762
                        return true;
1 ✔
763
                }
764

765
                return getUserContext().hasPrivilege(privilege, includeProxyPrivileges);
1 ✔
766
        }
767

768
        /**
769
         * Throws an exception if the currently authenticated user does not have the specified
770
         * privilege.
771
         *
772
         * @param privilege
773
         * @throws ContextAuthenticationException
774
         */
775
        public static void requirePrivilege(String privilege) throws ContextAuthenticationException {
776
                if (!hasPrivilege(privilege)) {
1 ✔
777
                        String errorMessage;
778
                        if (StringUtils.isNotBlank(privilege)) {
×
779
                                errorMessage = Context.getMessageSourceService().getMessage("error.privilegesRequired",
×
780
                                                new Object[] { privilege }, null);
781
                        } else {
782
                                //Should we even be here if the privilege is blank?
783
                                errorMessage = Context.getMessageSourceService().getMessage("error.privilegesRequiredNoArgs");
×
784
                        }
785

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

849
        /**
850
         * Removes one or more privileges from the list of privileges that that {@link #hasPrivilege(String)} will
851
         * regard as available regardless of whether the user would otherwise have the privilege.
852
         * <p/>
853
         * This is the compliment for {@link #addProxyPrivilege(String...)} to clean-up the context.
854
         * <p/>
855
         *
856
         * @param privilege privileges to remove in string form
857
         * @see #hasPrivilege(String)
858
         * @see #addProxyPrivilege(String)
859
         */
860
        public static void removeProxyPrivilege(String privilege) {
861
                getUserContext().removeProxyPrivilege(privilege);
1 ✔
862
        }
1 ✔
863

864
        /**
865
         * Removes a privilege from the list of privileges that that {@link #hasPrivilege(String)} will
866
         * regard as available regardless of whether the user would otherwise have the privilege.
867
         * <p/>
868
         * This is the compliment for {@link #addProxyPrivilege(String...)} to clean-up the context.
869
         * <p/>
870
         *
871
         * @param privileges privileges to remove in string form
872
         * @see #hasPrivilege(String)
873
         * @see #addProxyPrivilege(String...)
874
         * * @since 3.0.0, 2.8.2, 2.7.8
875
         */
876
        public static void removeProxyPrivilege(String... privileges) {
877
                getUserContext().removeProxyPrivilege(privileges);
1 ✔
878
        }
1 ✔
879

880
        /**
881
         * Used by {@link org.openmrs.aop.AuthorizationAdvice} to give access for unauthenticated users when
882
         * running initialization code with proxy privileges. See e.g.
883
         * {@link org.openmrs.event.outbox.tasks.OutboxTaskSchedulerInitializer#schedule()}.
884
         *
885
         * @return true if there are any proxy privileges
886
         * @since 2.8.10
887
         */
888
        public static boolean hasProxyPrivileges() {
889
                return getUserContext().hasProxyPrivileges();
1 ✔
890
        }
891

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

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

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

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

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

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

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

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

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

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

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

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

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

1057
                // find/set/check whether the current database version is compatible
1058
                checkForDatabaseUpdates(props);
×
1059

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

1064
                openSession();
×
1065
                clearSession();
×
1066

1067
                // add any privileges/roles that /must/ exist for openmrs to work
1068
                // correctly.
1069
                checkCoreDataset();
×
1070

1071
                getContextDAO().setupSearchIndex();
×
1072

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

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

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

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

1109
                startup(properties);
×
1110

1111
                // start the scheduled tasks
1112
                SchedulerUtil.startup(properties);
×
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");
×
1123
                try {
1124
                        // Needs to be shutdown before Hibernate
1125
                        SchedulerUtil.shutdown();
×
1126
                }
1127
                catch (Exception e) {
×
1128
                        log.warn("Error while shutting down scheduler service", e);
×
1129
                }
×
1130

1131
                log.debug("Shutting down the modules");
×
1132
                try {
1133
                        ModuleUtil.shutdown();
×
1134
                }
1135
                catch (Exception e) {
×
1136
                        log.warn("Error while shutting down module system", e);
×
1137
                }
×
1138

1139
                log.debug("Shutting down the context");
×
1140
                try {
1141
                        ContextDAO dao = null;
×
1142
                        try {
1143
                                dao = getContextDAO();
×
1144
                        }
1145
                        catch (APIException e) {
×
1146
                                // pass
1147
                        }
×
1148
                        if (dao != null) {
×
1149
                                dao.shutdown();
×
1150
                        }
1151
                }
1152
                catch (Exception e) {
×
1153
                        log.warn("Error while shutting down context dao", e);
×
1154
                }
×
1155
        }
×
1156

1157
        /**
1158
         * Used for getting services not in the previous get*Service() calls
1159
         *
1160
         * @param cls The Class of the service to get
1161
         * @return The requested Service
1162
         * <strong>Should</strong> return the same object when called multiple times for the same class
1163
         */
1164
        public static <T> T getService(Class<? extends T> cls) {
1165
                return getServiceContext().getService(cls);
1 ✔
1166
        }
1167

1168
        /**
1169
         * Adds an AOP advisor around the given Class <code>cls</code>
1170
         * <p>
1171
         * Advisors can wrap around a method and effect the method before or after
1172
         *
1173
         * @param cls
1174
         * @param advisor
1175
         */
1176
        public static void addAdvisor(Class cls, Advisor advisor) {
1177
                getServiceContext().addAdvisor(cls, advisor);
×
1178
        }
×
1179

1180
        /**
1181
         * Adds an AOP advice object around the given Class <code>cls</code>
1182
         * <p>
1183
         * Advice comes in the form of before or afterReturning methods
1184
         *
1185
         * @param cls
1186
         * @param advice
1187
         */
1188
        public static void addAdvice(Class cls, Advice advice) {
1189
                getServiceContext().addAdvice(cls, advice);
×
1190
        }
×
1191

1192
        /**
1193
         * Removes the given AOP advisor from Class <code>cls</code>
1194
         *
1195
         * @param cls
1196
         * @param advisor
1197
         */
1198
        public static void removeAdvisor(Class cls, Advisor advisor) {
1199
                getServiceContext().removeAdvisor(cls, advisor);
×
1200
        }
×
1201

1202
        /**
1203
         * Removes the given AOP advice object from Class <code>cls</code>
1204
         *
1205
         * @param cls
1206
         * @param advice
1207
         */
1208
        public static void removeAdvice(Class cls, Advice advice) {
1209
                getServiceContext().removeAdvice(cls, advice);
×
1210
        }
×
1211

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

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

1267
                // setting core global properties
1268
                try {
1269
                        Context.addProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
×
1270
                        Context.addProxyPrivilege(PrivilegeConstants.GET_GLOBAL_PROPERTIES);
×
1271
                        Set<String> currentPropNames = new HashSet<>();
×
1272
                        Map<String, GlobalProperty> propsMissingDescription = new HashMap<>();
×
1273
                        Map<String, GlobalProperty> propsMissingDatatype = new HashMap<>();
×
1274
                        for (GlobalProperty prop : Context.getAdministrationService().getAllGlobalProperties()) {
×
1275
                                currentPropNames.add(prop.getProperty().toUpperCase());
×
1276
                                if (prop.getDescription() == null) {
×
1277
                                        propsMissingDescription.put(prop.getProperty().toUpperCase(), prop);
×
1278
                                }
1279
                                if (prop.getDatatypeClassname() == null) {
×
1280
                                        propsMissingDatatype.put(prop.getProperty().toUpperCase(), prop);
×
1281
                                }
1282
                        }
×
1283

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

1318
                // setting default validation rule
1319
                AdministrationService as = Context.getAdministrationService();
×
1320
                Boolean disableValidation = Boolean.valueOf(as.getGlobalProperty(OpenmrsConstants.GP_DISABLE_VALIDATION, "false"));
×
1321
                ValidateUtil.setDisableValidation(disableValidation);
×
1322

1323
                PersonName.setFormat(Context.getAdministrationService().getGlobalProperty(
×
1324
                                OpenmrsConstants.GLOBAL_PROPERTY_LAYOUT_NAME_FORMAT));
1325

1326
                Allergen.setOtherNonCodedConceptUuid(Context.getAdministrationService().getGlobalProperty(
×
1327
                                OpenmrsConstants.GP_ALLERGEN_OTHER_NON_CODED_UUID));
1328
        }
×
1329

1330
        /**
1331
         * Runs any needed updates on the current database if the user has the allow_auto_update runtime
1332
         * property set to true. If not set to true, then {@link #updateDatabase(Map)} must be called.<br>
1333
         * <br>
1334
         * If an {@link InputRequiredException} is thrown, a call to {@link #updateDatabase(Map)} is
1335
         * required with a mapping from question prompt to user answer.
1336
         *
1337
         * @param props the runtime properties
1338
         * @throws InputRequiredException if the {@link DatabaseUpdater} has determined that updates
1339
         *             cannot continue without input from the user
1340
         * @see InputRequiredException#getRequiredInput() InputRequiredException#getRequiredInput() for
1341
         *      the required question/datatypes
1342
         */
1343
        private static void checkForDatabaseUpdates(Properties props) throws DatabaseUpdateException, InputRequiredException {
1344
                boolean updatesRequired;
1345
                try {
1346
                        updatesRequired = DatabaseUpdater.updatesRequired();
×
1347
                }
1348
                catch (Exception e) {
×
1349
                        throw new DatabaseUpdateException("Unable to check if database updates are required", e);
×
1350
                }
×
1351

1352
                // this must be the first thing run in case it changes database mappings
1353
                if (updatesRequired) {
×
1354
                        if (DatabaseUpdater.allowAutoUpdate()) {
×
1355
                                DatabaseUpdater.executeChangelog();
×
1356
                        } else {
1357
                                throw new DatabaseUpdateException(
×
1358
                                                "Database updates are required.  Call Context.updateDatabase() before .startup() to continue.");
1359
                        }
1360
                }
1361
        }
×
1362

1363
        /**
1364
         * Updates the openmrs database to the latest. This is only needed if using the API alone. <br>
1365
         * <br>
1366
         * The typical use-case would be: Try to {@link #startup(String, String, String, Properties)},
1367
         * if that fails, call this method to get the database up to speed.
1368
         *
1369
         * @param userInput (can be null) responses from the user about needed input
1370
         * @throws DatabaseUpdateException if an error occurred while updating
1371
         * @since 1.5
1372
         * @deprecated as of 2.4
1373
         * 
1374
         */
1375
        @Deprecated
1376
        public static void updateDatabase(Map<String, Object> userInput) throws DatabaseUpdateException {
1377
                throw new UnsupportedOperationException("As of 2.4, this method is not longer implemented");
×
1378
        }
1379

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

1392
        /**
1393
         * Gets the simple time format for the current user's locale. The format will be similar to
1394
         * hh:mm a
1395
         *
1396
         * @return SimpleDateFormat for the user's current locale
1397
         * @see org.openmrs.util.OpenmrsUtil#getTimeFormat(Locale)
1398
         * <strong>Should</strong> return a pattern with two h characters in it
1399
         */
1400
        public static SimpleDateFormat getTimeFormat() {
1401
                return OpenmrsUtil.getTimeFormat(getLocale());
×
1402
        }
1403

1404
        /**
1405
         * Gets the simple datetime format for the current user's locale. The format will be similar to
1406
         * mm/dd/yyyy hh:mm a
1407
         *
1408
         * @return SimpleDateFormat for the user's current locale
1409
         * @see org.openmrs.util.OpenmrsUtil#getDateTimeFormat(Locale)
1410
         * <strong>Should</strong> return a pattern with four y characters and two h characters in it
1411
         */
1412
        public static SimpleDateFormat getDateTimeFormat() {
1413
                return OpenmrsUtil.getDateTimeFormat(getLocale());
1 ✔
1414
        }
1415

1416
        /**
1417
         * @return true/false whether the service context is currently being refreshed
1418
         * @see org.openmrs.api.context.ServiceContext#isRefreshingContext()
1419
         */
1420
        public static boolean isRefreshingContext() {
1421
                return getServiceContext().isRefreshingContext();
1 ✔
1422
        }
1423

1424
        /**
1425
         * @since 1.5
1426
         * @see ServiceContext#getRegisteredComponents(Class)
1427
         */
1428
        public static <T> List<T> getRegisteredComponents(Class<T> type) {
1429
                return getServiceContext().getRegisteredComponents(type);
1 ✔
1430
        }
1431

1432
        /**
1433
         * @see ServiceContext#getRegisteredComponent(String, Class)
1434
         * @since 1.9.4
1435
         */
1436
        public static <T> T getRegisteredComponent(String beanName, Class<T> type) throws APIException {
1437
                return getServiceContext().getRegisteredComponent(beanName, type);
1 ✔
1438
        }
1439

1440
        /**
1441
         * @see ServiceContext#getModuleOpenmrsServices(String)
1442
         * @since 1.9
1443
         */
1444
        public static List<OpenmrsService> getModuleOpenmrsServices(String modulePackage) {
1445
                return getServiceContext().getModuleOpenmrsServices(modulePackage);
1 ✔
1446
        }
1447

1448
        /**
1449
         * @since 1.9
1450
         * @see ServiceContext#getVisitService()
1451
         */
1452
        public static VisitService getVisitService() {
1453
                return getServiceContext().getVisitService();
1 ✔
1454
        }
1455

1456
        /**
1457
         * @since 1.9
1458
         * @see ServiceContext#getProviderService()
1459
         */
1460
        public static ProviderService getProviderService() {
1461
                return getServiceContext().getProviderService();
1 ✔
1462
        }
1463

1464
        /**
1465
         * @since 1.9
1466
         * @see ServiceContext#getDatatypeService()
1467
         */
1468
        public static DatatypeService getDatatypeService() {
1469
                return getServiceContext().getDatatypeService();
1 ✔
1470
        }
1471

1472
        /**
1473
         * Add or replace a property in the config properties list
1474
         *
1475
         * @param key name of the property
1476
         * @param value value of the property
1477
         * @since 1.9
1478
         */
1479
        public static void addConfigProperty(Object key, Object value) {
1480
                configProperties.put(key, value);
×
1481
        }
×
1482

1483
        /**
1484
         * Remove a property from the list of config properties
1485
         *
1486
         * @param key name of the property
1487
         * @since 1.9
1488
         */
1489
        public static void removeConfigProperty(Object key) {
1490
                configProperties.remove(key);
×
1491
        }
×
1492

1493
        /**
1494
         * Get the config properties that have been added to this OpenMRS instance
1495
         *
1496
         * @return copy of the module properties
1497
         * @since 1.9
1498
         */
1499
        public static Properties getConfigProperties() {
1500
                Properties props = new Properties();
1 ✔
1501
                props.putAll(configProperties);
1 ✔
1502
                return props;
1 ✔
1503
        }
1504

1505
        /**
1506
         * Updates the search index. It is a blocking operation, which may take even a few minutes
1507
         * depending on the index size.
1508
         * <p>
1509
         * There is no need to call this method in normal usage since the index is automatically updated
1510
         * whenever DB transactions are committed.
1511
         * <p>
1512
         * The method is designated to be used in tests, which rollback transactions. Note that if the
1513
         * transaction is rolled back, changes to the index will not be reverted.
1514
         *
1515
         * @since 1.11
1516
         */
1517
        public static void updateSearchIndex() {
1518
                getContextDAO().updateSearchIndex();
×
1519
        }
×
1520

1521
        /**
1522
         * Updates the search index. It is an asynchronous operation.
1523
         * <p>
1524
         * There is no need to call this method in normal usage since the index is automatically updated
1525
         * whenever DB transactions are committed.
1526
         * <p>
1527
         *
1528
         * @return object representing the result of the started asynchronous operation
1529
         */
1530
        public static Future<?> updateSearchIndexAsync() {
1531
                return getContextDAO().updateSearchIndexAsync();
×
1532
        }
1533

1534
        /**
1535
         * It should be used <b>IN TESTS ONLY</b>. See {@link #updateSearchIndex(Class[])} for normal use.
1536
         * <p>
1537
         * Updates the search index for objects of the given type.
1538
         *
1539
         * @see #updateSearchIndex()
1540
         * @see #updateSearchIndex(Class[]) 
1541
         * @param type
1542
         * @since 1.11
1543
         */
1544
        public static void updateSearchIndexForType(Class<?> type) {
1545
                getContextDAO().updateSearchIndexForType(type);
1 ✔
1546
        }
1 ✔
1547

1548
        /**
1549
         * Updates the search index for objects of the given types using mass indexer.
1550
         * 
1551
         * @see #updateSearchIndex() 
1552
         * @param types
1553
         * @since 2.8.0
1554
         */
1555
        public static void updateSearchIndex(Class<?>... types) {
1556
                getContextDAO().updateSearchIndex(types);
×
1557
        }
×
1558

1559
        /**
1560
         * Updates the search index for the given object.
1561
         *
1562
         * @see #updateSearchIndex()
1563
         * @param object
1564
         * @since 1.11
1565
         */
1566
        public static void updateSearchIndexForObject(Object object) {
1567
                getContextDAO().updateSearchIndexForObject(object);
×
1568
        }
×
1569

1570
        /**
1571
         * @see org.openmrs.api.context.ServiceContext#setUseSystemClassLoader(boolean)
1572
         * @since 1.10
1573
         */
1574
        public static void setUseSystemClassLoader(boolean useSystemClassLoader) {
1575
                getServiceContext().setUseSystemClassLoader(useSystemClassLoader);
1 ✔
1576
        }
1 ✔
1577

1578
        /**
1579
         * @see org.openmrs.api.context.ServiceContext#isUseSystemClassLoader()
1580
         * @since 1.10
1581
         */
1582
        public static boolean isUseSystemClassLoader() {
1583
                return getServiceContext().isUseSystemClassLoader();
×
1584
        }
1585

1586
        /**
1587
         * @return a Connection from the OpenMRS database connection pool
1588
         * @since 2.5.7
1589
         */
1590
        public static Connection getDatabaseConnection() {
1591
                return getContextDAO().getDatabaseConnection();
×
1592
        }
1593
}
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