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

openmrs / openmrs-core / 15005414953

13 May 2025 07:48PM UTC coverage: 64.958% (+0.04%) from 64.915%
15005414953

push

github

web-flow
TRUNK-6339: Remove the add demo data option from the setup wizard (#5029)

* TRUNK-6339: Remove the add demo data option from the setup wizard

* remove unused import

* remove demo data liquibase file

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

7 existing lines in 3 files now uncovered.

23344 of 35937 relevant lines covered (64.96%)

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

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

81
import static org.openmrs.util.PrivilegeConstants.GET_GLOBAL_PROPERTIES;
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
        /**
101
         * The very first page of wizard, that asks user for select his preferred language
102
         */
103
        private static final String CHOOSE_LANG = "chooselang.vm";
104
        
105
        /**
106
         * The second page of the wizard that asks for simple or advanced installation.
107
         */
108
        private static final String INSTALL_METHOD = "installmethod.vm";
109
        
110
        /**
111
         * The simple installation setup page.
112
         */
113
        private static final String SIMPLE_SETUP = "simplesetup.vm";
114
        
115
        /**
116
         * The first page of the advanced installation of the wizard that asks for a current or past
117
         * database
118
         */
119
        private static final String DATABASE_SETUP = "databasesetup.vm";
120
        
121
        /**
122
         * The page from where the user specifies the url to a remote system, username and password
123
         */
124
        private static final String TESTING_REMOTE_DETAILS_SETUP = "remotedetails.vm";
125
        
126
        /**
127
         * The velocity macro page to redirect to if an error occurs or on initial startup
128
         */
129
        private static final String DEFAULT_PAGE = CHOOSE_LANG;
130
        
131
        /**
132
         * This page asks whether database tables/demo data should be inserted and what the
133
         * username/password that will be put into the runtime properties is
134
         */
135
        private static final String DATABASE_TABLES_AND_USER = "databasetablesanduser.vm";
136
        
137
        /**
138
         * This page lets the user define the admin user
139
         */
140
        private static final String ADMIN_USER_SETUP = "adminusersetup.vm";
141
        
142
        /**
143
         * This page lets the user pick an implementation id
144
         */
145
        private static final String IMPLEMENTATION_ID_SETUP = "implementationidsetup.vm";
146
        
147
        /**
148
         * This page asks for settings that will be put into the runtime properties files
149
         */
150
        private static final String OTHER_RUNTIME_PROPS = "otherruntimeproperties.vm";
151
        
152
        /**
153
         * A page that tells the user that everything is collected and will now be processed
154
         */
155
        private static final String WIZARD_COMPLETE = "wizardcomplete.vm";
156
        
157
        /**
158
         * A page that lists off what is happening while it is going on. This page has ajax that callst he
159
         * {@value #PROGRESS_VM_AJAXREQUEST} page
160
         */
161
        private static final String PROGRESS_VM = "progress.vm";
162
        
163
        /**
164
         * This url is called by javascript to get the status of the install
165
         */
166
        private static final String PROGRESS_VM_AJAXREQUEST = "progress.vm.ajaxRequest";
167
        
168
        public static final String RELEASE_TESTING_MODULE_PATH = "/module/releasetestinghelper/";
169
        
170
        /**
171
         * The model object that holds all the properties that the rendered templates use. All attributes on
172
         * this object are made available to all templates via reflection in the
173
         * {@link org.openmrs.web.filter.StartupFilter#renderTemplate(String, Map, HttpServletResponse)} method.
174
         */
175
        private InitializationWizardModel wizardModel = null;
×
176
        
177
        private InitializationCompletion initJob;
178
        
179
        /**
180
         * Variable set to true as soon as the installation begins and set to false when the process ends
181
         * This thread should only be accesses through the synchronized method.
182
         */
183
        private static boolean isInstallationStarted = false;
×
184
        
185
        // the actual driver loaded by the DatabaseUpdater class
186
        private String loadedDriverString;
187
        
188
        /**
189
         * Variable set at the end of the wizard when spring is being restarted
190
         */
191
        private static boolean initializationComplete = false;
×
192
        
193
        protected synchronized void setInitializationComplete(boolean initializationComplete) {
194
                InitializationFilter.initializationComplete = initializationComplete;
×
195
        }
×
196
        
197
        /**
198
         * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on GET requests
199
         *
200
         * @param httpRequest
201
         * @param httpResponse
202
         */
203
        @Override
204
        protected void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
205
                throws IOException {
206
                SessionModelUtils.loadFromSession(httpRequest.getSession(), wizardModel);
×
207
                loadInstallationScriptIfPresent();
×
208
                
209
                // we need to save current user language in references map since it will be used when template
210
                // will be rendered
211
                if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) == null) {
×
212
                        checkLocaleAttributesForFirstTime(httpRequest);
×
213
                }
214
                
215
                Map<String, Object> referenceMap = new HashMap<>();
×
216
                String page = httpRequest.getParameter("page");
×
217
                
218
                referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
219
                
220
                httpResponse.setHeader("Cache-Control", "no-cache");
×
221
                
222
                // if any body has already started installation and this is not an ajax request for the progress
223
                if (isInstallationStarted() && !PROGRESS_VM_AJAXREQUEST.equals(page)) {
×
224
                        referenceMap.put("isInstallationStarted", true);
×
225
                        httpResponse.setContentType("text/html");
×
226
                        renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
×
227
                } else if (PROGRESS_VM_AJAXREQUEST.equals(page)) {
×
228
                        httpResponse.setContentType("text/json");
×
229
                        Map<String, Object> result = new HashMap<>();
×
230
                        if (initJob != null) {
×
231
                                result.put("hasErrors", initJob.hasErrors());
×
232
                                if (initJob.hasErrors()) {
×
233
                                        result.put("errorPage", initJob.getErrorPage());
×
234
                                        errors.putAll(initJob.getErrors());
×
235
                                }
236
                                
237
                                result.put("initializationComplete", isInitializationComplete());
×
238
                                result.put("message", initJob.getMessage());
×
239
                                result.put("actionCounter", initJob.getStepsComplete());
×
240
                                if (!isInitializationComplete()) {
×
241
                                        result.put("executingTask", initJob.getExecutingTask());
×
242
                                        result.put("executedTasks", initJob.getExecutedTasks());
×
243
                                        result.put("completedPercentage", initJob.getCompletedPercentage());
×
244
                                }
245

246
                                SessionModelUtils.clearWizardSessionAttributes(httpRequest.getSession());
×
247
                                addLogLinesToResponse(result);
×
248
                        }
249
                        
250
                        PrintWriter writer = httpResponse.getWriter();
×
251
                        writer.write(toJSONString(result));
×
252
                        writer.close();
×
253
                } else if (InitializationWizardModel.INSTALL_METHOD_AUTO.equals(wizardModel.installMethod)
×
254
                        || httpRequest.getServletPath().equals("/" + AUTO_RUN_OPENMRS)) {
×
255
                        autoRunOpenMRS(httpRequest);
×
256
                        referenceMap.put("isInstallationStarted", true);
×
257
                        httpResponse.setContentType("text/html");
×
258
                        renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
×
259
                } else if (page == null) {
×
260
                        httpResponse.setContentType("text/html");// if any body has already started installation
×
261
                        
262
                        //If someone came straight here without setting the hidden page input,
263
                        // then we need to clear out all the passwords
264
                        clearPasswords();
×
265
                        
266
                        renderTemplate(DEFAULT_PAGE, referenceMap, httpResponse);
×
267
                } else if (INSTALL_METHOD.equals(page)) {
×
268
                        // get props and render the second page
269
                        File runtimeProperties = getRuntimePropertiesFile();
×
270
                        
271
                        if (!runtimeProperties.exists()) {
×
272
                                try {
273
                                        runtimeProperties.createNewFile();
×
274
                                        // reset the error objects in case of refresh
275
                                        wizardModel.canCreate = true;
×
276
                                        wizardModel.cannotCreateErrorMessage = "";
×
277
                                }
278
                                catch (IOException io) {
×
279
                                        wizardModel.canCreate = false;
×
280
                                        wizardModel.cannotCreateErrorMessage = io.getMessage();
×
281
                                }
×
282
                                
283
                                // check this before deleting the file again
284
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
285
                                
286
                                // delete the file again after testing the create/write
287
                                // so that if the user stops the webapp before finishing
288
                                // this wizard, they can still get back into it
289
                                runtimeProperties.delete();
×
290
                                
291
                        } else {
292
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
293
                                
294
                                wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
×
295
                                        wizardModel.databaseConnection);
296
                                
297
                                wizardModel.currentDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
×
298
                                        wizardModel.currentDatabaseUsername);
299
                                
300
                                wizardModel.currentDatabasePassword = Context.getRuntimeProperties().getProperty("connection.password",
×
301
                                        wizardModel.currentDatabasePassword);
302
                        }
303
                        
304
                        wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
×
305
                        
306
                        // do step one of the wizard
307
                        httpResponse.setContentType("text/html");
×
308
                        renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
309
                }
310
        }
×
311
        
312
        private void loadInstallationScriptIfPresent() {
313
                Properties script = getInstallationScript();
×
314
                if (!script.isEmpty()) {
×
315
                        wizardModel.installMethod = script.getProperty("install_method", wizardModel.installMethod);
×
316
                        
317
                        wizardModel.databaseConnection = script.getProperty("connection.url", wizardModel.databaseConnection);
×
318
                        wizardModel.databaseDriver = script.getProperty("connection.driver_class", wizardModel.databaseDriver);
×
319
                        wizardModel.currentDatabaseUsername = script.getProperty("connection.username",
×
320
                                wizardModel.currentDatabaseUsername);
321
                        wizardModel.currentDatabasePassword = script.getProperty("connection.password",
×
322
                                wizardModel.currentDatabasePassword);
323
                        
324
                        String hasCurrentOpenmrsDatabase = script.getProperty("has_current_openmrs_database");
×
325
                        if (hasCurrentOpenmrsDatabase != null) {
×
326
                                wizardModel.hasCurrentOpenmrsDatabase = Boolean.valueOf(hasCurrentOpenmrsDatabase);
×
327
                        }
328
                        wizardModel.createDatabaseUsername = script.getProperty("create_database_username",
×
329
                                wizardModel.createDatabaseUsername);
330
                        wizardModel.createDatabasePassword = script.getProperty("create_database_password",
×
331
                                wizardModel.createDatabasePassword);
332
                        
333
                        String createTables = script.getProperty("create_tables");
×
334
                        if (createTables != null) {
×
335
                                wizardModel.createTables = Boolean.valueOf(createTables);
×
336
                        }
337
                        
338
                        String createDatabaseUser = script.getProperty("create_database_user");
×
339
                        if (createDatabaseUser != null) {
×
340
                                wizardModel.createDatabaseUser = Boolean.valueOf(createDatabaseUser);
×
341
                        }
342
                        wizardModel.createUserUsername = script.getProperty("create_user_username", wizardModel.createUserUsername);
×
343
                        wizardModel.createUserPassword = script.getProperty("create_user_password", wizardModel.createUserPassword);
×
344
                        
345
                        String moduleWebAdmin = script.getProperty("module_web_admin");
×
346
                        if (moduleWebAdmin != null) {
×
347
                                wizardModel.moduleWebAdmin = Boolean.valueOf(moduleWebAdmin);
×
348
                        }
349
                        
350
                        String autoUpdateDatabase = script.getProperty("auto_update_database");
×
351
                        if (autoUpdateDatabase != null) {
×
352
                                wizardModel.autoUpdateDatabase = Boolean.valueOf(autoUpdateDatabase);
×
353
                        }
354
                        
355
                        wizardModel.adminUserPassword = script.getProperty("admin_user_password", wizardModel.adminUserPassword);
×
356
                }
357
        }
×
358
        
359
        private void clearPasswords() {
360
                wizardModel.databaseRootPassword = "";
×
361
                wizardModel.createDatabasePassword = "";
×
362
                wizardModel.createUserPassword = "";
×
363
                wizardModel.currentDatabasePassword = "";
×
364
                wizardModel.remotePassword = "";
×
365
        }
×
366
        
367
        /**
368
         * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests
369
         *
370
         * @param httpRequest
371
         * @param httpResponse
372
         */
373
        @Override
374
        protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
375
                throws IOException, ServletException {
376
                String page = httpRequest.getParameter("page");
×
377
                Map<String, Object> referenceMap = new HashMap<>();
×
378
                // we need to save current user language in references map since it will be used when template
379
                // will be rendered
380
                if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
×
381
                        referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
×
382
                                httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
383
                }
384
                
385
                // if any body has already started installation
386
                if (isInstallationStarted()) {
×
387
                        referenceMap.put("isInstallationStarted", true);
×
388
                        httpResponse.setContentType("text/html");
×
389
                        renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
×
390
                        return;
×
391
                }
392
                if (DEFAULT_PAGE.equals(page)) {
×
393
                        // get props and render the first page
394
                        File runtimeProperties = getRuntimePropertiesFile();
×
395
                        if (!runtimeProperties.exists()) {
×
396
                                try {
397
                                        runtimeProperties.createNewFile();
×
398
                                        // reset the error objects in case of refresh
399
                                        wizardModel.canCreate = true;
×
400
                                        wizardModel.cannotCreateErrorMessage = "";
×
401
                                }
402
                                catch (IOException io) {
×
403
                                        wizardModel.canCreate = false;
×
404
                                        wizardModel.cannotCreateErrorMessage = io.getMessage();
×
405
                                }
×
406
                                // check this before deleting the file again
407
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
408
                                
409
                                // delete the file again after testing the create/write
410
                                // so that if the user stops the webapp before finishing
411
                                // this wizard, they can still get back into it
412
                                runtimeProperties.delete();
×
413
                        } else {
414
                                wizardModel.canWrite = runtimeProperties.canWrite();
×
415
                                
416
                                wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
×
417
                                        wizardModel.databaseConnection);
418
                                
419
                                wizardModel.currentDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
×
420
                                        wizardModel.currentDatabaseUsername);
421
                                
422
                                wizardModel.currentDatabasePassword = Context.getRuntimeProperties().getProperty("connection.password",
×
423
                                        wizardModel.currentDatabasePassword);
424
                        }
425
                        
426
                        wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
×
427
                        
428
                        checkLocaleAttributes(httpRequest);
×
429
                        referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
×
430
                                httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
431
                        log.info("Locale stored in session is " + httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
432
                        
433
                        httpResponse.setContentType("text/html");
×
434
                        // otherwise do step one of the wizard
435
                        renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
436
                } else if (INSTALL_METHOD.equals(page)) {
×
437
                        if (goBack(httpRequest)) {
×
438
                                referenceMap.put(FilterUtil.REMEMBER_ATTRIBUTE,
×
439
                                        httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null);
×
440
                                referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
×
441
                                        httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
×
442
                                renderTemplate(CHOOSE_LANG, referenceMap, httpResponse);
×
443
                                return;
×
444
                        }
445
                        wizardModel.installMethod = httpRequest.getParameter("install_method");
×
446
                        if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
×
447
                                page = SIMPLE_SETUP;
×
448
                        } else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
×
449
                                page = TESTING_REMOTE_DETAILS_SETUP;
×
450
                                wizardModel.currentStepNumber = 1;
×
451
                                wizardModel.numberOfSteps = skipDatabaseSetupPage() ? 1 : 3;
×
452
                        } else {
453
                                page = DATABASE_SETUP;
×
454
                                wizardModel.currentStepNumber = 1;
×
455
                                wizardModel.numberOfSteps = 5;
×
456
                        }
457
                        renderTemplate(page, referenceMap, httpResponse);
×
458
                } // simple method
459
                else if (SIMPLE_SETUP.equals(page)) {
×
460
                        if (goBack(httpRequest)) {
×
461
                                renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
×
462
                                return;
×
463
                        }
464
                        wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
×
465

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

1520
                                                Properties installationScript = getInstallationScript();
×
1521
                                                installationScript.forEach(runtimeProperties::putIfAbsent);
×
1522

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