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

openmrs / openmrs-core / 18188744794

02 Oct 2025 09:14AM UTC coverage: 65.24% (-0.08%) from 65.318%
18188744794

push

github

rkorytkowski
TRUNK-6436: Add logging to monitor startup performance

(cherry picked from commit fb43aba18)

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

28 existing lines in 10 files now uncovered.

23611 of 36191 relevant lines covered (65.24%)

0.65 hits per line

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

3.44
/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.module.MandatoryModuleException;
15
import org.openmrs.module.Module;
16
import org.openmrs.module.ModuleFactory;
17
import org.openmrs.module.ModuleMustStartException;
18
import org.openmrs.module.web.OpenmrsJspServlet;
19
import org.openmrs.module.web.WebModuleUtil;
20
import org.openmrs.scheduler.SchedulerUtil;
21
import org.openmrs.util.DatabaseUpdateException;
22
import org.openmrs.util.DatabaseUpdater;
23
import org.openmrs.util.InputRequiredException;
24
import org.openmrs.util.MemoryLeakUtil;
25
import org.openmrs.util.OpenmrsClassLoader;
26
import org.openmrs.util.OpenmrsConstants;
27
import org.openmrs.util.OpenmrsUtil;
28
import org.openmrs.web.filter.initialization.DatabaseDetective;
29
import org.openmrs.web.filter.initialization.InitializationFilter;
30
import org.openmrs.web.filter.update.UpdateFilter;
31
import org.owasp.csrfguard.CsrfGuard;
32
import org.owasp.csrfguard.CsrfGuardServletContextListener;
33
import org.slf4j.LoggerFactory;
34
import org.slf4j.MarkerFactory;
35
import org.springframework.beans.factory.BeanCreationException;
36
import org.springframework.util.StringUtils;
37
import org.springframework.web.context.ContextLoader;
38
import org.springframework.web.context.WebApplicationContext;
39
import org.springframework.web.context.support.XmlWebApplicationContext;
40
import org.w3c.dom.Document;
41
import org.w3c.dom.Element;
42
import org.xml.sax.InputSource;
43

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

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

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

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

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

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

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

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