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

openmrs / openmrs-core / 27437461033

12 Jun 2026 07:14PM UTC coverage: 63.512% (+0.02%) from 63.494%
27437461033

push

github

ibacher
TRUNK-6646: Env-var key normalization drops create_database_* / create_user_* credentials in scripted setup (#6145)

14 of 17 new or added lines in 1 file covered. (82.35%)

3 existing lines in 2 files now uncovered.

23817 of 37500 relevant lines covered (63.51%)

0.64 hits per line

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

7.97
/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("INSTALL_METHOD", "DATABASE_NAME",
1✔
196
            "HAS_CURRENT_OPENMRS_DATABASE", "CREATE_DATABASE_USER", "CREATE_TABLES", "ADD_DEMO_DATA", "MODULE_WEB_ADMIN",
197
            "AUTO_UPDATE_DATABASE", "ADMIN_USER_PASSWORD", "CREATE_DATABASE_USERNAME", "CREATE_DATABASE_PASSWORD",
198
            "CREATE_USER_USERNAME", "CREATE_USER_PASSWORD", "CONNECTION_DRIVER_CLASS", "IMPORT_TEST_DATA", "REMOTE_URL",
199
            "REMOTE_USERNAME", "REMOTE_PASSWORD", "ADMIN_PASSWORD_LOCKED"));
200

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

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

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

337
                Properties installScript = getInstallationScript();
1✔
338
                script.putAll(installScript);
1✔
339

340
                getEnvironmentVariables().forEach((key, value) -> {
1✔
341
                        String normalizedKey = normalizeEnvVariableKey(key);
1✔
342
                        script.setProperty(normalizedKey, value);
1✔
343
                });
1✔
344

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

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

399
                        String importTestData = script.getProperty("import_test_data", script.getProperty("add_demo_data"));
1✔
400
                        if (importTestData != null) {
1✔
401
                                wizardModel.importTestData = Boolean.parseBoolean(importTestData);
1✔
402
                        }
403

404
                        wizardModel.remoteUrl = script.getProperty("remote_url", wizardModel.remoteUrl);
1✔
405
                        wizardModel.remoteUsername = script.getProperty("remote_username", wizardModel.remoteUsername);
1✔
406
                        wizardModel.remotePassword = script.getProperty("remote_password", wizardModel.remotePassword);
1✔
407

408
                        for (Map.Entry<Object, Object> entry : script.entrySet()) {
1✔
409
                                if (entry.getKey() instanceof String && ((String) entry.getKey()).startsWith("property.")) {
1✔
410
                                        wizardModel.additionalPropertiesFromInstallationScript.put(((String) entry.getKey()).substring(9), entry.getValue());
1✔
411
                                }
412
                        }
1✔
413

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

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

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

1986
        protected Map<String, String> getEnvironmentVariables() {
1987
                return System.getenv();
1✔
1988
        }
1989

1990
        /**
1991
         * Convenience method to get custom installation script
1992
         *
1993
         * @return Properties from custom installation script or empty if none specified
1994
         * @throws RuntimeException if path to installation script is invalid
1995
         */
1996
        protected Properties getInstallationScript() {
1997
                Properties prop = new Properties();
1✔
1998
                
1999
                String fileName = System.getProperty("OPENMRS_INSTALLATION_SCRIPT");
1✔
2000
                if (fileName == null) {
1✔
2001
                        return prop;
×
2002
                }
2003
                if (fileName.startsWith("classpath:")) {
1✔
2004
                        fileName = fileName.substring(10);
×
2005
                        InputStream input = null;
×
2006
                        try {
2007
                                input = getClass().getClassLoader().getResourceAsStream(fileName);
×
2008
                                if (input == null) {
×
2009
                                        return null;
×
2010
                                }
2011
                                prop.load(input);
×
2012
                                log.info("Using installation script from classpath: {}", fileName);
×
2013
                                
2014
                                input.close();
×
2015
                        }
2016
                        catch (IOException ex) {
×
2017
                                log.error("Failed to load installation script from classpath: {}", fileName, ex);
×
2018
                                throw new RuntimeException(ex);
×
2019
                        }
2020
                        finally {
2021
                                IOUtils.closeQuietly(input);
×
2022
                        }
2023
                } else {
×
2024
                        File file = new File(fileName);
1✔
2025
                        if (file.exists()) {
1✔
2026
                                InputStream input = null;
1✔
2027
                                try {
2028
                                        input = new FileInputStream(fileName);
1✔
2029
                                        prop.load(input);
1✔
2030
                                        log.info("Using installation script from absolute path: {}", file.getAbsolutePath());
1✔
2031
                                        
2032
                                        input.close();
1✔
2033
                                }
2034
                                catch (IOException ex) {
×
2035
                                        log.error("Failed to load installation script from absolute path: {}", file.getAbsolutePath(), ex);
×
2036
                                        throw new RuntimeException(ex);
×
2037
                                }
2038
                                finally {
2039
                                        IOUtils.closeQuietly(input);
1✔
2040
                                }
2041
                        }
2042
                }
2043
                return prop;
1✔
2044
        }
2045

2046
}
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