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

openmrs / openmrs-core / 16206128513

10 Jul 2025 09:12PM UTC coverage: 65.359% (+0.002%) from 65.357%
16206128513

push

github

web-flow
maven(deps): bump org.apache.commons:commons-lang3 from 3.17.0 to 3.18.0 (#5126)

Bumps org.apache.commons:commons-lang3 from 3.17.0 to 3.18.0.

---
updated-dependencies:
- dependency-name: org.apache.commons:commons-lang3
  dependency-version: 3.18.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

23547 of 36027 relevant lines covered (65.36%)

0.65 hits per line

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

2.92
/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
                                 */
248
                                XmlWebApplicationContext context = (XmlWebApplicationContext) createWebApplicationContext(servletContext);
×
249
                                configureAndRefreshWebApplicationContext(context, servletContext);
×
250
                                servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
×
251
                                
252
                                WebDaemon.startOpenmrs(event.getServletContext());
×
253
                        } else {
×
254
                                setupNeeded = true;
×
255
                        }
256
                        
257
                }
258
                catch (Exception e) {
×
259
                        setErrorAtStartup(e);
×
260
                        log.error(MarkerFactory.getMarker("FATAL"), "Failed to obtain JDBC connection", e);
×
261
                }
×
262
        }
×
263

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