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

openmrs / openmrs-core / 24803983538

22 Apr 2026 09:33PM UTC coverage: 63.689% (-0.04%) from 63.73%
24803983538

push

github

ibacher
Fix issues with Javadocs

21841 of 34293 relevant lines covered (63.69%)

0.64 hits per line

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

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

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

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

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

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

© 2026 Coveralls, Inc