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

openmrs / openmrs-core / 24414883221

14 Apr 2026 06:01PM UTC coverage: 65.637% (-0.01%) from 65.65%
24414883221

push

github

ibacher
Fix admin_password_locked implementation

3 of 4 new or added lines in 1 file covered. (75.0%)

8 existing lines in 4 files now uncovered.

23953 of 36493 relevant lines covered (65.64%)

0.66 hits per line

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

7.1
/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.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.initialization;
11

12
import java.io.File;
13
import java.io.FileInputStream;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.io.InputStream;
17
import java.io.PrintWriter;
18
import java.net.URI;
19
import java.nio.charset.StandardCharsets;
20
import java.sql.Connection;
21
import java.sql.DriverManager;
22
import java.sql.SQLException;
23
import java.sql.Statement;
24
import java.util.ArrayList;
25
import java.util.Arrays;
26
import java.util.Base64;
27
import java.util.Base64.Encoder;
28
import java.util.HashMap;
29
import java.util.HashSet;
30
import java.util.List;
31
import java.util.Locale;
32
import java.util.Map;
33
import java.util.Properties;
34
import java.util.Random;
35
import java.util.Set;
36
import java.util.concurrent.ExecutionException;
37
import java.util.concurrent.Future;
38
import java.util.zip.ZipInputStream;
39
import javax.servlet.FilterChain;
40
import javax.servlet.FilterConfig;
41
import javax.servlet.ServletException;
42
import javax.servlet.ServletRequest;
43
import javax.servlet.ServletResponse;
44
import javax.servlet.http.HttpServletRequest;
45
import javax.servlet.http.HttpServletResponse;
46

47
import liquibase.changelog.ChangeSet;
48
import org.apache.commons.io.IOUtils;
49
import org.openmrs.ImplementationId;
50
import org.openmrs.api.APIAuthenticationException;
51
import org.openmrs.api.PasswordException;
52
import org.openmrs.api.UserService;
53
import org.openmrs.api.context.Context;
54
import org.openmrs.api.context.ContextAuthenticationException;
55
import org.openmrs.api.context.UsernamePasswordCredentials;
56
import org.openmrs.liquibase.ChangeLogDetective;
57
import org.openmrs.liquibase.ChangeLogVersionFinder;
58
import org.openmrs.module.MandatoryModuleException;
59
import org.openmrs.module.web.WebModuleUtil;
60
import org.openmrs.util.DatabaseUpdateException;
61
import org.openmrs.util.DatabaseUpdater;
62
import org.openmrs.liquibase.ChangeSetExecutorCallback;
63
import org.openmrs.util.DatabaseUpdaterLiquibaseProvider;
64
import org.openmrs.util.DatabaseUtil;
65
import org.openmrs.util.InputRequiredException;
66
import org.openmrs.util.OpenmrsConstants;
67
import org.openmrs.util.OpenmrsThreadPoolHolder;
68
import org.openmrs.util.OpenmrsUtil;
69
import org.openmrs.util.PrivilegeConstants;
70
import org.openmrs.util.Security;
71
import org.openmrs.web.Listener;
72
import org.openmrs.web.WebConstants;
73
import org.openmrs.web.WebDaemon;
74
import org.openmrs.web.filter.StartupFilter;
75
import org.openmrs.web.filter.update.UpdateFilter;
76
import org.openmrs.web.filter.util.CustomResourceLoader;
77
import org.openmrs.web.filter.util.ErrorMessageConstants;
78
import org.openmrs.web.filter.util.FilterUtil;
79
import org.openmrs.web.filter.util.SessionModelUtils;
80
import org.slf4j.LoggerFactory;
81
import org.springframework.util.StringUtils;
82
import org.springframework.web.context.ContextLoader;
83

84
import static org.openmrs.util.PrivilegeConstants.GET_GLOBAL_PROPERTIES;
85
import static org.openmrs.web.filter.initialization.InitializationWizardModel.DEFAULT_MYSQL_CONNECTION;
86
import static org.openmrs.web.filter.initialization.InitializationWizardModel.DEFAULT_POSTGRESQL_CONNECTION;
87

88
/**
89
 * This is the first filter that is processed. It is only active when starting OpenMRS for the very
90
 * first time. It will redirect all requests to the {@link WebConstants#SETUP_PAGE_URL} if the
91
 * {@link Listener} wasn't able to find any runtime properties
92
 */
93
public class InitializationFilter extends StartupFilter {
1✔
94
        
95
        private static final org.slf4j.Logger log = LoggerFactory.getLogger(InitializationFilter.class);
1✔
96
        
97
        private static final String DATABASE_POSTGRESQL = "postgresql";
98
        
99
        private static final String DATABASE_MYSQL = "mysql";
100
        
101
        private static final String DATABASE_SQLSERVER = "sqlserver";
102
        
103
        private static final String DATABASE_H2 = "h2";
104

105
        private static final String DATABASE_MARIADB = "mariadb";
106
        
107
        /**
108
         * The very first page of wizard, that asks user for select his preferred language
109
         */
110
        private static final String CHOOSE_LANG = "chooselang.vm";
111
        
112
        /**
113
         * The second page of the wizard that asks for simple or advanced installation.
114
         */
115
        private static final String INSTALL_METHOD = "installmethod.vm";
116
        
117
        /**
118
         * The simple installation setup page.
119
         */
120
        private static final String SIMPLE_SETUP = "simplesetup.vm";
121
        
122
        /**
123
         * The first page of the advanced installation of the wizard that asks for a current or past
124
         * database
125
         */
126
        private static final String DATABASE_SETUP = "databasesetup.vm";
127
        
128
        /**
129
         * The page from where the user specifies the url to a remote system, username and password
130
         */
131
        private static final String TESTING_REMOTE_DETAILS_SETUP = "remotedetails.vm";
132
        
133
        /**
134
         * The velocity macro page to redirect to if an error occurs or on initial startup
135
         */
136
        private static final String DEFAULT_PAGE = CHOOSE_LANG;
137
        
138
        /**
139
         * This page asks whether database tables/demo data should be inserted and what the
140
         * username/password that will be put into the runtime properties is
141
         */
142
        private static final String DATABASE_TABLES_AND_USER = "databasetablesanduser.vm";
143
        
144
        /**
145
         * This page lets the user define the admin user
146
         */
147
        private static final String ADMIN_USER_SETUP = "adminusersetup.vm";
148
        
149
        /**
150
         * This page lets the user pick an implementation id
151
         */
152
        private static final String IMPLEMENTATION_ID_SETUP = "implementationidsetup.vm";
153
        
154
        /**
155
         * This page asks for settings that will be put into the runtime properties files
156
         */
157
        private static final String OTHER_RUNTIME_PROPS = "otherruntimeproperties.vm";
158
        
159
        /**
160
         * A page that tells the user that everything is collected and will now be processed
161
         */
162
        private static final String WIZARD_COMPLETE = "wizardcomplete.vm";
163
        
164
        /**
165
         * A page that lists off what is happening while it is going on. This page has ajax that callst he
166
         * {@value #PROGRESS_VM_AJAXREQUEST} page
167
         */
168
        private static final String PROGRESS_VM = "progress.vm";
169
        
170
        /**
171
         * This url is called by javascript to get the status of the install
172
         */
173
        private static final String PROGRESS_VM_AJAXREQUEST = "progress.vm.ajaxRequest";
174
        
175
        public static final String RELEASE_TESTING_MODULE_PATH = "/module/releasetestinghelper/";
176
        
177
        /**
178
         * The model object that holds all the properties that the rendered templates use. All attributes on
179
         * this object are made available to all templates via reflection in the
180
         * {@link org.openmrs.web.filter.StartupFilter#renderTemplate(String, Map, HttpServletResponse)} method.
181
         */
182
        protected InitializationWizardModel wizardModel = null;
1✔
183
        
184
        private InitializationCompletion initJob;
185
        
186
        /**
187
         * Variable set to true as soon as the installation begins and set to false when the process ends
188
         * This thread should only be accesses through the synchronized method.
189
         */
190
        private static boolean isInstallationStarted = false;
1✔
191
        
192
        // the actual driver loaded by the DatabaseUpdater class
193
        private String loadedDriverString;
194

195
        private static final Set<String> NON_NORMALIZED_KEYS = new HashSet<>(Arrays.asList(
1✔
196
                "INSTALL_METHOD", "DATABASE_NAME", "HAS_CURRENT_OPENMRS_DATABASE", "CREATE_DATABASE_USER",
197
                "CREATE_TABLES", "ADD_DEMO_DATA", "MODULE_WEB_ADMIN", "AUTO_UPDATE_DATABASE", "ADMIN_USER_PASSWORD"));
198
        /**
199
         * Variable set at the end of the wizard when spring is being restarted
200
         */
201
        private static boolean initializationComplete = false;
1✔
202
        
203
        protected synchronized void setInitializationComplete(boolean initializationComplete) {
204
                InitializationFilter.initializationComplete = initializationComplete;
×
205
        }
×
206
        
207
        /**
208
         * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on GET requests
209
         *
210
         * @param httpRequest
211
         * @param httpResponse
212
         */
213
        @Override
214
        protected void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
215
                throws IOException {
216
                log.debug("Entered initialization filter");
×
217
                
218
                SessionModelUtils.loadFromSession(httpRequest.getSession(), wizardModel);
×
219
                initializeWizardFromResolvedPropertiesIfPresent();
×
220
                
221
                // we need to save current user language in references map since it will be used when template
222
                // will be rendered
223
                if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) == null) {
×
224
                        checkLocaleAttributesForFirstTime(httpRequest);
×
225
                }
226
                
227
                Map<String, Object> referenceMap = new HashMap<>();
×
228
                String page = httpRequest.getParameter("page");
×
229
                
230
                referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
231
                
232
                httpResponse.setHeader("Cache-Control", "no-cache");
×
233
                
234
                // if any body has already started installation and this is not an ajax request for the progress
235
                if (isInstallationStarted() && !PROGRESS_VM_AJAXREQUEST.equals(page)) {
×
236
                        referenceMap.put("isInstallationStarted", true);
×
237
                        httpResponse.setContentType("text/html");
×
238
                        renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
×
239
                } else if (PROGRESS_VM_AJAXREQUEST.equals(page)) {
×
240
                        httpResponse.setContentType("text/json");
×
241
                        Map<String, Object> result = new HashMap<>();
×
242
                        if (initJob != null) {
×
243
                                result.put("hasErrors", initJob.hasErrors());
×
244
                                if (initJob.hasErrors()) {
×
245
                                        result.put("errorPage", initJob.getErrorPage());
×
246
                                        errors.putAll(initJob.getErrors());
×
247
                                }
248
                                
249
                                result.put("initializationComplete", isInitializationComplete());
×
250
                                result.put("message", initJob.getMessage());
×
251
                                result.put("actionCounter", initJob.getStepsComplete());
×
252
                                if (!isInitializationComplete()) {
×
253
                                        result.put("executingTask", initJob.getExecutingTask());
×
254
                                        result.put("executedTasks", initJob.getExecutedTasks());
×
255
                                        result.put("completedPercentage", initJob.getCompletedPercentage());
×
256
                                }
257

258
                                SessionModelUtils.clearWizardSessionAttributes(httpRequest.getSession());
×
259
                                addLogLinesToResponse(result);
×
260
                        }
261
                        
262
                        PrintWriter writer = httpResponse.getWriter();
×
263
                        writer.write(toJSONString(result));
×
264
                        writer.close();
×
265
                } else if (InitializationWizardModel.INSTALL_METHOD_AUTO.equals(wizardModel.installMethod)
×
266
                        || httpRequest.getServletPath().equals("/" + AUTO_RUN_OPENMRS)) {
×
267
                        autoRunOpenMRS(httpRequest);
×
268
                        referenceMap.put("isInstallationStarted", true);
×
269
                        httpResponse.setContentType("text/html");
×
270
                        renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
×
271
                } else if (page == null) {
×
272
                        httpResponse.setContentType("text/html");// if any body has already started installation
×
273
                        
274
                        //If someone came straight here without setting the hidden page input,
275
                        // then we need to clear out all the passwords
276
                        clearPasswords();
×
277
                        
278
                        renderTemplate(DEFAULT_PAGE, referenceMap, httpResponse);
×
279
                } else if (INSTALL_METHOD.equals(page)) {
×
280
                        // get props and render the second page
281
                        File runtimeProperties = getRuntimePropertiesFile();
×
282
                        
283
                        if (!runtimeProperties.exists()) {
×
284
                                try {
285
                                        runtimeProperties.createNewFile();
×
286
                                        // reset the error objects in case of refresh
287
                                        wizardModel.canCreate = true;
×
288
                                        wizardModel.cannotCreateErrorMessage = "";
×
289
                                }
290
                                catch (IOException io) {
×
291
                                        wizardModel.canCreate = false;
×
292
                                        wizardModel.cannotCreateErrorMessage = io.getMessage();
×
293
                                }
×
294
                                
295
                                // check this before deleting the file again
296
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
297
                                
298
                                // delete the file again after testing the create/write
299
                                // so that if the user stops the webapp before finishing
300
                                // this wizard, they can still get back into it
301
                                runtimeProperties.delete();
×
302
                                
303
                        } else {
304
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
305
                                
306
                                wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
×
307
                                        wizardModel.databaseConnection);
308
                                
309
                                wizardModel.currentDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
×
310
                                        wizardModel.currentDatabaseUsername);
311
                                
312
                                wizardModel.currentDatabasePassword = Context.getRuntimeProperties().getProperty("connection.password",
×
313
                                        wizardModel.currentDatabasePassword);
314
                        }
315
                        
316
                        wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
×
317
                        
318
                        // do step one of the wizard
319
                        httpResponse.setContentType("text/html");
×
320
                        renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
321
                }
322
        }
×
323

324
        /**
325
         * Initializes the setup wizard model by resolving configuration properties from multiple sources.
326
         * <p>
327
         * Properties are loaded and prioritized from system properties, environment variables (normalized),
328
         * and the installation script file. Resolved values are then applied to the corresponding fields
329
         * of the {@link InitializationWizardModel}.
330
         */
331
        protected void initializeWizardFromResolvedPropertiesIfPresent() {
332
                Properties script = new Properties();
1✔
333

334
                Properties installScript = getInstallationScript();
1✔
335
                script.putAll(installScript);
1✔
336

337
                getEnvironmentVariables().forEach((key, value) -> {
1✔
338
                        String normalizedKey = normalizeEnvVariableKey(key);
1✔
339
                        script.setProperty(normalizedKey, value);
1✔
340
                });
1✔
341

342
                System.getProperties().forEach((key, value) -> script.setProperty(key.toString(), value.toString()));
1✔
343

344
                if (log.isDebugEnabled()) {
1✔
345
                        for (String key : script.stringPropertyNames()) {
×
346
                                String value = script.getProperty(key);
×
347
                                log.debug("{} = {}", key, key.toLowerCase().contains("password") ? "*******" : value);
×
348
                        }
×
349
                }
350
                
351
                if (!script.isEmpty()) {
1✔
352
                        wizardModel.installMethod = script.getProperty("install_method", wizardModel.installMethod);
1✔
353
                        
354
                        wizardModel.databaseConnection = script.getProperty("connection.url", wizardModel.databaseConnection);
1✔
355
                        wizardModel.databaseDriver = script.getProperty("connection.driver_class", wizardModel.databaseDriver);
1✔
356
                        wizardModel.databaseName = script.getProperty("database_name", wizardModel.databaseName);
1✔
357
                        wizardModel.currentDatabaseUsername = script.getProperty("connection.username",
1✔
358
                                wizardModel.currentDatabaseUsername);
359
                        wizardModel.currentDatabasePassword = script.getProperty("connection.password",
1✔
360
                                wizardModel.currentDatabasePassword);
361
                        
362
                        String hasCurrentOpenmrsDatabase = script.getProperty("has_current_openmrs_database");
1✔
363
                        if (hasCurrentOpenmrsDatabase != null) {
1✔
364
                                wizardModel.hasCurrentOpenmrsDatabase = Boolean.parseBoolean(hasCurrentOpenmrsDatabase);
1✔
365
                        }
366
                        wizardModel.createDatabaseUsername = script.getProperty("create_database_username",
1✔
367
                                wizardModel.createDatabaseUsername);
368
                        wizardModel.createDatabasePassword = script.getProperty("create_database_password",
1✔
369
                                wizardModel.createDatabasePassword);
370
                        
371
                        String createTables = script.getProperty("create_tables");
1✔
372
                        if (createTables != null) {
1✔
373
                                wizardModel.createTables = Boolean.parseBoolean(createTables);
1✔
374
                        }
375
                        
376
                        String createDatabaseUser = script.getProperty("create_database_user");
1✔
377
                        if (createDatabaseUser != null) {
1✔
378
                                wizardModel.createDatabaseUser = Boolean.parseBoolean(createDatabaseUser);
1✔
379
                        }
380
                        wizardModel.createUserUsername = script.getProperty("create_user_username", wizardModel.createUserUsername);
1✔
381
                        wizardModel.createUserPassword = script.getProperty("create_user_password", wizardModel.createUserPassword);
1✔
382
                        
383
                        String moduleWebAdmin = script.getProperty("module_web_admin");
1✔
384
                        if (moduleWebAdmin != null) {
1✔
385
                                wizardModel.moduleWebAdmin = Boolean.parseBoolean(moduleWebAdmin);
1✔
386
                        }
387
                        
388
                        String autoUpdateDatabase = script.getProperty("auto_update_database");
1✔
389
                        if (autoUpdateDatabase != null) {
1✔
390
                                wizardModel.autoUpdateDatabase = Boolean.parseBoolean(autoUpdateDatabase);
1✔
391
                        }
392
                        
393
                        wizardModel.adminUserPassword = script.getProperty("admin_user_password", wizardModel.adminUserPassword);
1✔
394

395
                        String adminPasswordLocked = script.getProperty("admin_password_locked",
1✔
396
                            script.getProperty("admin.password.locked"));
1✔
397
                        if (adminPasswordLocked != null) {
1✔
NEW
398
                                wizardModel.additionalPropertiesFromInstallationScript.put(
×
399
                                    UserService.ADMIN_PASSWORD_LOCKED_PROPERTY, adminPasswordLocked);
400
                        }
401

402
                        for (Map.Entry<Object, Object> entry : installScript.entrySet()) {
1✔
403
                                if (entry.getKey() instanceof String && ((String) entry.getKey()).startsWith("property.")) {
1✔
404
                                        wizardModel.additionalPropertiesFromInstallationScript.put(((String) entry.getKey()).substring(9), entry.getValue());
×
405
                                }
406
                        }
1✔
407
                }
408
        }
1✔
409
        
410
        private void clearPasswords() {
411
                wizardModel.databaseRootPassword = "";
×
412
                wizardModel.createDatabasePassword = "";
×
413
                wizardModel.createUserPassword = "";
×
414
                wizardModel.currentDatabasePassword = "";
×
415
                wizardModel.remotePassword = "";
×
416
        }
×
417
        
418
        /**
419
         * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests
420
         *
421
         * @param httpRequest
422
         * @param httpResponse
423
         */
424
        @Override
425
        protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
426
                throws IOException, ServletException {
427
                String page = httpRequest.getParameter("page");
×
428
                Map<String, Object> referenceMap = new HashMap<>();
×
429
                // we need to save current user language in references map since it will be used when template
430
                // will be rendered
431
                if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
×
432
                        referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
×
433
                                httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
434
                }
435
                
436
                // if any body has already started installation
437
                if (isInstallationStarted()) {
×
438
                        referenceMap.put("isInstallationStarted", true);
×
439
                        httpResponse.setContentType("text/html");
×
440
                        renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
×
441
                        return;
×
442
                }
443
                if (DEFAULT_PAGE.equals(page)) {
×
444
                        // get props and render the first page
445
                        File runtimeProperties = getRuntimePropertiesFile();
×
446
                        if (!runtimeProperties.exists()) {
×
447
                                try {
448
                                        runtimeProperties.createNewFile();
×
449
                                        // reset the error objects in case of refresh
450
                                        wizardModel.canCreate = true;
×
451
                                        wizardModel.cannotCreateErrorMessage = "";
×
452
                                }
453
                                catch (IOException io) {
×
454
                                        wizardModel.canCreate = false;
×
455
                                        wizardModel.cannotCreateErrorMessage = io.getMessage();
×
456
                                }
×
457
                                // check this before deleting the file again
458
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
459
                                
460
                                // delete the file again after testing the create/write
461
                                // so that if the user stops the webapp before finishing
462
                                // this wizard, they can still get back into it
463
                                runtimeProperties.delete();
×
464
                        } else {
465
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
466
                                
467
                                wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
×
468
                                        wizardModel.databaseConnection);
469
                                
470
                                wizardModel.currentDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
×
471
                                        wizardModel.currentDatabaseUsername);
472
                                
473
                                wizardModel.currentDatabasePassword = Context.getRuntimeProperties().getProperty("connection.password",
×
474
                                        wizardModel.currentDatabasePassword);
475
                        }
476
                        
477
                        wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
×
478
                        
479
                        checkLocaleAttributes(httpRequest);
×
480
                        referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
×
481
                                httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
482
                        log.info("Locale stored in session is " + httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
483
                        
484
                        httpResponse.setContentType("text/html");
×
485
                        // otherwise do step one of the wizard
486
                        renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
487
                } else if (INSTALL_METHOD.equals(page)) {
×
488
                        if (goBack(httpRequest)) {
×
489
                                referenceMap.put(FilterUtil.REMEMBER_ATTRIBUTE,
×
490
                                        httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null);
×
491
                                referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
×
492
                                        httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
493
                                renderTemplate(CHOOSE_LANG, referenceMap, httpResponse);
×
494
                                return;
×
495
                        }
496
                        wizardModel.installMethod = httpRequest.getParameter("install_method");
×
497
                        if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
×
498
                                page = SIMPLE_SETUP;
×
499
                        } else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
×
500
                                page = TESTING_REMOTE_DETAILS_SETUP;
×
501
                                wizardModel.currentStepNumber = 1;
×
502
                                wizardModel.numberOfSteps = skipDatabaseSetupPage() ? 1 : 3;
×
503
                        } else {
504
                                page = DATABASE_SETUP;
×
505
                                wizardModel.currentStepNumber = 1;
×
506
                                wizardModel.numberOfSteps = 5;
×
507
                        }
508
                        renderTemplate(page, referenceMap, httpResponse);
×
509
                } // simple method
510
                else if (SIMPLE_SETUP.equals(page)) {
×
511
                        if (goBack(httpRequest)) {
×
512
                                renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
513
                                return;
×
514
                        }
515
                        
516
                        String databaseType = httpRequest.getParameter("database_type");
×
517
                        if (databaseType != null) {
×
518
                                wizardModel.databaseType = databaseType;
×
519
                                if (DATABASE_POSTGRESQL.equals(databaseType)) {
×
520
                                        wizardModel.databaseConnection = DEFAULT_POSTGRESQL_CONNECTION;
×
521
                                        String postgresUsername = httpRequest.getParameter("create_database_username");
×
522
                                        wizardModel.createDatabaseUsername = StringUtils.hasText(postgresUsername) ? 
×
523
                                                postgresUsername : Context.getRuntimeProperties().getProperty("connection.username", "postgres");
×
524
                                } else {
×
525
                                        wizardModel.databaseConnection = DEFAULT_MYSQL_CONNECTION;
×
526
                                        wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username", 
×
527
                                                wizardModel.createDatabaseUsername);
528
                                }
529
                        }
530

531
                        wizardModel.databaseRootPassword = httpRequest.getParameter("database_root_password");
×
532
                        checkForEmptyValue(wizardModel.databaseRootPassword, errors, ErrorMessageConstants.ERROR_DB_PSDW_REQ);
×
533
                        wizardModel.createUserUsername = wizardModel.createDatabaseUsername;
×
534
                        wizardModel.hasCurrentOpenmrsDatabase = false;
×
535
                        wizardModel.createTables = true;
×
536
                        // default wizardModel.databaseName is openmrs
537
                        // default wizardModel.createDatabaseUsername is root
538
                        wizardModel.createDatabasePassword = wizardModel.databaseRootPassword;
×
539
                        wizardModel.hasCurrentDatabaseUser = false;
×
540
                        wizardModel.createDatabaseUser = true;
×
541
                        // default wizardModel.createUserUsername is root
542
                        wizardModel.createUserPassword = wizardModel.databaseRootPassword;
×
543
                        
544
                        wizardModel.moduleWebAdmin = true;
×
545
                        wizardModel.autoUpdateDatabase = false;
×
546
                        
547
                        wizardModel.adminUserPassword = InitializationWizardModel.ADMIN_DEFAULT_PASSWORD;
×
548
                        
549
                        createSimpleSetup(httpRequest.getParameter("database_root_password"));
×
550
                        
551
                        try {
552
                                loadedDriverString = DatabaseUtil.loadDatabaseDriver(wizardModel.databaseConnection,
×
553
                                        wizardModel.databaseDriver);
554
                        }
555
                        catch (ClassNotFoundException e) {
×
556
                                errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
×
557
                                renderTemplate(page, referenceMap, httpResponse);
×
558
                                return;
×
559
                        }
×
560
                        
561
                        if (errors.isEmpty()) {
×
562
                                page = WIZARD_COMPLETE;
×
563
                        }
564
                        renderTemplate(page, referenceMap, httpResponse);
×
565
                } // step one
×
566
                else if (DATABASE_SETUP.equals(page)) {
×
567
                        if (goBack(httpRequest)) {
×
568
                                wizardModel.currentStepNumber -= 1;
×
569
                                if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
×
570
                                        renderTemplate(TESTING_REMOTE_DETAILS_SETUP, referenceMap, httpResponse);
×
571
                                } else {
572
                                        renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
573
                                }
574
                                return;
×
575
                        }
576
                        
577
                        wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
×
578
                        checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_CONN_REQ);
×
579
                        
580
                        wizardModel.databaseDriver = httpRequest.getParameter("database_driver");
×
581
                        checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_DRIVER_REQ);
×
582
                        
583
                        loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
×
584
                        if (!StringUtils.hasText(loadedDriverString)) {
×
585
                                errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
×
586
                                renderTemplate(page, referenceMap, httpResponse);
×
587
                                return;
×
588
                        }
589
                        
590
                        //TODO make each bit of page logic a (unit testable) method
591
                        
592
                        // asked the user for their desired database name
593
                        
594
                        if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
×
595
                                wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
×
596
                                checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_CURR_NAME_REQ);
×
597
                                wizardModel.hasCurrentOpenmrsDatabase = true;
×
598
                                // TODO check to see if this is an active database
599
                                
600
                        } else {
601
                                // mark this wizard as a "to create database" (done at the end)
602
                                wizardModel.hasCurrentOpenmrsDatabase = false;
×
603
                                
604
                                wizardModel.createTables = true;
×
605
                                
606
                                wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
×
607
                                checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_NEW_NAME_REQ);
×
608
                                // TODO create database now to check if its possible?
609
                                
610
                                wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
×
611
                                checkForEmptyValue(wizardModel.createDatabaseUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
×
612
                                wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
×
613
                                checkForEmptyValue(wizardModel.createDatabasePassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
×
614
                        }
615
                        
616
                        if (errors.isEmpty()) {
×
617
                                page = DATABASE_TABLES_AND_USER;
×
618
                                
619
                                if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
×
620
                                        wizardModel.currentStepNumber = 3;
×
621
                                } else {
622
                                        wizardModel.currentStepNumber = 2;
×
623
                                }
624
                        }
625
                        
626
                        renderTemplate(page, referenceMap, httpResponse);
×
627
                        
628
                } // step two
629
                else if (DATABASE_TABLES_AND_USER.equals(page)) {
×
630
                        
631
                        if (goBack(httpRequest)) {
×
632
                                wizardModel.currentStepNumber -= 1;
×
633
                                renderTemplate(DATABASE_SETUP, referenceMap, httpResponse);
×
634
                                return;
×
635
                        }
636
                        
637
                        if (wizardModel.hasCurrentOpenmrsDatabase) {
×
638
                                wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
×
639
                        }
640
                        
641
                        if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
×
642
                                wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
×
643
                                checkForEmptyValue(wizardModel.currentDatabaseUsername, errors,
×
644
                                        ErrorMessageConstants.ERROR_DB_CUR_USER_NAME_REQ);
645
                                wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
×
646
                                checkForEmptyValue(wizardModel.currentDatabasePassword, errors,
×
647
                                        ErrorMessageConstants.ERROR_DB_CUR_USER_PSWD_REQ);
648
                                wizardModel.hasCurrentDatabaseUser = true;
×
649
                                wizardModel.createDatabaseUser = false;
×
650
                        } else {
651
                                wizardModel.hasCurrentDatabaseUser = false;
×
652
                                wizardModel.createDatabaseUser = true;
×
653
                                // asked for the root mysql username/password
654
                                wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
×
655
                                checkForEmptyValue(wizardModel.createUserUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
×
656
                                wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
×
657
                                checkForEmptyValue(wizardModel.createUserPassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
×
658
                        }
659
                        
660
                        if (errors.isEmpty()) { // go to next page
×
661
                                page = InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod) ? WIZARD_COMPLETE
×
662
                                        : OTHER_RUNTIME_PROPS;
663
                        }
664
                        
665
                        renderTemplate(page, referenceMap, httpResponse);
×
666
                } // step three
667
                else if (OTHER_RUNTIME_PROPS.equals(page)) {
×
668
                        
669
                        if (goBack(httpRequest)) {
×
670
                                renderTemplate(DATABASE_TABLES_AND_USER, referenceMap, httpResponse);
×
671
                                return;
×
672
                        }
673
                        
674
                        wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
×
675
                        wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
×
676
                        
677
                        if (wizardModel.createTables) { // go to next page if they are creating tables
×
678
                                page = ADMIN_USER_SETUP;
×
679
                        } else { // skip a page
680
                                page = IMPLEMENTATION_ID_SETUP;
×
681
                        }
682
                        
683
                        renderTemplate(page, referenceMap, httpResponse);
×
684
                        
685
                } // optional step four
686
                else if (ADMIN_USER_SETUP.equals(page)) {
×
687
                        
688
                        if (goBack(httpRequest)) {
×
689
                                renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
×
690
                                return;
×
691
                        }
692
                        
693
                        wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
×
694
                        String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
×
695
                        
696
                        // throw back to admin user if passwords don't match
697
                        if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
×
698
                                errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSWDS_MATCH, null);
×
699
                                renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
×
700
                                return;
×
701
                        }
702
                        
703
                        // throw back if the user didn't put in a password
704
                        if ("".equals(wizardModel.adminUserPassword)) {
×
705
                                errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_EMPTY, null);
×
706
                                renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
×
707
                                return;
×
708
                        }
709
                        
710
                        try {
711
                                OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
×
712
                        }
713
                        catch (PasswordException p) {
×
714
                                errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_WEAK, null);
×
715
                                renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
×
716
                                return;
×
717
                        }
×
718
                        
719
                        if (errors.isEmpty()) { // go to next page
×
720
                                page = IMPLEMENTATION_ID_SETUP;
×
721
                        }
722
                        
723
                        renderTemplate(page, referenceMap, httpResponse);
×
724
                        
725
                } // optional step five
×
726
                else if (IMPLEMENTATION_ID_SETUP.equals(page)) {
×
727
                        
728
                        if (goBack(httpRequest)) {
×
729
                                if (wizardModel.createTables) {
×
730
                                        renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
×
731
                                } else {
732
                                        renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
×
733
                                }
734
                                return;
×
735
                        }
736
                        
737
                        wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
×
738
                        wizardModel.implementationId = httpRequest.getParameter("implementation_id");
×
739
                        wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
×
740
                        wizardModel.implementationIdDescription = httpRequest.getParameter("description");
×
741
                        
742
                        // throw back if the user-specified ID is invalid (contains ^ or |).
743
                        if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
×
744
                                errors.put(ErrorMessageConstants.ERROR_DB_IMPL_ID_REQ, null);
×
745
                                renderTemplate(IMPLEMENTATION_ID_SETUP, referenceMap, httpResponse);
×
746
                                return;
×
747
                        }
748
                        
749
                        if (errors.isEmpty()) { // go to next page
×
750
                                page = WIZARD_COMPLETE;
×
751
                        }
752
                        
753
                        renderTemplate(page, referenceMap, httpResponse);
×
754
                } else if (WIZARD_COMPLETE.equals(page)) {
×
755
                        
756
                        if (goBack(httpRequest)) {
×
757
                                
758
                                if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
×
759
                                        page = SIMPLE_SETUP;
×
760
                                } else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
×
761
                                        if (skipDatabaseSetupPage()) {
×
762
                                                page = TESTING_REMOTE_DETAILS_SETUP;
×
763
                                        } else {
764
                                                page = DATABASE_TABLES_AND_USER;
×
765
                                        }
766
                                } else {
767
                                        page = IMPLEMENTATION_ID_SETUP;
×
768
                                }
769
                                renderTemplate(page, referenceMap, httpResponse);
×
770
                                return;
×
771
                        }
772
                        
773
                        wizardModel.tasksToExecute = new ArrayList<>();
×
774
                        createDatabaseTask();
×
775
                        if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
×
776
                                wizardModel.importTestData = true;
×
777
                                wizardModel.createTables = false;
×
778
                                //if we have a runtime properties file
779
                                if (skipDatabaseSetupPage()) {
×
780
                                        wizardModel.hasCurrentOpenmrsDatabase = false;
×
781
                                        wizardModel.hasCurrentDatabaseUser = true;
×
782
                                        wizardModel.createDatabaseUser = false;
×
783
                                        Properties props = OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
×
784
                                        wizardModel.currentDatabaseUsername = props.getProperty("connection.username");
×
785
                                        wizardModel.currentDatabasePassword = props.getProperty("connection.password");
×
786
                                        wizardModel.createDatabaseUsername = wizardModel.currentDatabaseUsername;
×
787
                                        wizardModel.createDatabasePassword = wizardModel.currentDatabasePassword;
×
788
                                }
789
                                
790
                                wizardModel.tasksToExecute.add(WizardTask.IMPORT_TEST_DATA);
×
791
                                wizardModel.tasksToExecute.add(WizardTask.ADD_MODULES);
×
792
                        } else {
793
                                createTablesTask();
×
794
                        }
795
                        wizardModel.tasksToExecute.add(WizardTask.UPDATE_TO_LATEST);
×
796
                        
797
                        referenceMap.put("tasksToExecute", wizardModel.tasksToExecute);
×
798
                        startInstallation();
×
799
                        renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
×
800
                } else if (TESTING_REMOTE_DETAILS_SETUP.equals(page)) {
×
801
                        if (goBack(httpRequest)) {
×
802
                                wizardModel.currentStepNumber -= 1;
×
803
                                renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
804
                                return;
×
805
                        }
806
                        
807
                        wizardModel.remoteUrl = httpRequest.getParameter("remoteUrl");
×
808
                        checkForEmptyValue(wizardModel.remoteUrl, errors, "install.testing.remote.url.required");
×
809
                        if (errors.isEmpty()) {
×
810
                                //Check if the remote system is running
811
                                if (TestInstallUtil.testConnection(wizardModel.remoteUrl)) {
×
812
                                        //Check if the test module is installed by connecting to its setting page
813
                                        if (TestInstallUtil
×
814
                                                .testConnection(wizardModel.remoteUrl.concat(RELEASE_TESTING_MODULE_PATH + "settings.htm"))) {
×
815
                                                
816
                                                wizardModel.remoteUsername = httpRequest.getParameter("username");
×
817
                                                wizardModel.remotePassword = httpRequest.getParameter("password");
×
818
                                                checkForEmptyValue(wizardModel.remoteUsername, errors, "install.testing.username.required");
×
819
                                                checkForEmptyValue(wizardModel.remotePassword, errors, "install.testing.password.required");
×
820
                                                
821
                                                if (errors.isEmpty()) {
×
822
                                                        //check if the username and password are valid
823
                                                        try {
824
                                                                TestInstallUtil.getResourceInputStream(
×
825
                                                                        wizardModel.remoteUrl + RELEASE_TESTING_MODULE_PATH + "verifycredentials.htm",
826
                                                                        wizardModel.remoteUsername, wizardModel.remotePassword);
827
                                                        }
828
                                                        catch (APIAuthenticationException e) {
×
829
                                                                log.debug("Error generated: ", e);
×
830
                                                                page = TESTING_REMOTE_DETAILS_SETUP;
×
831
                                                                errors.put(ErrorMessageConstants.UPDATE_ERROR_UNABLE_AUTHENTICATE, null);
×
832
                                                                renderTemplate(page, referenceMap, httpResponse);
×
833
                                                                return;
×
834
                                                        }
×
835
                                                        
836
                                                        //If we have a runtime properties file, get the database setup details from it
837
                                                        if (skipDatabaseSetupPage()) {
×
838
                                                                Properties props = OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
×
839
                                                                wizardModel.databaseConnection = props.getProperty("connection.url");
×
840
                                                                loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
×
841
                                                                if (!StringUtils.hasText(loadedDriverString)) {
×
842
                                                                        page = TESTING_REMOTE_DETAILS_SETUP;
×
843
                                                                        errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
×
844
                                                                        renderTemplate(page, referenceMap, httpResponse);
×
845
                                                                        return;
×
846
                                                                }
847
                                                                
848
                                                                wizardModel.databaseName = InitializationWizardModel.DEFAULT_DATABASE_NAME;
×
849
                                                                page = WIZARD_COMPLETE;
×
850
                                                        } else {
×
851
                                                                page = DATABASE_SETUP;
×
852
                                                                wizardModel.currentStepNumber = 2;
×
853
                                                        }
854
                                                        msgs.put("install.testing.testingModuleFound", null);
×
855
                                                } else {
856
                                                        renderTemplate(page, referenceMap, httpResponse);
×
857
                                                        return;
×
858
                                                }
859
                                        } else {
860
                                                errors.put("install.testing.noTestingModule", null);
×
861
                                        }
862
                                } else {
863
                                        errors.put("install.testing.invalidProductionUrl", new Object[] { wizardModel.remoteUrl });
×
864
                                }
865
                        }
866
                        
867
                        SessionModelUtils.saveToSession(httpRequest.getSession(), wizardModel);
×
868
                        renderTemplate(page, referenceMap, httpResponse);
×
869
                }
870
        }
×
871
        
872
        private void startInstallation() {
873
                //if no one has run any installation
874
                if (!isInstallationStarted()) {
×
875
                        initJob = new InitializationCompletion();
×
876
                        setInstallationStarted(true);
×
877
                        initJob.start();
×
878
                }
879
        }
×
880
        
881
        private void createTablesTask() {
882
                if (wizardModel.createTables) {
×
883
                        wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
×
884
                        wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
×
885
                }
886
        }
×
887
        
888
        private void createDatabaseTask() {
889
                if (!wizardModel.hasCurrentOpenmrsDatabase) {
×
890
                        wizardModel.tasksToExecute.add(WizardTask.CREATE_SCHEMA);
×
891
                }
892
                if (wizardModel.createDatabaseUser) {
×
893
                        wizardModel.tasksToExecute.add(WizardTask.CREATE_DB_USER);
×
894
                }
895
        }
×
896
        
897
        private void createSimpleSetup(String databaseRootPassword) {
898
                setDatabaseNameIfInTestMode();
×
899
                wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
×
900
                        wizardModel.databaseConnection);
901
                
902
                wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
×
903
                        wizardModel.createDatabaseUsername);
904
                
905
                wizardModel.createUserUsername = wizardModel.createDatabaseUsername;
×
906
                
907
                wizardModel.databaseRootPassword = databaseRootPassword;
×
908
                checkForEmptyValue(wizardModel.databaseRootPassword, errors, ErrorMessageConstants.ERROR_DB_PSDW_REQ);
×
909
                
910
                wizardModel.hasCurrentOpenmrsDatabase = false;
×
911
                wizardModel.createTables = true;
×
912
                // default wizardModel.databaseName is openmrs
913
                // default wizardModel.createDatabaseUsername is root
914
                wizardModel.createDatabasePassword = wizardModel.databaseRootPassword;
×
915
                wizardModel.hasCurrentDatabaseUser = false;
×
916
                wizardModel.createDatabaseUser = true;
×
917
                // default wizardModel.createUserUsername is root
918
                wizardModel.createUserPassword = wizardModel.databaseRootPassword;
×
919
                
920
                wizardModel.moduleWebAdmin = true;
×
921
                wizardModel.autoUpdateDatabase = false;
×
922
                
923
                wizardModel.adminUserPassword = InitializationWizardModel.ADMIN_DEFAULT_PASSWORD;
×
924
        }
×
925
        
926
        private void setDatabaseNameIfInTestMode() {
927
                if (OpenmrsUtil.isTestMode()) {
×
928
                        wizardModel.databaseName = OpenmrsUtil.getOpenMRSVersionInTestMode();
×
929
                }
930
        }
×
931
        
932
        private void autoRunOpenMRS(HttpServletRequest httpRequest) {
933
                File runtimeProperties = getRuntimePropertiesFile();
×
934
                wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
×
935
                
936
                if (!InitializationWizardModel.INSTALL_METHOD_AUTO.equals(wizardModel.installMethod)) {
×
937
                        if (httpRequest.getParameter("database_user_name") != null) {
×
938
                                wizardModel.createDatabaseUsername = httpRequest.getParameter("database_user_name");
×
939
                        }
940
                        
941
                        createSimpleSetup(httpRequest.getParameter("database_root_password"));
×
942
                }
943
                
944
                checkLocaleAttributes(httpRequest);
×
945
                try {
946
                        loadedDriverString = DatabaseUtil.loadDatabaseDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
×
947
                }
948
                catch (ClassNotFoundException e) {
×
949
                        errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
×
950
                        return;
×
951
                }
×
952
                wizardModel.tasksToExecute = new ArrayList<>();
×
953
                createDatabaseTask();
×
954
                createTablesTask();
×
955
                wizardModel.tasksToExecute.add(WizardTask.UPDATE_TO_LATEST);
×
956
                startInstallation();
×
957
        }
×
958
        
959
        /**
960
         * This method should be called after the user has left wizard's first page (i.e. choose language).
961
         * It checks if user has changed any of locale related parameters and makes appropriate corrections
962
         * with filter's model or/and with locale attribute inside user's session.
963
         *
964
         * @param httpRequest the http request object
965
         */
966
        private void checkLocaleAttributes(HttpServletRequest httpRequest) {
967
                String localeParameter = httpRequest.getParameter(FilterUtil.LOCALE_ATTRIBUTE);
×
968
                Boolean rememberLocale = false;
×
969
                // we need to check if user wants that system will remember his selection of language
970
                if (httpRequest.getParameter(FilterUtil.REMEMBER_ATTRIBUTE) != null) {
×
971
                        rememberLocale = true;
×
972
                }
973
                if (localeParameter != null) {
×
974
                        String storedLocale = null;
×
975
                        if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
×
976
                                storedLocale = httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE).toString();
×
977
                        }
978
                        // if user has changed locale parameter to new one
979
                        // or chooses it parameter at first page loading
980
                        if (storedLocale == null || !storedLocale.equals(localeParameter)) {
×
981
                                log.info("Stored locale parameter to session " + localeParameter);
×
982
                                httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, localeParameter);
×
983
                        }
984
                        if (rememberLocale) {
×
985
                                httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, localeParameter);
×
986
                                httpRequest.getSession().setAttribute(FilterUtil.REMEMBER_ATTRIBUTE, true);
×
987
                                wizardModel.localeToSave = localeParameter;
×
988
                        } else {
989
                                // we need to reset it if it was set before
990
                                httpRequest.getSession().setAttribute(FilterUtil.REMEMBER_ATTRIBUTE, null);
×
991
                                wizardModel.localeToSave = null;
×
992
                        }
993
                }
994
        }
×
995
        
996
        /**
997
         * It sets locale parameter for current session when user is making first GET http request to
998
         * application. It retrieves user locale from request object and checks if this locale is supported
999
         * by application. If not, it uses {@link Locale#ENGLISH} by default
1000
         *
1001
         * @param httpRequest the http request object
1002
         */
1003
        public void checkLocaleAttributesForFirstTime(HttpServletRequest httpRequest) {
1004
                Locale locale = httpRequest.getLocale();
×
1005
                if (CustomResourceLoader.getInstance(httpRequest).getAvailablelocales().contains(locale)) {
×
1006
                        httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, locale.toString());
×
1007
                } else {
1008
                        httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, Locale.ENGLISH.toString());
×
1009
                }
1010
        }
×
1011
        
1012
        /**
1013
         * Verify the database connection works.
1014
         *
1015
         * @param connectionUsername
1016
         * @param connectionPassword
1017
         * @param databaseConnectionFinalUrl
1018
         * @return true/false whether it was verified or not
1019
         */
1020
        private boolean verifyConnection(String connectionUsername, String connectionPassword,
1021
                String databaseConnectionFinalUrl) {
1022
                try {
1023
                        // verify connection
1024
                        DatabaseUtil.loadDatabaseDriver(databaseConnectionFinalUrl, loadedDriverString);
×
1025
                        try (Connection ignored = DriverManager.getConnection(databaseConnectionFinalUrl, connectionUsername, connectionPassword)) {
×
1026
                                return true;
×
1027
                        }
1028
                }
1029
                catch (Exception e) {
×
1030
                        errors.put("User account " + connectionUsername + " does not work. " + e.getMessage()
×
1031
                                        + " See the error log for more details",
1032
                                null); // TODO internationalize this
1033
                        log.warn("Error while checking the connection user account", e);
×
1034
                        return false;
×
1035
                }
1036
        }
1037
        
1038
        /**
1039
         * Convenience method to load the runtime properties file.
1040
         *
1041
         * @return the runtime properties file.
1042
         */
1043
        private File getRuntimePropertiesFile() {
1044
                File file;
1045
                
1046
                String pathName = OpenmrsUtil.getRuntimePropertiesFilePathName(WebConstants.WEBAPP_NAME);
×
1047
                if (pathName != null) {
×
1048
                        file = new File(pathName);
×
1049
                } else {
1050
                        file = new File(OpenmrsUtil.getApplicationDataDirectory(), getRuntimePropertiesFileName());
×
1051
                }
1052
                
1053
                log.debug("Using file: " + file.getAbsolutePath());
×
1054
                
1055
                return file;
×
1056
        }
1057
        
1058
        private String getRuntimePropertiesFileName() {
1059
                String fileName = OpenmrsUtil.getRuntimePropertiesFileNameInTestMode();
×
1060
                if (fileName == null) {
×
1061
                        fileName = WebConstants.WEBAPP_NAME + "-runtime.properties";
×
1062
                }
1063
                return fileName;
×
1064
        }
1065
        
1066
        /**
1067
         * @see org.openmrs.web.filter.StartupFilter#getTemplatePrefix()
1068
         */
1069
        @Override
1070
        protected String getTemplatePrefix() {
1071
                return "org/openmrs/web/filter/initialization/";
×
1072
        }
1073
        
1074
        /**
1075
         * @see org.openmrs.web.filter.StartupFilter#getUpdateFilterModel()
1076
         */
1077
        @Override
1078
        protected Object getUpdateFilterModel() {
1079
                return wizardModel;
×
1080
        }
1081
        
1082
        /**
1083
         * @see org.openmrs.web.filter.StartupFilter#skipFilter(HttpServletRequest)
1084
         */
1085
        @Override
1086
        public boolean skipFilter(HttpServletRequest httpRequest) {
1087
                // If progress.vm makes an ajax request even immediately after initialization has completed
1088
                // let the request pass in order to let progress.vm load the start page of OpenMRS
1089
                // (otherwise progress.vm is displayed "forever")
1090
                return !PROGRESS_VM_AJAXREQUEST.equals(httpRequest.getParameter("page")) && !initializationRequired();
×
1091
        }
1092
        
1093
        /**
1094
         * Public method that returns true if database+runtime properties initialization is required
1095
         *
1096
         * @return true if this initialization wizard needs to run
1097
         */
1098
        public static boolean initializationRequired() {
1099
                return !isInitializationComplete();
×
1100
        }
1101
        
1102
        /**
1103
         * @param isInstallationStarted the value to set
1104
         */
1105
        protected static synchronized void setInstallationStarted(boolean isInstallationStarted) {
1106
                InitializationFilter.isInstallationStarted = isInstallationStarted;
×
1107
        }
×
1108
        
1109
        /**
1110
         * @return true if installation has been started
1111
         */
1112
        public static boolean isInstallationStarted() {
1113
                return isInstallationStarted;
1✔
1114
        }
1115
        
1116
        /**
1117
         * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
1118
         */
1119
        @Override
1120
        public void init(FilterConfig filterConfig) throws ServletException {
1121
                super.init(filterConfig);
×
1122
                wizardModel = new InitializationWizardModel();
×
1123
                DatabaseDetective databaseDetective = new DatabaseDetective();
×
1124
                //set whether need to do initialization work
1125
                if (databaseDetective.isDatabaseEmpty(OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME))) {
×
1126
                        //if runtime-properties file doesn't exist, have to do initialization work
1127
                        setInitializationComplete(false);
×
1128
                } else {
1129
                        //if database is not empty, then let UpdaterFilter to judge whether need database update
1130
                        setInitializationComplete(true);
×
1131
                }
1132
        }
×
1133
        
1134
        private void importTestDataSet(InputStream in, String connectionUrl, String connectionUsername,
1135
                String connectionPassword) throws IOException {
1136
                File tempFile = null;
×
1137
                FileOutputStream fileOut = null;
×
1138
                try {
1139
                        ZipInputStream zipIn = new ZipInputStream(in);
×
1140
                        zipIn.getNextEntry();
×
1141
                        
1142
                        tempFile = File.createTempFile("testDataSet", "dump");
×
1143
                        fileOut = new FileOutputStream(tempFile);
×
1144
                        
1145
                        IOUtils.copy(zipIn, fileOut);
×
1146
                        
1147
                        fileOut.close();
×
1148
                        zipIn.close();
×
1149
                        
1150
                        //Cater for the stand-alone connection url with has :mxj:
1151
                        if (connectionUrl.contains(":mxj:")) {
×
1152
                                connectionUrl = connectionUrl.replace(":mxj:", ":");
×
1153
                        }
1154
                        
1155
                        URI uri = URI.create(connectionUrl.substring(5)); //remove 'jdbc:' prefix to conform to the URI format
×
1156
                        String host = uri.getHost();
×
1157
                        int port = uri.getPort();
×
1158
                        
1159
                        TestInstallUtil.addTestData(host, port, wizardModel.databaseName, connectionUsername, connectionPassword,
×
1160
                                tempFile.getAbsolutePath());
×
1161
                }
1162
                finally {
1163
                        IOUtils.closeQuietly(in);
×
1164
                        IOUtils.closeQuietly(fileOut);
×
1165
                        
1166
                        if (tempFile != null) {
×
1167
                                tempFile.delete();
×
1168
                        }
1169
                }
1170
        }
×
1171
        
1172
        private boolean isCurrentDatabase(String database) {
1173
                return wizardModel.databaseConnection.contains(database);
×
1174
        }
1175
        
1176
        /**
1177
         * @param silent if this statement fails do not display stack trace or record an error in the wizard
1178
         *            object.
1179
         * @param user username to connect with
1180
         * @param pw password to connect with
1181
         * @param sql String containing sql and question marks
1182
         * @param args the strings to fill into the question marks in the given sql
1183
         * @return result of executeUpdate or -1 for error
1184
         */
1185
        private int executeStatement(boolean silent, String user, String pw, String sql, String... args) {
1186
                
1187
                Connection connection = null;
×
1188
                Statement statement = null;
×
1189
                try {
1190
                        String replacedSql = sql;
×
1191
                        
1192
                        // TODO how to get the driver for the other dbs...
1193
                        if (isCurrentDatabase(DATABASE_MYSQL)) {
×
1194
                                Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
×
1195
                        } else if (isCurrentDatabase(DATABASE_POSTGRESQL)) {
×
1196
                                Class.forName("org.postgresql.Driver").newInstance();
×
1197
                                replacedSql = replacedSql.replaceAll("`", "\"");
×
1198
                        } else {
1199
                                replacedSql = replacedSql.replaceAll("`", "\"");
×
1200
                        }
1201
                        
1202
                        String tempDatabaseConnection;
1203
                        if (sql.contains("create database")) {
×
1204
                                tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@",
×
1205
                                        ""); // make this dbname agnostic so we can create the db
1206
                        } else {
1207
                                tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName);
×
1208
                        }
1209
                        
1210
                        connection = DriverManager.getConnection(tempDatabaseConnection, user, pw);
×
1211
                        
1212
                        for (String arg : args) {
×
1213
                                arg = arg.replace(";", "&#094"); // to prevent any sql injection
×
1214
                                replacedSql = replacedSql.replaceFirst("\\?", arg);
×
1215
                        }
1216
                        
1217
                        // run the sql statement
1218
                        statement = connection.createStatement();
×
1219
                        
1220
                        return statement.executeUpdate(replacedSql);
×
1221
                        
1222
                }
1223
                catch (SQLException sqlex) {
×
1224
                        if (!silent) {
×
1225
                                // log and add error
1226
                                log.warn("error executing sql: " + sql, sqlex);
×
1227
                                errors.put("Error executing sql: " + sql + " - " + sqlex.getMessage(), null);
×
1228
                        }
1229
                }
1230
                catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) {
×
1231
                        log.error("Error generated", e);
×
1232
                }
1233
                finally {
1234
                        try {
1235
                                if (statement != null) {
×
1236
                                        statement.close();
×
1237
                                }
1238
                        }
1239
                        catch (SQLException e) {
×
1240
                                log.warn("Error while closing statement");
×
1241
                        }
×
1242
                        try {
1243
                                
1244
                                if (connection != null) {
×
1245
                                        connection.close();
×
1246
                                }
1247
                        }
1248
                        catch (Exception e) {
×
1249
                                log.warn("Error while closing connection", e);
×
1250
                        }
×
1251
                }
1252
                
1253
                return -1;
×
1254
        }
1255
        
1256
        /**
1257
         * Convenience variable to know if this wizard has completed successfully and that this wizard does
1258
         * not need to be executed again
1259
         *
1260
         * @return true if this has been run already
1261
         */
1262
        private static synchronized boolean isInitializationComplete() {
1263
                return initializationComplete;
×
1264
        }
1265
        
1266
        /**
1267
         * Checks if the given string value is empty or contains only whitespace. 
1268
         * If it is, an error is added to the provided errors map with the specified error message code.
1269
         *
1270
         * @param value            the string to check
1271
         * @param errors           the list of errors to append the errorMessage to if value is empty
1272
         * @param errorMessageCode the string with code of error message translation to append if value is
1273
         *                         empty
1274
         */
1275
        private void checkForEmptyValue(String value, Map<String, Object[]> errors, String errorMessageCode) {
1276
                if (!StringUtils.hasText(value)) {
×
1277
                        errors.put(errorMessageCode, null);
×
1278
                }
1279
        }
×
1280
        
1281
        /**
1282
         * Separate thread that will run through all tasks to complete the initialization. The database is
1283
         * created, user's created, etc here
1284
         */
1285
        private class InitializationCompletion {
1286
                
1287
                private final Future<Void> future;
1288
                
1289
                private int steps = 0;
×
1290
                
1291
                private String message = "";
×
1292
                
1293
                private Map<String, Object[]> errors = new HashMap<>();
×
1294
                
1295
                private String errorPage = null;
×
1296
                
1297
                private boolean erroneous = false;
×
1298
                
1299
                private int completedPercentage = 0;
×
1300
                
1301
                private WizardTask executingTask;
1302
                
1303
                private List<WizardTask> executedTasks = new ArrayList<>();
×
1304
                
1305
                public synchronized void reportError(String error, String errorPage, Object... params) {
1306
                        errors.put(error, params);
×
1307
                        this.errorPage = errorPage;
×
1308
                        erroneous = true;
×
1309
                }
×
1310
                
1311
                public synchronized boolean hasErrors() {
1312
                        return erroneous;
×
1313
                }
1314
                
1315
                public synchronized String getErrorPage() {
1316
                        return errorPage;
×
1317
                }
1318
                
1319
                public synchronized Map<String, Object[]> getErrors() {
1320
                        return errors;
×
1321
                }
1322
                
1323
                /**
1324
                 * Start the completion stage. This fires up the thread to do all the work.
1325
                 */
1326
                public void start() {
1327
                        setStepsComplete(0);
×
1328
                        setInitializationComplete(false);
×
1329
                }
×
1330
                
1331
                public void waitForCompletion() {
1332
                        try {
1333
                                future.get();
×
1334
                        } catch (InterruptedException | ExecutionException e) {
×
1335
                                throw new RuntimeException(e);
×
1336
                        }
×
1337
                }
×
1338
                
1339
                protected synchronized void setStepsComplete(int steps) {
1340
                        this.steps = steps;
×
1341
                }
×
1342
                
1343
                protected synchronized int getStepsComplete() {
1344
                        return steps;
×
1345
                }
1346
                
1347
                public synchronized String getMessage() {
1348
                        return message;
×
1349
                }
1350
                
1351
                public synchronized void setMessage(String message) {
1352
                        log.debug(message);
×
1353
                        this.message = message;
×
1354
                        setStepsComplete(getStepsComplete() + 1);
×
1355
                }
×
1356
                
1357
                /**
1358
                 * @return the executingTask
1359
                 */
1360
                protected synchronized WizardTask getExecutingTask() {
1361
                        return executingTask;
×
1362
                }
1363
                
1364
                /**
1365
                 * @return the completedPercentage
1366
                 */
1367
                protected synchronized int getCompletedPercentage() {
1368
                        return completedPercentage;
×
1369
                }
1370
                
1371
                /**
1372
                 * @param completedPercentage the completedPercentage to set
1373
                 */
1374
                protected synchronized void setCompletedPercentage(int completedPercentage) {
1375
                        this.completedPercentage = completedPercentage;
×
1376
                }
×
1377
                
1378
                /**
1379
                 * Adds a task that has been completed to the list of executed tasks
1380
                 *
1381
                 * @param task
1382
                 */
1383
                protected synchronized void addExecutedTask(WizardTask task) {
1384
                        this.executedTasks.add(task);
×
1385
                }
×
1386
                
1387
                /**
1388
                 * @param executingTask the executingTask to set
1389
                 */
1390
                protected synchronized void setExecutingTask(WizardTask executingTask) {
1391
                        this.executingTask = executingTask;
×
1392
                }
×
1393
                
1394
                /**
1395
                 * @return the executedTasks
1396
                 */
1397
                protected synchronized List<WizardTask> getExecutedTasks() {
1398
                        return this.executedTasks;
×
1399
                }
1400
                
1401
                /**
1402
                 * This class does all the work of creating the desired database, user, updates, etc
1403
                 */
1404
                public InitializationCompletion() {
×
1405
                        Runnable r = new Runnable() {
×
1406
                                
1407
                                /**
1408
                                 * TODO split this up into multiple testable methods
1409
                                 *
1410
                                 * @see java.lang.Runnable#run()
1411
                                 */
1412
                                @Override
1413
                                public void run() {
1414
                                        try {
1415
                                                String connectionUsername;
1416
                                                StringBuilder connectionPassword = new StringBuilder();
×
1417
                                                ChangeLogDetective changeLogDetective = ChangeLogDetective.getInstance();
×
1418
                                                ChangeLogVersionFinder changeLogVersionFinder = new ChangeLogVersionFinder();
×
1419
                                                
1420
                                                if (!wizardModel.hasCurrentOpenmrsDatabase) {
×
1421
                                                        setMessage("Create database");
×
1422
                                                        setExecutingTask(WizardTask.CREATE_SCHEMA);
×
1423
                                                        // connect via jdbc and create a database
1424
                                                        String sql;
1425
                                                        if (isCurrentDatabase(DATABASE_MYSQL)) {
×
1426
                                                                sql = "create database if not exists `?` default character set utf8";
×
1427
                                                        } else if (isCurrentDatabase(DATABASE_POSTGRESQL)) {
×
1428
                                                                sql = "create database `?` encoding 'utf8'";
×
1429
                                                        } else if (isCurrentDatabase(DATABASE_H2)) {
×
1430
                                                                sql = null;
×
1431
                                                        } else {
1432
                                                                sql = "create database `?`";
×
1433
                                                        }
1434
                                                        
1435
                                                        int result;
1436
                                                        if (sql != null) {
×
1437
                                                                result = executeStatement(false, wizardModel.createDatabaseUsername,
×
1438
                                                                        wizardModel.createDatabasePassword, sql, wizardModel.databaseName);
1439
                                                        } else {
1440
                                                                result = 1;
×
1441
                                                        }
1442
                                                        // throw the user back to the main screen if this error occurs
1443
                                                        if (result < 0) {
×
1444
                                                                reportError(ErrorMessageConstants.ERROR_DB_CREATE_NEW, DEFAULT_PAGE);
×
1445
                                                                return;
×
1446
                                                        } else {
1447
                                                                wizardModel.workLog.add("Created database " + wizardModel.databaseName);
×
1448
                                                        }
1449
                                                        
1450
                                                        addExecutedTask(WizardTask.CREATE_SCHEMA);
×
1451
                                                }
1452
                                                
1453
                                                if (wizardModel.createDatabaseUser) {
×
1454
                                                        setMessage("Create database user");
×
1455
                                                        setExecutingTask(WizardTask.CREATE_DB_USER);
×
1456
                                                        connectionUsername = wizardModel.databaseName + "_user";
×
1457
                                                        if (connectionUsername.length() > 16) {
×
1458
                                                                connectionUsername = wizardModel.databaseName.substring(0, 11)
×
1459
                                                                        + "_user"; // trim off enough to leave space for _user at the end
1460
                                                        }
1461
                                                        
1462
                                                        connectionPassword.append("");
×
1463
                                                        // generate random password from this subset of alphabet
1464
                                                        // intentionally left out these characters: ufsb$() to prevent certain words forming randomly
1465
                                                        String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&";
×
1466
                                                        Random r = new Random();
×
1467
                                                        StringBuilder randomStr = new StringBuilder("");
×
1468
                                                        for (int x = 0; x < 12; x++) {
×
1469
                                                                randomStr.append(chars.charAt(r.nextInt(chars.length())));
×
1470
                                                        }
1471
                                                        connectionPassword.append(randomStr);
×
1472
                                                        
1473
                                                        // connect via jdbc with root user and create an openmrs user
1474
                                                        String host = "'%'";
×
1475
                                                        if (wizardModel.databaseConnection.contains("localhost")
×
1476
                                                                || wizardModel.databaseConnection.contains("127.0.0.1")) {
×
1477
                                                                host = "'localhost'";
×
1478
                                                        }
1479
                                                        
1480
                                                        String sql = "";
×
1481
                                                        if (isCurrentDatabase(DATABASE_MYSQL)) {
×
1482
                                                                sql = "drop user '?'@" + host;
×
1483
                                                        } else if (isCurrentDatabase(DATABASE_POSTGRESQL)) {
×
1484
                                                                sql = "drop user `?`";
×
1485
                                                        }
1486
                                                        
1487
                                                        executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
×
1488
                                                                connectionUsername);
1489
                                                        
1490
                                                        if (isCurrentDatabase(DATABASE_MYSQL)) {
×
1491
                                                                sql = "create user '?'@" + host + " identified by '?'";
×
1492
                                                        } else if (isCurrentDatabase(DATABASE_POSTGRESQL)) {
×
1493
                                                                sql = "create user `?` with password '?'";
×
1494
                                                        }
1495
                                                        
1496
                                                        if (-1 != executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword,
×
1497
                                                                sql, connectionUsername, connectionPassword.toString())) {
×
1498
                                                                wizardModel.workLog.add("Created user " + connectionUsername);
×
1499
                                                        } else {
1500
                                                                // if error occurs stop
1501
                                                                reportError(ErrorMessageConstants.ERROR_DB_CREATE_DB_USER, DEFAULT_PAGE);
×
1502
                                                                return;
×
1503
                                                        }
1504
                                                        
1505
                                                        // grant the roles
1506
                                                        int result = 1;
×
1507
                                                        if (isCurrentDatabase(DATABASE_MYSQL)) {
×
1508
                                                                sql = "GRANT ALL ON `?`.* TO '?'@" + host;
×
1509
                                                                result = executeStatement(false, wizardModel.createUserUsername,
×
1510
                                                                        wizardModel.createUserPassword, sql, wizardModel.databaseName, connectionUsername);
1511
                                                        } else if (isCurrentDatabase(DATABASE_POSTGRESQL)) {
×
1512
                                                                sql = "ALTER USER `?` WITH SUPERUSER";
×
1513
                                                                result = executeStatement(false, wizardModel.createUserUsername,
×
1514
                                                                        wizardModel.createUserPassword, sql, connectionUsername);
1515
                                                        }
1516
                                                        
1517
                                                        // throw the user back to the main screen if this error occurs
1518
                                                        if (result < 0) {
×
1519
                                                                reportError(ErrorMessageConstants.ERROR_DB_GRANT_PRIV, DEFAULT_PAGE);
×
1520
                                                                return;
×
1521
                                                        } else {
1522
                                                                wizardModel.workLog.add("Granted user " + connectionUsername + " all privileges to database "
×
1523
                                                                        + wizardModel.databaseName);
1524
                                                        }
1525
                                                        
1526
                                                        addExecutedTask(WizardTask.CREATE_DB_USER);
×
1527
                                                } else {
×
1528
                                                        connectionUsername = wizardModel.currentDatabaseUsername;
×
1529
                                                        connectionPassword.setLength(0);
×
1530
                                                        connectionPassword.append(wizardModel.currentDatabasePassword);
×
1531
                                                }
1532
                                                
1533
                                                String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@",
×
1534
                                                        wizardModel.databaseName);
1535
                                                
1536
                                                finalDatabaseConnectionString = finalDatabaseConnectionString.replace("@APPLICATIONDATADIR@",
×
1537
                                                        OpenmrsUtil.getApplicationDataDirectory().replace("\\", "/"));
×
1538
                                                
1539
                                                // verify that the database connection works
1540
                                                if (!verifyConnection(connectionUsername, connectionPassword.toString(),
×
1541
                                                        finalDatabaseConnectionString)) {
1542
                                                        setMessage("Verify that the database connection works");
×
1543
                                                        // redirect to setup page if we got an error
1544
                                                        reportError("Unable to connect to database", DEFAULT_PAGE);
×
1545
                                                        return;
×
1546
                                                }
1547
                                                
1548
                                                // save the properties for startup purposes
1549
                                                Properties runtimeProperties = new Properties();
×
1550
                                                
1551
                                                runtimeProperties.put("connection.url", finalDatabaseConnectionString);
×
1552
                                                runtimeProperties.put("connection.username", connectionUsername);
×
1553
                                                runtimeProperties.put("connection.password", connectionPassword.toString());
×
1554
                                                if (StringUtils.hasText(wizardModel.databaseDriver)) {
×
1555
                                                        runtimeProperties.put("connection.driver_class", wizardModel.databaseDriver);
×
1556
                                                }
1557
                                                if (finalDatabaseConnectionString.contains(DATABASE_POSTGRESQL)) {
×
1558
                                                        runtimeProperties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQL82Dialect");
×
1559
                                                }
1560
                                                if (finalDatabaseConnectionString.contains(DATABASE_SQLSERVER)) {
×
1561
                                                        runtimeProperties.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
×
1562
                                                }
1563
                                                if (finalDatabaseConnectionString.contains(DATABASE_H2)) {
×
1564
                                                        runtimeProperties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
×
1565
                                                }
1566
                                                if (finalDatabaseConnectionString.contains(DATABASE_MARIADB)) {
×
1567
                                                        runtimeProperties.put("hibernate.dialect", "org.hibernate.dialect.MariaDBDialect");
×
1568
                                                }
1569
                                                runtimeProperties.put("module.allow_web_admin", "" + wizardModel.moduleWebAdmin);
×
1570
                                                runtimeProperties.put("auto_update_database", "" + wizardModel.autoUpdateDatabase);
×
1571
                                                final Encoder base64 = Base64.getEncoder();
×
1572
                                                runtimeProperties.put(OpenmrsConstants.ENCRYPTION_VECTOR_RUNTIME_PROPERTY,
×
1573
                                                        new String(base64.encode(Security.generateNewInitVector()), StandardCharsets.UTF_8));
×
1574
                                                runtimeProperties.put(OpenmrsConstants.ENCRYPTION_KEY_RUNTIME_PROPERTY,
×
1575
                                                        new String(base64.encode(Security.generateNewSecretKey()), StandardCharsets.UTF_8));
×
1576
                                                
1577
                                                runtimeProperties.putAll(wizardModel.additionalPropertiesFromInstallationScript);
×
1578
                                                
1579
                                                Properties properties = Context.getRuntimeProperties();
×
1580
                                                properties.putAll(runtimeProperties);
×
1581
                                                runtimeProperties = properties;
×
1582

1583
                                                Context.setRuntimeProperties(runtimeProperties);
×
1584
                                                
1585
                                                /**
1586
                                                 * A callback class that prints out info about liquibase changesets
1587
                                                 */
1588
                                                class PrintingChangeSetExecutorCallback implements ChangeSetExecutorCallback {
1589
                                                        
1590
                                                        private int i = 1;
×
1591
                                                        
1592
                                                        private String message;
1593
                                                        
1594
                                                        public PrintingChangeSetExecutorCallback(String message) {
×
1595
                                                                this.message = message;
×
1596
                                                        }
×
1597
                                                        
1598
                                                        /**
1599
                                                         * @see ChangeSetExecutorCallback#executing(liquibase.changelog.ChangeSet, int)
1600
                                                         */
1601
                                                        @Override
1602
                                                        public void executing(ChangeSet changeSet, int numChangeSetsToRun) {
1603
                                                                setMessage(message + " (" + i++ + "/" + numChangeSetsToRun + "): Author: "
×
1604
                                                                        + changeSet.getAuthor() + " Comments: " + changeSet.getComments() + " Description: "
×
1605
                                                                        + changeSet.getDescription());
×
1606
                                                                float numChangeSetsToRunFloat = (float) numChangeSetsToRun;
×
1607
                                                                float j = (float) i;
×
1608
                                                                setCompletedPercentage(Math.round(j * 100 / numChangeSetsToRunFloat));
×
1609
                                                        }
×
1610
                                                        
1611
                                                }
1612
                                                
1613
                                                if (wizardModel.createTables) {
×
1614
                                                        log.debug("Creating tables");
×
1615
                                                        // use liquibase to create core data + tables
1616
                                                        try {
1617
                                                                String liquibaseSchemaFileName = changeLogVersionFinder.getLatestSchemaSnapshotFilename()
×
1618
                                                                        .get();
×
1619
                                                                String liquibaseCoreDataFileName = changeLogVersionFinder.getLatestCoreDataSnapshotFilename()
×
1620
                                                                        .get();
×
1621
                                                                
1622
                                                                setMessage("Executing " + liquibaseSchemaFileName);
×
1623
                                                                setExecutingTask(WizardTask.CREATE_TABLES);
×
1624
                                                                
1625
                                                                log.debug("executing Liquibase file '{}' ", liquibaseSchemaFileName);
×
1626
                                                                
1627
                                                                DatabaseUpdater.executeChangelog(liquibaseSchemaFileName,
×
1628
                                                                        new PrintingChangeSetExecutorCallback("OpenMRS schema file"));
1629
                                                                addExecutedTask(WizardTask.CREATE_TABLES);
×
1630
                                                                
1631
                                                                //reset for this task
1632
                                                                setCompletedPercentage(0);
×
1633
                                                                setExecutingTask(WizardTask.ADD_CORE_DATA);
×
1634
                                                                
1635
                                                                log.debug("executing Liquibase file '{}' ", liquibaseCoreDataFileName);
×
1636
                                                                
1637
                                                                DatabaseUpdater.executeChangelog(liquibaseCoreDataFileName,
×
1638
                                                                        new PrintingChangeSetExecutorCallback("OpenMRS core data file"));
1639
                                                                wizardModel.workLog.add("Created database tables and added core data");
×
1640
                                                                addExecutedTask(WizardTask.ADD_CORE_DATA);
×
1641
                                                                
1642
                                                        }
1643
                                                        catch (Exception e) {
×
1644
                                                                reportError(ErrorMessageConstants.ERROR_DB_CREATE_TABLES_OR_ADD_DEMO_DATA, DEFAULT_PAGE,
×
1645
                                                                        e.getMessage());
×
1646
                                                                log.warn("Error while trying to create tables and demo data", e);
×
1647
                                                        }
×
1648
                                                }
1649
                                                
1650
                                                if (wizardModel.importTestData) {
×
1651
                                                        try {
1652
                                                                setMessage("Importing test data");
×
1653
                                                                setExecutingTask(WizardTask.IMPORT_TEST_DATA);
×
1654
                                                                setCompletedPercentage(0);
×
1655
                                                                
1656
                                                                try {
1657
                                                                        InputStream inData = TestInstallUtil.getResourceInputStream(
×
1658
                                                                                wizardModel.remoteUrl + RELEASE_TESTING_MODULE_PATH + "generateTestDataSet.form",
1659
                                                                                wizardModel.remoteUsername, wizardModel.remotePassword);
1660
                                                                        
1661
                                                                        setCompletedPercentage(40);
×
1662
                                                                        setMessage("Loading imported test data...");
×
1663
                                                                        importTestDataSet(inData, finalDatabaseConnectionString, connectionUsername,
×
1664
                                                                                connectionPassword.toString());
×
1665
                                                                        wizardModel.workLog.add("Imported test data");
×
1666
                                                                        addExecutedTask(WizardTask.IMPORT_TEST_DATA);
×
1667
                                                                        
1668
                                                                        //reset the progress for the next task
1669
                                                                        setCompletedPercentage(0);
×
1670
                                                                        setMessage("Importing modules from remote server...");
×
1671
                                                                        setExecutingTask(WizardTask.ADD_MODULES);
×
1672
                                                                        
1673
                                                                        InputStream inModules = TestInstallUtil.getResourceInputStream(
×
1674
                                                                                wizardModel.remoteUrl + RELEASE_TESTING_MODULE_PATH + "getModules.htm",
1675
                                                                                wizardModel.remoteUsername, wizardModel.remotePassword);
1676
                                                                        
1677
                                                                        setCompletedPercentage(90);
×
1678
                                                                        setMessage("Adding imported modules...");
×
1679
                                                                        if (!TestInstallUtil.addZippedTestModules(inModules)) {
×
1680
                                                                                reportError(ErrorMessageConstants.ERROR_DB_UNABLE_TO_ADD_MODULES, DEFAULT_PAGE, "");
×
1681
                                                                                return;
×
1682
                                                                        } else {
1683
                                                                                wizardModel.workLog.add("Added Modules");
×
1684
                                                                                addExecutedTask(WizardTask.ADD_MODULES);
×
1685
                                                                        }
1686
                                                                }
1687
                                                                catch (APIAuthenticationException e) {
×
1688
                                                                        log.warn("Unable to authenticate as a User with the System Developer role");
×
1689
                                                                        reportError(ErrorMessageConstants.UPDATE_ERROR_UNABLE_AUTHENTICATE,
×
1690
                                                                                TESTING_REMOTE_DETAILS_SETUP, "");
1691
                                                                        return;
×
1692
                                                                }
×
1693
                                                        }
1694
                                                        catch (Exception e) {
×
1695
                                                                reportError(ErrorMessageConstants.ERROR_DB_IMPORT_TEST_DATA, DEFAULT_PAGE, e.getMessage());
×
1696
                                                                log.warn("Error while trying to import test data", e);
×
1697
                                                                return;
×
1698
                                                        }
×
1699
                                                }
1700
                                                
1701
                                                // update the database to the latest version
1702
                                                try {
1703
                                                        setMessage("Updating the database to the latest version");
×
1704
                                                        setCompletedPercentage(0);
×
1705
                                                        setExecutingTask(WizardTask.UPDATE_TO_LATEST);
×
1706
                                                        
1707
                                                        String version = null;
×
1708
                                                        
1709
                                                        if (wizardModel.createTables) {
×
1710
                                                                version = changeLogVersionFinder.getLatestSnapshotVersion().get();
×
1711
                                                        } else {
1712
                                                                version = changeLogDetective.getInitialLiquibaseSnapshotVersion(DatabaseUpdater.CONTEXT,
×
1713
                                                                        new DatabaseUpdaterLiquibaseProvider());
1714
                                                        }
1715
                                                        
1716
                                                        log.debug(
×
1717
                                                                "updating the database with versions of liquibase-update-to-latest files greater than '{}'",
1718
                                                                version);
1719
                                                        
1720
                                                        List<String> changelogs = changeLogVersionFinder
×
1721
                                                                .getUpdateFileNames(changeLogVersionFinder.getUpdateVersionsGreaterThan(version));
×
1722
                                                        
1723
                                                        for (String changelog : changelogs) {
×
1724
                                                                log.debug("applying Liquibase changelog '{}'", changelog);
×
1725
                                                                
1726
                                                                DatabaseUpdater.executeChangelog(changelog,
×
1727
                                                                        new PrintingChangeSetExecutorCallback("executing Liquibase changelog " + changelog));
1728
                                                        }
×
1729
                                                        addExecutedTask(WizardTask.UPDATE_TO_LATEST);
×
1730
                                                }
1731
                                                catch (Exception e) {
×
1732
                                                        reportError(ErrorMessageConstants.ERROR_DB_UPDATE_TO_LATEST, DEFAULT_PAGE, e.getMessage());
×
1733
                                                        log.warn("Error while trying to update to the latest database version", e);
×
1734
                                                        return;
×
1735
                                                }
×
1736
                                                
1737
                                                setExecutingTask(null);
×
1738
                                                setMessage("Starting OpenMRS");
×
1739
                                                
1740
                                                // start spring
1741
                                                // after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext())
1742
                                                // logic copied from org.springframework.web.context.ContextLoaderListener
1743
                                                log.debug("Initializing WAC");
×
1744
                                                ContextLoader contextLoader = new ContextLoader();
×
1745
                                                contextLoader.initWebApplicationContext(filterConfig.getServletContext());
×
1746
                                                log.debug("Done initializing WAC");
×
1747
                                                
1748
                                                // output properties to the openmrs runtime properties file so that this wizard is not run again
1749
                                                FileOutputStream fos = null;
×
1750
                                                try {
1751
                                                        fos = new FileOutputStream(getRuntimePropertiesFile());
×
1752
                                                        OpenmrsUtil.storeProperties(runtimeProperties, fos,
×
1753
                                                                "Auto generated by OpenMRS initialization wizard");
1754
                                                        wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile());
×
1755
                                                        
1756
                                                        /*
1757
                                                         * Fix file readability permissions:
1758
                                                         * first revoke read permission from everyone, then set read permissions for only the user
1759
                                                         * there is no function to set specific readability for only one user
1760
                                                         * and revoke everyone else's, therefore this is the only way to accomplish this.
1761
                                                         */
1762
                                                        wizardModel.workLog.add("Adjusting file posix properties to user readonly");
×
1763
                                                        if (getRuntimePropertiesFile().setReadable(false, false)
×
1764
                                                                && getRuntimePropertiesFile().setReadable(true)) {
×
1765
                                                                wizardModel.workLog
×
1766
                                                                        .add("Successfully adjusted RuntimePropertiesFile to disallow world to read it");
×
1767
                                                        } else {
1768
                                                                wizardModel.workLog
×
1769
                                                                        .add("Unable to adjust RuntimePropertiesFile to disallow world to read it");
×
1770
                                                        }
1771
                                                        // don't need to catch errors here because we tested it at the beginning of the wizard
1772
                                                }
1773
                                                finally {
1774
                                                        if (fos != null) {
×
1775
                                                                fos.close();
×
1776
                                                        }
1777
                                                }
1778
                                                
1779
                                                Context.openSession();
×
1780
                                                
1781
                                                if (!"".equals(wizardModel.implementationId)) {
×
1782
                                                        try {
1783
                                                                Context.addProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
×
1784
                                                                Context.addProxyPrivilege(GET_GLOBAL_PROPERTIES);
×
1785
                                                                Context.addProxyPrivilege(PrivilegeConstants.MANAGE_CONCEPT_SOURCES);
×
1786
                                                                Context.addProxyPrivilege(PrivilegeConstants.GET_CONCEPT_SOURCES);
×
1787
                                                                Context.addProxyPrivilege(PrivilegeConstants.MANAGE_IMPLEMENTATION_ID);
×
1788
                                                                
1789
                                                                ImplementationId implId = new ImplementationId();
×
1790
                                                                implId.setName(wizardModel.implementationIdName);
×
1791
                                                                implId.setImplementationId(wizardModel.implementationId);
×
1792
                                                                implId.setPassphrase(wizardModel.implementationIdPassPhrase);
×
1793
                                                                implId.setDescription(wizardModel.implementationIdDescription);
×
1794
                                                                
1795
                                                                Context.getAdministrationService().setImplementationId(implId);
×
1796
                                                        }
1797
                                                        catch (Exception e) {
×
1798
                                                                reportError(ErrorMessageConstants.ERROR_SET_INPL_ID, DEFAULT_PAGE, e.getMessage());
×
1799
                                                                log.warn("Implementation ID could not be set.", e);
×
1800
                                                                Context.shutdown();
×
1801
                                                                WebModuleUtil.shutdownModules(filterConfig.getServletContext());
×
1802
                                                                contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
×
1803
                                                                return;
×
1804
                                                        }
1805
                                                        finally {
1806
                                                                Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
×
1807
                                                                Context.removeProxyPrivilege(GET_GLOBAL_PROPERTIES);
×
1808
                                                                Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_CONCEPT_SOURCES);
×
1809
                                                                Context.removeProxyPrivilege(PrivilegeConstants.GET_CONCEPT_SOURCES);
×
1810
                                                                Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_IMPLEMENTATION_ID);
×
1811
                                                        }
1812
                                                }
1813
                                                
1814
                                                try {
1815
                                                        // change the admin user password from "test" to what they input above
1816
                                                        if (wizardModel.createTables) {
×
1817
                                                                try {
1818
                                                                        Context.addProxyPrivilege(GET_GLOBAL_PROPERTIES);
×
1819
                                                                        Context.authenticate(new UsernamePasswordCredentials("admin", "test"));
×
1820
                                                                        
1821
                                                                        Properties props = Context.getRuntimeProperties();
×
1822
                                                                        String initValue = props.getProperty(UserService.ADMIN_PASSWORD_LOCKED_PROPERTY);
×
1823
                                                                        props.setProperty(UserService.ADMIN_PASSWORD_LOCKED_PROPERTY, "false");
×
1824
                                                                        Context.setRuntimeProperties(props);
×
1825
                                                                        
1826
                                                                        Context.getUserService().changePassword("test", wizardModel.adminUserPassword);
×
1827
                                                                        
1828
                                                                        if (initValue == null) {
×
1829
                                                                                props.remove(UserService.ADMIN_PASSWORD_LOCKED_PROPERTY);
×
1830
                                                                        } else {
1831
                                                                                props.setProperty(UserService.ADMIN_PASSWORD_LOCKED_PROPERTY, initValue);
×
1832
                                                                        }
1833
                                                                        Context.setRuntimeProperties(props);
×
1834
                                                                        Context.logout();
×
1835
                                                                }
1836
                                                                catch (ContextAuthenticationException ex) {
×
1837
                                                                        log.info("No need to change admin password.", ex);
×
1838
                                                                }
1839
                                                                finally {
1840
                                                                        Context.removeProxyPrivilege(GET_GLOBAL_PROPERTIES);
×
1841
                                                                }
1842
                                                        }
1843
                                                }
1844
                                                catch (Exception e) {
×
1845
                                                        Context.shutdown();
×
1846
                                                        WebModuleUtil.shutdownModules(filterConfig.getServletContext());
×
1847
                                                        contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
×
1848
                                                        reportError(ErrorMessageConstants.ERROR_COMPLETE_STARTUP, DEFAULT_PAGE, e.getMessage());
×
1849
                                                        log.warn("Unable to complete the startup.", e);
×
1850
                                                        return;
×
1851
                                                }
×
1852
                                                
1853
                                                try {
1854
                                                        // Update PostgreSQL Sequences after insertion of core data
1855
                                                        Context.getAdministrationService().updatePostgresSequence();
×
1856
                                                }
1857
                                                catch (Exception e) {
×
1858
                                                        log.warn("Not able to update PostgreSQL sequence. Startup failed for PostgreSQL", e);
×
1859
                                                        reportError(ErrorMessageConstants.ERROR_COMPLETE_STARTUP, DEFAULT_PAGE, e.getMessage());
×
1860
                                                        return;
×
1861
                                                }
×
1862
                                                
1863
                                                // set this so that the wizard isn't run again on next page load
1864
                                                Context.closeSession();
×
1865
                                                
1866
                                                // start openmrs
1867
                                                try {
1868
                                                        UpdateFilter.setUpdatesRequired(false);
×
1869
                                                        WebDaemon.startOpenmrs(filterConfig.getServletContext());
×
1870
                                                }
1871
                                                catch (DatabaseUpdateException updateEx) {
×
1872
                                                        log.warn("Error while running the database update file", updateEx);
×
1873
                                                        reportError(ErrorMessageConstants.ERROR_DB_UPDATE, DEFAULT_PAGE, updateEx.getMessage());
×
1874
                                                        return;
×
1875
                                                }
1876
                                                catch (InputRequiredException inputRequiredEx) {
×
1877
                                                        // TODO display a page looping over the required input and ask the user for each.
1878
                                                        //                 When done and the user and put in their say, call DatabaseUpdater.update(Map);
1879
                                                        //                with the user's question/answer pairs
1880
                                                        log.warn(
×
1881
                                                                "Unable to continue because user input is required for the db updates and we cannot do anything about that right now");
1882
                                                        reportError(ErrorMessageConstants.ERROR_INPUT_REQ, DEFAULT_PAGE);
×
1883
                                                        return;
×
1884
                                                }
1885
                                                catch (MandatoryModuleException mandatoryModEx) {
×
1886
                                                        log.warn(
×
1887
                                                                "A mandatory module failed to start. Fix the error or unmark it as mandatory to continue.",
1888
                                                                mandatoryModEx);
1889
                                                        reportError(ErrorMessageConstants.ERROR_MANDATORY_MOD_REQ, DEFAULT_PAGE,
×
1890
                                                                mandatoryModEx.getMessage());
×
1891
                                                        return;
×
1892
                                                }
×
1893
                                                
1894
                                                // TODO catch openmrs errors here and drop the user back out to the setup screen
1895
                                                
1896
                                        }
1897
                                        catch (IOException e) {
×
1898
                                                reportError(ErrorMessageConstants.ERROR_COMPLETE_STARTUP, DEFAULT_PAGE, e.getMessage());
×
1899
                                        }
1900
                                        finally {
1901
                                                if (!hasErrors()) {
×
1902
                                                        // set this so that the wizard isn't run again on next page load
1903
                                                        setInitializationComplete(true);
×
1904
                                                        // we should also try to store selected by user language
1905
                                                        // if user wants to system will do it for him 
1906
                                                        FilterUtil.storeLocale(wizardModel.localeToSave);
×
1907
                                                }
1908
                                                setInstallationStarted(false);
×
1909
                                        }
1910
                                }
×
1911
                        };
1912
                        
1913
                        future = OpenmrsThreadPoolHolder.threadExecutor.submit(() -> { r.run(); return null; });
×
1914
                }
×
1915
        }
1916
        
1917
        /**
1918
         * Convenience method that loads the database driver
1919
         *
1920
         * @param connection the database connection string
1921
         * @param databaseDriver the database driver class name to load
1922
         * @return the loaded driver string
1923
         */
1924
        public static String loadDriver(String connection, String databaseDriver) {
1925
                String loadedDriverString = null;
×
1926
                try {
1927
                        loadedDriverString = DatabaseUtil.loadDatabaseDriver(connection, databaseDriver);
×
1928
                        log.info("using database driver :" + loadedDriverString);
×
1929
                }
1930
                catch (ClassNotFoundException e) {
×
1931
                        log.error("The given database driver class was not found. "
×
1932
                                + "Please ensure that the database driver jar file is on the class path "
1933
                                + "(like in the webapp's lib folder)");
1934
                }
×
1935
                
1936
                return loadedDriverString;
×
1937
        }
1938
        
1939
        /**
1940
         * Utility method that checks if there is a runtime properties file containing database connection
1941
         * credentials
1942
         *
1943
         * @return
1944
         */
1945
        private static boolean skipDatabaseSetupPage() {
1946
                Properties props = OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
×
1947
                return (props != null && StringUtils.hasText(props.getProperty("connection.url"))
×
1948
                        && StringUtils.hasText(props.getProperty("connection.username"))
×
1949
                        && StringUtils.hasText(props.getProperty("connection.password")));
×
1950
        }
1951
        
1952
        /**
1953
         * Utility methods that checks if the user clicked the back image
1954
         *
1955
         * @param httpRequest
1956
         * @return
1957
         */
1958
        private static boolean goBack(HttpServletRequest httpRequest) {
1959
                return "Back".equals(httpRequest.getParameter("back"))
×
1960
                        || (httpRequest.getParameter("back.x") != null && httpRequest.getParameter("back.y") != null);
×
1961
        }
1962
        
1963
        private String normalizeEnvVariableKey(String envVarKey) {
1964
                if (NON_NORMALIZED_KEYS.contains(envVarKey)) {
1✔
1965
                        return envVarKey.toLowerCase();
1✔
1966
                }
1967
                return envVarKey.toLowerCase().replace('_', '.');
1✔
1968
        }
1969

1970
        protected Map<String, String> getEnvironmentVariables() {
1971
                return System.getenv();
1✔
1972
        }
1973

1974
        /**
1975
         * Convenience method to get custom installation script
1976
         *
1977
         * @return Properties from custom installation script or empty if none specified
1978
         * @throws RuntimeException if path to installation script is invalid
1979
         */
1980
        protected Properties getInstallationScript() {
1981
                Properties prop = new Properties();
1✔
1982
                
1983
                String fileName = System.getProperty("OPENMRS_INSTALLATION_SCRIPT");
1✔
1984
                if (fileName == null) {
1✔
1985
                        return prop;
×
1986
                }
1987
                if (fileName.startsWith("classpath:")) {
1✔
1988
                        fileName = fileName.substring(10);
×
1989
                        InputStream input = null;
×
1990
                        try {
1991
                                input = getClass().getClassLoader().getResourceAsStream(fileName);
×
1992
                                if (input == null) {
×
1993
                                        return null;
×
1994
                                }
1995
                                prop.load(input);
×
1996
                                log.info("Using installation script from classpath: {}", fileName);
×
1997
                                
1998
                                input.close();
×
1999
                        }
2000
                        catch (IOException ex) {
×
2001
                                log.error("Failed to load installation script from classpath: {}", fileName, ex);
×
2002
                                throw new RuntimeException(ex);
×
2003
                        }
2004
                        finally {
2005
                                IOUtils.closeQuietly(input);
×
2006
                        }
2007
                } else {
×
2008
                        File file = new File(fileName);
1✔
2009
                        if (file.exists()) {
1✔
2010
                                InputStream input = null;
1✔
2011
                                try {
2012
                                        input = new FileInputStream(fileName);
1✔
2013
                                        prop.load(input);
1✔
2014
                                        log.info("Using installation script from absolute path: {}", file.getAbsolutePath());
1✔
2015
                                        
2016
                                        input.close();
1✔
2017
                                }
2018
                                catch (IOException ex) {
×
2019
                                        log.error("Failed to load installation script from absolute path: {}", file.getAbsolutePath(), ex);
×
2020
                                        throw new RuntimeException(ex);
×
2021
                                }
2022
                                finally {
2023
                                        IOUtils.closeQuietly(input);
1✔
2024
                                }
2025
                        }
2026
                }
2027
                return prop;
1✔
2028
        }
2029

2030
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc