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

openmrs / openmrs-core / 24722773057

21 Apr 2026 12:38PM UTC coverage: 65.217% (-0.01%) from 65.229%
24722773057

push

github

web-flow
TRUNK-6481: Backport native support for MariaDB  (#5648)

2 of 14 new or added lines in 4 files covered. (14.29%)

8 existing lines in 5 files now uncovered.

23613 of 36207 relevant lines covered (65.22%)

0.65 hits per line

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

0.0
/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.Base64;
26
import java.util.Base64.Encoder;
27
import java.util.HashMap;
28
import java.util.HashSet;
29
import java.util.List;
30
import java.util.Locale;
31
import java.util.Map;
32
import java.util.Properties;
33
import java.util.Random;
34
import java.util.Set;
35
import java.util.concurrent.ExecutionException;
36
import java.util.concurrent.Future;
37
import java.util.zip.ZipInputStream;
38
import javax.servlet.FilterChain;
39
import javax.servlet.FilterConfig;
40
import javax.servlet.ServletException;
41
import javax.servlet.ServletRequest;
42
import javax.servlet.ServletResponse;
43
import javax.servlet.http.HttpServletRequest;
44
import javax.servlet.http.HttpServletResponse;
45

46
import liquibase.changelog.ChangeSet;
47
import org.apache.commons.io.IOUtils;
48
import org.openmrs.ImplementationId;
49
import org.openmrs.api.APIAuthenticationException;
50
import org.openmrs.api.PasswordException;
51
import org.openmrs.api.UserService;
52
import org.openmrs.api.context.Context;
53
import org.openmrs.api.context.ContextAuthenticationException;
54
import org.openmrs.api.context.UsernamePasswordCredentials;
55
import org.openmrs.liquibase.ChangeLogDetective;
56
import org.openmrs.liquibase.ChangeLogVersionFinder;
57
import org.openmrs.module.MandatoryModuleException;
58
import org.openmrs.module.OpenmrsCoreModuleException;
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.slf4j.LoggerFactory;
80
import org.springframework.util.StringUtils;
81
import org.springframework.web.context.ContextLoader;
82

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

100
        private static final String DATABASE_MARIADB = "mariadb";
101
        
102
        private static final String LIQUIBASE_DEMO_DATA = "liquibase-demo-data.xml";
103
        
104
        /**
105
         * The very first page of wizard, that asks user for select his preferred language
106
         */
107
        private static final String CHOOSE_LANG = "chooselang.vm";
108
        
109
        /**
110
         * The second page of the wizard that asks for simple or advanced installation.
111
         */
112
        private static final String INSTALL_METHOD = "installmethod.vm";
113
        
114
        /**
115
         * The simple installation setup page.
116
         */
117
        private static final String SIMPLE_SETUP = "simplesetup.vm";
118
        
119
        /**
120
         * The first page of the advanced installation of the wizard that asks for a current or past
121
         * database
122
         */
123
        private static final String DATABASE_SETUP = "databasesetup.vm";
124
        
125
        /**
126
         * The page from where the user specifies the url to a remote system, username and password
127
         */
128
        private static final String TESTING_REMOTE_DETAILS_SETUP = "remotedetails.vm";
129
        
130
        /**
131
         * The velocity macro page to redirect to if an error occurs or on initial startup
132
         */
133
        private static final String DEFAULT_PAGE = CHOOSE_LANG;
134
        
135
        /**
136
         * This page asks whether database tables/demo data should be inserted and what the
137
         * username/password that will be put into the runtime properties is
138
         */
139
        private static final String DATABASE_TABLES_AND_USER = "databasetablesanduser.vm";
140
        
141
        /**
142
         * This page lets the user define the admin user
143
         */
144
        private static final String ADMIN_USER_SETUP = "adminusersetup.vm";
145
        
146
        /**
147
         * This page lets the user pick an implementation id
148
         */
149
        private static final String IMPLEMENTATION_ID_SETUP = "implementationidsetup.vm";
150
        
151
        /**
152
         * This page asks for settings that will be put into the runtime properties files
153
         */
154
        private static final String OTHER_RUNTIME_PROPS = "otherruntimeproperties.vm";
155
        
156
        /**
157
         * A page that tells the user that everything is collected and will now be processed
158
         */
159
        private static final String WIZARD_COMPLETE = "wizardcomplete.vm";
160
        
161
        /**
162
         * A page that lists off what is happening while it is going on. This page has ajax that callst he
163
         * {@value #PROGRESS_VM_AJAXREQUEST} page
164
         */
165
        private static final String PROGRESS_VM = "progress.vm";
166
        
167
        /**
168
         * This url is called by javascript to get the status of the install
169
         */
170
        private static final String PROGRESS_VM_AJAXREQUEST = "progress.vm.ajaxRequest";
171
        
172
        public static final String RELEASE_TESTING_MODULE_PATH = "/module/releasetestinghelper/";
173
        
174
        /**
175
         * The model object that holds all the properties that the rendered templates use. All attributes on
176
         * this object are made available to all templates via reflection in the
177
         * {@link org.openmrs.web.filter.StartupFilter#renderTemplate(String, Map, HttpServletResponse)} method.
178
         */
179
        private InitializationWizardModel wizardModel = null;
×
180
        
181
        private InitializationCompletion initJob;
182
        
183
        /**
184
         * Variable set to true as soon as the installation begins and set to false when the process ends
185
         * This thread should only be accesses through the synchronized method.
186
         */
187
        private static boolean isInstallationStarted = false;
×
188
        
189
        // the actual driver loaded by the DatabaseUpdater class
190
        private String loadedDriverString;
191
        
192
        /**
193
         * Variable set at the end of the wizard when spring is being restarted
194
         */
195
        private static boolean initializationComplete = false;
×
196
        
197
        protected synchronized void setInitializationComplete(boolean initializationComplete) {
198
                InitializationFilter.initializationComplete = initializationComplete;
×
199
        }
×
200
        
201
        /**
202
         * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on GET requests
203
         *
204
         * @param httpRequest
205
         * @param httpResponse
206
         */
207
        @Override
208
        protected void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
209
                throws IOException, ServletException {
210
                log.debug("Entered initialization filter");
×
211
                loadInstallationScriptIfPresent();
×
212
                
213
                // we need to save current user language in references map since it will be used when template
214
                // will be rendered
215
                if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) == null) {
×
216
                        checkLocaleAttributesForFirstTime(httpRequest);
×
217
                }
218
                
219
                Map<String, Object> referenceMap = new HashMap<>();
×
220
                String page = httpRequest.getParameter("page");
×
221
                
222
                referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
223
                
224
                httpResponse.setHeader("Cache-Control", "no-cache");
×
225
                
226
                // if any body has already started installation and this is not an ajax request for the progress
227
                if (isInstallationStarted() && !PROGRESS_VM_AJAXREQUEST.equals(page)) {
×
228
                        referenceMap.put("isInstallationStarted", true);
×
229
                        httpResponse.setContentType("text/html");
×
230
                        renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
×
231
                } else if (PROGRESS_VM_AJAXREQUEST.equals(page)) {
×
232
                        httpResponse.setContentType("text/json");
×
233
                        Map<String, Object> result = new HashMap<>();
×
234
                        if (initJob != null) {
×
235
                                result.put("hasErrors", initJob.hasErrors());
×
236
                                if (initJob.hasErrors()) {
×
237
                                        result.put("errorPage", initJob.getErrorPage());
×
238
                                        errors.putAll(initJob.getErrors());
×
239
                                }
240
                                
241
                                result.put("initializationComplete", isInitializationComplete());
×
242
                                result.put("message", initJob.getMessage());
×
243
                                result.put("actionCounter", initJob.getStepsComplete());
×
244
                                if (!isInitializationComplete()) {
×
245
                                        result.put("executingTask", initJob.getExecutingTask());
×
246
                                        result.put("executedTasks", initJob.getExecutedTasks());
×
247
                                        result.put("completedPercentage", initJob.getCompletedPercentage());
×
248
                                }
249
                                
250
                                addLogLinesToResponse(result);
×
251
                        }
252
                        
253
                        PrintWriter writer = httpResponse.getWriter();
×
254
                        writer.write(toJSONString(result));
×
255
                        writer.close();
×
256
                } else if (InitializationWizardModel.INSTALL_METHOD_AUTO.equals(wizardModel.installMethod)
×
257
                        || httpRequest.getServletPath().equals("/" + AUTO_RUN_OPENMRS)) {
×
258
                        autoRunOpenMRS(httpRequest);
×
259
                        referenceMap.put("isInstallationStarted", true);
×
260
                        httpResponse.setContentType("text/html");
×
261
                        renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
×
262
                } else if (page == null) {
×
263
                        httpResponse.setContentType("text/html");// if any body has already started installation
×
264
                        
265
                        //If someone came straight here without setting the hidden page input,
266
                        // then we need to clear out all the passwords
267
                        clearPasswords();
×
268
                        
269
                        renderTemplate(DEFAULT_PAGE, referenceMap, httpResponse);
×
270
                } else if (INSTALL_METHOD.equals(page)) {
×
271
                        // get props and render the second page
272
                        File runtimeProperties = getRuntimePropertiesFile();
×
273
                        
274
                        if (!runtimeProperties.exists()) {
×
275
                                try {
276
                                        runtimeProperties.createNewFile();
×
277
                                        // reset the error objects in case of refresh
278
                                        wizardModel.canCreate = true;
×
279
                                        wizardModel.cannotCreateErrorMessage = "";
×
280
                                }
281
                                catch (IOException io) {
×
282
                                        wizardModel.canCreate = false;
×
283
                                        wizardModel.cannotCreateErrorMessage = io.getMessage();
×
284
                                }
×
285
                                
286
                                // check this before deleting the file again
287
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
288
                                
289
                                // delete the file again after testing the create/write
290
                                // so that if the user stops the webapp before finishing
291
                                // this wizard, they can still get back into it
292
                                runtimeProperties.delete();
×
293
                                
294
                        } else {
295
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
296
                                
297
                                wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
×
298
                                        wizardModel.databaseConnection);
299
                                
300
                                wizardModel.currentDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
×
301
                                        wizardModel.currentDatabaseUsername);
302
                                
303
                                wizardModel.currentDatabasePassword = Context.getRuntimeProperties().getProperty("connection.password",
×
304
                                        wizardModel.currentDatabasePassword);
305
                        }
306
                        
307
                        wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
×
308
                        
309
                        // do step one of the wizard
310
                        httpResponse.setContentType("text/html");
×
311
                        renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
312
                }
313
        }
×
314
        
315
        private void loadInstallationScriptIfPresent() {
316
                Properties script = getInstallationScript();
×
317
                if (!script.isEmpty()) {
×
318
                        wizardModel.installMethod = script.getProperty("install_method", wizardModel.installMethod);
×
319
                        
320
                        wizardModel.databaseConnection = script.getProperty("connection.url", wizardModel.databaseConnection);
×
321
                        wizardModel.databaseDriver = script.getProperty("connection.driver_class", wizardModel.databaseDriver);
×
322
                        wizardModel.currentDatabaseUsername = script.getProperty("connection.username",
×
323
                                wizardModel.currentDatabaseUsername);
324
                        wizardModel.currentDatabasePassword = script.getProperty("connection.password",
×
325
                                wizardModel.currentDatabasePassword);
326
                        
327
                        String hasCurrentOpenmrsDatabase = script.getProperty("has_current_openmrs_database");
×
328
                        if (hasCurrentOpenmrsDatabase != null) {
×
329
                                wizardModel.hasCurrentOpenmrsDatabase = Boolean.parseBoolean(hasCurrentOpenmrsDatabase);
×
330
                        }
331
                        wizardModel.createDatabaseUsername = script.getProperty("create_database_username",
×
332
                                wizardModel.createDatabaseUsername);
333
                        wizardModel.createDatabasePassword = script.getProperty("create_database_password",
×
334
                                wizardModel.createDatabasePassword);
335
                        
336
                        String createTables = script.getProperty("create_tables");
×
337
                        if (createTables != null) {
×
338
                                wizardModel.createTables = Boolean.parseBoolean(createTables);
×
339
                        }
340
                        
341
                        String createDatabaseUser = script.getProperty("create_database_user");
×
342
                        if (createDatabaseUser != null) {
×
343
                                wizardModel.createDatabaseUser = Boolean.parseBoolean(createDatabaseUser);
×
344
                        }
345
                        wizardModel.createUserUsername = script.getProperty("create_user_username", wizardModel.createUserUsername);
×
346
                        wizardModel.createUserPassword = script.getProperty("create_user_password", wizardModel.createUserPassword);
×
347
                        
348
                        String addDemoData = script.getProperty("add_demo_data");
×
349
                        if (addDemoData != null) {
×
350
                                wizardModel.addDemoData = Boolean.parseBoolean(addDemoData);
×
351
                        }
352
                        
353
                        String moduleWebAdmin = script.getProperty("module_web_admin");
×
354
                        if (moduleWebAdmin != null) {
×
355
                                wizardModel.moduleWebAdmin = Boolean.parseBoolean(moduleWebAdmin);
×
356
                        }
357
                        
358
                        String autoUpdateDatabase = script.getProperty("auto_update_database");
×
359
                        if (autoUpdateDatabase != null) {
×
360
                                wizardModel.autoUpdateDatabase = Boolean.parseBoolean(autoUpdateDatabase);
×
361
                        }
362
                        
363
                        wizardModel.adminUserPassword = script.getProperty("admin_user_password", wizardModel.adminUserPassword);
×
364

365
                        String adminPasswordLocked = script.getProperty("admin_password_locked",
×
366
                            script.getProperty("admin.password.locked"));
×
367
                        if (adminPasswordLocked != null) {
×
368
                                wizardModel.additionalPropertiesFromInstallationScript.put(
×
369
                                    UserService.ADMIN_PASSWORD_LOCKED_PROPERTY, adminPasswordLocked);
370
                        }
371

372
                        for (Map.Entry<Object, Object> entry : script.entrySet()) {
×
373
                                if (entry.getKey() instanceof String && ((String) entry.getKey()).startsWith("property.")) {
×
374
                                        wizardModel.additionalPropertiesFromInstallationScript.put(((String) entry.getKey()).substring(9), entry.getValue());
×
375
                                }
376
                        }
×
377
                }
378
        }
×
379
        
380
        private void clearPasswords() {
381
                wizardModel.databaseRootPassword = "";
×
382
                wizardModel.createDatabasePassword = "";
×
383
                wizardModel.createUserPassword = "";
×
384
                wizardModel.currentDatabasePassword = "";
×
385
                wizardModel.remotePassword = "";
×
386
        }
×
387
        
388
        /**
389
         * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests
390
         *
391
         * @param httpRequest
392
         * @param httpResponse
393
         */
394
        @Override
395
        protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
396
                throws IOException, ServletException {
397
                String page = httpRequest.getParameter("page");
×
398
                Map<String, Object> referenceMap = new HashMap<>();
×
399
                // we need to save current user language in references map since it will be used when template
400
                // will be rendered
401
                if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
×
402
                        referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
×
403
                                httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
404
                }
405
                
406
                // if any body has already started installation
407
                if (isInstallationStarted()) {
×
408
                        referenceMap.put("isInstallationStarted", true);
×
409
                        httpResponse.setContentType("text/html");
×
410
                        renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
×
411
                        return;
×
412
                }
413
                if (DEFAULT_PAGE.equals(page)) {
×
414
                        // get props and render the first page
415
                        File runtimeProperties = getRuntimePropertiesFile();
×
416
                        if (!runtimeProperties.exists()) {
×
417
                                try {
418
                                        runtimeProperties.createNewFile();
×
419
                                        // reset the error objects in case of refresh
420
                                        wizardModel.canCreate = true;
×
421
                                        wizardModel.cannotCreateErrorMessage = "";
×
422
                                }
423
                                catch (IOException io) {
×
424
                                        wizardModel.canCreate = false;
×
425
                                        wizardModel.cannotCreateErrorMessage = io.getMessage();
×
426
                                }
×
427
                                // check this before deleting the file again
428
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
429
                                
430
                                // delete the file again after testing the create/write
431
                                // so that if the user stops the webapp before finishing
432
                                // this wizard, they can still get back into it
433
                                runtimeProperties.delete();
×
434
                        } else {
435
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
436
                                
437
                                wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
×
438
                                        wizardModel.databaseConnection);
439
                                
440
                                wizardModel.currentDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
×
441
                                        wizardModel.currentDatabaseUsername);
442
                                
443
                                wizardModel.currentDatabasePassword = Context.getRuntimeProperties().getProperty("connection.password",
×
444
                                        wizardModel.currentDatabasePassword);
445
                        }
446
                        
447
                        wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
×
448
                        
449
                        checkLocaleAttributes(httpRequest);
×
450
                        referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
×
451
                                httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
452
                        log.info("Locale stored in session is " + httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
453
                        
454
                        httpResponse.setContentType("text/html");
×
455
                        // otherwise do step one of the wizard
456
                        renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
457
                } else if (INSTALL_METHOD.equals(page)) {
×
458
                        if (goBack(httpRequest)) {
×
459
                                referenceMap.put(FilterUtil.REMEMBER_ATTRIBUTE,
×
460
                                        httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null);
×
461
                                referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
×
462
                                        httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
463
                                renderTemplate(CHOOSE_LANG, referenceMap, httpResponse);
×
464
                                return;
×
465
                        }
466
                        wizardModel.installMethod = httpRequest.getParameter("install_method");
×
467
                        if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
×
468
                                page = SIMPLE_SETUP;
×
469
                        } else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
×
470
                                page = TESTING_REMOTE_DETAILS_SETUP;
×
471
                                wizardModel.currentStepNumber = 1;
×
472
                                wizardModel.numberOfSteps = skipDatabaseSetupPage() ? 1 : 3;
×
473
                        } else {
474
                                page = DATABASE_SETUP;
×
475
                                wizardModel.currentStepNumber = 1;
×
476
                                wizardModel.numberOfSteps = 5;
×
477
                        }
478
                        renderTemplate(page, referenceMap, httpResponse);
×
479
                } // simple method
480
                else if (SIMPLE_SETUP.equals(page)) {
×
481
                        if (goBack(httpRequest)) {
×
482
                                renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
483
                                return;
×
484
                        }
485
                        wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
×
486
                        ;
487
                        
488
                        wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
×
489
                                wizardModel.createDatabaseUsername);
490
                        
491
                        wizardModel.createUserUsername = wizardModel.createDatabaseUsername;
×
492
                        
493
                        wizardModel.databaseRootPassword = httpRequest.getParameter("database_root_password");
×
494
                        checkForEmptyValue(wizardModel.databaseRootPassword, errors, ErrorMessageConstants.ERROR_DB_PSDW_REQ);
×
495
                        
496
                        wizardModel.hasCurrentOpenmrsDatabase = false;
×
497
                        wizardModel.createTables = true;
×
498
                        // default wizardModel.databaseName is openmrs
499
                        // default wizardModel.createDatabaseUsername is root
500
                        wizardModel.createDatabasePassword = wizardModel.databaseRootPassword;
×
501
                        wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
×
502
                        
503
                        wizardModel.hasCurrentDatabaseUser = false;
×
504
                        wizardModel.createDatabaseUser = true;
×
505
                        // default wizardModel.createUserUsername is root
506
                        wizardModel.createUserPassword = wizardModel.databaseRootPassword;
×
507
                        
508
                        wizardModel.moduleWebAdmin = true;
×
509
                        wizardModel.autoUpdateDatabase = false;
×
510
                        
511
                        wizardModel.adminUserPassword = InitializationWizardModel.ADMIN_DEFAULT_PASSWORD;
×
512
                        
513
                        createSimpleSetup(httpRequest.getParameter("database_root_password"), httpRequest.getParameter("add_demo_data"));
×
514
                        
515
                        try {
516
                                loadedDriverString = DatabaseUtil.loadDatabaseDriver(wizardModel.databaseConnection,
×
517
                                        wizardModel.databaseDriver);
518
                        }
519
                        catch (ClassNotFoundException e) {
×
520
                                errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
×
521
                                renderTemplate(page, referenceMap, httpResponse);
×
522
                                return;
×
523
                        }
×
524
                        
525
                        if (errors.isEmpty()) {
×
526
                                page = WIZARD_COMPLETE;
×
527
                        }
528
                        renderTemplate(page, referenceMap, httpResponse);
×
529
                } // step one
530
                else if (DATABASE_SETUP.equals(page)) {
×
531
                        if (goBack(httpRequest)) {
×
532
                                wizardModel.currentStepNumber -= 1;
×
533
                                if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
×
534
                                        renderTemplate(TESTING_REMOTE_DETAILS_SETUP, referenceMap, httpResponse);
×
535
                                } else {
536
                                        renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
537
                                }
538
                                return;
×
539
                        }
540
                        
541
                        wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
×
542
                        checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_CONN_REQ);
×
543
                        
544
                        wizardModel.databaseDriver = httpRequest.getParameter("database_driver");
×
545
                        checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_DRIVER_REQ);
×
546
                        
547
                        loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
×
548
                        if (!StringUtils.hasText(loadedDriverString)) {
×
549
                                errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
×
550
                                renderTemplate(page, referenceMap, httpResponse);
×
551
                                return;
×
552
                        }
553
                        
554
                        //TODO make each bit of page logic a (unit testable) method
555
                        
556
                        // asked the user for their desired database name
557
                        
558
                        if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
×
559
                                wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
×
560
                                checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_CURR_NAME_REQ);
×
561
                                wizardModel.hasCurrentOpenmrsDatabase = true;
×
562
                                // TODO check to see if this is an active database
563
                                
564
                        } else {
565
                                // mark this wizard as a "to create database" (done at the end)
566
                                wizardModel.hasCurrentOpenmrsDatabase = false;
×
567
                                
568
                                wizardModel.createTables = true;
×
569
                                
570
                                wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
×
571
                                checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_NEW_NAME_REQ);
×
572
                                // TODO create database now to check if its possible?
573
                                
574
                                wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
×
575
                                checkForEmptyValue(wizardModel.createDatabaseUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
×
576
                                wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
×
577
                                checkForEmptyValue(wizardModel.createDatabasePassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
×
578
                        }
579
                        
580
                        if (errors.isEmpty()) {
×
581
                                page = DATABASE_TABLES_AND_USER;
×
582
                                
583
                                if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
×
584
                                        wizardModel.currentStepNumber = 3;
×
585
                                } else {
586
                                        wizardModel.currentStepNumber = 2;
×
587
                                }
588
                        }
589
                        
590
                        renderTemplate(page, referenceMap, httpResponse);
×
591
                        
592
                } // step two
593
                else if (DATABASE_TABLES_AND_USER.equals(page)) {
×
594
                        
595
                        if (goBack(httpRequest)) {
×
596
                                wizardModel.currentStepNumber -= 1;
×
597
                                renderTemplate(DATABASE_SETUP, referenceMap, httpResponse);
×
598
                                return;
×
599
                        }
600
                        
601
                        if (wizardModel.hasCurrentOpenmrsDatabase) {
×
602
                                wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
×
603
                        }
604
                        
605
                        wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
×
606
                        
607
                        if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
×
608
                                wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
×
609
                                checkForEmptyValue(wizardModel.currentDatabaseUsername, errors,
×
610
                                        ErrorMessageConstants.ERROR_DB_CUR_USER_NAME_REQ);
611
                                wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
×
612
                                checkForEmptyValue(wizardModel.currentDatabasePassword, errors,
×
613
                                        ErrorMessageConstants.ERROR_DB_CUR_USER_PSWD_REQ);
614
                                wizardModel.hasCurrentDatabaseUser = true;
×
615
                                wizardModel.createDatabaseUser = false;
×
616
                        } else {
617
                                wizardModel.hasCurrentDatabaseUser = false;
×
618
                                wizardModel.createDatabaseUser = true;
×
619
                                // asked for the root mysql username/password
620
                                wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
×
621
                                checkForEmptyValue(wizardModel.createUserUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
×
622
                                wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
×
623
                                checkForEmptyValue(wizardModel.createUserPassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
×
624
                        }
625
                        
626
                        if (errors.isEmpty()) { // go to next page
×
627
                                page = InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod) ? WIZARD_COMPLETE
×
628
                                        : OTHER_RUNTIME_PROPS;
629
                        }
630
                        
631
                        renderTemplate(page, referenceMap, httpResponse);
×
632
                } // step three
633
                else if (OTHER_RUNTIME_PROPS.equals(page)) {
×
634
                        
635
                        if (goBack(httpRequest)) {
×
636
                                renderTemplate(DATABASE_TABLES_AND_USER, referenceMap, httpResponse);
×
637
                                return;
×
638
                        }
639
                        
640
                        wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
×
641
                        wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
×
642
                        
643
                        if (wizardModel.createTables) { // go to next page if they are creating tables
×
644
                                page = ADMIN_USER_SETUP;
×
645
                        } else { // skip a page
646
                                page = IMPLEMENTATION_ID_SETUP;
×
647
                        }
648
                        
649
                        renderTemplate(page, referenceMap, httpResponse);
×
650
                        
651
                } // optional step four
652
                else if (ADMIN_USER_SETUP.equals(page)) {
×
653
                        
654
                        if (goBack(httpRequest)) {
×
655
                                renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
×
656
                                return;
×
657
                        }
658
                        
659
                        wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
×
660
                        String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
×
661
                        
662
                        // throw back to admin user if passwords don't match
663
                        if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
×
664
                                errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSWDS_MATCH, null);
×
665
                                renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
×
666
                                return;
×
667
                        }
668
                        
669
                        // throw back if the user didn't put in a password
670
                        if ("".equals(wizardModel.adminUserPassword)) {
×
671
                                errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_EMPTY, null);
×
672
                                renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
×
673
                                return;
×
674
                        }
675
                        
676
                        try {
677
                                OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
×
678
                        }
679
                        catch (PasswordException p) {
×
680
                                errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_WEAK, null);
×
681
                                renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
×
682
                                return;
×
683
                        }
×
684
                        
685
                        if (errors.isEmpty()) { // go to next page
×
686
                                page = IMPLEMENTATION_ID_SETUP;
×
687
                        }
688
                        
689
                        renderTemplate(page, referenceMap, httpResponse);
×
690
                        
691
                } // optional step five
×
692
                else if (IMPLEMENTATION_ID_SETUP.equals(page)) {
×
693
                        
694
                        if (goBack(httpRequest)) {
×
695
                                if (wizardModel.createTables) {
×
696
                                        renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
×
697
                                } else {
698
                                        renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
×
699
                                }
700
                                return;
×
701
                        }
702
                        
703
                        wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
×
704
                        wizardModel.implementationId = httpRequest.getParameter("implementation_id");
×
705
                        wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
×
706
                        wizardModel.implementationIdDescription = httpRequest.getParameter("description");
×
707
                        
708
                        // throw back if the user-specified ID is invalid (contains ^ or |).
709
                        if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
×
710
                                errors.put(ErrorMessageConstants.ERROR_DB_IMPL_ID_REQ, null);
×
711
                                renderTemplate(IMPLEMENTATION_ID_SETUP, referenceMap, httpResponse);
×
712
                                return;
×
713
                        }
714
                        
715
                        if (errors.isEmpty()) { // go to next page
×
716
                                page = WIZARD_COMPLETE;
×
717
                        }
718
                        
719
                        renderTemplate(page, referenceMap, httpResponse);
×
720
                } else if (WIZARD_COMPLETE.equals(page)) {
×
721
                        
722
                        if (goBack(httpRequest)) {
×
723
                                
724
                                if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
×
725
                                        page = SIMPLE_SETUP;
×
726
                                } else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
×
727
                                        if (skipDatabaseSetupPage()) {
×
728
                                                page = TESTING_REMOTE_DETAILS_SETUP;
×
729
                                        } else {
730
                                                page = DATABASE_TABLES_AND_USER;
×
731
                                        }
732
                                } else {
733
                                        page = IMPLEMENTATION_ID_SETUP;
×
734
                                }
735
                                renderTemplate(page, referenceMap, httpResponse);
×
736
                                return;
×
737
                        }
738
                        
739
                        wizardModel.tasksToExecute = new ArrayList<>();
×
740
                        createDatabaseTask();
×
741
                        if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
×
742
                                wizardModel.importTestData = true;
×
743
                                wizardModel.createTables = false;
×
744
                                wizardModel.addDemoData = false;
×
745
                                //if we have a runtime properties file
746
                                if (skipDatabaseSetupPage()) {
×
747
                                        wizardModel.hasCurrentOpenmrsDatabase = false;
×
748
                                        wizardModel.hasCurrentDatabaseUser = true;
×
749
                                        wizardModel.createDatabaseUser = false;
×
750
                                        Properties props = OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
×
751
                                        wizardModel.currentDatabaseUsername = props.getProperty("connection.username");
×
752
                                        wizardModel.currentDatabasePassword = props.getProperty("connection.password");
×
753
                                        wizardModel.createDatabaseUsername = wizardModel.currentDatabaseUsername;
×
754
                                        wizardModel.createDatabasePassword = wizardModel.currentDatabasePassword;
×
755
                                }
756
                                
757
                                wizardModel.tasksToExecute.add(WizardTask.IMPORT_TEST_DATA);
×
758
                                wizardModel.tasksToExecute.add(WizardTask.ADD_MODULES);
×
759
                        } else {
760
                                createTablesTask();
×
761
                                createDemoDataTask();
×
762
                        }
763
                        wizardModel.tasksToExecute.add(WizardTask.UPDATE_TO_LATEST);
×
764
                        
765
                        referenceMap.put("tasksToExecute", wizardModel.tasksToExecute);
×
766
                        startInstallation();
×
767
                        renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
×
768
                } else if (TESTING_REMOTE_DETAILS_SETUP.equals(page)) {
×
769
                        if (goBack(httpRequest)) {
×
770
                                wizardModel.currentStepNumber -= 1;
×
771
                                renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
772
                                return;
×
773
                        }
774
                        
775
                        wizardModel.remoteUrl = httpRequest.getParameter("remoteUrl");
×
776
                        checkForEmptyValue(wizardModel.remoteUrl, errors, "install.testing.remote.url.required");
×
777
                        if (errors.isEmpty()) {
×
778
                                //Check if the remote system is running
779
                                if (TestInstallUtil.testConnection(wizardModel.remoteUrl)) {
×
780
                                        //Check if the test module is installed by connecting to its setting page
781
                                        if (TestInstallUtil
×
782
                                                .testConnection(wizardModel.remoteUrl.concat(RELEASE_TESTING_MODULE_PATH + "settings.htm"))) {
×
783
                                                
784
                                                wizardModel.remoteUsername = httpRequest.getParameter("username");
×
785
                                                wizardModel.remotePassword = httpRequest.getParameter("password");
×
786
                                                checkForEmptyValue(wizardModel.remoteUsername, errors, "install.testing.username.required");
×
787
                                                checkForEmptyValue(wizardModel.remotePassword, errors, "install.testing.password.required");
×
788
                                                
789
                                                if (errors.isEmpty()) {
×
790
                                                        //check if the username and password are valid
791
                                                        try {
792
                                                                TestInstallUtil.getResourceInputStream(
×
793
                                                                        wizardModel.remoteUrl + RELEASE_TESTING_MODULE_PATH + "verifycredentials.htm",
794
                                                                        wizardModel.remoteUsername, wizardModel.remotePassword);
795
                                                        }
796
                                                        catch (APIAuthenticationException e) {
×
797
                                                                log.debug("Error generated: ", e);
×
798
                                                                page = TESTING_REMOTE_DETAILS_SETUP;
×
799
                                                                errors.put(ErrorMessageConstants.UPDATE_ERROR_UNABLE_AUTHENTICATE, null);
×
800
                                                                renderTemplate(page, referenceMap, httpResponse);
×
801
                                                                return;
×
802
                                                        }
×
803
                                                        
804
                                                        //If we have a runtime properties file, get the database setup details from it
805
                                                        if (skipDatabaseSetupPage()) {
×
806
                                                                Properties props = OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
×
807
                                                                wizardModel.databaseConnection = props.getProperty("connection.url");
×
808
                                                                loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
×
809
                                                                if (!StringUtils.hasText(loadedDriverString)) {
×
810
                                                                        page = TESTING_REMOTE_DETAILS_SETUP;
×
811
                                                                        errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
×
812
                                                                        renderTemplate(page, referenceMap, httpResponse);
×
813
                                                                        return;
×
814
                                                                }
815
                                                                
816
                                                                wizardModel.databaseName = InitializationWizardModel.DEFAULT_DATABASE_NAME;
×
817
                                                                page = WIZARD_COMPLETE;
×
818
                                                        } else {
×
819
                                                                page = DATABASE_SETUP;
×
820
                                                                wizardModel.currentStepNumber = 2;
×
821
                                                        }
822
                                                        msgs.put("install.testing.testingModuleFound", null);
×
823
                                                } else {
824
                                                        renderTemplate(page, referenceMap, httpResponse);
×
825
                                                        return;
×
826
                                                }
827
                                        } else {
828
                                                errors.put("install.testing.noTestingModule", null);
×
829
                                        }
830
                                } else {
831
                                        errors.put("install.testing.invalidProductionUrl", new Object[] { wizardModel.remoteUrl });
×
832
                                }
833
                        }
834
                        
835
                        renderTemplate(page, referenceMap, httpResponse);
×
836
                }
837
        }
×
838
        
839
        private void startInstallation() {
840
                //if no one has run any installation
841
                if (!isInstallationStarted()) {
×
842
                        initJob = new InitializationCompletion();
×
843
                        setInstallationStarted(true);
×
844
                        initJob.start();
×
845
                }
846
        }
×
847
        
848
        private void createDemoDataTask() {
849
                if (wizardModel.addDemoData) {
×
850
                        wizardModel.tasksToExecute.add(WizardTask.ADD_DEMO_DATA);
×
851
                }
852
        }
×
853
        
854
        private void createTablesTask() {
855
                if (wizardModel.createTables) {
×
856
                        wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
×
857
                        wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
×
858
                }
859
        }
×
860
        
861
        private void createDatabaseTask() {
862
                if (!wizardModel.hasCurrentOpenmrsDatabase) {
×
863
                        wizardModel.tasksToExecute.add(WizardTask.CREATE_SCHEMA);
×
864
                }
865
                if (wizardModel.createDatabaseUser) {
×
866
                        wizardModel.tasksToExecute.add(WizardTask.CREATE_DB_USER);
×
867
                }
868
        }
×
869
        
870
        private void createSimpleSetup(String databaseRootPassword, String addDemoData) {
871
                setDatabaseNameIfInTestMode();
×
872
                wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
×
873
                        wizardModel.databaseConnection);
874
                
875
                wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
×
876
                        wizardModel.createDatabaseUsername);
877
                
878
                wizardModel.createUserUsername = wizardModel.createDatabaseUsername;
×
879
                
880
                wizardModel.databaseRootPassword = databaseRootPassword;
×
881
                checkForEmptyValue(wizardModel.databaseRootPassword, errors, ErrorMessageConstants.ERROR_DB_PSDW_REQ);
×
882
                
883
                wizardModel.hasCurrentOpenmrsDatabase = false;
×
884
                wizardModel.createTables = true;
×
885
                // default wizardModel.databaseName is openmrs
886
                // default wizardModel.createDatabaseUsername is root
887
                wizardModel.createDatabasePassword = wizardModel.databaseRootPassword;
×
888
                wizardModel.addDemoData = "yes".equals(addDemoData);
×
889
                
890
                wizardModel.hasCurrentDatabaseUser = false;
×
891
                wizardModel.createDatabaseUser = true;
×
892
                // default wizardModel.createUserUsername is root
893
                wizardModel.createUserPassword = wizardModel.databaseRootPassword;
×
894
                
895
                wizardModel.moduleWebAdmin = true;
×
896
                wizardModel.autoUpdateDatabase = false;
×
897
                
898
                wizardModel.adminUserPassword = InitializationWizardModel.ADMIN_DEFAULT_PASSWORD;
×
899
        }
×
900
        
901
        private void setDatabaseNameIfInTestMode() {
902
                if (OpenmrsUtil.isTestMode()) {
×
903
                        wizardModel.databaseName = OpenmrsUtil.getOpenMRSVersionInTestMode();
×
904
                }
905
        }
×
906
        
907
        private void autoRunOpenMRS(HttpServletRequest httpRequest) {
908
                File runtimeProperties = getRuntimePropertiesFile();
×
909
                wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
×
910
                
911
                if (!InitializationWizardModel.INSTALL_METHOD_AUTO.equals(wizardModel.installMethod)) {
×
912
                        if (httpRequest.getParameter("database_user_name") != null) {
×
913
                                wizardModel.createDatabaseUsername = httpRequest.getParameter("database_user_name");
×
914
                        }
915
                        
916
                        createSimpleSetup(httpRequest.getParameter("database_root_password"), "yes");
×
917
                }
918
                
919
                checkLocaleAttributes(httpRequest);
×
920
                try {
921
                        loadedDriverString = DatabaseUtil.loadDatabaseDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
×
922
                }
923
                catch (ClassNotFoundException e) {
×
924
                        errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
×
925
                        return;
×
926
                }
×
927
                wizardModel.tasksToExecute = new ArrayList<>();
×
928
                createDatabaseTask();
×
929
                createTablesTask();
×
930
                createDemoDataTask();
×
931
                wizardModel.tasksToExecute.add(WizardTask.UPDATE_TO_LATEST);
×
932
                startInstallation();
×
933
        }
×
934
        
935
        /**
936
         * This method should be called after the user has left wizard's first page (i.e. choose language).
937
         * It checks if user has changed any of locale related parameters and makes appropriate corrections
938
         * with filter's model or/and with locale attribute inside user's session.
939
         *
940
         * @param httpRequest the http request object
941
         */
942
        private void checkLocaleAttributes(HttpServletRequest httpRequest) {
943
                String localeParameter = httpRequest.getParameter(FilterUtil.LOCALE_ATTRIBUTE);
×
944
                Boolean rememberLocale = false;
×
945
                // we need to check if user wants that system will remember his selection of language
946
                if (httpRequest.getParameter(FilterUtil.REMEMBER_ATTRIBUTE) != null) {
×
947
                        rememberLocale = true;
×
948
                }
949
                if (localeParameter != null) {
×
950
                        String storedLocale = null;
×
951
                        if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
×
952
                                storedLocale = httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE).toString();
×
953
                        }
954
                        // if user has changed locale parameter to new one
955
                        // or chooses it parameter at first page loading
956
                        if (storedLocale == null || !storedLocale.equals(localeParameter)) {
×
957
                                log.info("Stored locale parameter to session " + localeParameter);
×
958
                                httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, localeParameter);
×
959
                        }
960
                        if (rememberLocale) {
×
961
                                httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, localeParameter);
×
962
                                httpRequest.getSession().setAttribute(FilterUtil.REMEMBER_ATTRIBUTE, true);
×
963
                                wizardModel.localeToSave = localeParameter;
×
964
                        } else {
965
                                // we need to reset it if it was set before
966
                                httpRequest.getSession().setAttribute(FilterUtil.REMEMBER_ATTRIBUTE, null);
×
967
                                wizardModel.localeToSave = null;
×
968
                        }
969
                }
970
        }
×
971
        
972
        /**
973
         * It sets locale parameter for current session when user is making first GET http request to
974
         * application. It retrieves user locale from request object and checks if this locale is supported
975
         * by application. If not, it uses {@link Locale#ENGLISH} by default
976
         *
977
         * @param httpRequest the http request object
978
         */
979
        public void checkLocaleAttributesForFirstTime(HttpServletRequest httpRequest) {
980
                Locale locale = httpRequest.getLocale();
×
981
                if (CustomResourceLoader.getInstance(httpRequest).getAvailablelocales().contains(locale)) {
×
982
                        httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, locale.toString());
×
983
                } else {
984
                        httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, Locale.ENGLISH.toString());
×
985
                }
986
        }
×
987
        
988
        /**
989
         * Verify the database connection works.
990
         *
991
         * @param connectionUsername
992
         * @param connectionPassword
993
         * @param databaseConnectionFinalUrl
994
         * @return true/false whether it was verified or not
995
         */
996
        private boolean verifyConnection(String connectionUsername, String connectionPassword,
997
                String databaseConnectionFinalUrl) {
998
                try {
999
                        // verify connection
1000
                        //Set Database Driver using driver String
1001
                        Class.forName(loadedDriverString).newInstance();
×
1002
                        try (Connection ignored = DriverManager.getConnection(databaseConnectionFinalUrl, connectionUsername, connectionPassword)) {
×
1003
                                return true;
×
1004
                        }
1005
                }
1006
                catch (Exception e) {
×
1007
                        errors.put("User account " + connectionUsername + " does not work. " + e.getMessage()
×
1008
                                        + " See the error log for more details",
1009
                                null); // TODO internationalize this
1010
                        log.warn("Error while checking the connection user account", e);
×
1011
                        return false;
×
1012
                }
1013
        }
1014
        
1015
        /**
1016
         * Convenience method to load the runtime properties file.
1017
         *
1018
         * @return the runtime properties file.
1019
         */
1020
        private File getRuntimePropertiesFile() {
1021
                File file;
1022
                
1023
                String pathName = OpenmrsUtil.getRuntimePropertiesFilePathName(WebConstants.WEBAPP_NAME);
×
1024
                if (pathName != null) {
×
1025
                        file = new File(pathName);
×
1026
                } else {
1027
                        file = new File(OpenmrsUtil.getApplicationDataDirectory(), getRuntimePropertiesFileName());
×
1028
                }
1029
                
1030
                log.debug("Using file: " + file.getAbsolutePath());
×
1031
                
1032
                return file;
×
1033
        }
1034
        
1035
        private String getRuntimePropertiesFileName() {
1036
                String fileName = OpenmrsUtil.getRuntimePropertiesFileNameInTestMode();
×
1037
                if (fileName == null) {
×
1038
                        fileName = WebConstants.WEBAPP_NAME + "-runtime.properties";
×
1039
                }
1040
                return fileName;
×
1041
        }
1042
        
1043
        /**
1044
         * @see org.openmrs.web.filter.StartupFilter#getTemplatePrefix()
1045
         */
1046
        @Override
1047
        protected String getTemplatePrefix() {
1048
                return "org/openmrs/web/filter/initialization/";
×
1049
        }
1050
        
1051
        /**
1052
         * @see org.openmrs.web.filter.StartupFilter#getUpdateFilterModel()
1053
         */
1054
        @Override
1055
        protected Object getUpdateFilterModel() {
1056
                return wizardModel;
×
1057
        }
1058
        
1059
        /**
1060
         * @see org.openmrs.web.filter.StartupFilter#skipFilter(HttpServletRequest)
1061
         */
1062
        @Override
1063
        public boolean skipFilter(HttpServletRequest httpRequest) {
1064
                // If progress.vm makes an ajax request even immediately after initialization has completed
1065
                // let the request pass in order to let progress.vm load the start page of OpenMRS
1066
                // (otherwise progress.vm is displayed "forever")
1067
                return !PROGRESS_VM_AJAXREQUEST.equals(httpRequest.getParameter("page")) && !initializationRequired();
×
1068
        }
1069
        
1070
        /**
1071
         * Public method that returns true if database+runtime properties initialization is required
1072
         *
1073
         * @return true if this initialization wizard needs to run
1074
         */
1075
        public static boolean initializationRequired() {
1076
                return !isInitializationComplete();
×
1077
        }
1078
        
1079
        /**
1080
         * @param isInstallationStarted the value to set
1081
         */
1082
        protected static synchronized void setInstallationStarted(boolean isInstallationStarted) {
1083
                InitializationFilter.isInstallationStarted = isInstallationStarted;
×
1084
        }
×
1085
        
1086
        /**
1087
         * @return true if installation has been started
1088
         */
1089
        protected static boolean isInstallationStarted() {
1090
                return isInstallationStarted;
×
1091
        }
1092
        
1093
        /**
1094
         * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
1095
         */
1096
        @Override
1097
        public void init(FilterConfig filterConfig) throws ServletException {
1098
                super.init(filterConfig);
×
1099
                wizardModel = new InitializationWizardModel();
×
1100
                DatabaseDetective databaseDetective = new DatabaseDetective();
×
1101
                //set whether need to do initialization work
1102
                if (databaseDetective.isDatabaseEmpty(OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME))) {
×
1103
                        //if runtime-properties file doesn't exist, have to do initialization work
1104
                        setInitializationComplete(false);
×
1105
                } else {
1106
                        //if database is not empty, then let UpdaterFilter to judge whether need database update
1107
                        setInitializationComplete(true);
×
1108
                }
1109
        }
×
1110
        
1111
        private void importTestDataSet(InputStream in, String connectionUrl, String connectionUsername,
1112
                String connectionPassword) throws IOException {
1113
                File tempFile = null;
×
1114
                FileOutputStream fileOut = null;
×
1115
                try {
1116
                        ZipInputStream zipIn = new ZipInputStream(in);
×
1117
                        zipIn.getNextEntry();
×
1118
                        
1119
                        tempFile = File.createTempFile("testDataSet", "dump");
×
1120
                        fileOut = new FileOutputStream(tempFile);
×
1121
                        
1122
                        IOUtils.copy(zipIn, fileOut);
×
1123
                        
1124
                        fileOut.close();
×
1125
                        zipIn.close();
×
1126
                        
1127
                        //Cater for the stand-alone connection url with has :mxj:
1128
                        if (connectionUrl.contains(":mxj:")) {
×
1129
                                connectionUrl = connectionUrl.replace(":mxj:", ":");
×
1130
                        }
1131
                        
1132
                        URI uri = URI.create(connectionUrl.substring(5)); //remove 'jdbc:' prefix to conform to the URI format
×
1133
                        String host = uri.getHost();
×
1134
                        int port = uri.getPort();
×
1135
                        
1136
                        TestInstallUtil.addTestData(host, port, wizardModel.databaseName, connectionUsername, connectionPassword,
×
1137
                                tempFile.getAbsolutePath());
×
1138
                }
1139
                finally {
1140
                        IOUtils.closeQuietly(in);
×
1141
                        IOUtils.closeQuietly(fileOut);
×
1142
                        
1143
                        if (tempFile != null) {
×
1144
                                tempFile.delete();
×
1145
                        }
1146
                }
1147
        }
×
1148
        
1149
        private boolean isCurrentDatabase(String database) {
1150
                return wizardModel.databaseConnection.contains(database);
×
1151
        }
1152
        
1153
        /**
1154
         * @param silent if this statement fails do not display stack trace or record an error in the wizard
1155
         *            object.
1156
         * @param user username to connect with
1157
         * @param pw password to connect with
1158
         * @param sql String containing sql and question marks
1159
         * @param args the strings to fill into the question marks in the given sql
1160
         * @return result of executeUpdate or -1 for error
1161
         */
1162
        private int executeStatement(boolean silent, String user, String pw, String sql, String... args) {
1163
                
1164
                Connection connection = null;
×
1165
                Statement statement = null;
×
1166
                try {
1167
                        String replacedSql = sql;
×
1168
                        
1169
                        // TODO how to get the driver for the other dbs...
1170
                        if (isCurrentDatabase(DATABASE_MYSQL)) {
×
1171
                                Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
×
NEW
1172
                        }else if(isCurrentDatabase(DATABASE_MARIADB)){
×
NEW
1173
                                Class.forName("org.mariadb.jdbc.Driver").newInstance();
×
1174
                        } else if (isCurrentDatabase(DATABASE_POSTGRESQL)) {
×
1175
                                Class.forName("org.postgresql.Driver").newInstance();
×
1176
                                replacedSql = replacedSql.replaceAll("`", "\"");
×
1177
                        } else {
1178
                                replacedSql = replacedSql.replaceAll("`", "\"");
×
1179
                        }
1180
                        
1181
                        String tempDatabaseConnection;
1182
                        if (sql.contains("create database")) {
×
1183
                                tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@",
×
1184
                                        ""); // make this dbname agnostic so we can create the db
1185
                        } else {
1186
                                tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName);
×
1187
                        }
1188
                        
1189
                        connection = DriverManager.getConnection(tempDatabaseConnection, user, pw);
×
1190
                        
1191
                        for (String arg : args) {
×
1192
                                arg = arg.replace(";", "&#094"); // to prevent any sql injection
×
1193
                                replacedSql = replacedSql.replaceFirst("\\?", arg);
×
1194
                        }
1195
                        
1196
                        // run the sql statement
1197
                        statement = connection.createStatement();
×
1198
                        
1199
                        return statement.executeUpdate(replacedSql);
×
1200
                        
1201
                }
1202
                catch (SQLException sqlex) {
×
1203
                        if (!silent) {
×
1204
                                // log and add error
1205
                                log.warn("error executing sql: " + sql, sqlex);
×
1206
                                errors.put("Error executing sql: " + sql + " - " + sqlex.getMessage(), null);
×
1207
                        }
1208
                }
1209
                catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) {
×
1210
                        log.error("Error generated", e);
×
1211
                }
1212
                finally {
1213
                        try {
1214
                                if (statement != null) {
×
1215
                                        statement.close();
×
1216
                                }
1217
                        }
1218
                        catch (SQLException e) {
×
1219
                                log.warn("Error while closing statement");
×
1220
                        }
×
1221
                        try {
1222
                                
1223
                                if (connection != null) {
×
1224
                                        connection.close();
×
1225
                                }
1226
                        }
1227
                        catch (Exception e) {
×
1228
                                log.warn("Error while closing connection", e);
×
1229
                        }
×
1230
                }
1231
                
1232
                return -1;
×
1233
        }
1234
        
1235
        /**
1236
         * Convenience variable to know if this wizard has completed successfully and that this wizard does
1237
         * not need to be executed again
1238
         *
1239
         * @return true if this has been run already
1240
         */
1241
        private static synchronized boolean isInitializationComplete() {
1242
                return initializationComplete;
×
1243
        }
1244
        
1245
        /**
1246
         * Check if the given value is null or a zero-length String
1247
         *
1248
         * @param value the string to check
1249
         * @param errors the list of errors to append the errorMessage to if value is empty
1250
         * @param errorMessageCode the string with code of error message translation to append if value is
1251
         *            empty
1252
         * @return true if the value is non-empty
1253
         */
1254
        private boolean checkForEmptyValue(String value, Map<String, Object[]> errors, String errorMessageCode) {
1255
                if (!StringUtils.isEmpty(value)) {
×
1256
                        return true;
×
1257
                }
1258
                errors.put(errorMessageCode, null);
×
1259
                return false;
×
1260
        }
1261
        
1262
        /**
1263
         * Separate thread that will run through all tasks to complete the initialization. The database is
1264
         * created, user's created, etc here
1265
         */
1266
        private class InitializationCompletion {
1267
                
1268
                private final Future<Void> future;
1269
                
1270
                private int steps = 0;
×
1271
                
1272
                private String message = "";
×
1273
                
1274
                private Map<String, Object[]> errors = new HashMap<>();
×
1275
                
1276
                private String errorPage = null;
×
1277
                
1278
                private boolean erroneous = false;
×
1279
                
1280
                private int completedPercentage = 0;
×
1281
                
1282
                private WizardTask executingTask;
1283
                
1284
                private List<WizardTask> executedTasks = new ArrayList<>();
×
1285
                
1286
                public synchronized void reportError(String error, String errorPage, Object... params) {
1287
                        errors.put(error, params);
×
1288
                        this.errorPage = errorPage;
×
1289
                        erroneous = true;
×
1290
                }
×
1291
                
1292
                public synchronized boolean hasErrors() {
1293
                        return erroneous;
×
1294
                }
1295
                
1296
                public synchronized String getErrorPage() {
1297
                        return errorPage;
×
1298
                }
1299
                
1300
                public synchronized Map<String, Object[]> getErrors() {
1301
                        return errors;
×
1302
                }
1303
                
1304
                /**
1305
                 * Start the completion stage. This fires up the thread to do all the work.
1306
                 */
1307
                public void start() {
1308
                        setStepsComplete(0);
×
1309
                        setInitializationComplete(false);
×
1310
                }
×
1311
                
1312
                public void waitForCompletion() {
1313
                        try {
1314
                                future.get();
×
1315
                        } catch (InterruptedException | ExecutionException e) {
×
1316
                                throw new RuntimeException(e);
×
1317
                        }
×
1318
                }
×
1319
                
1320
                protected synchronized void setStepsComplete(int steps) {
1321
                        this.steps = steps;
×
1322
                }
×
1323
                
1324
                protected synchronized int getStepsComplete() {
1325
                        return steps;
×
1326
                }
1327
                
1328
                public synchronized String getMessage() {
1329
                        return message;
×
1330
                }
1331
                
1332
                public synchronized void setMessage(String message) {
1333
                        log.debug(message);
×
1334
                        this.message = message;
×
1335
                        setStepsComplete(getStepsComplete() + 1);
×
1336
                }
×
1337
                
1338
                /**
1339
                 * @return the executingTask
1340
                 */
1341
                protected synchronized WizardTask getExecutingTask() {
1342
                        return executingTask;
×
1343
                }
1344
                
1345
                /**
1346
                 * @return the completedPercentage
1347
                 */
1348
                protected synchronized int getCompletedPercentage() {
1349
                        return completedPercentage;
×
1350
                }
1351
                
1352
                /**
1353
                 * @param completedPercentage the completedPercentage to set
1354
                 */
1355
                protected synchronized void setCompletedPercentage(int completedPercentage) {
1356
                        this.completedPercentage = completedPercentage;
×
1357
                }
×
1358
                
1359
                /**
1360
                 * Adds a task that has been completed to the list of executed tasks
1361
                 *
1362
                 * @param task
1363
                 */
1364
                protected synchronized void addExecutedTask(WizardTask task) {
1365
                        this.executedTasks.add(task);
×
1366
                }
×
1367
                
1368
                /**
1369
                 * @param executingTask the executingTask to set
1370
                 */
1371
                protected synchronized void setExecutingTask(WizardTask executingTask) {
1372
                        this.executingTask = executingTask;
×
1373
                }
×
1374
                
1375
                /**
1376
                 * @return the executedTasks
1377
                 */
1378
                protected synchronized List<WizardTask> getExecutedTasks() {
1379
                        return this.executedTasks;
×
1380
                }
1381
                
1382
                /**
1383
                 * This class does all the work of creating the desired database, user, updates, etc
1384
                 */
1385
                public InitializationCompletion() {
×
1386
                        Runnable r = new Runnable() {
×
1387
                                
1388
                                /**
1389
                                 * TODO split this up into multiple testable methods
1390
                                 *
1391
                                 * @see java.lang.Runnable#run()
1392
                                 */
1393
                                @Override
1394
                                public void run() {
1395
                                        try {
1396
                                                String connectionUsername;
1397
                                                StringBuilder connectionPassword = new StringBuilder();
×
1398
                                                ChangeLogDetective changeLogDetective = ChangeLogDetective.getInstance();
×
1399
                                                ChangeLogVersionFinder changeLogVersionFinder = new ChangeLogVersionFinder();
×
1400
                                                
1401
                                                if (!wizardModel.hasCurrentOpenmrsDatabase) {
×
1402
                                                        setMessage("Create database");
×
1403
                                                        setExecutingTask(WizardTask.CREATE_SCHEMA);
×
1404
                                                        // connect via jdbc and create a database
1405
                                                        String sql;
1406
                                                        if (isCurrentDatabase(DATABASE_MYSQL)) {
×
1407
                                                                sql = "create database if not exists `?` default character set utf8";
×
1408
                                                        } else if (isCurrentDatabase(DATABASE_POSTGRESQL)) {
×
1409
                                                                sql = "create database `?` encoding 'utf8'";
×
1410
                                                        } else if (isCurrentDatabase(DATABASE_H2)) {
×
1411
                                                                sql = null;
×
1412
                                                        } else {
1413
                                                                sql = "create database `?`";
×
1414
                                                        }
1415
                                                        
1416
                                                        int result;
1417
                                                        if (sql != null) {
×
1418
                                                                result = executeStatement(false, wizardModel.createDatabaseUsername,
×
1419
                                                                        wizardModel.createDatabasePassword, sql, wizardModel.databaseName);
×
1420
                                                        } else {
1421
                                                                result = 1;
×
1422
                                                        }
1423
                                                        // throw the user back to the main screen if this error occurs
1424
                                                        if (result < 0) {
×
1425
                                                                reportError(ErrorMessageConstants.ERROR_DB_CREATE_NEW, DEFAULT_PAGE);
×
1426
                                                                return;
×
1427
                                                        } else {
1428
                                                                wizardModel.workLog.add("Created database " + wizardModel.databaseName);
×
1429
                                                        }
1430
                                                        
1431
                                                        addExecutedTask(WizardTask.CREATE_SCHEMA);
×
1432
                                                }
1433
                                                
1434
                                                if (wizardModel.createDatabaseUser) {
×
1435
                                                        setMessage("Create database user");
×
1436
                                                        setExecutingTask(WizardTask.CREATE_DB_USER);
×
1437
                                                        connectionUsername = wizardModel.databaseName + "_user";
×
1438
                                                        if (connectionUsername.length() > 16) {
×
1439
                                                                connectionUsername = wizardModel.databaseName.substring(0, 11)
×
1440
                                                                        + "_user"; // trim off enough to leave space for _user at the end
1441
                                                        }
1442
                                                        
1443
                                                        connectionPassword.append("");
×
1444
                                                        // generate random password from this subset of alphabet
1445
                                                        // intentionally left out these characters: ufsb$() to prevent certain words forming randomly
1446
                                                        String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&";
×
1447
                                                        Random r = new Random();
×
1448
                                                        StringBuilder randomStr = new StringBuilder("");
×
1449
                                                        for (int x = 0; x < 12; x++) {
×
1450
                                                                randomStr.append(chars.charAt(r.nextInt(chars.length())));
×
1451
                                                        }
1452
                                                        connectionPassword.append(randomStr);
×
1453
                                                        
1454
                                                        // connect via jdbc with root user and create an openmrs user
1455
                                                        String host = "'%'";
×
1456
                                                        if (wizardModel.databaseConnection.contains("localhost")
×
1457
                                                                || wizardModel.databaseConnection.contains("127.0.0.1")) {
×
1458
                                                                host = "'localhost'";
×
1459
                                                        }
1460
                                                        
1461
                                                        String sql = "";
×
1462
                                                        if (isCurrentDatabase(DATABASE_MYSQL)) {
×
1463
                                                                sql = "drop user '?'@" + host;
×
1464
                                                        } else if (isCurrentDatabase(DATABASE_POSTGRESQL)) {
×
1465
                                                                sql = "drop user `?`";
×
1466
                                                        }
1467
                                                        
1468
                                                        executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
×
1469
                                                                connectionUsername);
1470
                                                        
1471
                                                        if (isCurrentDatabase(DATABASE_MYSQL)) {
×
1472
                                                                sql = "create user '?'@" + host + " identified by '?'";
×
1473
                                                        } else if (isCurrentDatabase(DATABASE_POSTGRESQL)) {
×
1474
                                                                sql = "create user `?` with password '?'";
×
1475
                                                        }
1476
                                                        
1477
                                                        if (-1 != executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword,
×
1478
                                                                sql, connectionUsername, connectionPassword.toString())) {
×
1479
                                                                wizardModel.workLog.add("Created user " + connectionUsername);
×
1480
                                                        } else {
1481
                                                                // if error occurs stop
1482
                                                                reportError(ErrorMessageConstants.ERROR_DB_CREATE_DB_USER, DEFAULT_PAGE);
×
1483
                                                                return;
×
1484
                                                        }
1485
                                                        
1486
                                                        // grant the roles
1487
                                                        int result = 1;
×
1488
                                                        if (isCurrentDatabase(DATABASE_MYSQL)) {
×
1489
                                                                sql = "GRANT ALL ON `?`.* TO '?'@" + host;
×
1490
                                                                result = executeStatement(false, wizardModel.createUserUsername,
×
1491
                                                                        wizardModel.createUserPassword, sql, wizardModel.databaseName, connectionUsername);
×
1492
                                                        } else if (isCurrentDatabase(DATABASE_POSTGRESQL)) {
×
1493
                                                                sql = "ALTER USER `?` WITH SUPERUSER";
×
1494
                                                                result = executeStatement(false, wizardModel.createUserUsername,
×
1495
                                                                        wizardModel.createUserPassword, sql, connectionUsername);
×
1496
                                                        }
1497
                                                        
1498
                                                        // throw the user back to the main screen if this error occurs
1499
                                                        if (result < 0) {
×
1500
                                                                reportError(ErrorMessageConstants.ERROR_DB_GRANT_PRIV, DEFAULT_PAGE);
×
1501
                                                                return;
×
1502
                                                        } else {
1503
                                                                wizardModel.workLog.add("Granted user " + connectionUsername + " all privileges to database "
×
1504
                                                                        + wizardModel.databaseName);
×
1505
                                                        }
1506
                                                        
1507
                                                        addExecutedTask(WizardTask.CREATE_DB_USER);
×
1508
                                                } else {
×
1509
                                                        connectionUsername = wizardModel.currentDatabaseUsername;
×
1510
                                                        connectionPassword.setLength(0);
×
1511
                                                        connectionPassword.append(wizardModel.currentDatabasePassword);
×
1512
                                                }
1513
                                                
1514
                                                String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@",
×
1515
                                                        wizardModel.databaseName);
×
1516
                                                
1517
                                                finalDatabaseConnectionString = finalDatabaseConnectionString.replace("@APPLICATIONDATADIR@",
×
1518
                                                        OpenmrsUtil.getApplicationDataDirectory().replace("\\", "/"));
×
1519
                                                
1520
                                                // verify that the database connection works
1521
                                                if (!verifyConnection(connectionUsername, connectionPassword.toString(),
×
1522
                                                        finalDatabaseConnectionString)) {
1523
                                                        setMessage("Verify that the database connection works");
×
1524
                                                        // redirect to setup page if we got an error
1525
                                                        reportError("Unable to connect to database", DEFAULT_PAGE);
×
1526
                                                        return;
×
1527
                                                }
1528
                                                
1529
                                                // save the properties for startup purposes
1530
                                                Properties runtimeProperties = new Properties();
×
1531
                                                
1532
                                                runtimeProperties.put("connection.url", finalDatabaseConnectionString);
×
1533
                                                runtimeProperties.put("connection.username", connectionUsername);
×
1534
                                                runtimeProperties.put("connection.password", connectionPassword.toString());
×
1535
                                                if (StringUtils.hasText(wizardModel.databaseDriver)) {
×
1536
                                                        runtimeProperties.put("connection.driver_class", wizardModel.databaseDriver);
×
1537
                                                }
1538
                                                if (finalDatabaseConnectionString.contains(DATABASE_POSTGRESQL)) {
×
1539
                                                        runtimeProperties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQL82Dialect");
×
1540
                                                }
1541
                                                if (finalDatabaseConnectionString.contains(DATABASE_SQLSERVER)) {
×
1542
                                                        runtimeProperties.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
×
1543
                                                }
1544
                                                if (finalDatabaseConnectionString.contains(DATABASE_H2)) {
×
1545
                                                        runtimeProperties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
×
1546
                                                }
NEW
1547
                                                if (finalDatabaseConnectionString.contains(DATABASE_MARIADB)) {
×
NEW
1548
                                                        runtimeProperties.put("hibernate.dialect", "org.hibernate.dialect.MariaDBDialect");
×
1549
                                                }
1550
                                                runtimeProperties.put("module.allow_web_admin", "" + wizardModel.moduleWebAdmin);
×
1551
                                                runtimeProperties.put("auto_update_database", "" + wizardModel.autoUpdateDatabase);
×
1552
                                                final Encoder base64 = Base64.getEncoder();
×
1553
                                                runtimeProperties.put(OpenmrsConstants.ENCRYPTION_VECTOR_RUNTIME_PROPERTY,
×
1554
                                                        new String(base64.encode(Security.generateNewInitVector()), StandardCharsets.UTF_8));
×
1555
                                                runtimeProperties.put(OpenmrsConstants.ENCRYPTION_KEY_RUNTIME_PROPERTY,
×
1556
                                                        new String(base64.encode(Security.generateNewSecretKey()), StandardCharsets.UTF_8));
×
1557
                                                
1558
                                                runtimeProperties.putAll(wizardModel.additionalPropertiesFromInstallationScript);
×
1559
                                                
1560
                                                Properties properties = Context.getRuntimeProperties();
×
1561
                                                properties.putAll(runtimeProperties);
×
1562
                                                runtimeProperties = properties;
×
1563
                                                Context.setRuntimeProperties(runtimeProperties);
×
1564
                                                
1565
                                                /**
1566
                                                 * A callback class that prints out info about liquibase changesets
1567
                                                 */
1568
                                                class PrintingChangeSetExecutorCallback implements ChangeSetExecutorCallback {
1569
                                                        
1570
                                                        private int i = 1;
×
1571
                                                        
1572
                                                        private String message;
1573
                                                        
1574
                                                        public PrintingChangeSetExecutorCallback(String message) {
×
1575
                                                                this.message = message;
×
1576
                                                        }
×
1577
                                                        
1578
                                                        /**
1579
                                                         * @see ChangeSetExecutorCallback#executing(liquibase.changelog.ChangeSet, int)
1580
                                                         */
1581
                                                        @Override
1582
                                                        public void executing(ChangeSet changeSet, int numChangeSetsToRun) {
1583
                                                                setMessage(message + " (" + i++ + "/" + numChangeSetsToRun + "): Author: "
×
1584
                                                                        + changeSet.getAuthor() + " Comments: " + changeSet.getComments() + " Description: "
×
1585
                                                                        + changeSet.getDescription());
×
1586
                                                                float numChangeSetsToRunFloat = (float) numChangeSetsToRun;
×
1587
                                                                float j = (float) i;
×
1588
                                                                setCompletedPercentage(Math.round(j * 100 / numChangeSetsToRunFloat));
×
1589
                                                        }
×
1590
                                                        
1591
                                                }
1592
                                                
1593
                                                if (wizardModel.createTables) {
×
1594
                                                        log.debug("Creating tables");
×
1595
                                                        // use liquibase to create core data + tables
1596
                                                        try {
1597
                                                                String liquibaseSchemaFileName = changeLogVersionFinder.getLatestSchemaSnapshotFilename()
×
1598
                                                                        .get();
×
1599
                                                                String liquibaseCoreDataFileName = changeLogVersionFinder.getLatestCoreDataSnapshotFilename()
×
1600
                                                                        .get();
×
1601
                                                                
1602
                                                                setMessage("Executing " + liquibaseSchemaFileName);
×
1603
                                                                setExecutingTask(WizardTask.CREATE_TABLES);
×
1604
                                                                
1605
                                                                log.debug("executing Liquibase file '{}' ", liquibaseSchemaFileName);
×
1606
                                                                
1607
                                                                DatabaseUpdater.executeChangelog(liquibaseSchemaFileName,
×
1608
                                                                        new PrintingChangeSetExecutorCallback("OpenMRS schema file"));
1609
                                                                addExecutedTask(WizardTask.CREATE_TABLES);
×
1610
                                                                
1611
                                                                //reset for this task
1612
                                                                setCompletedPercentage(0);
×
1613
                                                                setExecutingTask(WizardTask.ADD_CORE_DATA);
×
1614
                                                                
1615
                                                                log.debug("executing Liquibase file '{}' ", liquibaseCoreDataFileName);
×
1616
                                                                
1617
                                                                DatabaseUpdater.executeChangelog(liquibaseCoreDataFileName,
×
1618
                                                                        new PrintingChangeSetExecutorCallback("OpenMRS core data file"));
1619
                                                                wizardModel.workLog.add("Created database tables and added core data");
×
1620
                                                                addExecutedTask(WizardTask.ADD_CORE_DATA);
×
1621
                                                                
1622
                                                        }
1623
                                                        catch (Exception e) {
×
1624
                                                                reportError(ErrorMessageConstants.ERROR_DB_CREATE_TABLES_OR_ADD_DEMO_DATA, DEFAULT_PAGE,
×
1625
                                                                        e.getMessage());
×
1626
                                                                log.warn("Error while trying to create tables and demo data", e);
×
1627
                                                        }
×
1628
                                                }
1629
                                                
1630
                                                if (wizardModel.importTestData) {
×
1631
                                                        try {
1632
                                                                setMessage("Importing test data");
×
1633
                                                                setExecutingTask(WizardTask.IMPORT_TEST_DATA);
×
1634
                                                                setCompletedPercentage(0);
×
1635
                                                                
1636
                                                                try {
1637
                                                                        InputStream inData = TestInstallUtil.getResourceInputStream(
×
1638
                                                                                wizardModel.remoteUrl + RELEASE_TESTING_MODULE_PATH + "generateTestDataSet.form",
×
1639
                                                                                wizardModel.remoteUsername, wizardModel.remotePassword);
×
1640
                                                                        
1641
                                                                        setCompletedPercentage(40);
×
1642
                                                                        setMessage("Loading imported test data...");
×
1643
                                                                        importTestDataSet(inData, finalDatabaseConnectionString, connectionUsername,
×
1644
                                                                                connectionPassword.toString());
×
1645
                                                                        wizardModel.workLog.add("Imported test data");
×
1646
                                                                        addExecutedTask(WizardTask.IMPORT_TEST_DATA);
×
1647
                                                                        
1648
                                                                        //reset the progress for the next task
1649
                                                                        setCompletedPercentage(0);
×
1650
                                                                        setMessage("Importing modules from remote server...");
×
1651
                                                                        setExecutingTask(WizardTask.ADD_MODULES);
×
1652
                                                                        
1653
                                                                        InputStream inModules = TestInstallUtil.getResourceInputStream(
×
1654
                                                                                wizardModel.remoteUrl + RELEASE_TESTING_MODULE_PATH + "getModules.htm",
×
1655
                                                                                wizardModel.remoteUsername, wizardModel.remotePassword);
×
1656
                                                                        
1657
                                                                        setCompletedPercentage(90);
×
1658
                                                                        setMessage("Adding imported modules...");
×
1659
                                                                        if (!TestInstallUtil.addZippedTestModules(inModules)) {
×
1660
                                                                                reportError(ErrorMessageConstants.ERROR_DB_UNABLE_TO_ADD_MODULES, DEFAULT_PAGE, "");
×
1661
                                                                                return;
×
1662
                                                                        } else {
1663
                                                                                wizardModel.workLog.add("Added Modules");
×
1664
                                                                                addExecutedTask(WizardTask.ADD_MODULES);
×
1665
                                                                        }
1666
                                                                }
1667
                                                                catch (APIAuthenticationException e) {
×
1668
                                                                        log.warn("Unable to authenticate as a User with the System Developer role");
×
1669
                                                                        reportError(ErrorMessageConstants.UPDATE_ERROR_UNABLE_AUTHENTICATE,
×
1670
                                                                                TESTING_REMOTE_DETAILS_SETUP, "");
1671
                                                                        return;
×
1672
                                                                }
×
1673
                                                        }
1674
                                                        catch (Exception e) {
×
1675
                                                                reportError(ErrorMessageConstants.ERROR_DB_IMPORT_TEST_DATA, DEFAULT_PAGE, e.getMessage());
×
1676
                                                                log.warn("Error while trying to import test data", e);
×
1677
                                                                return;
×
1678
                                                        }
×
1679
                                                }
1680
                                                
1681
                                                // add demo data only if creating tables fresh and user selected the option add demo data
1682
                                                if (wizardModel.createTables && wizardModel.addDemoData) {
×
1683
                                                        try {
1684
                                                                setMessage("Adding demo data");
×
1685
                                                                setCompletedPercentage(0);
×
1686
                                                                setExecutingTask(WizardTask.ADD_DEMO_DATA);
×
1687
                                                                
1688
                                                                log.debug("executing Liquibase file '{}' ", LIQUIBASE_DEMO_DATA);
×
1689
                                                                
1690
                                                                DatabaseUpdater.executeChangelog(LIQUIBASE_DEMO_DATA,
×
1691
                                                                        new PrintingChangeSetExecutorCallback("OpenMRS demo patients, users, and forms"));
1692
                                                                wizardModel.workLog.add("Added demo data");
×
1693
                                                                
1694
                                                                addExecutedTask(WizardTask.ADD_DEMO_DATA);
×
1695
                                                        }
1696
                                                        catch (Exception e) {
×
1697
                                                                reportError(ErrorMessageConstants.ERROR_DB_CREATE_TABLES_OR_ADD_DEMO_DATA, DEFAULT_PAGE,
×
1698
                                                                        e.getMessage());
×
1699
                                                                log.warn("Error while trying to add demo data", e);
×
1700
                                                        }
×
1701
                                                }
1702
                                                
1703
                                                // update the database to the latest version
1704
                                                try {
1705
                                                        setMessage("Updating the database to the latest version");
×
1706
                                                        setCompletedPercentage(0);
×
1707
                                                        setExecutingTask(WizardTask.UPDATE_TO_LATEST);
×
1708
                                                        
1709
                                                        String version = null;
×
1710
                                                        
1711
                                                        if (wizardModel.createTables) {
×
1712
                                                                version = changeLogVersionFinder.getLatestSnapshotVersion().get();
×
1713
                                                        } else {
1714
                                                                version = changeLogDetective.getInitialLiquibaseSnapshotVersion(DatabaseUpdater.CONTEXT,
×
1715
                                                                        new DatabaseUpdaterLiquibaseProvider());
1716
                                                        }
1717
                                                        
1718
                                                        log.debug(
×
1719
                                                                "updating the database with versions of liquibase-update-to-latest files greater than '{}'",
1720
                                                                version);
1721
                                                        
1722
                                                        List<String> changelogs = changeLogVersionFinder
×
1723
                                                                .getUpdateFileNames(changeLogVersionFinder.getUpdateVersionsGreaterThan(version));
×
1724
                                                        
1725
                                                        for (String changelog : changelogs) {
×
1726
                                                                log.debug("applying Liquibase changelog '{}'", changelog);
×
1727
                                                                
1728
                                                                DatabaseUpdater.executeChangelog(changelog,
×
1729
                                                                        new PrintingChangeSetExecutorCallback("executing Liquibase changelog " + changelog));
1730
                                                        }
×
1731
                                                        addExecutedTask(WizardTask.UPDATE_TO_LATEST);
×
1732
                                                }
1733
                                                catch (Exception e) {
×
1734
                                                        reportError(ErrorMessageConstants.ERROR_DB_UPDATE_TO_LATEST, DEFAULT_PAGE, e.getMessage());
×
1735
                                                        log.warn("Error while trying to update to the latest database version", e);
×
1736
                                                        return;
×
1737
                                                }
×
1738
                                                
1739
                                                setExecutingTask(null);
×
1740
                                                setMessage("Starting OpenMRS");
×
1741
                                                
1742
                                                // start spring
1743
                                                // after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext())
1744
                                                // logic copied from org.springframework.web.context.ContextLoaderListener
1745
                                                log.debug("Initializing WAC");
×
1746
                                                ContextLoader contextLoader = new ContextLoader();
×
1747
                                                contextLoader.initWebApplicationContext(filterConfig.getServletContext());
×
1748
                                                log.debug("Done initializing WAC");
×
1749
                                                
1750
                                                // output properties to the openmrs runtime properties file so that this wizard is not run again
1751
                                                FileOutputStream fos = null;
×
1752
                                                try {
1753
                                                        fos = new FileOutputStream(getRuntimePropertiesFile());
×
1754
                                                        OpenmrsUtil.storeProperties(runtimeProperties, fos,
×
1755
                                                                "Auto generated by OpenMRS initialization wizard");
1756
                                                        wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile());
×
1757
                                                        
1758
                                                        /*
1759
                                                         * Fix file readability permissions:
1760
                                                         * first revoke read permission from everyone, then set read permissions for only the user
1761
                                                         * there is no function to set specific readability for only one user
1762
                                                         * and revoke everyone else's, therefore this is the only way to accomplish this.
1763
                                                         */
1764
                                                        wizardModel.workLog.add("Adjusting file posix properties to user readonly");
×
1765
                                                        if (getRuntimePropertiesFile().setReadable(false, false)
×
1766
                                                                && getRuntimePropertiesFile().setReadable(true)) {
×
1767
                                                                wizardModel.workLog
×
1768
                                                                        .add("Successfully adjusted RuntimePropertiesFile to disallow world to read it");
×
1769
                                                        } else {
1770
                                                                wizardModel.workLog
×
1771
                                                                        .add("Unable to adjust RuntimePropertiesFile to disallow world to read it");
×
1772
                                                        }
1773
                                                        // don't need to catch errors here because we tested it at the beginning of the wizard
1774
                                                }
1775
                                                finally {
1776
                                                        if (fos != null) {
×
1777
                                                                fos.close();
×
1778
                                                        }
1779
                                                }
1780
                                                
1781
                                                Context.openSession();
×
1782
                                                
1783
                                                if (!"".equals(wizardModel.implementationId)) {
×
1784
                                                        try {
1785
                                                                Context.addProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
×
1786
                                                                Context.addProxyPrivilege(PrivilegeConstants.MANAGE_CONCEPT_SOURCES);
×
1787
                                                                Context.addProxyPrivilege(PrivilegeConstants.GET_CONCEPT_SOURCES);
×
1788
                                                                Context.addProxyPrivilege(PrivilegeConstants.MANAGE_IMPLEMENTATION_ID);
×
1789
                                                                
1790
                                                                ImplementationId implId = new ImplementationId();
×
1791
                                                                implId.setName(wizardModel.implementationIdName);
×
1792
                                                                implId.setImplementationId(wizardModel.implementationId);
×
1793
                                                                implId.setPassphrase(wizardModel.implementationIdPassPhrase);
×
1794
                                                                implId.setDescription(wizardModel.implementationIdDescription);
×
1795
                                                                
1796
                                                                Context.getAdministrationService().setImplementationId(implId);
×
1797
                                                        }
1798
                                                        catch (Exception e) {
×
1799
                                                                reportError(ErrorMessageConstants.ERROR_SET_INPL_ID, DEFAULT_PAGE, e.getMessage());
×
1800
                                                                log.warn("Implementation ID could not be set.", e);
×
1801
                                                                Context.shutdown();
×
1802
                                                                WebModuleUtil.shutdownModules(filterConfig.getServletContext());
×
1803
                                                                contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
×
1804
                                                                return;
×
1805
                                                        }
1806
                                                        finally {
1807
                                                                Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
×
1808
                                                                Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_CONCEPT_SOURCES);
×
1809
                                                                Context.removeProxyPrivilege(PrivilegeConstants.GET_CONCEPT_SOURCES);
×
1810
                                                                Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_IMPLEMENTATION_ID);
×
1811
                                                        }
1812
                                                }
1813
                                                
1814
                                                try {
1815
                                                        // change the admin user password from "test" to what they input above
1816
                                                        if (wizardModel.createTables) {
×
1817
                                                                try {
1818
                                                                        Context.authenticate(new UsernamePasswordCredentials("admin", "test"));
×
1819
                                                                        
1820
                                                                        Properties props = Context.getRuntimeProperties();
×
1821
                                                                        String initValue = props.getProperty(UserService.ADMIN_PASSWORD_LOCKED_PROPERTY);
×
1822
                                                                        props.setProperty(UserService.ADMIN_PASSWORD_LOCKED_PROPERTY, "false");
×
1823
                                                                        Context.setRuntimeProperties(props);
×
1824
                                                                        
1825
                                                                        Context.getUserService().changePassword("test", wizardModel.adminUserPassword);
×
1826
                                                                        
1827
                                                                        if (initValue == null) {
×
1828
                                                                                props.remove(UserService.ADMIN_PASSWORD_LOCKED_PROPERTY);
×
1829
                                                                        } else {
1830
                                                                                props.setProperty(UserService.ADMIN_PASSWORD_LOCKED_PROPERTY, initValue);
×
1831
                                                                        }
1832
                                                                        Context.setRuntimeProperties(props);
×
1833
                                                                        Context.logout();
×
1834
                                                                }
1835
                                                                catch (ContextAuthenticationException ex) {
×
1836
                                                                        log.info("No need to change admin password.", ex);
×
1837
                                                                }
×
1838
                                                        }
1839
                                                }
1840
                                                catch (Exception e) {
×
1841
                                                        Context.shutdown();
×
1842
                                                        WebModuleUtil.shutdownModules(filterConfig.getServletContext());
×
1843
                                                        contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
×
1844
                                                        reportError(ErrorMessageConstants.ERROR_COMPLETE_STARTUP, DEFAULT_PAGE, e.getMessage());
×
1845
                                                        log.warn("Unable to complete the startup.", e);
×
1846
                                                        return;
×
1847
                                                }
×
1848
                                                
1849
                                                try {
1850
                                                        // Update PostgreSQL Sequences after insertion of core data
1851
                                                        Context.getAdministrationService().updatePostgresSequence();
×
1852
                                                }
1853
                                                catch (Exception e) {
×
1854
                                                        log.warn("Not able to update PostgreSQL sequence. Startup failed for PostgreSQL", e);
×
1855
                                                        reportError(ErrorMessageConstants.ERROR_COMPLETE_STARTUP, DEFAULT_PAGE, e.getMessage());
×
1856
                                                        return;
×
1857
                                                }
×
1858
                                                
1859
                                                // set this so that the wizard isn't run again on next page load
1860
                                                Context.closeSession();
×
1861
                                                
1862
                                                // start openmrs
1863
                                                try {
1864
                                                        UpdateFilter.setUpdatesRequired(false);
×
1865
                                                        WebDaemon.startOpenmrs(filterConfig.getServletContext());
×
1866
                                                }
1867
                                                catch (DatabaseUpdateException updateEx) {
×
1868
                                                        log.warn("Error while running the database update file", updateEx);
×
1869
                                                        reportError(ErrorMessageConstants.ERROR_DB_UPDATE, DEFAULT_PAGE, updateEx.getMessage());
×
1870
                                                        return;
×
1871
                                                }
1872
                                                catch (InputRequiredException inputRequiredEx) {
×
1873
                                                        // TODO display a page looping over the required input and ask the user for each.
1874
                                                        //                 When done and the user and put in their say, call DatabaseUpdater.update(Map);
1875
                                                        //                with the user's question/answer pairs
1876
                                                        log.warn(
×
1877
                                                                "Unable to continue because user input is required for the db updates and we cannot do anything about that right now");
1878
                                                        reportError(ErrorMessageConstants.ERROR_INPUT_REQ, DEFAULT_PAGE);
×
1879
                                                        return;
×
1880
                                                }
1881
                                                catch (MandatoryModuleException mandatoryModEx) {
×
1882
                                                        log.warn(
×
1883
                                                                "A mandatory module failed to start. Fix the error or unmark it as mandatory to continue.",
1884
                                                                mandatoryModEx);
1885
                                                        reportError(ErrorMessageConstants.ERROR_MANDATORY_MOD_REQ, DEFAULT_PAGE,
×
1886
                                                                mandatoryModEx.getMessage());
×
1887
                                                        return;
×
1888
                                                }
1889
                                                catch (OpenmrsCoreModuleException coreModEx) {
×
1890
                                                        log.warn(
×
1891
                                                                "A core module failed to start. Make sure that all core modules (with the required minimum versions) are installed and starting properly.",
1892
                                                                coreModEx);
1893
                                                        reportError(ErrorMessageConstants.ERROR_CORE_MOD_REQ, DEFAULT_PAGE, coreModEx.getMessage());
×
1894
                                                        return;
×
1895
                                                }
×
1896
                                                
1897
                                                // TODO catch openmrs errors here and drop the user back out to the setup screen
1898
                                                
1899
                                        }
1900
                                        catch (IOException e) {
×
1901
                                                reportError(ErrorMessageConstants.ERROR_COMPLETE_STARTUP, DEFAULT_PAGE, e.getMessage());
×
1902
                                        }
1903
                                        finally {
1904
                                                if (!hasErrors()) {
×
1905
                                                        // set this so that the wizard isn't run again on next page load
1906
                                                        setInitializationComplete(true);
×
1907
                                                        // we should also try to store selected by user language
1908
                                                        // if user wants to system will do it for him 
1909
                                                        FilterUtil.storeLocale(wizardModel.localeToSave);
×
1910
                                                }
1911
                                                setInstallationStarted(false);
×
1912
                                        }
1913
                                }
×
1914
                        };
1915
                        
1916
                        future = OpenmrsThreadPoolHolder.threadExecutor.submit(() -> { r.run(); return null; });
×
1917
                }
×
1918
        }
1919
        
1920
        /**
1921
         * Convenience method that loads the database driver
1922
         *
1923
         * @param connection the database connection string
1924
         * @param databaseDriver the database driver class name to load
1925
         * @return the loaded driver string
1926
         */
1927
        public static String loadDriver(String connection, String databaseDriver) {
1928
                String loadedDriverString = null;
×
1929
                try {
1930
                        loadedDriverString = DatabaseUtil.loadDatabaseDriver(connection, databaseDriver);
×
1931
                        log.info("using database driver :" + loadedDriverString);
×
1932
                }
1933
                catch (ClassNotFoundException e) {
×
1934
                        log.error("The given database driver class was not found. "
×
1935
                                + "Please ensure that the database driver jar file is on the class path "
1936
                                + "(like in the webapp's lib folder)");
1937
                }
×
1938
                
1939
                return loadedDriverString;
×
1940
        }
1941
        
1942
        /**
1943
         * Utility method that checks if there is a runtime properties file containing database connection
1944
         * credentials
1945
         *
1946
         * @return
1947
         */
1948
        private static boolean skipDatabaseSetupPage() {
1949
                Properties props = OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
×
1950
                return (props != null && StringUtils.hasText(props.getProperty("connection.url"))
×
1951
                        && StringUtils.hasText(props.getProperty("connection.username"))
×
1952
                        && StringUtils.hasText(props.getProperty("connection.password")));
×
1953
        }
1954
        
1955
        /**
1956
         * Utility methods that checks if the user clicked the back image
1957
         *
1958
         * @param httpRequest
1959
         * @return
1960
         */
1961
        private static boolean goBack(HttpServletRequest httpRequest) {
1962
                return "Back".equals(httpRequest.getParameter("back"))
×
1963
                        || (httpRequest.getParameter("back.x") != null && httpRequest.getParameter("back.y") != null);
×
1964
        }
1965
        
1966
        /**
1967
         * Convenience method to get custom installation script
1968
         *
1969
         * @return Properties from custom installation script or empty if none specified
1970
         * @throws RuntimeException if path to installation script is invalid
1971
         */
1972
        private Properties getInstallationScript() {
1973
                Properties prop = new Properties();
×
1974
                
1975
                String fileName = System.getProperty("OPENMRS_INSTALLATION_SCRIPT");
×
1976
                if (fileName == null) {
×
1977
                        return prop;
×
1978
                }
1979
                if (fileName.startsWith("classpath:")) {
×
1980
                        fileName = fileName.substring(10);
×
1981
                        InputStream input = null;
×
1982
                        try {
1983
                                input = getClass().getClassLoader().getResourceAsStream(fileName);
×
1984
                                prop.load(input);
×
1985
                                log.info("Using installation script from classpath: " + fileName);
×
1986
                                
1987
                                input.close();
×
1988
                        }
1989
                        catch (IOException ex) {
×
1990
                                log.error("Failed to load installation script from classpath: " + fileName, ex);
×
1991
                                throw new RuntimeException(ex);
×
1992
                        }
1993
                        finally {
1994
                                IOUtils.closeQuietly(input);
×
1995
                        }
1996
                } else {
×
1997
                        File file = new File(fileName);
×
1998
                        if (file.exists()) {
×
1999
                                InputStream input = null;
×
2000
                                try {
2001
                                        input = new FileInputStream(fileName);
×
2002
                                        prop.load(input);
×
2003
                                        log.info("Using installation script from absolute path: " + file.getAbsolutePath());
×
2004
                                        
2005
                                        input.close();
×
2006
                                }
2007
                                catch (IOException ex) {
×
2008
                                        log.error("Failed to load installation script from absolute path: " + file.getAbsolutePath(), ex);
×
2009
                                        throw new RuntimeException(ex);
×
2010
                                }
2011
                                finally {
2012
                                        IOUtils.closeQuietly(input);
×
2013
                                }
2014
                        }
2015
                }
2016
                return prop;
×
2017
        }
2018
}
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