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

openmrs / openmrs-core / 14868735258

06 May 2025 08:07PM UTC coverage: 64.907% (-0.05%) from 64.957%
14868735258

push

github

web-flow
TRUNK-6301 Add ElasticSearch backend for full text search (#5017)

3 of 29 new or added lines in 3 files covered. (10.34%)

7 existing lines in 5 files now uncovered.

23343 of 35964 relevant lines covered (64.91%)

0.65 hits per line

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

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

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

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

82
import static org.openmrs.util.PrivilegeConstants.GET_GLOBAL_PROPERTIES;
83

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

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

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

NEW
1543
                                                Properties installationScript = getInstallationScript();
×
NEW
1544
                                                installationScript.forEach(runtimeProperties::putIfAbsent);
×
1545

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