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

openmrs / openmrs-core / 24803564891

22 Apr 2026 09:27PM UTC coverage: 63.73% (+0.04%) from 63.694%
24803564891

push

github

web-flow
TRUNK-6481: Backport native MariaDB support to 2.5.x (#5644)

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

6 existing lines in 3 files now uncovered.

21857 of 34296 relevant lines covered (63.73%)

0.64 hits per line

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

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

12
import java.io.File;
13
import java.io.FileInputStream;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.io.InputStream;
17
import java.io.PrintWriter;
18
import java.net.URI;
19
import java.nio.charset.StandardCharsets;
20
import java.sql.Connection;
21
import java.sql.DriverManager;
22
import java.sql.SQLException;
23
import java.sql.Statement;
24
import java.util.ArrayList;
25
import java.util.Base64;
26
import java.util.Base64.Encoder;
27
import java.util.HashMap;
28
import java.util.HashSet;
29
import java.util.List;
30
import java.util.Locale;
31
import java.util.Map;
32
import java.util.Properties;
33
import java.util.Random;
34
import java.util.Set;
35
import java.util.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.OpenmrsCoreModuleException;
57
import org.openmrs.module.web.WebModuleUtil;
58
import org.openmrs.util.DatabaseUpdateException;
59
import org.openmrs.util.DatabaseUpdater;
60
import org.openmrs.liquibase.ChangeSetExecutorCallback;
61
import org.openmrs.util.DatabaseUpdaterLiquibaseProvider;
62
import org.openmrs.util.DatabaseUtil;
63
import org.openmrs.util.InputRequiredException;
64
import org.openmrs.util.OpenmrsConstants;
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.slf4j.LoggerFactory;
77
import org.springframework.util.StringUtils;
78
import org.springframework.web.context.ContextLoader;
79

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

97
        private static final String DATABASE_MARIADB = "mariadb";
98
        
99
        private static final String LIQUIBASE_DEMO_DATA = "liquibase-demo-data.xml";
100
        
101
        /**
102
         * The very first page of wizard, that asks user for select his preferred language
103
         */
104
        private static final String CHOOSE_LANG = "chooselang.vm";
105
        
106
        /**
107
         * The second page of the wizard that asks for simple or advanced installation.
108
         */
109
        private static final String INSTALL_METHOD = "installmethod.vm";
110
        
111
        /**
112
         * The simple installation setup page.
113
         */
114
        private static final String SIMPLE_SETUP = "simplesetup.vm";
115
        
116
        /**
117
         * The first page of the advanced installation of the wizard that asks for a current or past
118
         * database
119
         */
120
        private static final String DATABASE_SETUP = "databasesetup.vm";
121
        
122
        /**
123
         * The page from where the user specifies the url to a remote system, username and password
124
         */
125
        private static final String TESTING_REMOTE_DETAILS_SETUP = "remotedetails.vm";
126
        
127
        /**
128
         * The velocity macro page to redirect to if an error occurs or on initial startup
129
         */
130
        private static final String DEFAULT_PAGE = CHOOSE_LANG;
131
        
132
        /**
133
         * This page asks whether database tables/demo data should be inserted and what the
134
         * username/password that will be put into the runtime properties is
135
         */
136
        private static final String DATABASE_TABLES_AND_USER = "databasetablesanduser.vm";
137
        
138
        /**
139
         * This page lets the user define the admin user
140
         */
141
        private static final String ADMIN_USER_SETUP = "adminusersetup.vm";
142
        
143
        /**
144
         * This page lets the user pick an implementation id
145
         */
146
        private static final String IMPLEMENTATION_ID_SETUP = "implementationidsetup.vm";
147
        
148
        /**
149
         * This page asks for settings that will be put into the runtime properties files
150
         */
151
        private static final String OTHER_RUNTIME_PROPS = "otherruntimeproperties.vm";
152
        
153
        /**
154
         * A page that tells the user that everything is collected and will now be processed
155
         */
156
        private static final String WIZARD_COMPLETE = "wizardcomplete.vm";
157
        
158
        /**
159
         * A page that lists off what is happening while it is going on. This page has ajax that callst he
160
         * {@value #PROGRESS_VM_AJAXREQUEST} page
161
         */
162
        private static final String PROGRESS_VM = "progress.vm";
163
        
164
        /**
165
         * This url is called by javascript to get the status of the install
166
         */
167
        private static final String PROGRESS_VM_AJAXREQUEST = "progress.vm.ajaxRequest";
168
        
169
        public static final String RELEASE_TESTING_MODULE_PATH = "/module/releasetestinghelper/";
170

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