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

openmrs / openmrs-core / 18188744794

02 Oct 2025 09:14AM UTC coverage: 65.24% (-0.08%) from 65.318%
18188744794

push

github

rkorytkowski
TRUNK-6436: Add logging to monitor startup performance

(cherry picked from commit fb43aba18)

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

28 existing lines in 10 files now uncovered.

23611 of 36191 relevant lines covered (65.24%)

0.65 hits per line

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

59.63
/api/src/main/java/org/openmrs/module/ModuleUtil.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.module;
11

12
import java.io.ByteArrayInputStream;
13
import java.io.ByteArrayOutputStream;
14
import java.io.File;
15
import java.io.FileOutputStream;
16
import java.io.IOException;
17
import java.io.InputStream;
18
import java.net.HttpURLConnection;
19
import java.net.MalformedURLException;
20
import java.net.URL;
21
import java.net.URLConnection;
22
import java.nio.charset.StandardCharsets;
23
import java.util.ArrayList;
24
import java.util.Collection;
25
import java.util.Collections;
26
import java.util.Enumeration;
27
import java.util.HashSet;
28
import java.util.LinkedHashSet;
29
import java.util.List;
30
import java.util.Properties;
31
import java.util.Set;
32
import java.util.jar.JarEntry;
33
import java.util.jar.JarFile;
34
import java.util.regex.Matcher;
35
import java.util.regex.Pattern;
36
import java.util.zip.ZipEntry;
37

38
import org.apache.commons.io.IOUtils;
39
import org.apache.commons.lang3.StringUtils;
40
import org.apache.commons.lang3.math.NumberUtils;
41
import org.openmrs.GlobalProperty;
42
import org.openmrs.api.AdministrationService;
43
import org.openmrs.api.context.Context;
44
import org.openmrs.api.context.ServiceContext;
45
import org.openmrs.scheduler.SchedulerUtil;
46
import org.openmrs.util.OpenmrsClassLoader;
47
import org.openmrs.util.OpenmrsConstants;
48
import org.openmrs.util.OpenmrsUtil;
49
import org.slf4j.Logger;
50
import org.slf4j.LoggerFactory;
51
import org.springframework.context.support.AbstractRefreshableApplicationContext;
52

53
/**
54
 * Utility methods for working and manipulating modules
55
 */
56
public class ModuleUtil {
57

58
        private ModuleUtil() {
59
        }
60
        
61
        private static final Logger log = LoggerFactory.getLogger(ModuleUtil.class);
1✔
62
        
63
        /**
64
         * Start up the module system with the given properties.
65
         *
66
         * @param props Properties (OpenMRS runtime properties)
67
         */
68
        public static void startup(Properties props) throws ModuleMustStartException {
69
                
70
                String moduleListString = props.getProperty(ModuleConstants.RUNTIMEPROPERTY_MODULE_LIST_TO_LOAD);
1✔
71
                
72
                if (moduleListString == null || moduleListString.isEmpty()) {
1✔
73
                        // Attempt to get all of the modules from the modules folder
74
                        // and store them in the modules list
75
                        log.debug("Starting all modules");
×
76
                        ModuleFactory.loadModules();
×
77
                } else {
78
                        // use the list of modules and load only those
79
                        log.debug("Starting all modules in this list: " + moduleListString);
1✔
80
                        
81
                        String[] moduleArray = moduleListString.split(" ");
1✔
82
                        List<File> modulesToLoad = new ArrayList<>();
1✔
83
                        
84
                        for (String modulePath : moduleArray) {
1✔
85
                                if (modulePath != null && modulePath.length() > 0) {
1✔
86
                                        File file = new File(modulePath);
1✔
87
                                        if (file.exists()) {
1✔
88
                                                modulesToLoad.add(file);
×
89
                                        } else {
90
                                                // try to load the file from the classpath
91
                                                InputStream stream = ModuleUtil.class.getClassLoader().getResourceAsStream(modulePath);
1✔
92
                                                
93
                                                // expand the classpath-found file to a temporary location
94
                                                if (stream != null) {
1✔
95
                                                        try {
96
                                                                // get and make a temp directory if necessary
97
                                                                String tmpDir = System.getProperty("java.io.tmpdir");
1✔
98
                                                                File expandedFile = File.createTempFile(file.getName() + "-", ".omod", new File(tmpDir));
1✔
99
                                                                
100
                                                                // pull the name from the absolute path load attempt
101
                                                                FileOutputStream outStream = new FileOutputStream(expandedFile, false);
1✔
102
                                                                
103
                                                                // do the actual file copying
104
                                                                OpenmrsUtil.copyFile(stream, outStream);
1✔
105
                                                                
106
                                                                // add the freshly expanded file to the list of modules we're going to start up
107
                                                                modulesToLoad.add(expandedFile);
1✔
108
                                                                expandedFile.deleteOnExit();
1✔
109
                                                        }
110
                                                        catch (IOException io) {
×
111
                                                                log.error("Unable to expand classpath found module: " + modulePath, io);
×
112
                                                        }
1✔
113
                                                } else {
114
                                                        log
×
115
                                                                .error("Unable to load module at path: "
×
116
                                                                        + modulePath
117
                                                                        + " because no file exists there and it is not found on the classpath. (absolute path tried: "
118
                                                                        + file.getAbsolutePath() + ")");
×
119
                                                }
120
                                        }
121
                                }
122
                        }
123
                        
124
                        ModuleFactory.loadModules(modulesToLoad);
1✔
125
                }
126
                
127
                // start all of the modules we just loaded
128
                ModuleFactory.startModules();
1✔
129
                
130
                // some debugging info
131
                if (log.isDebugEnabled()) {
1✔
132
                        Collection<Module> modules = ModuleFactory.getStartedModules();
×
133
                        if (modules == null || modules.isEmpty()) {
×
134
                                log.debug("No modules loaded");
×
135
                        } else {
136
                                log.debug("Found and loaded {} module(s)", modules.size());
×
137
                        }
138
                }
139
                
140
                // make sure all mandatory modules are loaded and started
141
                checkMandatoryModulesStarted();
1✔
142
        }
1✔
143
        
144
        /**
145
         * Stops the module system by calling stopModule for all modules that are currently started
146
         */
147
        public static void shutdown() {
148

149
                List<Module> modules = new ArrayList<>(ModuleFactory.getStartedModules());
1✔
150
                
151
                for (Module mod : modules) {
1✔
152
                        log.debug("stopping module: {}", mod.getModuleId());
1✔
153
                        
154
                        if (mod.isStarted()) {
1✔
155
                                ModuleFactory.stopModule(mod, true, true);
1✔
156
                        }
157
                }
1✔
158
                
159
                log.debug("done shutting down modules");
1✔
160
                
161
                // clean up the static variables just in case they weren't done before
162
                ModuleFactory.extensionMap.clear();
1✔
163
                ModuleFactory.loadedModules.invalidateAll();
1✔
164
                ModuleFactory.moduleClassLoaders.invalidateAll();
1✔
165
                ModuleFactory.startedModules.invalidateAll();
1✔
166
        }
1✔
167
        
168
        /**
169
         * Add the <code>inputStream</code> as a file in the modules repository
170
         *
171
         * @param inputStream <code>InputStream</code> to load
172
         * @return filename String of the file's name of the stream
173
         */
174
        public static File insertModuleFile(InputStream inputStream, String filename) {
175
                File folder = getModuleRepository();
×
176
                
177
                // check if module filename is already loaded
178
                if (OpenmrsUtil.folderContains(folder, filename)) {
×
179
                        throw new ModuleException(filename + " is already associated with a loaded module.");
×
180
                }
181
                
182
                File file = new File(folder.getAbsolutePath(), filename);
×
183
                
184
                try (FileOutputStream outputStream = new FileOutputStream(file)) {
×
185
                        OpenmrsUtil.copyFile(inputStream, outputStream);
×
186
                }
187
                catch (IOException e) {
×
188
                        throw new ModuleException("Can't create module file for " + filename, e);
×
189
                }
190
                finally {
191
                        try {
192
                                inputStream.close();
×
193
                        }
194
                        catch (Exception e) { /* pass */}
×
195
                }
196
                
197
                return file;
×
198
        }
199

200
        /**
201
         * Checks if the current OpenMRS version is in an array of versions.
202
         * <p>
203
         * This method calls {@link ModuleUtil#matchRequiredVersions(String, String)} internally.
204
         * </p>
205
         *
206
         * @param versions the openmrs versions to be checked against the current openmrs version
207
         * @return true if the current openmrs version is in versions otherwise false
208
         * <strong>Should</strong> return false when versions is null
209
         * <strong>Should</strong> return false when versions is empty
210
         * <strong>Should</strong> return true if current openmrs version matches one element in versions
211
         * <strong>Should</strong> return false if current openmrs version does not match any element in versions
212
         */
213
        public static boolean isOpenmrsVersionInVersions(String ...versions) {
214
                return isVersionInVersions(OpenmrsConstants.OPENMRS_VERSION_SHORT, versions);
1✔
215
        }
216

217
        /**
218
         * For testing of {@link #isOpenmrsVersionInVersions(String...)} only.
219
         * 
220
         * @param version the version
221
         * @param versions versions to match
222
         * @return true if version matches any value from versions
223
         */
224
        static boolean isVersionInVersions(String version, String ...versions) {
225
                if (versions == null || versions.length == 0) {
1✔
226
                        return false;
1✔
227
                }
228

229
                boolean result = false;
1✔
230
                for (String candidateVersion : versions) {
1✔
231
                        if (matchRequiredVersions(version, candidateVersion)) {
1✔
232
                                result = true;
1✔
233
                                break;
1✔
234
                        }
235
                }
236
                return result;
1✔
237
        }
238
        
239
        /**
240
         * This method is an enhancement of {@link #compareVersion(String, String)} and adds support for
241
         * wildcard characters and upperbounds. <br>
242
         * <br>
243
         * This method calls {@link ModuleUtil#checkRequiredVersion(String, String)} internally. <br>
244
         * <br>
245
         * The require version number in the config file can be in the following format:
246
         * <ul>
247
         * <li>1.2.3</li>
248
         * <li>1.2.*</li>
249
         * <li>1.2.2 - 1.2.3</li>
250
         * <li>1.2.* - 1.3.*</li>
251
         * </ul>
252
         * <p>
253
         * Again the possible require version number formats with their interpretation:
254
         * <ul>
255
         * <li>1.2.3 means 1.2.3 and above</li>
256
         * <li>1.2.* means any version of the 1.2.x branch. That is 1.2.0, 1.2.1, 1.2.2,... but not 1.3.0, 1.4.0</li>
257
         * <li>1.2.2 - 1.2.3 means 1.2.2 and 1.2.3 (inclusive)</li>
258
         * <li>1.2.* - 1.3.* means any version of the 1.2.x and 1.3.x branch</li>
259
         * </ul>
260
         * </p>
261
         *
262
         * @param version openmrs version number to be compared
263
         * @param versionRange value in the config file for required openmrs version
264
         * @return true if the <code>version</code> is within the <code>value</code>
265
         * <strong>Should</strong> allow ranged required version
266
         * <strong>Should</strong> allow ranged required version with wild card
267
         * <strong>Should</strong> allow ranged required version with wild card on one end
268
         * <strong>Should</strong> allow single entry for required version
269
         * <strong>Should</strong> allow required version with wild card
270
         * <strong>Should</strong> allow non numeric character required version
271
         * <strong>Should</strong> allow ranged non numeric character required version
272
         * <strong>Should</strong> allow ranged non numeric character with wild card
273
         * <strong>Should</strong> allow ranged non numeric character with wild card on one end
274
         * <strong>Should</strong> return false when openmrs version beyond wild card range
275
         * <strong>Should</strong> return false when required version beyond openmrs version
276
         * <strong>Should</strong> return false when required version with wild card beyond openmrs version
277
         * <strong>Should</strong> return false when required version with wild card on one end beyond openmrs version
278
         * <strong>Should</strong> return false when single entry required version beyond openmrs version
279
         * <strong>Should</strong> allow release type in the version
280
         * <strong>Should</strong> match when revision number is below maximum revision number
281
         * <strong>Should</strong> not match when revision number is above maximum revision number
282
         * <strong>Should</strong> correctly set upper and lower limit for versionRange with qualifiers and wild card
283
         * <strong>Should</strong> match when version has wild card plus qualifier and is within boundary
284
         * <strong>Should</strong> not match when version has wild card plus qualifier and is outside boundary
285
         * <strong>Should</strong> match when version has wild card and is within boundary
286
         * <strong>Should</strong> not match when version has wild card and is outside boundary
287
         * <strong>Should</strong> return true when required version is empty
288
         */
289
        public static boolean matchRequiredVersions(String version, String versionRange) {
290
                // There is a null check so no risk in keeping the literal on the right side
291
                if (StringUtils.isNotEmpty(versionRange)) {
1✔
292
                        String[] ranges = versionRange.split(",");
1✔
293
                        for (String range : ranges) {
1✔
294
                                // need to externalize this string
295
                                String separator = "-";
1✔
296
                                if (range.indexOf("*") > 0 || range.indexOf(separator) > 0 && (!isVersionWithQualifier(range))) {
1✔
297
                                        // if it contains "*" or "-" then we must separate those two
298
                                        // assume it's always going to be two part
299
                                        // assign the upper and lower bound
300
                                        // if there's no "-" to split lower and upper bound
301
                                        // then assign the same value for the lower and upper
302
                                        String lowerBound = range;
1✔
303
                                        String upperBound = range;
1✔
304
                                        
305
                                        int indexOfSeparator = range.indexOf(separator);
1✔
306
                                        while (indexOfSeparator > 0) {
1✔
307
                                                lowerBound = range.substring(0, indexOfSeparator);
1✔
308
                                                upperBound = range.substring(indexOfSeparator + 1);
1✔
309
                                                if (upperBound.matches("^\\s?\\d+.*")) {
1✔
310
                                                        break;
1✔
311
                                                }
312
                                                indexOfSeparator = range.indexOf(separator, indexOfSeparator + 1);
1✔
313
                                        }
314
                                        
315
                                        // only preserve part of the string that match the following format:
316
                                        // - xx.yy.*
317
                                        // - xx.yy.zz*
318
                                        lowerBound = StringUtils.remove(lowerBound, lowerBound.replaceAll("^\\s?\\d+[\\.\\d+\\*?|\\.\\*]+", ""));
1✔
319
                                        upperBound = StringUtils.remove(upperBound, upperBound.replaceAll("^\\s?\\d+[\\.\\d+\\*?|\\.\\*]+", ""));
1✔
320
                                        
321
                                        // if the lower contains "*" then change it to zero
322
                                        if (lowerBound.indexOf("*") > 0) {
1✔
323
                                                lowerBound = lowerBound.replaceAll("\\*", "0");
1✔
324
                                        }
325
                                        
326
                                        // if the upper contains "*" then change it to maxRevisionNumber
327
                                        if (upperBound.indexOf("*") > 0) {
1✔
328
                                                upperBound = upperBound.replaceAll("\\*", Integer.toString(Integer.MAX_VALUE));
1✔
329
                                        }
330
                                        
331
                                        int lowerReturn = compareVersionIgnoringQualifier(version, lowerBound);
1✔
332
                                        
333
                                        int upperReturn = compareVersionIgnoringQualifier(version, upperBound);
1✔
334
                                        
335
                                        if (lowerReturn < 0 || upperReturn > 0) {
1✔
336
                                                log.debug("Version " + version + " is not between " + lowerBound + " and " + upperBound);
1✔
337
                                        } else {
338
                                                return true;
1✔
339
                                        }
340
                                } else {
1✔
341
                                        if (compareVersionIgnoringQualifier(version, range) < 0) {
1✔
342
                                                log.debug("Version " + version + " is below " + range);
1✔
343
                                        } else {
344
                                                return true;
1✔
345
                                        }
346
                                }
347
                        }
348
                }
1✔
349
                else {
350
                        //no version checking if required version is not specified
351
                        return true;
1✔
352
                }
353
                
354
                return false;
1✔
355
        }
356
        
357
        /**
358
         * This method is an enhancement of {@link #compareVersion(String, String)} and adds support for
359
         * wildcard characters and upperbounds. <br>
360
         * <br>
361
         * <br>
362
         * The require version number in the config file can be in the following format:
363
         * <ul>
364
         * <li>1.2.3</li>
365
         * <li>1.2.*</li>
366
         * <li>1.2.2 - 1.2.3</li>
367
         * <li>1.2.* - 1.3.*</li>
368
         * </ul>
369
         * <p>
370
         * Again the possible require version number formats with their interpretation:
371
         * <ul>
372
         * <li>1.2.3 means 1.2.3 and above</li>
373
         * <li>1.2.* means any version of the 1.2.x branch. That is 1.2.0, 1.2.1, 1.2.2,... but not 1.3.0, 1.4.0</li>
374
         * <li>1.2.2 - 1.2.3 means 1.2.2 and 1.2.3 (inclusive)</li>
375
         * <li>1.2.* - 1.3.* means any version of the 1.2.x and 1.3.x branch</li>
376
         * </ul>
377
         * </p>
378
         *
379
         * @param version openmrs version number to be compared
380
         * @param versionRange value in the config file for required openmrs version
381
         * @throws ModuleException if the <code>version</code> is not within the <code>value</code>
382
         * <strong>Should</strong> throw ModuleException if openmrs version beyond wild card range
383
         * <strong>Should</strong> throw ModuleException if required version beyond openmrs version
384
         * <strong>Should</strong> throw ModuleException if required version with wild card beyond openmrs version
385
         * <strong>Should</strong> throw ModuleException if required version with wild card on one end beyond openmrs
386
         *         version
387
         * <strong>Should</strong> throw ModuleException if single entry required version beyond openmrs version
388
         * <strong>Should</strong> throw ModuleException if SNAPSHOT not handled correctly
389
         * <strong>Should</strong> handle SNAPSHOT versions
390
         * <strong>Should</strong> handle ALPHA versions
391
         */
392
        public static void checkRequiredVersion(String version, String versionRange) throws ModuleException {
393
                if (!matchRequiredVersions(version, versionRange)) {
1✔
394
                        String ms = Context.getMessageSourceService().getMessage("Module.requireVersion.outOfBounds",
1✔
395
                            new String[] { versionRange, version }, Context.getLocale());
1✔
396
                        throw new ModuleException(ms);
1✔
397
                }
398
        }
1✔
399
        
400
        /**
401
         * Compare two version strings.
402
         *
403
         * @param versionA String like 1.9.2.0, may include a qualifier like "-SNAPSHOT", may be null
404
         * @param versionB String like 1.9.2.0, may include a qualifier like "-SNAPSHOT", may be null
405
         * @return the value <code>0</code> if versions are equal; a value less than <code>0</code> if first version is
406
         *                    before the second one; a value greater than <code>0</code> if first version is after the second one.
407
         *                    If version numbers are equal and only one of them has a qualifier, the version without the qualifier is
408
         *                    considered greater.
409
         */
410
        public static int compareVersion(String versionA, String versionB) {
411
                return compareVersion(versionA, versionB, false);
1✔
412
        }
413

414
        /**
415
         * Compare two version strings. Any version qualifiers are ignored in the comparison.
416
         *
417
         * @param versionA String like 1.9.2.0, may include a qualifier like "-SNAPSHOT", may be null
418
         * @param versionB String like 1.9.2.0, may include a qualifier like "-SNAPSHOT", may be null
419
         * @return the value <code>0</code> if versions are equal; a value less than <code>0</code> if first version is
420
         *                    before the second one; a value greater than <code>0</code> if first version is after the second one.
421
         */
422
        public static int compareVersionIgnoringQualifier(String versionA, String versionB) {
423
                return compareVersion(versionA, versionB, true);
1✔
424
        }
425

426
        private static int compareVersion(String versionA, String versionB, boolean ignoreQualifier) {
427
                try {
428
                        if (versionA == null || versionB == null) {
1✔
429
                                return 0;
1✔
430
                        }
431

432
                        List<String> versionANumbers = new ArrayList<>();
1✔
433
                        List<String> versionBNumbers = new ArrayList<>();
1✔
434
                        String qualifierSeparator = "-";
1✔
435

436
                        // strip off any qualifier e.g. "-SNAPSHOT"
437
                        int qualifierIndexA = versionA.indexOf(qualifierSeparator);
1✔
438
                        if (qualifierIndexA != -1) {
1✔
439
                                versionA = versionA.substring(0, qualifierIndexA);
1✔
440
                        }
441

442
                        // strip off any qualifier e.g. "-SNAPSHOT"
443
                        int qualifierIndexB = versionB.indexOf(qualifierSeparator);
1✔
444
                        if (qualifierIndexB != -1) {
1✔
445
                                versionB = versionB.substring(0, qualifierIndexB);
1✔
446
                        }
447

448
                        Collections.addAll(versionANumbers, versionA.split("\\."));
1✔
449
                        Collections.addAll(versionBNumbers, versionB.split("\\."));
1✔
450

451
                        // match the sizes of the lists
452
                        while (versionANumbers.size() < versionBNumbers.size()) {
1✔
453
                                versionANumbers.add("0");
1✔
454
                        }
455
                        while (versionBNumbers.size() < versionANumbers.size()) {
1✔
456
                                versionBNumbers.add("0");
1✔
457
                        }
458

459
                        for (int x = 0; x < versionANumbers.size(); x++) {
1✔
460
                                String verAPartString = versionANumbers.get(x).trim();
1✔
461
                                String verBPartString = versionBNumbers.get(x).trim();
1✔
462
                                Long verAPart = NumberUtils.toLong(verAPartString, 0);
1✔
463
                                Long verBPart = NumberUtils.toLong(verBPartString, 0);
1✔
464

465
                                int ret = verAPart.compareTo(verBPart);
1✔
466
                                if (ret != 0) {
1✔
467
                                        return ret;
1✔
468
                                }
469
                        }
470
                        
471
                        // At this point the version numbers are equal.
472
                        if (!ignoreQualifier) {
1✔
473
                                if (qualifierIndexA >= 0 && qualifierIndexB < 0) {
1✔
474
                                        return -1;
1✔
475
                                } else if (qualifierIndexA < 0 && qualifierIndexB >= 0) {
1✔
476
                                        return 1;
1✔
477
                                }
478
                        }
479
                }
480
                catch (NumberFormatException e) {
×
481
                        log.error("Error while converting a version/value to an integer: " + versionA + "/" + versionB, e);
×
482
                }
1✔
483
                
484
                // default return value if an error occurs or elements are equal
485
                return 0;
1✔
486
        }
487
        
488
        /**
489
         * Checks for qualifier version (i.e "-SNAPSHOT", "-ALPHA" etc. after maven version conventions)
490
         *
491
         * @param version String like 1.9.2-SNAPSHOT
492
         * @return true if version contains qualifier
493
         */
494
        public static boolean isVersionWithQualifier(String version) {
495
                Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.(\\d+))?(\\-([A-Za-z]+))").matcher(version);
1✔
496
                return matcher.matches();
1✔
497
        }
498
        
499
        /**
500
         * Gets the folder where modules are stored. ModuleExceptions are thrown on errors
501
         *
502
         * @return folder containing modules
503
         * <strong>Should</strong> use the runtime property as the first choice if specified
504
         * <strong>Should</strong> return the correct file if the runtime property is an absolute path
505
         */
506
        public static File getModuleRepository() {
507
                
508
                String folderName = Context.getRuntimeProperties().getProperty(ModuleConstants.REPOSITORY_FOLDER_RUNTIME_PROPERTY);
1✔
509
                if (StringUtils.isBlank(folderName)) {
1✔
510
                        AdministrationService as = Context.getAdministrationService();
1✔
511
                        folderName = as.getGlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY,
1✔
512
                            ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT);
513
                }
514
                // try to load the repository folder straight away.
515
                File folder = new File(folderName);
1✔
516
                
517
                // if the property wasn't a full path already, assume it was intended to be a folder in the
518
                // application directory
519
                if (!folder.exists()) {
1✔
520
                        folder = new File(OpenmrsUtil.getApplicationDataDirectory(), folderName);
1✔
521
                }
522
                
523
                // now create the modules folder if it doesn't exist
524
                if (!folder.exists()) {
1✔
525
                        log.warn("Module repository " + folder.getAbsolutePath() + " doesn't exist.  Creating directories now.");
1✔
526
                        folder.mkdirs();
1✔
527
                }
528
                
529
                if (!folder.isDirectory()) {
1✔
530
                        throw new ModuleException("Module repository is not a directory at: " + folder.getAbsolutePath());
×
531
                }
532
                
533
                return folder;
1✔
534
        }
535
        
536
        /**
537
         * Utility method to convert a {@link File} object to a local URL.
538
         *
539
         * @param file a file object
540
         * @return absolute URL that points to the given file
541
         * @throws MalformedURLException if file can't be represented as URL for some reason
542
         */
543
        public static URL file2url(final File file) throws MalformedURLException {
544
                if (file == null) {
1✔
545
                        return null;
1✔
546
                }
547
                try {
548
                        return file.getCanonicalFile().toURI().toURL();
1✔
549
                }
550
                catch (IOException | NoSuchMethodError ioe) {
1✔
551
                        throw new MalformedURLException("Cannot convert: " + file.getName() + " to url");
1✔
552
                }
553
        }
554
        
555
        /**
556
         * Expand the given <code>fileToExpand</code> jar to the <code>tmpModuleFile</code> directory
557
         *
558
         * If <code>name</code> is null, the entire jar is expanded. If<code>name</code> is not null,
559
         * then only that path/file is expanded.
560
         *
561
         * @param fileToExpand file pointing at a .jar
562
         * @param tmpModuleDir directory in which to place the files
563
         * @param name filename inside of the jar to look for and expand
564
         * @param keepFullPath if true, will recreate entire directory structure in tmpModuleDir
565
         *            relating to <code>name</code>. if false will start directory structure at
566
         *            <code>name</code>
567
         * <strong>Should</strong> expand entire jar if name is null
568
         * <strong>Should</strong> expand entire jar if name is empty string
569
         * <strong>Should</strong> expand directory with parent tree if name is directory and keepFullPath is true
570
         * <strong>Should</strong> expand directory without parent tree if name is directory and keepFullPath is false
571
         * <strong>Should</strong> expand file with parent tree if name is file and keepFullPath is true
572
         */
573
        public static void expandJar(File fileToExpand, File tmpModuleDir, String name, boolean keepFullPath) throws IOException {
574
                String docBase = tmpModuleDir.getAbsolutePath();
1✔
575
                try (JarFile jarFile = new JarFile(fileToExpand)) {
1✔
576
                        Enumeration<JarEntry> jarEntries = jarFile.entries();
1✔
577
                        boolean foundName = (name == null);
1✔
578
                        
579
                        // loop over all of the elements looking for the match to 'name'
580
                        while (jarEntries.hasMoreElements()) {
1✔
581
                                JarEntry jarEntry = jarEntries.nextElement();
1✔
582
                                if (name == null || jarEntry.getName().startsWith(name)) {
1✔
583
                                        String entryName = jarEntry.getName();
1✔
584
                                        // trim out the name path from the name of the new file
585
                                        if (!keepFullPath && name != null) {
1✔
586
                                                entryName = entryName.replaceFirst(name, "");
1✔
587
                                        }
588
                                        
589
                                        // if it has a slash, it's in a directory
590
                                        int last = entryName.lastIndexOf('/');
1✔
591
                                        if (last >= 0) {
1✔
592
                                                File parent = new File(docBase, entryName.substring(0, last));
1✔
593
                                                parent.mkdirs();
1✔
594
                                                log.debug("Creating parent dirs: " + parent.getAbsolutePath());
1✔
595
                                        }
596
                                        // we don't want to "expand" directories or empty names
597
                                        if (entryName.endsWith("/") || "".equals(entryName)) {
1✔
598
                                                continue;
×
599
                                        }
600
                                        try(InputStream input = jarFile.getInputStream(jarEntry)) {
1✔
601
                                                expand(input, docBase, entryName);
1✔
602
                                        }
603
                                        foundName = true;
1✔
604
                                }
605
                        }
1✔
606
                        if (!foundName) {
1✔
607
                                log.debug("Unable to find: " + name + " in file " + fileToExpand.getAbsolutePath());
1✔
608
                        }
609
                        
610
                }
611
                catch (IOException e) {
×
612
                        log.warn("Unable to delete tmpModuleFile on error", e);
×
613
                        throw e;
×
614
                }
1✔
615
        }
1✔
616
        
617
        /**
618
         * Expand the given file in the given stream to a location (fileDir/name) The <code>input</code>
619
         * InputStream is not closed in this method
620
         *
621
         * @param input stream to read from
622
         * @param fileDir directory to copy to
623
         * @param name file/directory within the <code>fileDir</code> to which we expand
624
         *            <code>input</code>
625
         * @return File the file created by the expansion.
626
         * @throws IOException if an error occurred while copying
627
         */
628
        private static void expand(InputStream input, String fileDir, String name) throws IOException {
629
                log.debug("expanding: {}", name);
1✔
630

631
                File file = new File(fileDir, name);
1✔
632

633
                if (!file.toPath().normalize().startsWith(fileDir)) {
1✔
634
                        throw new UnsupportedOperationException("Attempted to write file '" + name + "' rejected as it attempts to write outside the chosen directory. This may be the result of a zip-slip style attack.");
×
635
                }
636
                
637
                try (FileOutputStream outStream = new FileOutputStream(file)) {
1✔
638
                        OpenmrsUtil.copyFile(input, outStream);
1✔
639
                }
640
        }
1✔
641
        
642
        /**
643
         * Downloads the contents of a URL and copies them to a string (Borrowed from oreilly)
644
         *
645
         * @param url
646
         * @return InputStream of contents
647
         * <strong>Should</strong> return a valid input stream for old module urls
648
         */
649
        public static InputStream getURLStream(URL url) {
650
                InputStream in = null;
1✔
651
                try {
652
                        URLConnection uc = url.openConnection();
1✔
653
                        uc.setDefaultUseCaches(false);
1✔
654
                        uc.setUseCaches(false);
1✔
655
                        uc.setRequestProperty("Cache-Control", "max-age=0,no-cache");
1✔
656
                        uc.setRequestProperty("Pragma", "no-cache");
1✔
657
                        
658
                        log.debug("Logging an attempt to connect to: " + url);
1✔
659
                        
660
                        in = openConnectionCheckRedirects(uc);
×
661
                }
662
                catch (IOException io) {
1✔
663
                        log.warn("io while reading: " + url, io);
1✔
664
                }
×
665
                
666
                return in;
1✔
667
        }
668
        
669
        /**
670
         * Convenience method to follow http to https redirects. Will follow a total of 5 redirects,
671
         * then fail out due to foolishness on the url's part.
672
         *
673
         * @param c the {@link URLConnection} to open
674
         * @return an {@link InputStream} that is not necessarily at the same url, possibly at a 403
675
         *         redirect.
676
         * @throws IOException
677
         * @see #getURLStream(URL)
678
         */
679
        protected static InputStream openConnectionCheckRedirects(URLConnection c) throws IOException {
680
                boolean redir;
681
                int redirects = 0;
1✔
682
                InputStream in;
683
                do {
684
                        if (c instanceof HttpURLConnection) {
1✔
685
                                ((HttpURLConnection) c).setInstanceFollowRedirects(false);
1✔
686
                        }
687
                        // We want to open the input stream before getting headers
688
                        // because getHeaderField() et al swallow IOExceptions.
689
                        in = c.getInputStream();
×
690
                        redir = false;
×
691
                        if (c instanceof HttpURLConnection) {
×
692
                                HttpURLConnection http = (HttpURLConnection) c;
×
693
                                int stat = http.getResponseCode();
×
694
                                if (stat == 300 || stat == 301 || stat == 302 || stat == 303 || stat == 305 || stat == 307) {
×
695
                                        URL base = http.getURL();
×
696
                                        String loc = http.getHeaderField("Location");
×
697
                                        URL target = null;
×
698
                                        if (loc != null) {
×
699
                                                target = new URL(base, loc);
×
700
                                        }
701
                                        http.disconnect();
×
702
                                        // Redirection should be allowed only for HTTP and HTTPS
703
                                        // and should be limited to 5 redirects at most.
704
                                        if (target == null || !("http".equals(target.getProtocol()) || "https".equals(target.getProtocol()))
×
705
                                                || redirects >= 5) {
706
                                                throw new SecurityException("illegal URL redirect");
×
707
                                        }
708
                                        redir = true;
×
709
                                        c = target.openConnection();
×
710
                                        redirects++;
×
711
                                }
712
                        }
713
                } while (redir);
×
714
                return in;
×
715
        }
716
        
717
        /**
718
         * Downloads the contents of a URL and copies them to a string (Borrowed from oreilly)
719
         *
720
         * @param url
721
         * @return String contents of the URL
722
         * <strong>Should</strong> return an update rdf page for old https dev urls
723
         * <strong>Should</strong> return an update rdf page for old https module urls
724
         * <strong>Should</strong> return an update rdf page for module urls
725
         */
726
        public static String getURL(URL url) {
727
                InputStream in = null;
×
728
                ByteArrayOutputStream out = null;
×
729
                String output = "";
×
730
                try {
731
                        in = getURLStream(url);
×
732
                        if (in == null) {
×
733
                                // skip this module if updateURL is not defined
734
                                return "";
×
735
                        }
736
                        
737
                        out = new ByteArrayOutputStream();
×
738
                        OpenmrsUtil.copyFile(in, out);
×
739
                        output = out.toString(StandardCharsets.UTF_8.name());
×
740
                }
741
                catch (IOException io) {
×
742
                        log.warn("io while reading: " + url, io);
×
743
                }
744
                finally {
745
                        try {
746
                                in.close();
×
747
                        }
748
                        catch (Exception e) { /* pass */}
×
749
                        try {
750
                                out.close();
×
751
                        }
752
                        catch (Exception e) { /* pass */}
×
753
                }
754
                
755
                return output;
×
756
        }
757
        
758
        /**
759
         * Iterates over the modules and checks each update.rdf file for an update
760
         *
761
         * @return True if an update was found for one of the modules, false if none were found
762
         * @throws ModuleException
763
         */
764
        public static Boolean checkForModuleUpdates() throws ModuleException {
765
                
766
                Boolean updateFound = false;
×
767
                
768
                for (Module mod : ModuleFactory.getLoadedModules()) {
×
769
                        String updateURL = mod.getUpdateURL();
×
770
                        if (StringUtils.isNotEmpty(updateURL)) {
×
771
                                try {
772
                                        // get the contents pointed to by the url
773
                                        URL url = new URL(updateURL);
×
774
                                        if (!url.toString().endsWith(ModuleConstants.UPDATE_FILE_NAME)) {
×
775
                                                log.warn("Illegal url: " + url);
×
776
                                                continue;
×
777
                                        }
778
                                        String content = getURL(url);
×
779
                                        
780
                                        // skip empty or invalid updates
781
                                        if ("".equals(content)) {
×
782
                                                continue;
×
783
                                        }
784
                                        
785
                                        // process and parse the contents
786
                                        UpdateFileParser parser = new UpdateFileParser(content);
×
787
                                        parser.parse();
×
788
                                        
789
                                        log.debug("Update for mod: " + mod.getModuleId() + " compareVersion result: "
×
790
                                                + compareVersion(mod.getVersion(), parser.getCurrentVersion()));
×
791
                                        
792
                                        // check the update.rdf version against the installed version
793
                                        if (compareVersion(mod.getVersion(), parser.getCurrentVersion()) < 0) {
×
794
                                                if (mod.getModuleId().equals(parser.getModuleId())) {
×
795
                                                        mod.setDownloadURL(parser.getDownloadURL());
×
796
                                                        mod.setUpdateVersion(parser.getCurrentVersion());
×
797
                                                        updateFound = true;
×
798
                                                } else {
799
                                                        log.warn("Module id does not match in update.rdf:" + parser.getModuleId());
×
800
                                                }
801
                                        } else {
802
                                                mod.setDownloadURL(null);
×
803
                                                mod.setUpdateVersion(null);
×
804
                                        }
805
                                }
806
                                catch (ModuleException e) {
×
807
                                        log.warn("Unable to get updates from update.xml", e);
×
808
                                }
809
                                catch (MalformedURLException e) {
×
810
                                        log.warn("Unable to form a URL object out of: " + updateURL, e);
×
811
                                }
×
812
                        }
813
                }
×
814
                
815
                return updateFound;
×
816
        }
817
        
818
        /**
819
         * @return true/false whether the 'allow upload' or 'allow web admin' property has been turned
820
         *         on
821
         */
822
        public static Boolean allowAdmin() {
823
                
824
                Properties properties = Context.getRuntimeProperties();
×
825
                String prop = properties.getProperty(ModuleConstants.RUNTIMEPROPERTY_ALLOW_UPLOAD, null);
×
826
                if (prop == null) {
×
827
                        prop = properties.getProperty(ModuleConstants.RUNTIMEPROPERTY_ALLOW_ADMIN, "false");
×
828
                }
829
                
830
                return "true".equals(prop);
×
831
        }
832
        
833
        /**
834
         * @see ModuleUtil#refreshApplicationContext(AbstractRefreshableApplicationContext, boolean, Module)
835
         */
836
        public static AbstractRefreshableApplicationContext refreshApplicationContext(AbstractRefreshableApplicationContext ctx) {
837
                return refreshApplicationContext(ctx, false, null);
×
838
        }
839
        
840
        /**
841
         * Refreshes the given application context "properly" in OpenMRS. Will first shut down the
842
         * Context and destroy the classloader, then will refresh and set everything back up again.
843
         *
844
         * @param ctx Spring application context that needs refreshing.
845
         * @param isOpenmrsStartup if this refresh is being done at application startup.
846
         * @param startedModule the module that was just started and waiting on the context refresh.
847
         * @return AbstractRefreshableApplicationContext The newly refreshed application context.
848
         */
849
        public static AbstractRefreshableApplicationContext refreshApplicationContext(AbstractRefreshableApplicationContext ctx,
850
                boolean isOpenmrsStartup, Module startedModule) {
851
                //notify all started modules that we are about to refresh the context
852
                Set<Module> startedModules = new LinkedHashSet<>(ModuleFactory.getStartedModulesInOrder());
×
853
                for (Module module : startedModules) {
×
854
                        try {
855
                                if (module.getModuleActivator() != null) {
×
NEW
856
                                        log.debug("Run module willRefreshContext: {}", module.getModuleId());
×
857
                                        Thread.currentThread().setContextClassLoader(ModuleFactory.getModuleClassLoader(module));
×
858
                                        module.getModuleActivator().willRefreshContext();
×
859
                                }
860
                        }
861
                        catch (Exception e) {
×
862
                                log.warn("Unable to call willRefreshContext() method in the module's activator", e);
×
863
                        }
×
864
                }
×
865
                
866
                OpenmrsClassLoader.saveState();
×
867
                SchedulerUtil.shutdown();
×
868
                ServiceContext.destroyInstance();
×
869
                
870
                try {
871
                        ctx.stop();
×
872
                        ctx.close();
×
873
                }
874
                catch (Exception e) {
×
875
                        log.warn("Exception while stopping and closing context: ", e);
×
876
                        // Spring seems to be trying to refresh the context instead of /just/ stopping
877
                        // pass
878
                }
×
879
                OpenmrsClassLoader.destroyInstance();
×
880
                ctx.setClassLoader(OpenmrsClassLoader.getInstance());
×
881
                Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
×
882
                
NEW
883
                log.debug("Refreshing context");
×
UNCOV
884
                ServiceContext.getInstance().startRefreshingContext();
×
885
                try {
886
                        ctx.refresh();
×
887
                }
888
                finally {
889
                        ServiceContext.getInstance().doneRefreshingContext();
×
890
                }
NEW
891
                log.debug("Done refreshing context");
×
892
                
893
                ctx.setClassLoader(OpenmrsClassLoader.getInstance());
×
894
                Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
×
895
                
896
                OpenmrsClassLoader.restoreState();
×
NEW
897
                log.debug("Startup scheduler");
×
UNCOV
898
                SchedulerUtil.startup(Context.getRuntimeProperties());
×
899
                
900
                OpenmrsClassLoader.setThreadsToNewClassLoader();
×
901
                
902
                // reload the advice points that were lost when refreshing Spring
903
                log.debug("Reloading advice for all started modules: {}", startedModules.size());
×
904
                
905
                try {
906
                        //The call backs in this block may need lazy loading of objects
907
                        //which will fail because we use an OpenSessionInViewFilter whose opened session
908
                        //was closed when the application context was refreshed as above.
909
                        //So we need to open another session now. TRUNK-3739
910
                        Context.openSessionWithCurrentUser();
×
911
                        for (Module module : startedModules) {
×
912
                                if (!module.isStarted()) {
×
913
                                        continue;
×
914
                                }
915
                                
916
                                ModuleFactory.loadAdvice(module);
×
917
                                try {
918
                                        ModuleFactory.passDaemonToken(module);
×
919
                                        
920
                                        if (module.getModuleActivator() != null) {
×
NEW
921
                                                log.debug("Run module contextRefreshed: {}", module.getModuleId());
×
UNCOV
922
                                                module.getModuleActivator().contextRefreshed();
×
923
                                                try {
924
                                                        //if it is system start up, call the started method for all started modules
925
                                                        if (isOpenmrsStartup) {
×
NEW
926
                                                                log.debug("Run module started: {}", module.getModuleId());
×
UNCOV
927
                                                                module.getModuleActivator().started();
×
928
                                                        }
929
                                                        //if refreshing the context after a user started or uploaded a new module
930
                                                        else if (!isOpenmrsStartup && module.equals(startedModule)) {
×
NEW
931
                                                                log.debug("Run module started: {}", module.getModuleId());
×
UNCOV
932
                                                                module.getModuleActivator().started();
×
933
                                                        }
NEW
934
                                                        log.debug("Done running module started: {}", module.getModuleId());
×
935
                                                }
936
                                                catch (Exception e) {
×
937
                                                        log.warn("Unable to invoke started() method on the module's activator", e);
×
938
                                                        ModuleFactory.stopModule(module, true, true);
×
939
                                                }
×
940
                                        }
941
                                        
942
                                }
943
                                catch (Exception e) {
×
944
                                        log.warn("Unable to invoke method on the module's activator ", e);
×
945
                                }
×
946
                        }
×
947
                }
948
                finally {
949
                        Context.closeSessionWithCurrentUser();
×
950
                }
951
                
952
                return ctx;
×
953
        }
954
        
955
        /**
956
         * Looks at the &lt;moduleid&gt;.mandatory properties and at the currently started modules to make
957
         * sure that all mandatory modules have been started successfully.
958
         *
959
         * @throws ModuleException if a mandatory module isn't started
960
         * <strong>Should</strong> throw ModuleException if a mandatory module is not started
961
         */
962
        protected static void checkMandatoryModulesStarted() throws ModuleException {
963
                
964
                List<String> mandatoryModuleIds = getMandatoryModules();
1✔
965
                Set<String> startedModuleIds = ModuleFactory.getStartedModulesMap().keySet();
1✔
966
                
967
                mandatoryModuleIds.removeAll(startedModuleIds);
1✔
968
                
969
                // any module ids left in the list are not started
970
                if (!mandatoryModuleIds.isEmpty()) {
1✔
971
                        throw new MandatoryModuleException(mandatoryModuleIds);
1✔
972
                }
973
        }
1✔
974
        
975
        /**
976
         * Returns all modules that are marked as mandatory. Currently this means there is a
977
         * &lt;moduleid&gt;.mandatory=true global property.
978
         *
979
         * @return list of modules ids for mandatory modules
980
         * <strong>Should</strong> return mandatory module ids
981
         */
982
        public static List<String> getMandatoryModules() {
983
                
984
                List<String> mandatoryModuleIds = new ArrayList<>();
1✔
985
                
986
                try {
987
                        List<GlobalProperty> props = Context.getAdministrationService().getGlobalPropertiesBySuffix(".mandatory");
1✔
988
                        
989
                        for (GlobalProperty prop : props) {
1✔
990
                                if ("true".equalsIgnoreCase(prop.getPropertyValue())) {
1✔
991
                                        mandatoryModuleIds.add(prop.getProperty().replace(".mandatory", ""));
1✔
992
                                }
993
                        }
1✔
994
                }
995
                catch (Exception e) {
×
996
                        log.warn("Unable to get the mandatory module list", e);
×
997
                }
1✔
998
                
999
                return mandatoryModuleIds;
1✔
1000
        }
1001
        
1002
        /**
1003
         * <pre>
1004
         * Gets the module that should handle a path. The path you pass in should be a module id (in
1005
         * path format, i.e. /ui/springmvc, not ui.springmvc) followed by a resource. Something like
1006
         * the following:
1007
         *   /ui/springmvc/css/ui.css
1008
         *
1009
         * The first running module out of the following would be returned:
1010
         *   ui.springmvc.css
1011
         *   ui.springmvc
1012
         *   ui
1013
         * </pre>
1014
         *
1015
         * @param path
1016
         * @return the running module that matches the most of the given path
1017
         * <strong>Should</strong> handle ui springmvc css ui dot css when ui dot springmvc module is running
1018
         * <strong>Should</strong> handle ui springmvc css ui dot css when ui module is running
1019
         * <strong>Should</strong> return null for ui springmvc css ui dot css when no relevant module is running
1020
         */
1021
        public static Module getModuleForPath(String path) {
1022
                int ind = path.lastIndexOf('/');
1✔
1023
                if (ind <= 0) {
1✔
1024
                        throw new IllegalArgumentException(
×
1025
                                "Input must be /moduleId/resource. Input needs a / after the first character: " + path);
1026
                }
1027
                String moduleId = path.startsWith("/") ? path.substring(1, ind) : path.substring(0, ind);
1✔
1028
                moduleId = moduleId.replace('/', '.');
1✔
1029
                // iterate over progressively shorter module ids
1030
                while (true) {
1031
                        Module mod = ModuleFactory.getStartedModuleById(moduleId);
1✔
1032
                        if (mod != null) {
1✔
1033
                                return mod;
1✔
1034
                        }
1035
                        // try the next shorter module id
1036
                        ind = moduleId.lastIndexOf('.');
1✔
1037
                        if (ind < 0) {
1✔
1038
                                break;
1✔
1039
                        }
1040
                        moduleId = moduleId.substring(0, ind);
1✔
1041
                }
1✔
1042
                return null;
1✔
1043
        }
1044
        
1045
        /**
1046
         * Takes a global path and returns the local path within the specified module. For example
1047
         * calling this method with the path "/ui/springmvc/css/ui.css" and the ui.springmvc module, you
1048
         * would get "/css/ui.css".
1049
         *
1050
         * @param module
1051
         * @param path
1052
         * @return local path
1053
         * <strong>Should</strong> handle ui springmvc css ui dot css example
1054
         */
1055
        public static String getPathForResource(Module module, String path) {
1056
                if (path.startsWith("/")) {
1✔
1057
                        path = path.substring(1);
1✔
1058
                }
1059
                return path.substring(module.getModuleIdAsPath().length());
1✔
1060
        }
1061
        
1062
        /**
1063
         * This loops over all FILES in this jar to get the package names. If there is an empty
1064
         * directory in this jar it is not returned as a providedPackage.
1065
         *
1066
         * @param file jar file to look into
1067
         * @return list of strings of package names in this jar
1068
         */
1069
        public static Collection<String> getPackagesFromFile(File file) {
1070
                
1071
                // End early if we're given a non jar file
1072
                if (!file.getName().endsWith(".jar")) {
1✔
1073
                        return Collections.emptySet();
1✔
1074
                }
1075
                
1076
                Set<String> packagesProvided = new HashSet<>();
1✔
1077
                
1078
                JarFile jar = null;
1✔
1079
                try {
1080
                        jar = new JarFile(file);
1✔
1081
                        
1082
                        Enumeration<JarEntry> jarEntries = jar.entries();
1✔
1083
                        while (jarEntries.hasMoreElements()) {
1✔
1084
                                JarEntry jarEntry = jarEntries.nextElement();
1✔
1085
                                if (jarEntry.isDirectory()) {
1✔
1086
                                        // skip over directory entries, we only care about files
1087
                                        continue;
1✔
1088
                                }
1089
                                String name = jarEntry.getName();
1✔
1090
                                
1091
                                // Skip over some folders in the jar/omod
1092
                                if (name.startsWith("lib") || name.startsWith("META-INF") || name.startsWith("web/module")) {
1✔
1093
                                        continue;
1✔
1094
                                }
1095
                                
1096
                                Integer indexOfLastSlash = name.lastIndexOf("/");
1✔
1097
                                if (indexOfLastSlash <= 0) {
1✔
1098
                                        continue;
1✔
1099
                                }
1100
                                String packageName = name.substring(0, indexOfLastSlash);
1✔
1101
                                
1102
                                packageName = packageName.replaceAll("/", ".");
1✔
1103
                                
1104
                                if (packagesProvided.add(packageName) && log.isTraceEnabled()) {
1✔
1105
                                        log.trace("Adding module's jarentry with package: " + packageName);
×
1106
                                }
1107
                        }
1✔
1108
                        
1109
                        jar.close();
1✔
1110
                }
1111
                catch (IOException e) {
×
1112
                        log.error("Error while reading file: " + file.getAbsolutePath(), e);
×
1113
                }
1114
                finally {
1115
                        if (jar != null) {
1✔
1116
                                try {
1117
                                        jar.close();
1✔
1118
                                }
1119
                                catch (IOException e) {
×
1120
                                        // Ignore quietly
1121
                                }
1✔
1122
                        }
1123
                }
1124
                
1125
                return packagesProvided;
1✔
1126
        }
1127
        
1128
        /**
1129
         * Get a resource as from the module's api jar. Api jar should be in the omod's lib folder.
1130
         * 
1131
         * @param jarFile omod file loaded as jar
1132
         * @param moduleId id of the module
1133
         * @param version version of the module
1134
         * @param resource name of a resource from the api jar
1135
         * @return resource as an input stream or <code>null</code> if resource cannot be loaded
1136
         * <strong>Should</strong> load file from api as input stream
1137
         * <strong>Should</strong> return null if api is not found
1138
         * <strong>Should</strong> return null if file is not found in api
1139
         */
1140
        public static InputStream getResourceFromApi(JarFile jarFile, String moduleId, String version, String resource) {
1141
                String apiLocation = "lib/" + moduleId + "-api-" + version + ".jar";
1✔
1142
                return getResourceFromInnerJar(jarFile, apiLocation, resource);
1✔
1143
        }
1144
        
1145
        /**
1146
         * Load resource from a jar inside a jar.
1147
         * 
1148
         * @param outerJarFile jar file that contains a jar file
1149
         * @param innerJarFileLocation inner jar file location relative to the outer jar
1150
         * @param resource path to a resource relative to the inner jar
1151
         * @return resource from the inner jar as an input stream or <code>null</code> if resource cannot be loaded
1152
         */
1153
        private static InputStream getResourceFromInnerJar(JarFile outerJarFile, String innerJarFileLocation, String resource) {
1154
                File tempFile = null;
1✔
1155
                FileOutputStream tempOut = null;
1✔
1156
                JarFile innerJarFile = null;
1✔
1157
                InputStream innerInputStream = null;
1✔
1158
                try {
1159
                        tempFile = File.createTempFile("tempFile", "jar");
1✔
1160
                        tempOut = new FileOutputStream(tempFile);
1✔
1161
                        ZipEntry innerJarFileEntry = outerJarFile.getEntry(innerJarFileLocation);
1✔
1162
                        if (innerJarFileEntry != null) {
1✔
1163
                                IOUtils.copy(outerJarFile.getInputStream(innerJarFileEntry), tempOut);
1✔
1164
                                innerJarFile = new JarFile(tempFile);
1✔
1165
                                ZipEntry targetEntry = innerJarFile.getEntry(resource);
1✔
1166
                                if (targetEntry != null) {
1✔
1167
                                        // clone InputStream to make it work after the innerJarFile is closed
1168
                                        innerInputStream = innerJarFile.getInputStream(targetEntry);
1✔
1169
                                        byte[] byteArray = IOUtils.toByteArray(innerInputStream);
1✔
1170
                                        return new ByteArrayInputStream(byteArray);
1✔
1171
                                }
1172
                        }
1173
                }
1174
                catch (IOException e) {
×
1175
                        log.error("Unable to get '" + resource + "' from '" + innerJarFileLocation + "' of '" + outerJarFile.getName()
×
1176
                                + "'", e);
1177
                }
1178
                finally {
1179
                        IOUtils.closeQuietly(tempOut);
1✔
1180
                        IOUtils.closeQuietly(innerInputStream);
1✔
1181

1182
                        // close inner jar file before attempting to delete temporary file
1183
                        try {
1184
                                if (innerJarFile != null) {
1✔
1185
                                        innerJarFile.close();
1✔
1186
                                }
1187
                        }
1188
                        catch (IOException e) {
×
1189
                                log.warn("Unable to close inner jarfile: " + innerJarFile, e);
×
1190
                        }
1✔
1191

1192
                        // delete temporary file
1193
                        if (tempFile != null && !tempFile.delete()) {
1✔
1194
                                log.warn("Could not delete temporary jarfile: " + tempFile);
×
1195
                        }
1196
                }
1197
                return null;
1✔
1198
        }
1199
        
1200
        /**
1201
         * Gets the root folder of a module's sources during development
1202
         * 
1203
         * @param moduleId the module id
1204
         * @return the module's development folder is specified, else null
1205
         */
1206
        public static File getDevelopmentDirectory(String moduleId) {
1207
                String directory = System.getProperty(moduleId + ".development.directory");
1✔
1208
                if (StringUtils.isNotBlank(directory)) {
1✔
1209
                        return new File(directory);
×
1210
                }
1211
                
1212
                return null;
1✔
1213
        }
1214
}
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