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

openmrs / openmrs-core / 24414969502

14 Apr 2026 06:03PM UTC coverage: 65.229% (-0.02%) from 65.248%
24414969502

push

github

ibacher
Fix admin_password_locked implementation

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

4 existing lines in 3 files now uncovered.

23613 of 36200 relevant lines covered (65.23%)

0.65 hits per line

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

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

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

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

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

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

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