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

openmrs / openmrs-core / 18188864354

02 Oct 2025 09:19AM UTC coverage: 64.889% (-0.04%) from 64.931%
18188864354

push

github

rkorytkowski
TRUNK-6436: Add logging to monitor startup performance

(cherry picked from commit ece973daa)

2 of 29 new or added lines in 4 files covered. (6.9%)

16 existing lines in 8 files now uncovered.

23423 of 36097 relevant lines covered (64.89%)

0.65 hits per line

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

2.81
/web/src/main/java/org/openmrs/web/Listener.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.web;
11

12
import org.apache.logging.log4j.LogManager;
13
import org.openmrs.api.context.Context;
14
import org.openmrs.logging.OpenmrsLoggingUtil;
15
import org.openmrs.module.MandatoryModuleException;
16
import org.openmrs.module.Module;
17
import org.openmrs.module.ModuleFactory;
18
import org.openmrs.module.ModuleMustStartException;
19
import org.openmrs.module.OpenmrsCoreModuleException;
20
import org.openmrs.module.web.OpenmrsJspServlet;
21
import org.openmrs.module.web.WebModuleUtil;
22
import org.openmrs.scheduler.SchedulerUtil;
23
import org.openmrs.util.DatabaseUpdateException;
24
import org.openmrs.util.DatabaseUpdater;
25
import org.openmrs.util.InputRequiredException;
26
import org.openmrs.util.MemoryLeakUtil;
27
import org.openmrs.util.OpenmrsClassLoader;
28
import org.openmrs.util.OpenmrsConstants;
29
import org.openmrs.util.OpenmrsUtil;
30
import org.openmrs.web.filter.initialization.DatabaseDetective;
31
import org.openmrs.web.filter.initialization.InitializationFilter;
32
import org.openmrs.web.filter.update.UpdateFilter;
33
import org.owasp.csrfguard.CsrfGuard;
34
import org.owasp.csrfguard.CsrfGuardServletContextListener;
35
import org.slf4j.LoggerFactory;
36
import org.slf4j.MarkerFactory;
37
import org.springframework.beans.factory.BeanCreationException;
38
import org.springframework.util.StringUtils;
39
import org.springframework.web.context.ContextLoader;
40
import org.springframework.web.context.WebApplicationContext;
41
import org.springframework.web.context.support.XmlWebApplicationContext;
42
import org.w3c.dom.Document;
43
import org.w3c.dom.Element;
44
import org.xml.sax.InputSource;
45

46
import javax.servlet.ServletContext;
47
import javax.servlet.ServletContextEvent;
48
import javax.servlet.ServletContextListener;
49
import javax.servlet.ServletException;
50
import javax.servlet.http.HttpSessionEvent;
51
import javax.servlet.http.HttpSessionListener;
52
import javax.xml.parsers.DocumentBuilder;
53
import javax.xml.parsers.DocumentBuilderFactory;
54
import java.io.File;
55
import java.io.FileInputStream;
56
import java.io.FileOutputStream;
57
import java.io.IOException;
58
import java.io.InputStream;
59
import java.io.OutputStreamWriter;
60
import java.io.StringReader;
61
import java.lang.reflect.Field;
62
import java.nio.charset.StandardCharsets;
63
import java.nio.file.Files;
64
import java.nio.file.Paths;
65
import java.sql.Driver;
66
import java.sql.DriverManager;
67
import java.util.ArrayList;
68
import java.util.Collection;
69
import java.util.Collections;
70
import java.util.Enumeration;
71
import java.util.HashMap;
72
import java.util.List;
73
import java.util.Map;
74
import java.util.Properties;
75

76
/**
77
 * Our Listener class performs the basic starting functions for our webapp. Basic needs for starting
78
 * the API: 1) Get the runtime properties 2) Start Spring 3) Start the OpenMRS APi (via
79
 * Context.startup) Basic startup needs specific to the web layer: 1) Do the web startup of the
80
 * modules 2) Copy the custom look/images/messages over into the web layer
81
 */
82
public final class Listener extends ContextLoader implements ServletContextListener, HttpSessionListener {
×
83
        
84
        private static final org.slf4j.Logger log = LoggerFactory.getLogger(Listener.class);
1✔
85
        
86
        private static boolean runtimePropertiesFound = false;
1✔
87
        
88
        private static Throwable errorAtStartup = null;
1✔
89
        
90
        private static boolean setupNeeded = false;
1✔
91
        
92
        private static boolean openmrsStarted = false;
1✔
93
        
94
        /**
95
         * Boolean flag set on webapp startup marking whether there is a runtime properties file or not.
96
         * If there is not, then the {@link InitializationFilter} takes over any openmrs url and
97
         * redirects to the {@link WebConstants#SETUP_PAGE_URL}
98
         *
99
         * @return true/false whether an openmrs runtime properties file is defined
100
         */
101
        public static boolean runtimePropertiesFound() {
102
                return runtimePropertiesFound;
×
103
        }
104
        
105
        /**
106
         * Boolean flag set by the {@link #contextInitialized(ServletContextEvent)} method if an error
107
         * occurred when trying to start up. The StartupErrorFilter displays the error to the admin
108
         *
109
         * @return true/false if an error occurred when starting up
110
         */
111
        public static boolean errorOccurredAtStartup() {
112
                return errorAtStartup != null;
1✔
113
        }
114
        
115
        /**
116
         * Boolean flag that tells if we need to run the database setup wizard.
117
         *
118
         * @return true if setup is needed, else false.
119
         */
120
        public static boolean isSetupNeeded() {
121
                return setupNeeded;
×
122
        }
123
        
124
        /**
125
         * Boolean flag that tells if OpenMRS is started and ready to handle requests via REST.
126
         *
127
         * @return true if started, else false.
128
         */
129
        public static boolean isOpenmrsStarted() {
130
                return openmrsStarted;
×
131
        }
132
        
133
        /**
134
         * Get the error thrown at startup
135
         *
136
         * @return get the error thrown at startup
137
         */
138
        public static Throwable getErrorAtStartup() {
139
                return errorAtStartup;
1✔
140
        }
141
        
142
        public static void setRuntimePropertiesFound(boolean runtimePropertiesFound) {
143
                Listener.runtimePropertiesFound = runtimePropertiesFound;
×
144
        }
×
145
        
146
        public static void setErrorAtStartup(Throwable errorAtStartup) {
147
                Listener.errorAtStartup = errorAtStartup;
×
148
        }
×
149

150
        /**
151
         * This gets all Spring components that implement HttpSessionListener 
152
         * and passes the HttpSession event to them whenever an HttpSession is created
153
         * @see HttpSessionListener#sessionCreated(HttpSessionEvent) 
154
         */
155
        @Override
156
        public void sessionCreated(HttpSessionEvent se) {
157
                for (HttpSessionListener listener : getHttpSessionListeners()) {
×
158
                        listener.sessionCreated(se);
×
159
                }
×
160
        }
×
161

162
        /**
163
         *         This gets all Spring components that implement HttpSessionListener 
164
         *         and passes the HttpSession event to them whenever an HttpSession is destroyed
165
         * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
166
         */
167
        @Override
168
        public void sessionDestroyed(HttpSessionEvent se) {
169
                for (HttpSessionListener listener : getHttpSessionListeners()) {
×
170
                        listener.sessionDestroyed(se);
×
171
                }
×
172
        }
×
173

174
        /**
175
         *         This retrieves all Spring components that implement HttpSessionListener
176
         *         If an exception is thrown trying to retrieve these beans from the Context, a warning is logged
177
         * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
178
         */
179
        private List<HttpSessionListener> getHttpSessionListeners() {
180
                List<HttpSessionListener> httpSessionListeners = Collections.emptyList();
×
181
                
182
                if (openmrsStarted) {
×
183
                        try {
184
                                httpSessionListeners = Context.getRegisteredComponents(HttpSessionListener.class);
×
185
                        }
186
                        catch (Exception e) {
×
187
                                log.warn("An error occurred trying to retrieve HttpSessionListener beans from the context", e);
×
188
                        }
×
189
                }
190
                
191
                return httpSessionListeners;
×
192
        }
193

194
        /**
195
         * This method is called when the servlet context is initialized(when the Web Application is
196
         * deployed). You can initialize servlet context related data here.
197
         *
198
         * @param event
199
         */
200
        @Override
201
        public void contextInitialized(ServletContextEvent event) {
202
                log.debug("Starting the OpenMRS webapp");
×
203
                
204
                try {
205
                        // validate the current JVM version
206
                        OpenmrsUtil.validateJavaVersion();
×
207
                        
208
                        ServletContext servletContext = event.getServletContext();
×
209
                        
210
                        // pulled from web.xml.
211
                        loadConstants(servletContext);
×
212
                        
213
                        // erase things in the dwr file
214
                        clearDWRFile(servletContext);
×
215
                        
216
                        setApplicationDataDirectory(servletContext);
×
217
                        
218
                        
219
                        // Try to get the runtime properties
220
                        Properties props = getRuntimeProperties();
×
221
                        if (props != null) {
×
222
                                // the user has defined a runtime properties file
223
                                setRuntimePropertiesFound(true);
×
224
                                // set props to the context so that they can be
225
                                // used during sessionFactory creation
226
                                Context.setRuntimeProperties(props);
×
227
                                
228
                                String appDataRuntimeProperty = props
×
229
                                        .getProperty(OpenmrsConstants.APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY, null);
×
230
                                if (StringUtils.hasLength(appDataRuntimeProperty)) {
×
231
                                        OpenmrsUtil.setApplicationDataDirectory(null);
×
232
                                }
233
                                log.warn("Using runtime properties file: {}",
×
234
                                         OpenmrsUtil.getRuntimePropertiesFilePathName(WebConstants.WEBAPP_NAME));
×
235
                        }
236

237
                        loadCsrfGuardProperties(servletContext);
×
238
                        
239
                        Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
×
240
                        
241
                        if (!setupNeeded()) {
×
242
                                // must be done after the runtime properties are
243
                                // found but before the database update is done
244
                                copyCustomizationIntoWebapp(servletContext, props);
×
245
                                
246
                                /**
247
                                 * This logic is from ContextLoader.initWebApplicationContext. Copied here instead
248
                                 * of calling that so that the context is not cached and hence not garbage collected
249
                                 */
NEW
250
                                log.debug("Refreshing WAC");
×
251
                                XmlWebApplicationContext context = (XmlWebApplicationContext) createWebApplicationContext(servletContext);
×
252
                                configureAndRefreshWebApplicationContext(context, servletContext);
×
253
                                servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
×
NEW
254
                                log.debug("Done refreshing WAC");
×
255
                                
256
                                WebDaemon.startOpenmrs(event.getServletContext());
×
257
                        } else {
×
258
                                setupNeeded = true;
×
259
                        }
260
                        
261
                }
262
                catch (Exception e) {
×
263
                        setErrorAtStartup(e);
×
264
                        log.error(MarkerFactory.getMarker("FATAL"), "Failed to obtain JDBC connection", e);
×
265
                }
×
266
        }
×
267

268
        private void loadCsrfGuardProperties(ServletContext servletContext) throws IOException {
269
                File csrfGuardFile = new File(OpenmrsUtil.getApplicationDataDirectory(), "csrfguard.properties");
×
270
                Properties csrfGuardProperties = new Properties();
×
271
                if (csrfGuardFile.exists()) {
×
272
                        try (InputStream csrfGuardInputStream = Files.newInputStream(csrfGuardFile.toPath())) {
×
273
                                csrfGuardProperties.load(csrfGuardInputStream);
×
274
                        }
275
                        catch (Exception e) {
×
276
                                log.error("Error loading csrfguard.properties file at " + csrfGuardFile.getAbsolutePath(), e);
×
277
                                throw e;
×
278
                        }
×
279
                }
280
                else {
281
                        String fileName = servletContext.getRealPath("/WEB-INF/csrfguard.properties");
×
282
                        try (InputStream csrfGuardInputStream = Files.newInputStream(Paths.get(fileName))) {
×
283
                                csrfGuardProperties.load(csrfGuardInputStream);
×
284
                        }
285
                        catch (Exception e) {
×
286
                                log.error("Error loading csrfguard.properties file at " +  fileName, e);
×
287
                                throw e;
×
288
                        }
×
289
                }
290
                
291
                Properties runtimeProperties = getRuntimeProperties();
×
292
                if (runtimeProperties != null) {
×
293
                        runtimeProperties.stringPropertyNames().forEach(property -> {
×
294
                                if (property.startsWith("org.owasp.csrfguard")) {
×
295
                                        csrfGuardProperties.setProperty(property, runtimeProperties.getProperty(property));
×
296
                                }
297
                        });        
×
298
                }
299
                
300
                CsrfGuard.load(csrfGuardProperties);
×
301
                
302
                try {
303
                        //CSRFGuard by default loads properties using CsrfGuardServletContextListener
304
                        //which sets the servlet context path to be used during variable substitution of
305
                        //%servletContext% in the properties file.
306
                        Field field = CsrfGuardServletContextListener.class.getDeclaredField("servletContext");
×
307
                        field.setAccessible(true);
×
308
                        field.set(null, servletContext.getContextPath());
×
309
                }
310
                catch (Exception ex) {
×
311
                        log.error("Failed to set the CSRFGuard servlet context", ex);
×
312
                }
×
313
        }
×
314
        
315
        /**
316
         * This method knows about all the filters that openmrs uses for setup. Currently those are the
317
         * {@link InitializationFilter} and the {@link UpdateFilter}. If either of these have to do
318
         * something, openmrs won't start in this Listener.
319
         *
320
         * @return true if one of the filters needs to take some action
321
         */
322
        private boolean setupNeeded() throws Exception {
323
                if (!runtimePropertiesFound) {
×
324
                        return true;
×
325
                }
326
                
327
                DatabaseDetective databaseDetective = new DatabaseDetective();
×
328
                if (databaseDetective.isDatabaseEmpty(OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME))) {
×
329
                        return true;
×
330
                }
331
                
332
                return DatabaseUpdater.updatesRequired() && !DatabaseUpdater.allowAutoUpdate();
×
333
        }
334
        
335
        /**
336
         * Do the work of starting openmrs.
337
         *
338
         * @param servletContext
339
         * @throws ServletException
340
         */
341
        public static void startOpenmrs(ServletContext servletContext) throws ServletException {
342
                openmrsStarted = false;
1✔
343
                // start openmrs
344
                try {
345
                        // load bundled modules that are packaged into the webapp
346
                        log.debug("Loading bundled modules");
1✔
UNCOV
347
                        Listener.loadBundledModules(servletContext);
×
348
                        
349
                        Context.startup(getRuntimeProperties());
×
350
                }
351
                catch (DatabaseUpdateException | InputRequiredException updateEx) {
×
352
                        throw new ServletException("Should not be here because updates were run previously", updateEx);
×
353
                }
354
                catch (MandatoryModuleException mandatoryModEx) {
×
355
                        throw new ServletException(mandatoryModEx);
×
356
                }
357
                catch (OpenmrsCoreModuleException coreModEx) {
×
358
                        // don't wrap this error in a ServletException because we want to deal with it differently
359
                        // in the StartupErrorFilter class
360
                        throw coreModEx;
×
361
                }
×
362
                
363
                // TODO catch openmrs errors here and drop the user back out to the setup screen
364
                
365
                try {
NEW
366
                        log.debug("Performing start of modules");
×
367
                        // web load modules
368
                        Listener.performWebStartOfModules(servletContext);
×
369
                        
370
                        // start the scheduled tasks
371
                        SchedulerUtil.startup(getRuntimeProperties());
×
372
                }
373
                catch (Exception t) {
×
374
                        Context.shutdown();
×
375
                        WebModuleUtil.shutdownModules(servletContext);
×
376
                        throw new ServletException(t);
×
377
                }
378
                finally {
379
                        Context.closeSession();
×
380
                }
381
                openmrsStarted = true;
×
382
        }
×
383
        
384
        /**
385
         * Load the openmrs constants with values from web.xml init parameters
386
         *
387
         * @param servletContext startup context (web.xml)
388
         */
389
        private void loadConstants(ServletContext servletContext) {
390
                WebConstants.BUILD_TIMESTAMP = servletContext.getInitParameter("build.timestamp");
×
391
                WebConstants.WEBAPP_NAME = getContextPath(servletContext);
×
392
                WebConstants.MODULE_REPOSITORY_URL = servletContext.getInitParameter("module.repository.url");
×
393
                
394
                if (!"openmrs".equalsIgnoreCase(WebConstants.WEBAPP_NAME)) {
×
395
                        OpenmrsConstants.KEY_OPENMRS_APPLICATION_DATA_DIRECTORY = WebConstants.WEBAPP_NAME
×
396
                                + "_APPLICATION_DATA_DIRECTORY";
397
                }
398
        }
×
399
        
400
        private void setApplicationDataDirectory(ServletContext servletContext) {
401
                // note: the below value will be overridden after reading the runtime properties if the
402
                // "application_data_directory" runtime property is set
403
                String appDataDir = servletContext.getInitParameter("application.data.directory");
×
404
                if (StringUtils.hasLength(appDataDir)) {
×
405
                        OpenmrsUtil.setApplicationDataDirectory(appDataDir);
×
406
                } else if (!"openmrs".equalsIgnoreCase(WebConstants.WEBAPP_NAME)) {
×
407
                        OpenmrsUtil.setApplicationDataDirectory(
×
408
                            Paths.get(OpenmrsUtil.getApplicationDataDirectory(), WebConstants.WEBAPP_NAME).toString());
×
409
                }
410
        }
×
411
        
412
        /**
413
         * @return current contextPath of this webapp without initial slash
414
         */
415
        private String getContextPath(ServletContext servletContext) {
416
                // Get the context path without the request.
417
                String contextPath = servletContext.getContextPath();
×
418
                
419
                // trim off initial slash if it exists
420
                if (contextPath.startsWith("/")) {
×
421
                        contextPath = contextPath.substring(1);
×
422
                }
423
                
424
                return contextPath;
×
425
        }
426
        
427
        /**
428
         * Convenience method to empty out the dwr-modules.xml file to fix any errors that might have
429
         * occurred in it when loading or unloading modules.
430
         *
431
         * @param servletContext
432
         */
433
        private void clearDWRFile(ServletContext servletContext) {
434
                File dwrFile = Paths.get(servletContext.getRealPath(""), "WEB-INF", "dwr-modules.xml").toFile();
×
435
                
436
                try {
437
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
×
438
                        DocumentBuilder db = dbf.newDocumentBuilder();
×
439
                        // When asked to resolve external entities (such as a DTD) we return an InputSource
440
                        // with no data at the end, causing the parser to ignore the DTD.
441
                        db.setEntityResolver((publicId, systemId) -> new InputSource(new StringReader("")));
×
442
                        Document doc = db.parse(dwrFile);
×
443
                        Element elem = doc.getDocumentElement();
×
444
                        elem.setTextContent("");
×
445
                        OpenmrsUtil.saveDocument(doc, dwrFile);
×
446
                }
447
                catch (Exception e) {
×
448
                        // got here because the dwr-modules.xml file is empty for some reason.  This might
449
                        // happen because the servlet container (i.e. tomcat) crashes when first loading this file
450
                        log.debug("Error clearing dwr-modules.xml", e);
×
451
                        dwrFile.delete();
×
452
                        OutputStreamWriter writer = null;
×
453
                        try {
454
                                writer = new OutputStreamWriter(new FileOutputStream(dwrFile), StandardCharsets.UTF_8);
×
455
                                writer.write(
×
456
                                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE dwr PUBLIC \"-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN\" \"http://directwebremoting.org/schema/dwr20.dtd\">\n<dwr></dwr>");
457
                        }
458
                        catch (IOException io) {
×
459
                                log.error(
×
460
                                    "Unable to clear out the " + dwrFile.getAbsolutePath() + " file.  Please redeploy the openmrs war file",
×
461
                                    io);
462
                        }
463
                        finally {
464
                                if (writer != null) {
×
465
                                        try {
466
                                                writer.close();
×
467
                                        }
468
                                        catch (IOException io) {
×
469
                                                log.warn("Couldn't close Writer: " + io);
×
470
                                        }
×
471
                                }
472
                        }
473
                }
×
474
        }
×
475
        
476
        /**
477
         * Copy the customization scripts over into the webapp
478
         *
479
         * @param servletContext
480
         */
481
        private void copyCustomizationIntoWebapp(ServletContext servletContext, Properties props) {
482
                String realPath = servletContext.getRealPath("");
×
483
                // TODO centralize map to WebConstants?
484
                Map<String, String> custom = new HashMap<>();
×
485
                custom.put("custom.template.dir", "/WEB-INF/template");
×
486
                custom.put("custom.index.jsp.file", "/WEB-INF/view/index.jsp");
×
487
                custom.put("custom.login.jsp.file", "/WEB-INF/view/login.jsp");
×
488
                custom.put("custom.patientDashboardForm.jsp.file", "/WEB-INF/view/patientDashboardForm.jsp");
×
489
                custom.put("custom.images.dir", "/images");
×
490
                custom.put("custom.style.css.file", "/style.css");
×
491
                custom.put("custom.messages", "/WEB-INF/custom_messages.properties");
×
492
                custom.put("custom.messages_fr", "/WEB-INF/custom_messages_fr.properties");
×
493
                custom.put("custom.messages_es", "/WEB-INF/custom_messages_es.properties");
×
494
                custom.put("custom.messages_de", "/WEB-INF/custom_messages_de.properties");
×
495
                
496
                for (Map.Entry<String, String> entry : custom.entrySet()) {
×
497
                        String prop = entry.getKey();
×
498
                        String webappPath = entry.getValue();
×
499
                        String userOverridePath = props.getProperty(prop);
×
500
                        // if they defined the variable
501
                        if (userOverridePath != null) {
×
502
                                String absolutePath = realPath + webappPath;
×
503
                                File file = new File(userOverridePath);
×
504
                                
505
                                // if they got the path correct
506
                                // also, if file does not start with a "." (hidden files, like SVN files)
507
                                if (file.exists() && !userOverridePath.startsWith(".")) {
×
508
                                        log.debug("Overriding file: " + absolutePath);
×
509
                                        log.debug("Overriding file with: " + userOverridePath);
×
510
                                        if (file.isDirectory()) {
×
511
                                                File[] files = file.listFiles();
×
512
                                                if (files != null) {
×
513
                                                        for (File f : files) {
×
514
                                                                userOverridePath = f.getAbsolutePath();
×
515
                                                                if (!f.getName().startsWith(".")) {
×
516
                                                                        String tmpAbsolutePath = absolutePath + "/" + f.getName();
×
517
                                                                        if (!copyFile(userOverridePath, tmpAbsolutePath)) {
×
518
                                                                                log.warn("Unable to copy file in folder defined by runtime property: " + prop);
×
519
                                                                                log.warn("Your source directory (or a file in it) '" + userOverridePath
×
520
                                                                                                        + " cannot be loaded or destination '" + tmpAbsolutePath + "' cannot be found");
521
                                                                        }
522
                                                                }
523
                                                        }
524
                                                }
525
                                        } else {
×
526
                                                // file is not a directory
527
                                                if (!copyFile(userOverridePath, absolutePath)) {
×
528
                                                        log.warn("Unable to copy file defined by runtime property: " + prop);
×
529
                                                        log.warn("Your source file '" + userOverridePath + " cannot be loaded or destination '"
×
530
                                                                + absolutePath + "' cannot be found");
531
                                                }
532
                                        }
533
                                }
534
                        }
535
                        
536
                }
×
537
        }
×
538
        
539
        /**
540
         * Copies file pointed to by <code>fromPath</code> to <code>toPath</code>
541
         *
542
         * @param fromPath
543
         * @param toPath
544
         * @return true/false whether the copy was a success
545
         */
546
        private boolean copyFile(String fromPath, String toPath) {
547
                FileInputStream inputStream = null;
×
548
                FileOutputStream outputStream = null;
×
549
                try {
550
                        inputStream = new FileInputStream(fromPath);
×
551
                        outputStream = new FileOutputStream(toPath);
×
552
                        OpenmrsUtil.copyFile(inputStream, outputStream);
×
553
                }
554
                catch (IOException io) {
×
555
                        return false;
×
556
                }
557
                finally {
558
                        try {
559
                                if (inputStream != null) {
×
560
                                        inputStream.close();
×
561
                                }
562
                        }
563
                        catch (IOException io) {
×
564
                                log.warn("Unable to close input stream", io);
×
565
                        }
×
566
                        try {
567
                                if (outputStream != null) {
×
568
                                        outputStream.close();
×
569
                                }
570
                        }
571
                        catch (IOException io) {
×
572
                                log.warn("Unable to close input stream", io);
×
573
                        }
×
574
                }
575
                return true;
×
576
        }
577
        
578
        /**
579
         * Load the pre-packaged modules from web/WEB-INF/bundledModules. <br>
580
         * <br>
581
         * This method assumes that the api startup() and WebModuleUtil.startup() will be called later
582
         * for modules that loaded here
583
         *
584
         * @param servletContext the current servlet context for the webapp
585
         */
586
        public static void loadBundledModules(ServletContext servletContext) {
587
                File folder = Paths.get(servletContext.getRealPath(""), "WEB-INF", "bundledModules").toFile();
×
588
                
589
                if (!folder.exists()) {
×
590
                        log.warn("Bundled module folder doesn't exist: " + folder.getAbsolutePath());
×
591
                        return;
×
592
                }
593
                if (!folder.isDirectory()) {
×
594
                        log.warn("Bundled module folder isn't really a directory: " + folder.getAbsolutePath());
×
595
                        return;
×
596
                }
597
                
598
                // loop over the modules and load the modules that we can
599
                File[] files = folder.listFiles();
×
600
                if (files != null) {
×
601
                        for (File f : files) {
×
602
                                if (!f.getName().startsWith(".")) { // ignore .svn folder and the like
×
603
                                        try {
604
                                                Module mod = ModuleFactory.loadModule(f);
×
605
                                                log.debug("Loaded bundled module: " + mod + " successfully");
×
606
                                        }
607
                                        catch (Exception e) {
×
608
                                                log.warn("Error while trying to load bundled module " + f.getName() + "", e);
×
609
                                        }
×
610
                                }
611
                        }
612
                }
613
        }
×
614
        
615
        /**
616
         * Called when the webapp is shut down properly Must call Context.shutdown() and then shutdown
617
         * all the web layers of the modules
618
         *
619
         * @see org.springframework.web.context.ContextLoaderListener#contextDestroyed(javax.servlet.ServletContextEvent)
620
         */
621
        @SuppressWarnings("squid:S1215")
622
        @Override
623
        public void contextDestroyed(ServletContextEvent event) {
624
                
625
                try {
626
                        openmrsStarted = false;
×
627
                        Context.openSession();
×
628
                        
629
                        Context.shutdown();
×
630
                        
631
                        WebModuleUtil.shutdownModules(event.getServletContext());
×
632
                        
633
                }
634
                catch (Exception e) {
×
635
                        // don't print the unhelpful "contextDAO is null" message
636
                        if (!"contextDAO is null".equals(e.getMessage())) {
×
637
                                // not using log.error here so it can be garbage collected
638
                                System.out.println("Listener.contextDestroyed: Error while shutting down openmrs: ");
×
639
                                log.error("Listener.contextDestroyed: Error while shutting down openmrs: ", e);
×
640
                        }
641
                }
642
                finally {
643
                        if ("true".equalsIgnoreCase(System.getProperty("FUNCTIONAL_TEST_MODE"))) {
×
644
                                //Delete the temporary file created for functional testing and shutdown the mysql daemon
645
                                String filename = WebConstants.WEBAPP_NAME + "-test-runtime.properties";
×
646
                                File file = new File(OpenmrsUtil.getApplicationDataDirectory(), filename);
×
647
                                System.out.println(filename + " delete=" + file.delete());
×
648
                                
649
                        }
650
                        // remove the user context that we set earlier
651
                        Context.closeSession();
×
652
                }
653
                try {
654
                        for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements();) {
×
655
                                Driver driver = e.nextElement();
×
656
                                ClassLoader classLoader = driver.getClass().getClassLoader();
×
657
                                // only unload drivers for this webapp
658
                                if (classLoader == null || classLoader == getClass().getClassLoader()) {
×
659
                                        DriverManager.deregisterDriver(driver);
×
660
                                } else {
661
                                        System.err.println("Didn't remove driver class: " + driver.getClass() + " with classloader of: "
×
662
                                                + driver.getClass().getClassLoader());
×
663
                                }
664
                        }
×
665
                }
666
                catch (Exception e) {
×
667
                        System.err.println("Listener.contextDestroyed: Failed to cleanup drivers in webapp");
×
668
                        log.error("Listener.contextDestroyed: Failed to cleanup drivers in webapp", e);
×
669
                }
×
670
                
671
                MemoryLeakUtil.shutdownMysqlCancellationTimer();
×
672
                
673
                OpenmrsClassLoader.onShutdown();
×
674
                
675
                LogManager.shutdown();
×
676
                
677
                // just to make things nice and clean.
678
                // Suppressing sonar issue squid:S1215
679
                System.gc();
×
680
                System.gc();
×
681
        }
×
682
        
683
        /**
684
         * Finds and loads the runtime properties
685
         *
686
         * @return Properties
687
         * @see OpenmrsUtil#getRuntimeProperties(String)
688
         */
689
        public static Properties getRuntimeProperties() {
690
                return OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
×
691
        }
692
        
693
        /**
694
         * Call WebModuleUtil.startModule on each started module
695
         *
696
         * @param servletContext
697
         * @throws ModuleMustStartException if the context cannot restart due to a
698
         *             {@link MandatoryModuleException} or {@link OpenmrsCoreModuleException}
699
         */
700
        public static void performWebStartOfModules(ServletContext servletContext) throws ModuleMustStartException, Exception {
701
                List<Module> startedModules = new ArrayList<>(ModuleFactory.getStartedModules());
×
702
                performWebStartOfModules(startedModules, servletContext);
×
703
        }
×
704
        
705
        public static void performWebStartOfModules(Collection<Module> startedModules, ServletContext servletContext)
706
                throws ModuleMustStartException, Exception {
707
                
708
                boolean someModuleNeedsARefresh = false;
×
709
                for (Module mod : startedModules) {
×
NEW
710
                        log.debug("Staring module: {}", mod.getModuleId());
×
711
                        try {
712
                                boolean thisModuleCausesRefresh = WebModuleUtil.startModule(mod, servletContext,
×
713
                                    /* delayContextRefresh */true);
714
                                someModuleNeedsARefresh = someModuleNeedsARefresh || thisModuleCausesRefresh;
×
715
                        }
716
                        catch (Exception e) {
×
717
                                mod.setStartupErrorMessage("Unable to start module", e);
×
718
                        }
×
719
                }
×
720
                
721
                if (someModuleNeedsARefresh) {
×
722
                        try {
NEW
723
                                log.debug("Refreshing WAC as required by some module");
×
UNCOV
724
                                WebModuleUtil.refreshWAC(servletContext, true, null);
×
NEW
725
                                log.debug("Done refreshing WAC as required by some module");
×
726
                        }
727
                        catch (ModuleMustStartException | BeanCreationException ex) {
×
728
                                // pass this up to the calling method so that openmrs loading stops
729
                                throw ex;
×
730
                        }
731
                        catch (Exception e) {
×
732
                                Throwable rootCause = getActualRootCause(e, true);
×
733
                                if (rootCause != null) {
×
734
                                        log.error(MarkerFactory.getMarker("FATAL"),
×
735
                                            "Unable to refresh the spring application context.  Root Cause was:", rootCause);
736
                                } else {
737
                                        log.error(MarkerFactory.getMarker("FATAL"),
×
738
                                            "nable to refresh the spring application context. Unloading all modules,  Error was:", e);
739
                                }
740
                                
741
                                try {
742
                                        WebModuleUtil.shutdownModules(servletContext);
×
743
                                        for (Module mod : ModuleFactory.getLoadedModules()) {// use loadedModules to avoid a concurrentmodificationexception
×
744
                                                if (!mod.isCoreModule() && !mod.isMandatory()) {
×
745
                                                        try {
746
                                                                ModuleFactory.stopModule(mod, true, true);
×
747
                                                        }
748
                                                        catch (Exception t3) {
×
749
                                                                // just keep going if we get an error shutting down.  was probably caused by the module
750
                                                                // that actually got us to this point!
751
                                                                log.trace("Unable to shutdown module:" + mod, t3);
×
752
                                                        }
×
753
                                                }
754
                                        }
×
NEW
755
                                        log.debug("Retrying refreshing WebApplicationContext");
×
UNCOV
756
                                        WebModuleUtil.refreshWAC(servletContext, true, null);
×
NEW
757
                                        log.debug("Done refreshing WebApplicationContext");
×
758
                                }
759
                                catch (MandatoryModuleException ex) {
×
760
                                        // pass this up to the calling method so that openmrs loading stops
761
                                        throw new MandatoryModuleException(ex.getModuleId(), "Got an error while starting a mandatory module: "
×
762
                                                + e.getMessage() + ". Check the server logs for more information");
×
763
                                }
764
                                catch (Exception t2) {
×
765
                                        // a mandatory or core module is causing spring to fail to start up.  We don't want those
766
                                        // stopped so we must report this error to the higher authorities
767
                                        log.warn("caught another error: ", t2);
×
768
                                        throw t2;
×
769
                                }
×
770
                        }
×
771
                }
772
                
773
                // because we delayed the refresh, we need to load+start all servlets and filters now
774
                // (this is to protect servlets/filters that depend on their module's spring xml config being available)
775
                for (Module mod : ModuleFactory.getStartedModulesInOrder()) {
×
NEW
776
                        log.debug("Loading servlets and filters for module: {}", mod.getModuleId());
×
777
                        WebModuleUtil.loadServlets(mod, servletContext);
×
778
                        WebModuleUtil.loadFilters(mod, servletContext);
×
779
                }
×
780
                servletContext.setAttribute(OpenmrsJspServlet.OPENMRS_TLD_SCAN_NEEDED, true);
×
781
        }
×
782
        
783
        /**
784
         * Convenience method that recursively attempts to pull the root case from a Throwable
785
         *
786
         * @param t the Throwable object
787
         * @param isOriginalError specifies if the passed in Throwable is the original Exception that
788
         *            was thrown
789
         * @return the root cause if any was found
790
         */
791
        private static Throwable getActualRootCause(Throwable t, boolean isOriginalError) {
792
                if (t.getCause() != null) {
×
793
                        return getActualRootCause(t.getCause(), false);
×
794
                }
795
                
796
                if (!isOriginalError) {
×
797
                        return t;
×
798
                }
799
                
800
                return null;
×
801
        }
802
        
803
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc