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

openmrs / openmrs-core / 17208163644

25 Aug 2025 11:59AM UTC coverage: 64.885% (+0.03%) from 64.86%
17208163644

push

github

ibacher
TRUNK-6395: Saner scheme for copying properties from the installation script (#5260)

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

1 existing line in 1 file now uncovered.

23369 of 36016 relevant lines covered (64.89%)

0.65 hits per line

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

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

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

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

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