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

openmrs / openmrs-core / 13506579996

24 Feb 2025 07:51PM UTC coverage: 64.839% (-0.002%) from 64.841%
13506579996

push

github

web-flow
TRUNK-6309: Fix logging issue at Listener.java (#4940)

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

2 existing lines in 2 files now uncovered.

23174 of 35741 relevant lines covered (64.84%)

0.65 hits per line

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

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

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

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

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

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

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

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

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

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