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

openmrs / openmrs-core / 15461553759

05 Jun 2025 07:52AM UTC coverage: 64.868% (-0.009%) from 64.877%
15461553759

push

github

rkorytkowski
TRUNK-6345 Fix testing framework to be used by modules for openmrs-core 2.4+

(cherry picked from commit 202eb8b65)

4 of 9 new or added lines in 2 files covered. (44.44%)

10 existing lines in 8 files now uncovered.

23340 of 35981 relevant lines covered (64.87%)

0.65 hits per line

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

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