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

openmrs / openmrs-core / 24414976480

14 Apr 2026 06:03PM UTC coverage: 63.878% (+0.001%) from 63.877%
24414976480

push

github

ibacher
Fix admin_password_locked implementation

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

1 existing line in 1 file now uncovered.

22204 of 34760 relevant lines covered (63.88%)

0.64 hits per line

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

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

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

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

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

NEW
359
                        String adminPasswordLocked = script.getProperty("admin_password_locked",
×
NEW
360
                            script.getProperty("admin.password.locked"));
×
NEW
361
                        if (adminPasswordLocked != null) {
×
NEW
362
                                wizardModel.additionalPropertiesFromInstallationScript.put(
×
363
                                    UserService.ADMIN_PASSWORD_LOCKED_PROPERTY, adminPasswordLocked);
364
                        }
365

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