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

openmrs / openmrs-core / 38929403339

16 Oct 2026 04:06PM UTC coverage: 66.433% (-0.008%) from 66.441%
38929403339

push

github

ibacher
Complete move off Bamboo and fix release

25966 of 39086 relevant lines covered (66.43%)

0.66 hits per line

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

55.41
/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

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

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

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

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

164

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

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

599
                private Runnable r;
600

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

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

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

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

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

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

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

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

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

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

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

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