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

openmrs / openmrs-core / 44614234419

19 Nov 2026 08:59PM UTC coverage: 67.36% (+0.009%) from 67.351%
44614234419

Pull #6840

github

web-flow
Merge b6999a53d into cc20f662d
Pull Request #6840: TRUNK-6868: Allow the session timeout to be configured (2.9.x)

24 of 27 new or added lines in 2 files covered. (88.89%)

10 existing lines in 7 files now uncovered.

26928 of 39976 relevant lines covered (67.36%)

0.67 hits per line

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

64.59
/web/src/main/java/org/openmrs/web/filter/update/UpdateFilter.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.filter.update;
11

12
import liquibase.changelog.ChangeSet;
13
import liquibase.exception.LockException;
14
import org.apache.commons.collections.CollectionUtils;
15
import org.apache.commons.lang3.StringUtils;
16
import org.openmrs.liquibase.ChangeLogDetective;
17
import org.openmrs.util.DatabaseUpdateException;
18
import org.openmrs.util.DatabaseUpdater;
19
import org.openmrs.liquibase.ChangeSetExecutorCallback;
20
import org.openmrs.util.DatabaseUpdaterLiquibaseProvider;
21
import org.openmrs.util.InputRequiredException;
22
import org.openmrs.liquibase.ChangeLogVersionFinder;
23
import org.openmrs.util.OpenmrsThreadPoolHolder;
24
import org.openmrs.util.OpenmrsUtil;
25
import org.openmrs.util.RoleConstants;
26
import org.openmrs.util.Security;
27
import org.openmrs.web.Listener;
28
import org.openmrs.web.WebConstants;
29
import org.openmrs.web.WebDaemon;
30
import org.openmrs.web.filter.StartupFilter;
31
import org.openmrs.web.filter.initialization.InitializationFilter;
32
import org.openmrs.web.filter.util.CustomResourceLoader;
33
import org.openmrs.web.filter.util.ErrorMessageConstants;
34
import org.openmrs.web.filter.util.FilterUtil;
35
import org.slf4j.Logger;
36
import org.slf4j.LoggerFactory;
37
import org.springframework.web.context.ContextLoader;
38
import org.springframework.web.util.HtmlUtils;
39

40
import javax.servlet.FilterChain;
41
import javax.servlet.FilterConfig;
42
import javax.servlet.ServletContext;
43
import javax.servlet.ServletContextEvent;
44
import javax.servlet.ServletException;
45
import javax.servlet.ServletRequest;
46
import javax.servlet.ServletResponse;
47
import javax.servlet.http.HttpServletRequest;
48
import javax.servlet.http.HttpServletResponse;
49
import java.io.IOException;
50
import java.sql.Connection;
51
import java.sql.PreparedStatement;
52
import java.sql.ResultSet;
53
import java.sql.SQLException;
54
import java.util.ArrayList;
55
import java.util.Arrays;
56
import java.util.HashMap;
57
import java.util.LinkedList;
58
import java.util.List;
59
import java.util.Locale;
60
import java.util.Map;
61
import java.util.concurrent.Future;
62

63
/**
64
 * This is the second filter that is processed. It is only active when OpenMRS has some liquibase
65
 * updates that need to be run. If updates are needed, this filter/wizard asks for a super user to
66
 * authenticate and review the updates before continuing.
67
 */
68
public class UpdateFilter extends StartupFilter {
1 ✔
69
        
70
        protected final Logger log = LoggerFactory.getLogger(UpdateFilter.class);
1 ✔
71
        
72
        /**
73
         * The velocity macro page to redirect to if an error occurs or on initial startup
74
         */
75
        private static final String DEFAULT_PAGE = "maintenance.vm";
76
        
77
        /**
78
         * The page that lists off all the currently unexecuted changes
79
         */
80
        private static final String REVIEW_CHANGES = "reviewchanges.vm";
81
        
82
        private static final String PROGRESS_VM_AJAXREQUEST = "updateProgress.vm.ajaxRequest";
83
        
84
        /**
85
         * Session attribute set once a super user authenticates at the first step and checked on every
86
         * later step. Holding it on the session, rather than on the shared filter instance, stops one
87
         * user's successful authentication from being reused by another user's unauthenticated request.
88
         */
89
        private static final String AUTHENTICATED_SUCCESSFULLY = "updateFilter.authenticatedSuccessfully";
90

91
        /**
92
         * The model object behind this set of screens
93
         */
94
        private UpdateFilterModel updateFilterModel = null;
1 ✔
95
        
96
        /**
97
         * Variable set as soon as the update is done or verified to not be needed so that future calls
98
         * through this filter are a simple boolean check
99
         */
100
        private static volatile boolean updatesRequired = true;
1 ✔
101

102
        private UpdateFilterCompletion updateJob;
103
        
104
        /**
105
         * Variable set to true as soon as the update begins and set to false when the process ends. This
106
         * thread should only be accesses through the synchronized method.
107
         */
108
        private static boolean isDatabaseUpdateInProgress = false;
1 ✔
109
        
110
        /**
111
         * Variable set to true when the db lock is released. It's needed to prevent repeatedly releasing
112
         * this lock by other threads. This var should only be accessed through the synchronized method.
113
         */
114
        private static Boolean lockReleased = false;
1 ✔
115
        
116
        /**
117
         * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on GET requests
118
         *
119
         * @param httpRequest
120
         * @param httpResponse
121
         */
122
        @Override
123
        protected void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
124
                throws IOException, ServletException {
125
                
126
                Map<String, Object> referenceMap = new HashMap<>();
1 ✔
127
                checkLocaleAttributesForFirstTime(httpRequest);
1 ✔
128
                // we need to save current user language in references map since it will be used when template
129
                // will be rendered
130
                if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
1 ✔
131
                        referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
1 ✔
132
                            httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
1 ✔
133
                }
134
                // do step one of the wizard
135
                renderTemplate(DEFAULT_PAGE, referenceMap, httpResponse);
1 ✔
136
        }
1 ✔
137
        
138
        /**
139
         * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests
140
         */
141
        @Override
142
        protected synchronized void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
143
                throws IOException, ServletException {
144
                
145
                final String updJobStatus = "updateJobStarted";
1 ✔
146
                String page = httpRequest.getParameter("page");
1 ✔
147
                Map<String, Object> referenceMap = new HashMap<>();
1 ✔
148
                if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
1 ✔
149
                        referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
1 ✔
150
                            httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
1 ✔
151
                }
152
                
153
                // step one
154
                if (DEFAULT_PAGE.equals(page)) {
1 ✔
155
                        
156
                        String username = httpRequest.getParameter("username");
1 ✔
157
                        String password = httpRequest.getParameter("password");
1 ✔
158
                        
159
                        log.debug("Attempting to authenticate user: " + username);
1 ✔
160
                        if (authenticateAsSuperUser(username, password)) {
1 ✔
161
                                log.debug("Authentication successful.  Redirecting to 'reviewupdates' page.");
1 ✔
162
                                // mark this session as authenticated so later steps can verify it
163
                                httpRequest.getSession().setAttribute(AUTHENTICATED_SUCCESSFULLY, Boolean.TRUE);
1 ✔
164

165

166
                                //Set variable to tell us whether updates are already in progress
167
                                referenceMap.put("isDatabaseUpdateInProgress", isDatabaseUpdateInProgress);
1 ✔
168
                                
169
                                // if another super user has already launched database update
170
                                // allow current super user to review update progress
171
                                if (isDatabaseUpdateInProgress) {
1 ✔
172
                                        referenceMap.put(updJobStatus, true);
1 ✔
173
                                        httpResponse.setContentType("text/html");
1 ✔
174
                                        renderTemplate(REVIEW_CHANGES, referenceMap, httpResponse);
1 ✔
175
                                        return;
1 ✔
176
                                }
177
                                
178
                                // we will only get here if the db update is NOT running. 
179
                                // so if we find a db lock, we should release it because
180
                                // it was leftover from a previous db update crash
181
                                
182
                                if (!isLockReleased() && DatabaseUpdater.isLocked()) {
1 ✔
183
                                        // first we trying to release db lock if it exists
184
                                        try {
UNCOV
185
                                                DatabaseUpdater.releaseDatabaseLock();
×
UNCOV
186
                                                setLockReleased(true);
×
187
                                        }
188
                                        catch (LockException e) {
×
189
                                                // do nothing
UNCOV
190
                                        }
×
191
                                        // if lock was released successfully we need to get unrun changes
UNCOV
192
                                        updateFilterModel.updateChanges();
×
193
                                }
194
                                
195
                                // need to configure velocity tool box for using user's preferred locale
196
                                // so we should store it for further using when configuring velocity tool context
197
                                String localeParameter = FilterUtil.restoreLocale(username);
1 ✔
198
                                httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, localeParameter);
1 ✔
199
                                referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE, localeParameter);
1 ✔
200
                                
201
                                renderTemplate(REVIEW_CHANGES, referenceMap, httpResponse);
1 ✔
202
                        } else {
1 ✔
203
                                // if not authenticated, show main page again
204
                                try {
205
                                        log.debug("Sleeping for 3 seconds because of a bad username/password");
1 ✔
206
                                        Thread.sleep(3000);
1 ✔
207
                                }
208
                                catch (InterruptedException e) {
×
209
                                        log.error("Unable to sleep", e);
×
210
                                        throw new ServletException("Got interrupted while trying to sleep thread", e);
×
211
                                }
1 ✔
212
                                errors.put(ErrorMessageConstants.UPDATE_ERROR_UNABLE_AUTHENTICATE, null);
1 ✔
213
                                renderTemplate(DEFAULT_PAGE, referenceMap, httpResponse);
1 ✔
214
                        }
215
                }
1 ✔
216
                // step two of wizard in case if there were some warnings
217
                else if (REVIEW_CHANGES.equals(page)) {
1 ✔
218

219
                        if (!Boolean.TRUE.equals(httpRequest.getSession().getAttribute(AUTHENTICATED_SUCCESSFULLY))) {
1 ✔
220
                                // throw the user back to the main page because they are cheating
221
                                renderTemplate(DEFAULT_PAGE, referenceMap, httpResponse);
1 ✔
222
                                return;
1 ✔
223
                        }
224
                        
225
                        //if no one has run any required updates
226
                        if (!isDatabaseUpdateInProgress) {
1 ✔
227
                                isDatabaseUpdateInProgress = true;
1 ✔
228
                                updateJob = new UpdateFilterCompletion();
1 ✔
229
                                updateJob.start();
1 ✔
230
                                
231
                                // allows current user see progress of running update
232
                                // and also will hide the "Run Updates" button
233
                                
234
                                referenceMap.put(updJobStatus, true);
1 ✔
235
                        } else {
236
                                referenceMap.put("isDatabaseUpdateInProgress", true);
1 ✔
237
                                // as well we need to allow current user to
238
                                // see progress of already started updates
239
                                // and also will hide the "Run Updates" button
240
                                referenceMap.put(updJobStatus, true);
1 ✔
241
                        }
242
                        
243
                        renderTemplate(REVIEW_CHANGES, referenceMap, httpResponse);
1 ✔
244
                        
245
                } else if (PROGRESS_VM_AJAXREQUEST.equals(page)) {
1 ✔
246
                        
247
                        httpResponse.setContentType("text/json");
1 ✔
248
                        httpResponse.setHeader("Cache-Control", "no-cache");
1 ✔
249
                        Map<String, Object> result = new HashMap<>();
1 ✔
250
                        if (updateJob != null) {
1 ✔
251
                                result.put("hasErrors", updateJob.hasErrors());
1 ✔
252
                                if (updateJob.hasErrors()) {
1 ✔
253
                                        errors.putAll(updateJob.getErrors());
×
254
                                }
255
                                
256
                                if (updateJob.hasWarnings() && updateJob.getExecutingChangesetId() == null) {
1 ✔
257
                                        result.put("hasWarnings", updateJob.hasWarnings());
1 ✔
258
                                        StringBuilder sb = new StringBuilder("<ul>");
1 ✔
259
                                        
260
                                        for (String warning : updateJob.getUpdateWarnings()) {
1 ✔
261
                                                sb.append("<li>").append(HtmlUtils.htmlEscape(warning)).append("</li>");
1 ✔
262
                                        }
1 ✔
263
                                        
264
                                        sb.append("</ul>");
1 ✔
265
                                        result.put("updateWarnings", sb.toString());
1 ✔
266
                                        result.put("updateLogFile",
1 ✔
267
                                            StringUtils.replace(
1 ✔
268
                                                OpenmrsUtil.getApplicationDataDirectory() + DatabaseUpdater.DATABASE_UPDATES_LOG_FILE, "\\",
1 ✔
269
                                                "\\\\"));
270
                                        updateJob.hasUpdateWarnings = false;
1 ✔
271
                                        updateJob.getUpdateWarnings().clear();
1 ✔
272
                                }
273
                                
274
                                result.put("updatesRequired", updatesRequired());
1 ✔
275
                                result.put("message", updateJob.getMessage());
1 ✔
276
                                result.put("changesetIds", updateJob.getChangesetIds());
1 ✔
277
                                result.put("executingChangesetId", updateJob.getExecutingChangesetId());
1 ✔
278
                                
279
                                addLogLinesToResponse(result);
1 ✔
280
                        }
281
                        
282
                        String jsonText = toJSONString(result);
1 ✔
283
                        httpResponse.getWriter().write(jsonText);
1 ✔
284
                }
285
        }
1 ✔
286
        
287
        /**
288
         * It sets locale attribute for current session when user is making first GET http request to
289
         * application. It retrieves user locale from request object and checks if this locale is supported
290
         * by application. If not, it tries to load system default locale. If it's not specified it uses
291
         * {@link Locale#ENGLISH} by default
292
         *
293
         * @param httpRequest the http request object
294
         */
295
        public void checkLocaleAttributesForFirstTime(HttpServletRequest httpRequest) {
296
                Locale locale = httpRequest.getLocale();
1 ✔
297
                String systemDefaultLocale = FilterUtil.readSystemDefaultLocale(null);
1 ✔
298
                if (CustomResourceLoader.getInstance(httpRequest).getAvailablelocales().contains(locale)) {
1 ✔
299
                        httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, locale.toString());
1 ✔
300
                        log.info("Used client's locale " + locale.toString());
1 ✔
301
                } else if (StringUtils.isNotBlank(systemDefaultLocale)) {
×
302
                        httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, systemDefaultLocale);
×
303
                        log.info("Used system default locale " + systemDefaultLocale);
×
304
                } else {
305
                        httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, Locale.ENGLISH.toString());
×
306
                        log.info("Used default locale " + Locale.ENGLISH.toString());
×
307
                }
308
        }
1 ✔
309
        
310
        /**
311
         * Look in the users table for a user with this username and password and see if they have a role of
312
         * {@link RoleConstants#SUPERUSER}.
313
         *
314
         * @param usernameOrSystemId user entered username
315
         * @param password user entered password
316
         * @return true if this user has the super user role
317
         * @see #isSuperUser(Connection, Integer) <strong>Should</strong> return false if given invalid
318
         *      credentials <strong>Should</strong> return false if given user is not superuser
319
         *      <strong>Should</strong> return true if given user is superuser <strong>Should</strong> not
320
         *      authorize retired superusers <strong>Should</strong> authenticate with systemId
321
         */
322
        protected boolean authenticateAsSuperUser(String usernameOrSystemId, String password) throws ServletException {
323
                Connection connection = null;
1 ✔
324
                try {
325
                        connection = DatabaseUpdater.getConnection();
1 ✔
326
                        
327
                        String select = "select user_id, password, salt from users where (username = ? or system_id = ?) and retired = '0'";
1 ✔
328
                        PreparedStatement statement = null;
1 ✔
329
                        try {
330
                                statement = connection.prepareStatement(select);
1 ✔
331
                                statement.setString(1, usernameOrSystemId);
1 ✔
332
                                statement.setString(2, usernameOrSystemId);
1 ✔
333
                                
334
                                if (statement.execute()) {
1 ✔
335
                                        ResultSet results = null;
1 ✔
336
                                        try {
337
                                                results = statement.getResultSet();
1 ✔
338
                                                if (results.next()) {
1 ✔
339
                                                        Integer userId = results.getInt(1);
1 ✔
340
                                                        DatabaseUpdater.setAuthenticatedUserId(userId);
1 ✔
341
                                                        String storedPassword = results.getString(2);
1 ✔
342
                                                        String salt = results.getString(3);
1 ✔
343
                                                        return Security.checkPassword(storedPassword, password + salt) && isSuperUser(connection, userId);
1 ✔
344
                                                }
345
                                        }
346
                                        finally {
347
                                                if (results != null) {
1 ✔
348
                                                        try {
349
                                                                results.close();
1 ✔
350
                                                        }
351
                                                        catch (Exception resultsCloseEx) {
×
352
                                                                log.error("Failed to quietly close ResultSet", resultsCloseEx);
×
353
                                                        }
1 ✔
354
                                                }
355
                                        }
356
                                }
357
                        }
358
                        finally {
359
                                if (statement != null) {
1 ✔
360
                                        try {
361
                                                statement.close();
1 ✔
362
                                        }
363
                                        catch (Exception statementCloseEx) {
×
364
                                                log.error("Failed to quietly close Statement", statementCloseEx);
×
365
                                        }
1 ✔
366
                                }
367
                        }
368
                }
369
                catch (Exception connectionEx) {
×
370
                        log.error(
×
371
                            "Error while trying to authenticate as super user. Ignore this if you are upgrading from OpenMRS 1.5 to 1.6",
372
                            connectionEx);
373
                        
374
                        // we may not have upgraded User to have retired instead of voided yet, so if the query above fails, we try
375
                        // again the old way
376
                        if (connection != null) {
×
377
                                String select = "select user_id, password, salt from users where (username = ? or system_id = ?) and voided = '0'";
×
378
                                PreparedStatement statement = null;
×
379
                                try {
380
                                        statement = connection.prepareStatement(select);
×
381
                                        statement.setString(1, usernameOrSystemId);
×
382
                                        statement.setString(2, usernameOrSystemId);
×
383
                                        if (statement.execute()) {
×
384
                                                ResultSet results = null;
×
385
                                                try {
386
                                                        results = statement.getResultSet();
×
387
                                                        if (results.next()) {
×
388
                                                                Integer userId = results.getInt(1);
×
389
                                                                DatabaseUpdater.setAuthenticatedUserId(userId);
×
390
                                                                String storedPassword = results.getString(2);
×
391
                                                                String salt = results.getString(3);
×
392
                                                                return Security.checkPassword(storedPassword, password + salt)
×
393
                                                                        && isSuperUser(connection, userId);
×
394
                                                        }
395
                                                }
396
                                                finally {
397
                                                        if (results != null) {
×
398
                                                                try {
399
                                                                        results.close();
×
400
                                                                }
401
                                                                catch (Exception resultsCloseEx) {
×
402
                                                                        log.error("Failed to quietly close ResultSet", resultsCloseEx);
×
403
                                                                }
×
404
                                                        }
405
                                                }
406
                                        }
407
                                }
408
                                catch (Exception unhandeledEx) {
×
409
                                        log.error("Error while trying to authenticate as super user (voided version)", unhandeledEx);
×
410
                                }
411
                                finally {
412
                                        if (statement != null) {
×
413
                                                try {
414
                                                        statement.close();
×
415
                                                }
416
                                                catch (Exception statementCloseEx) {
×
417
                                                        log.error("Failed to quietly close Statement", statementCloseEx);
×
418
                                                }
×
419
                                        }
420
                                }
421
                        }
422
                }
423
                finally {
424
                        if (connection != null) {
1 ✔
425
                                try {
426
                                        connection.close();
1 ✔
427
                                }
428
                                catch (SQLException e) {
×
429
                                        log.debug("Error while closing the database", e);
×
430
                                }
1 ✔
431
                        }
432
                }
433
                
434
                return false;
1 ✔
435
        }
436
        
437
        /**
438
         * Checks the given user to see if they have been given the {@link RoleConstants#SUPERUSER}
439
         * role. This method does not look at child roles.
440
         *
441
         * @param connection the java sql connection to use
442
         * @param userId the user id to look at
443
         * @return true if the given user is a super user
444
         * @throws SQLException <strong>Should</strong> return true if given user has superuser role
445
         *             <strong>Should</strong> return false if given user does not have the super user role
446
         */
447
        protected boolean isSuperUser(Connection connection, Integer userId) throws SQLException {
448
                // the 'Administrator' part of this string is necessary because if the database was upgraded
449
                // by OpenMRS 1.6 alpha then System Developer was renamed to that. This has to be here so we
450
                // can roll back that change in 1.6 beta+
451
                String select = "select 1 from user_role where user_id = ? and (role = ? or role = 'Administrator')";
1 ✔
452
                PreparedStatement statement = connection.prepareStatement(select);
1 ✔
453
                statement.setInt(1, userId);
1 ✔
454
                statement.setString(2, RoleConstants.SUPERUSER);
1 ✔
455
                if (statement.execute()) {
1 ✔
456
                        ResultSet results = statement.getResultSet();
1 ✔
457
                        if (results.next()) {
1 ✔
458
                                return results.getInt(1) == 1;
1 ✔
459
                        }
460
                }
461
                
462
                return false;
1 ✔
463
        }
464
        
465
        /**
466
         * `` Do everything to get openmrs going.
467
         *
468
         * @param servletContext the servletContext from the filterconfig
469
         * @see Listener#startOpenmrs(ServletContext)
470
         */
471
        private void startOpenmrs(ServletContext servletContext) throws Exception {
472
                // start spring
473
                // after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext())
474
                // logic copied from org.springframework.web.context.ContextLoaderListener
475
                ContextLoader contextLoader = new ContextLoader();
×
476
                contextLoader.initWebApplicationContext(servletContext);
×
477
                
478
                try {
479
                        WebDaemon.startOpenmrs(servletContext);
×
480
                }
481
                catch (Exception exception) {
×
482
                        contextLoader.closeWebApplicationContext(servletContext);
×
483
                        throw exception;
×
484
                }
×
485
        }
×
486
        
487
        /**
488
         * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
489
         */
490
        @Override
491
        public void init(FilterConfig filterConfig) throws ServletException {
492
                super.init(filterConfig);
×
493
                
494
                log.debug("Initializing the UpdateFilter");
×
495
                
496
                if (!InitializationFilter.initializationRequired()
×
497
                        || (Listener.isSetupNeeded() && Listener.runtimePropertiesFound())) {
×
498
                        updateFilterModel = new UpdateFilterModel();
×
499
                        /*
500
                         * In this case, Listener#runtimePropertiesFound == true and InitializationFilter Wizard is skipped,
501
                         * so no need to reset Context's RuntimeProperties again, because of Listener.contextInitialized has set it.
502
                         */
503
                        try {
504
                                // this pings the DatabaseUpdater.updatesRequired which also
505
                                // considers a db lock to be a 'required update'
506
                                if (updateFilterModel.updateRequired) {
×
507
                                        setUpdatesRequired(true);
×
508
                                } else if (updateFilterModel.changes == null) {
×
509
                                        setUpdatesRequired(false);
×
510
                                } else {
511
                                        log.debug("Setting updates required to {} because of the size of unrun changes", (!updateFilterModel.changes.isEmpty()));
×
512
                                        setUpdatesRequired(!updateFilterModel.changes.isEmpty());
×
513
                                }
514
                        }
515
                        catch (Exception e) {
×
516
                                throw new ServletException("Unable to determine if updates are required", e);
×
517
                        }
×
518
                } else {
519
                        /*
520
                         * The initialization wizard will update the database to the latest version, so the user will not need any updates here.
521
                         * See end of InitializationFilter#InitializationCompletion
522
                         */
523
                        log.debug(
×
524
                            "Setting updates required to false because the user doesn't have any runtime properties yet or database is empty");
525
                        setUpdatesRequired(false);
×
526
                }
527
        }
×
528
        
529
        /**
530
         * @see org.openmrs.web.filter.StartupFilter#getUpdateFilterModel()
531
         */
532
        @Override
533
        protected Object getUpdateFilterModel() {
534
                // this object was initialized in the #init(FilterConfig) method
535
                return updateFilterModel;
×
536
        }
537
        
538
        /**
539
         * @see org.openmrs.web.filter.StartupFilter#skipFilter(HttpServletRequest)
540
         */
541
        @Override
542
        public boolean skipFilter(HttpServletRequest httpRequest) {
543
                if (updatesRequired()) {
1 ✔
544
                        return false;
1 ✔
545
                }
546
                // Once updates finish, only the progress page's final poll still needs this filter; without it
547
                // reviewchanges.vm never leaves the wizard. Check the servlet path first so other requests aren't parsed.
548
                if (!("/" + WebConstants.SETUP_PAGE_URL).equals(httpRequest.getServletPath())) {
1 ✔
549
                        return true;
1 ✔
550
                }
551
                return !PROGRESS_VM_AJAXREQUEST.equals(httpRequest.getParameter("page"));
1 ✔
552
        }
553
        
554
        /**
555
         * Used by the Listener to know if this filter wants to do its magic
556
         *
557
         * @return true if updates have been determined to be required
558
         * @see #init(FilterConfig)
559
         * @see Listener#isSetupNeeded()
560
         * @see Listener#contextInitialized(ServletContextEvent)
561
         */
562
        public static boolean updatesRequired() {
563
                return updatesRequired;
1 ✔
564
        }
565
        
566
        /**
567
         * @param updatesRequired the updatesRequired to set
568
         */
569
        public static void setUpdatesRequired(boolean updatesRequired) {
570
                UpdateFilter.updatesRequired = updatesRequired;
1 ✔
571
        }
1 ✔
572
        
573
        /**
574
         * Indicates if database lock was released. It will also used to prevent releasing existing lock of
575
         * liquibasechangeloglock table by another user, when he also tries to run database update when
576
         * another user is currently running it
577
         */
578
        public static Boolean isLockReleased() {
579
                return lockReleased;
1 ✔
580
        }
581
        
582
        public static synchronized void setLockReleased(Boolean lockReleased) {
583
                UpdateFilter.lockReleased = lockReleased;
1 ✔
584
        }
1 ✔
585
        
586
        /**
587
         * @see org.openmrs.web.filter.StartupFilter#getTemplatePrefix()
588
         */
589
        @Override
590
        protected String getTemplatePrefix() {
591
                return "org/openmrs/web/filter/update/";
×
592
        }
593
        
594
        /**
595
         * This class controls the final steps and is used by the ajax calls to know what updates have been
596
         * executed. TODO: Break this out into a separate (non-inner) class
597
         */
598
        private class UpdateFilterCompletion {
599

600
                private Runnable r;
601

602
                private String executingChangesetId = null;
1 ✔
603
                
604
                private List<String> changesetIds = new ArrayList<>();
1 ✔
605
                
606
                private Map<String, Object[]> errors = new HashMap<>();
1 ✔
607
                
608
                private String message = null;
1 ✔
609
                
610
                private boolean erroneous = false;
1 ✔
611
                
612
                private boolean hasUpdateWarnings = false;
1 ✔
613
                
614
                private List<String> updateWarnings = new LinkedList<>();
1 ✔
615
                
616
                public synchronized void reportError(String error, Object... params) {
617
                        Map<String, Object[]> reportedErrors = new HashMap<>();
×
618
                        reportedErrors.put(error, params);
×
619
                        reportErrors(reportedErrors);
×
620
                }
×
621
                
622
                public synchronized void reportErrors(Map<String, Object[]> errs) {
623
                        errors.putAll(errs);
1 ✔
624
                        erroneous = true;
1 ✔
625
                }
1 ✔
626
                
627
                public synchronized boolean hasErrors() {
628
                        return erroneous;
1 ✔
629
                }
630
                
631
                public synchronized Map<String, Object[]> getErrors() {
632
                        return errors;
×
633
                }
634
                
635
                /**
636
                 * Start the completion stage. This fires up the thread to do all the work.
637
                 */
638
                public void start() {
639
                        setUpdatesRequired(true);
1 ✔
640
                        OpenmrsThreadPoolHolder.threadExecutor.submit(r);
1 ✔
641
                }
1 ✔
642
                
643
                public synchronized void setMessage(String message) {
644
                        this.message = message;
1 ✔
645
                }
1 ✔
646
                
647
                public synchronized String getMessage() {
648
                        return message;
1 ✔
649
                }
650
                
651
                public synchronized void addChangesetId(String changesetid) {
652
                        this.changesetIds.add(changesetid);
1 ✔
653
                        this.executingChangesetId = changesetid;
1 ✔
654
                }
1 ✔
655
                
656
                public synchronized List<String> getChangesetIds() {
657
                        return changesetIds;
1 ✔
658
                }
659
                
660
                public synchronized String getExecutingChangesetId() {
661
                        return executingChangesetId;
1 ✔
662
                }
663
                
664
                /**
665
                 * @return the database updater Warnings
666
                 */
667
                public synchronized List<String> getUpdateWarnings() {
668
                        return updateWarnings;
1 ✔
669
                }
670
                
671
                public synchronized boolean hasWarnings() {
672
                        return hasUpdateWarnings;
1 ✔
673
                }
674
                
675
                public synchronized void reportWarnings(List<String> warnings) {
676
                        updateWarnings.addAll(warnings);
1 ✔
677
                        hasUpdateWarnings = true;
1 ✔
678
                }
1 ✔
679
                
680
                /**
681
                 * This class does all the work of creating the desired database, user, updates, etc
682
                 */
683
                public UpdateFilterCompletion() {
1 ✔
684
                         r = new Runnable() {
1 ✔
685
                                
686
                                /**
687
                                 * TODO split this up into multiple testable methods
688
                                 *
689
                                 * @see java.lang.Runnable#run()
690
                                 */
691
                                @Override
692
                                public void run() {
693
                                        try {
694
                                                /**
695
                                                 * A callback class that prints out info about liquibase changesets
696
                                                 */
697
                                                class PrintingChangeSetExecutorCallback implements ChangeSetExecutorCallback {
698
                                                        
699
                                                        private String message;
700
                                                        
701
                                                        public PrintingChangeSetExecutorCallback(String message) {
1 ✔
702
                                                                this.message = message;
1 ✔
703
                                                        }
1 ✔
704
                                                        
705
                                                        /**
706
                                                         * @see ChangeSetExecutorCallback#executing(liquibase.changelog.ChangeSet, int)
707
                                                         */
708
                                                        @Override
709
                                                        public void executing(ChangeSet changeSet, int numChangeSetsToRun) {
710
                                                                addChangesetId(changeSet.getId());
1 ✔
711
                                                                setMessage(message);
1 ✔
712
                                                        }
1 ✔
713
                                                        
714
                                                }
715

716
                                                
717
                                                try {
718
                                                        if (DatabaseUpdater.updatesRequired()) {
1 ✔
719
                                                                setMessage("Updating the database to the latest version");
1 ✔
720

721
                                                                ChangeLogDetective changeLogDetective = ChangeLogDetective.getInstance();
1 ✔
722
                                                                ChangeLogVersionFinder changeLogVersionFinder = new ChangeLogVersionFinder();
1 ✔
723

724
                                                                List<String> changelogs = new ArrayList<>();
1 ✔
725
                                                                List<String> warnings = new ArrayList<>();
1 ✔
726

727
                                                                String version = changeLogDetective.getInitialLiquibaseSnapshotVersion(DatabaseUpdater.CONTEXT,
1 ✔
728
                                                                        new DatabaseUpdaterLiquibaseProvider());
729

730
                                                                log.debug(
1 ✔
731
                                                                        "updating the database with versions of liquibase-update-to-latest files greater than '{}'",
732
                                                                        version);
733

734
                                                                changelogs.addAll(changeLogVersionFinder
1 ✔
735
                                                                        .getUpdateFileNames(changeLogVersionFinder.getUpdateVersionsGreaterThan(version)));
1 ✔
736

737
                                                                log.debug("found applicable Liquibase update change logs: {}", changelogs);
1 ✔
738

739
                                                                for (String changelog : changelogs) {
1 ✔
740
                                                                        log.debug("applying Liquibase changelog '{}'", changelog);
1 ✔
741

742
                                                                        List<String> currentWarnings = DatabaseUpdater.executeChangelog(changelog,
×
743
                                                                                new PrintingChangeSetExecutorCallback("executing Liquibase changelog :" + changelog));
744

745
                                                                        if (currentWarnings != null) {
×
746
                                                                                warnings.addAll(currentWarnings);
×
747
                                                                        }
748
                                                                }
×
749
                                                                executingChangesetId = null; // clear out the last changeset
×
750

751
                                                                if (CollectionUtils.isNotEmpty(warnings)) {
×
752
                                                                        reportWarnings(warnings);
×
753
                                                                }
754
                                                        }
755
                                                }
756
                                                catch (InputRequiredException inputRequired) {
×
757
                                                        // the user would be stepped through the questions returned here.
758
                                                        log.error("Not implemented", inputRequired);
×
759
                                                        updateFilterModel.updateChanges();
×
760
                                                        reportError(ErrorMessageConstants.UPDATE_ERROR_INPUT_NOT_IMPLEMENTED,
×
761
                                                            inputRequired.getMessage());
×
762
                                                        return;
×
763
                                                }
764
                                                catch (DatabaseUpdateException e) {
1 ✔
765
                                                        log.error("Unable to update the database", e);
1 ✔
766
                                                        Map<String, Object[]> databaseUpdateErrors = new HashMap<>();
1 ✔
767
                                                        databaseUpdateErrors.put(ErrorMessageConstants.UPDATE_ERROR_UNABLE, null);
1 ✔
768
                                                        for (String errorMessage : Arrays.asList(e.getMessage().split("\n"))) {
1 ✔
769
                                                                databaseUpdateErrors.put(errorMessage, null);
1 ✔
770
                                                        }
1 ✔
771
                                                        updateFilterModel.updateChanges();
1 ✔
772
                                                        reportErrors(databaseUpdateErrors);
1 ✔
773
                                                        return;
1 ✔
774
                                                }
775
                                                catch (Exception e) {
×
776
                                                        log.error("Unable to update the database", e);
×
777
                                                        reportError(ErrorMessageConstants.UPDATE_ERROR_UNABLE, e.getMessage());
×
778
                                                        return;
×
779
                                                }
×
780
                                                
781
                                                setMessage("Starting OpenMRS");
×
782
                                                try {
783
                                                        startOpenmrs(filterConfig.getServletContext());
×
784
                                                }
785
                                                catch (Exception e) {
×
786
                                                        log.error("Unable to complete the startup.", e);
×
787
                                                        reportError(ErrorMessageConstants.UPDATE_ERROR_COMPLETE_STARTUP, e.getMessage());
×
788
                                                }
×
789
                                        } finally {
790
                                                if (!hasErrors()) {
1 ✔
791
                                                        // set this so that the wizard isn't run again on next page load
792
                                                        setUpdatesRequired(false);
×
793
                                                }
794
                                                //reset to let other user's make requests after updates are run
795
                                                isDatabaseUpdateInProgress = false;
1 ✔
796
                                        }
797
                                }
×
798
                        };
799
                }
1 ✔
800
        }
801
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc