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

openmrs / openmrs-core / 14735285473

29 Apr 2025 03:33PM UTC coverage: 65.095% (-0.09%) from 65.187%
14735285473

push

github

web-flow
TRUNK-6329: Modernize OpenMRS installation wizard UI to match the current OpenMRS branding (#4995)

0 of 50 new or added lines in 2 files covered. (0.0%)

11 existing lines in 4 files now uncovered.

23397 of 35943 relevant lines covered (65.09%)

0.65 hits per line

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

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

12
import java.io.File;
13
import java.io.FileInputStream;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.io.InputStream;
17
import java.io.PrintWriter;
18
import java.net.URI;
19
import java.nio.charset.StandardCharsets;
20
import java.sql.Connection;
21
import java.sql.DriverManager;
22
import java.sql.SQLException;
23
import java.sql.Statement;
24
import java.util.ArrayList;
25
import java.util.Base64;
26
import java.util.Base64.Encoder;
27
import java.util.HashMap;
28
import java.util.List;
29
import java.util.Locale;
30
import java.util.Map;
31
import java.util.Properties;
32
import java.util.Random;
33
import java.util.concurrent.ExecutionException;
34
import java.util.concurrent.Future;
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.web.WebModuleUtil;
57
import org.openmrs.util.DatabaseUpdateException;
58
import org.openmrs.util.DatabaseUpdater;
59
import org.openmrs.liquibase.ChangeSetExecutorCallback;
60
import org.openmrs.util.DatabaseUpdaterLiquibaseProvider;
61
import org.openmrs.util.DatabaseUtil;
62
import org.openmrs.util.InputRequiredException;
63
import org.openmrs.util.OpenmrsConstants;
64
import org.openmrs.util.OpenmrsThreadPoolHolder;
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.openmrs.web.filter.util.SessionModelUtils;
77
import org.slf4j.LoggerFactory;
78
import org.springframework.util.StringUtils;
79
import org.springframework.web.context.ContextLoader;
80

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

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

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

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