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

openmrs / openmrs-core / 18188864354

02 Oct 2025 09:19AM UTC coverage: 64.889% (-0.04%) from 64.931%
18188864354

push

github

rkorytkowski
TRUNK-6436: Add logging to monitor startup performance

(cherry picked from commit ece973daa)

2 of 29 new or added lines in 4 files covered. (6.9%)

16 existing lines in 8 files now uncovered.

23423 of 36097 relevant lines covered (64.89%)

0.65 hits per line

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

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

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

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

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