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

openmrs / openmrs-core / 16181274003

09 Jul 2025 10:11PM UTC coverage: 65.357% (+0.003%) from 65.354%
16181274003

push

github

web-flow
TRUNK-6343: Make sure the database root password check for empty value happens appropriately (#5120)

0 of 1 new or added line in 1 file covered. (0.0%)

3 existing lines in 1 file now uncovered.

23546 of 36027 relevant lines covered (65.36%)

0.65 hits per line

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

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

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

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

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

330
                if (log.isDebugEnabled()) {
1✔
331
                        for (String key : script.stringPropertyNames()) {
×
332
                                String value = script.getProperty(key);
×
333
                                log.debug("{} = {}", key, key.toLowerCase().contains("password") ? "*******" : value);
×
334
                        }
×
335
                }
336
                
337
                if (!script.isEmpty()) {
1✔
338
                        wizardModel.installMethod = script.getProperty("install_method", wizardModel.installMethod);
1✔
339
                        
340
                        wizardModel.databaseConnection = script.getProperty("connection.url", wizardModel.databaseConnection);
1✔
341
                        wizardModel.databaseDriver = script.getProperty("connection.driver_class", wizardModel.databaseDriver);
1✔
342
                        wizardModel.currentDatabaseUsername = script.getProperty("connection.username",
1✔
343
                                wizardModel.currentDatabaseUsername);
344
                        wizardModel.currentDatabasePassword = script.getProperty("connection.password",
1✔
345
                                wizardModel.currentDatabasePassword);
346
                        
347
                        String hasCurrentOpenmrsDatabase = script.getProperty("has_current_openmrs_database");
1✔
348
                        if (hasCurrentOpenmrsDatabase != null) {
1✔
349
                                wizardModel.hasCurrentOpenmrsDatabase = Boolean.valueOf(hasCurrentOpenmrsDatabase);
1✔
350
                        }
351
                        wizardModel.createDatabaseUsername = script.getProperty("create_database_username",
1✔
352
                                wizardModel.createDatabaseUsername);
353
                        wizardModel.createDatabasePassword = script.getProperty("create_database_password",
1✔
354
                                wizardModel.createDatabasePassword);
355
                        
356
                        String createTables = script.getProperty("create_tables");
1✔
357
                        if (createTables != null) {
1✔
358
                                wizardModel.createTables = Boolean.valueOf(createTables);
1✔
359
                        }
360
                        
361
                        String createDatabaseUser = script.getProperty("create_database_user");
1✔
362
                        if (createDatabaseUser != null) {
1✔
363
                                wizardModel.createDatabaseUser = Boolean.valueOf(createDatabaseUser);
1✔
364
                        }
365
                        wizardModel.createUserUsername = script.getProperty("create_user_username", wizardModel.createUserUsername);
1✔
366
                        wizardModel.createUserPassword = script.getProperty("create_user_password", wizardModel.createUserPassword);
1✔
367
                        
368
                        String moduleWebAdmin = script.getProperty("module_web_admin");
1✔
369
                        if (moduleWebAdmin != null) {
1✔
370
                                wizardModel.moduleWebAdmin = Boolean.valueOf(moduleWebAdmin);
1✔
371
                        }
372
                        
373
                        String autoUpdateDatabase = script.getProperty("auto_update_database");
1✔
374
                        if (autoUpdateDatabase != null) {
1✔
375
                                wizardModel.autoUpdateDatabase = Boolean.valueOf(autoUpdateDatabase);
1✔
376
                        }
377
                        
378
                        wizardModel.adminUserPassword = script.getProperty("admin_user_password", wizardModel.adminUserPassword);
1✔
379
                }
380
        }
1✔
381
        
382
        private void clearPasswords() {
383
                wizardModel.databaseRootPassword = "";
×
384
                wizardModel.createDatabasePassword = "";
×
385
                wizardModel.createUserPassword = "";
×
386
                wizardModel.currentDatabasePassword = "";
×
387
                wizardModel.remotePassword = "";
×
388
        }
×
389
        
390
        /**
391
         * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests
392
         *
393
         * @param httpRequest
394
         * @param httpResponse
395
         */
396
        @Override
397
        protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
398
                throws IOException, ServletException {
399
                String page = httpRequest.getParameter("page");
×
400
                Map<String, Object> referenceMap = new HashMap<>();
×
401
                // we need to save current user language in references map since it will be used when template
402
                // will be rendered
403
                if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
×
404
                        referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
×
405
                                httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
406
                }
407
                
408
                // if any body has already started installation
409
                if (isInstallationStarted()) {
×
410
                        referenceMap.put("isInstallationStarted", true);
×
411
                        httpResponse.setContentType("text/html");
×
412
                        renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
×
413
                        return;
×
414
                }
415
                if (DEFAULT_PAGE.equals(page)) {
×
416
                        // get props and render the first page
417
                        File runtimeProperties = getRuntimePropertiesFile();
×
418
                        if (!runtimeProperties.exists()) {
×
419
                                try {
420
                                        runtimeProperties.createNewFile();
×
421
                                        // reset the error objects in case of refresh
422
                                        wizardModel.canCreate = true;
×
423
                                        wizardModel.cannotCreateErrorMessage = "";
×
424
                                }
425
                                catch (IOException io) {
×
426
                                        wizardModel.canCreate = false;
×
427
                                        wizardModel.cannotCreateErrorMessage = io.getMessage();
×
428
                                }
×
429
                                // check this before deleting the file again
430
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
431
                                
432
                                // delete the file again after testing the create/write
433
                                // so that if the user stops the webapp before finishing
434
                                // this wizard, they can still get back into it
435
                                runtimeProperties.delete();
×
436
                        } else {
437
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
438
                                
439
                                wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
×
440
                                        wizardModel.databaseConnection);
441
                                
442
                                wizardModel.currentDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
×
443
                                        wizardModel.currentDatabaseUsername);
444
                                
445
                                wizardModel.currentDatabasePassword = Context.getRuntimeProperties().getProperty("connection.password",
×
446
                                        wizardModel.currentDatabasePassword);
447
                        }
448
                        
449
                        wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
×
450
                        
451
                        checkLocaleAttributes(httpRequest);
×
452
                        referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
×
453
                                httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
454
                        log.info("Locale stored in session is " + httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
455
                        
456
                        httpResponse.setContentType("text/html");
×
457
                        // otherwise do step one of the wizard
458
                        renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
459
                } else if (INSTALL_METHOD.equals(page)) {
×
460
                        if (goBack(httpRequest)) {
×
461
                                referenceMap.put(FilterUtil.REMEMBER_ATTRIBUTE,
×
462
                                        httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null);
×
463
                                referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
×
464
                                        httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
465
                                renderTemplate(CHOOSE_LANG, referenceMap, httpResponse);
×
466
                                return;
×
467
                        }
468
                        wizardModel.installMethod = httpRequest.getParameter("install_method");
×
469
                        if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
×
470
                                page = SIMPLE_SETUP;
×
471
                        } else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
×
472
                                page = TESTING_REMOTE_DETAILS_SETUP;
×
473
                                wizardModel.currentStepNumber = 1;
×
474
                                wizardModel.numberOfSteps = skipDatabaseSetupPage() ? 1 : 3;
×
475
                        } else {
476
                                page = DATABASE_SETUP;
×
477
                                wizardModel.currentStepNumber = 1;
×
478
                                wizardModel.numberOfSteps = 5;
×
479
                        }
480
                        renderTemplate(page, referenceMap, httpResponse);
×
481
                } // simple method
482
                else if (SIMPLE_SETUP.equals(page)) {
×
483
                        if (goBack(httpRequest)) {
×
484
                                renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
485
                                return;
×
486
                        }
487
                        
488
                        String databaseType = httpRequest.getParameter("database_type");
×
489
                        if (databaseType != null) {
×
490
                                wizardModel.databaseType = databaseType;
×
491
                                if (DATABASE_POSTGRESQL.equals(databaseType)) {
×
492
                                        wizardModel.databaseConnection = DEFAULT_POSTGRESQL_CONNECTION;
×
493
                                        String postgresUsername = httpRequest.getParameter("create_database_username");
×
494
                                        wizardModel.createDatabaseUsername = StringUtils.hasText(postgresUsername) ? 
×
495
                                                postgresUsername : Context.getRuntimeProperties().getProperty("connection.username", "postgres");
×
496
                                } else {
×
497
                                        wizardModel.databaseConnection = DEFAULT_MYSQL_CONNECTION;
×
498
                                        wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username", 
×
499
                                                wizardModel.createDatabaseUsername);
500
                                }
501
                        }
502

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

1552
                                                Properties installationScript = getInstallationScript();
×
1553
                                                installationScript.forEach(runtimeProperties::putIfAbsent);
×
1554

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

1932
        /**
1933
         * Resolves and merges initialization properties from multiple sources in the following order:
1934
         * 1. install.properties (lowest priority)
1935
         * 2. OS environment variables
1936
         * 3. Java system properties (-Dkey=value) (highest priority)
1937
         *
1938
         * @return a merged {@link Properties} object with proper precedence.
1939
         */
1940
        protected Properties resolveInitializationProperties() {
1941
                Properties merged = new Properties();
1✔
1942

1943
                Properties installScript = getInstallationScript();
1✔
1944
                installScript.forEach((key, value) -> merged.setProperty(key.toString(), value.toString()));
1✔
1945

1946
                getEnvironmentVariables().forEach((key, value) -> {
1✔
1947
                        String normalizedKey = normalizeEnvVariableKey(key);
1✔
1948
                        merged.setProperty(normalizedKey, value);
1✔
1949
                });
1✔
1950

1951
                System.getProperties().forEach((key, value) -> merged.setProperty(key.toString(), value.toString()));
1✔
1952
                return merged;
1✔
1953
        }
1954
        
1955
        private String normalizeEnvVariableKey(String envVarKey) {
1956
                if (NON_NORMALIZED_KEYS.contains(envVarKey)) {
1✔
1957
                        return envVarKey.toLowerCase();
1✔
1958
                }
1959
                return envVarKey.toLowerCase().replace('_', '.');
1✔
1960
        }
1961

1962
        protected Map<String, String> getEnvironmentVariables() {
1963
                return System.getenv();
1✔
1964
        }
1965

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

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