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

openmrs / openmrs-core / 18188744794

02 Oct 2025 09:14AM UTC coverage: 65.24% (-0.08%) from 65.318%
18188744794

push

github

rkorytkowski
TRUNK-6436: Add logging to monitor startup performance

(cherry picked from commit fb43aba18)

2 of 29 new or added lines in 4 files covered. (6.9%)

28 existing lines in 10 files now uncovered.

23611 of 36191 relevant lines covered (65.24%)

0.65 hits per line

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

6.82
/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.java
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
3
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
4
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
5
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
6
 * 
7
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
8
 * graphic logo is a trademark of OpenMRS Inc.
9
 */
10
package org.openmrs.web.filter.initialization;
11

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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