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

openmrs / openmrs-core / 24803983538

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

push

github

ibacher
Fix issues with Javadocs

21841 of 34293 relevant lines covered (63.69%)

0.64 hits per line

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

58.59
/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.HashMap;
28
import java.util.HashSet;
29
import java.util.LinkedHashSet;
30
import java.util.List;
31
import java.util.Map;
32
import java.util.Properties;
33
import java.util.Set;
34
import java.util.jar.JarEntry;
35
import java.util.jar.JarFile;
36
import java.util.regex.Matcher;
37
import java.util.regex.Pattern;
38
import java.util.zip.ZipEntry;
39

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

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

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

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

211
        /**
212
         * Checks if the current OpenMRS version is in an array of versions.
213
         * <p>
214
         * This method calls {@link ModuleUtil#matchRequiredVersions(String, String)} internally.
215
         * </p>
216
         *
217
         * @param versions the openmrs versions to be checked against the current openmrs version
218
         * @return true if the current openmrs version is in versions otherwise false
219
         * <strong>Should</strong> return false when versions is null
220
         * <strong>Should</strong> return false when versions is empty
221
         * <strong>Should</strong> return true if current openmrs version matches one element in versions
222
         * <strong>Should</strong> return false if current openmrs version does not match any element in versions
223
         */
224
        public static boolean isOpenmrsVersionInVersions(String ...versions) {
225

226
                if (versions == null || versions.length == 0) {
1✔
227
                        return false;
1✔
228
                }
229

230
                boolean result = false;
1✔
231
                for (String version : versions) {
1✔
232
                        if (matchRequiredVersions(OpenmrsConstants.OPENMRS_VERSION_SHORT, version)) {
1✔
233
                                result = true;
1✔
234
                                break;
1✔
235
                        }
236
                }
237
                return result;
1✔
238
        }
239
        
240
        /**
241
         * This method is an enhancement of {@link #compareVersion(String, String)} and adds support for
242
         * wildcard characters and upperbounds. <br>
243
         * <br>
244
         * This method calls {@link ModuleUtil#checkRequiredVersion(String, String)} internally. <br>
245
         * <br>
246
         * The require version number in the config file can be in the following format:
247
         * <ul>
248
         * <li>1.2.3</li>
249
         * <li>1.2.*</li>
250
         * <li>1.2.2 - 1.2.3</li>
251
         * <li>1.2.* - 1.3.*</li>
252
         * </ul>
253
         * <p>
254
         * Again the possible require version number formats with their interpretation:
255
         * <ul>
256
         * <li>1.2.3 means 1.2.3 and above</li>
257
         * <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>
258
         * <li>1.2.2 - 1.2.3 means 1.2.2 and 1.2.3 (inclusive)</li>
259
         * <li>1.2.* - 1.3.* means any version of the 1.2.x and 1.3.x branch</li>
260
         * </ul>
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 = compareVersion(version, lowerBound);
1✔
332
                                        
333
                                        int upperReturn = compareVersion(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 (compareVersion(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
         *
378
         * @param version openmrs version number to be compared
379
         * @param versionRange value in the config file for required openmrs version
380
         * @throws ModuleException if the <code>version</code> is not within the <code>value</code>
381
         * <strong>Should</strong> throw ModuleException if openmrs version beyond wild card range
382
         * <strong>Should</strong> throw ModuleException if required version beyond openmrs version
383
         * <strong>Should</strong> throw ModuleException if required version with wild card beyond openmrs version
384
         * <strong>Should</strong> throw ModuleException if required version with wild card on one end beyond openmrs
385
         *         version
386
         * <strong>Should</strong> throw ModuleException if single entry required version beyond openmrs version
387
         * <strong>Should</strong> throw ModuleException if SNAPSHOT not handled correctly
388
         * <strong>Should</strong> handle SNAPSHOT versions
389
         * <strong>Should</strong> handle ALPHA versions
390
         */
391
        public static void checkRequiredVersion(String version, String versionRange) throws ModuleException {
392
                if (!matchRequiredVersions(version, versionRange)) {
1✔
393
                        String ms = Context.getMessageSourceService().getMessage("Module.requireVersion.outOfBounds",
1✔
394
                            new String[] { versionRange, version }, Context.getLocale());
1✔
395
                        throw new ModuleException(ms);
1✔
396
                }
397
        }
1✔
398
        
399
        /**
400
         * Compares <code>version</code> to <code>value</code> version and value are strings like
401
         * 1.9.2.0 Returns <code>0</code> if either <code>version</code> or <code>value</code> is null.
402
         *
403
         * @param version String like 1.9.2.0
404
         * @param value String like 1.9.2.0
405
         * @return the value <code>0</code> if <code>version</code> is equal to the argument
406
         *         <code>value</code>; a value less than <code>0</code> if <code>version</code> is
407
         *         numerically less than the argument <code>value</code>; and a value greater than
408
         *         <code>0</code> if <code>version</code> is numerically greater than the argument
409
         *         <code>value</code>
410
         * <strong>Should</strong> correctly comparing two version numbers
411
         * <strong>Should</strong> treat SNAPSHOT as earliest version
412
         */
413
        public static int compareVersion(String version, String value) {
414
                try {
415
                        if (version == null || value == null) {
1✔
416
                                return 0;
×
417
                        }
418
                        
419
                        List<String> versions = new ArrayList<>();
1✔
420
                        List<String> values = new ArrayList<>();
1✔
421
                        String separator = "-";
1✔
422
                        
423
                        // strip off any qualifier e.g. "-SNAPSHOT"
424
                        int qualifierIndex = version.indexOf(separator);
1✔
425
                        if (qualifierIndex != -1) {
1✔
426
                                version = version.substring(0, qualifierIndex);
1✔
427
                        }
428
                        
429
                        qualifierIndex = value.indexOf(separator);
1✔
430
                        if (qualifierIndex != -1) {
1✔
431
                                value = value.substring(0, qualifierIndex);
1✔
432
                        }
433
                        
434
                        Collections.addAll(versions, version.split("\\."));
1✔
435
                        Collections.addAll(values, value.split("\\."));
1✔
436
                        
437
                        // match the sizes of the lists
438
                        while (versions.size() < values.size()) {
1✔
439
                                versions.add("0");
1✔
440
                        }
441
                        while (values.size() < versions.size()) {
1✔
442
                                values.add("0");
1✔
443
                        }
444
                        
445
                        for (int x = 0; x < versions.size(); x++) {
1✔
446
                                String verNum = versions.get(x).trim();
1✔
447
                                String valNum = values.get(x).trim();
1✔
448
                                Long ver = NumberUtils.toLong(verNum, 0);
1✔
449
                                Long val = NumberUtils.toLong(valNum, 0);
1✔
450
                                
451
                                int ret = ver.compareTo(val);
1✔
452
                                if (ret != 0) {
1✔
453
                                        return ret;
1✔
454
                                }
455
                        }
456
                }
457
                catch (NumberFormatException e) {
×
458
                        log.error("Error while converting a version/value to an integer: " + version + "/" + value, e);
×
459
                }
1✔
460
                
461
                // default return value if an error occurs or elements are equal
462
                return 0;
1✔
463
        }
464
        
465
        /**
466
         * Checks for qualifier version (i.e "-SNAPSHOT", "-ALPHA" etc. after maven version conventions)
467
         *
468
         * @param version String like 1.9.2-SNAPSHOT
469
         * @return true if version contains qualifier
470
         */
471
        public static boolean isVersionWithQualifier(String version) {
472
                Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.(\\d+))?(\\-([A-Za-z]+))").matcher(version);
1✔
473
                return matcher.matches();
1✔
474
        }
475
        
476
        /**
477
         * Gets the folder where modules are stored. ModuleExceptions are thrown on errors
478
         *
479
         * @return folder containing modules
480
         * <strong>Should</strong> use the runtime property as the first choice if specified
481
         * <strong>Should</strong> return the correct file if the runtime property is an absolute path
482
         */
483
        public static File getModuleRepository() {
484
                
485
                String folderName = Context.getRuntimeProperties().getProperty(ModuleConstants.REPOSITORY_FOLDER_RUNTIME_PROPERTY);
1✔
486
                if (StringUtils.isBlank(folderName)) {
1✔
487
                        AdministrationService as = Context.getAdministrationService();
1✔
488
                        folderName = as.getGlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY,
1✔
489
                            ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT);
490
                }
491
                // try to load the repository folder straight away.
492
                File folder = new File(folderName);
1✔
493
                
494
                // if the property wasn't a full path already, assume it was intended to be a folder in the
495
                // application directory
496
                if (!folder.exists()) {
1✔
497
                        folder = new File(OpenmrsUtil.getApplicationDataDirectory(), folderName);
1✔
498
                }
499
                
500
                // now create the modules folder if it doesn't exist
501
                if (!folder.exists()) {
1✔
502
                        log.warn("Module repository " + folder.getAbsolutePath() + " doesn't exist.  Creating directories now.");
1✔
503
                        folder.mkdirs();
1✔
504
                }
505
                
506
                if (!folder.isDirectory()) {
1✔
507
                        throw new ModuleException("Module repository is not a directory at: " + folder.getAbsolutePath());
×
508
                }
509
                
510
                return folder;
1✔
511
        }
512
        
513
        /**
514
         * Utility method to convert a {@link File} object to a local URL.
515
         *
516
         * @param file a file object
517
         * @return absolute URL that points to the given file
518
         * @throws MalformedURLException if file can't be represented as URL for some reason
519
         */
520
        public static URL file2url(final File file) throws MalformedURLException {
521
                if (file == null) {
1✔
522
                        return null;
1✔
523
                }
524
                try {
525
                        return file.getCanonicalFile().toURI().toURL();
1✔
526
                }
527
                catch (MalformedURLException mue) {
×
528
                        throw mue;
×
529
                }
530
                catch (IOException | NoSuchMethodError ioe) {
1✔
531
                        throw new MalformedURLException("Cannot convert: " + file.getName() + " to url");
1✔
532
                }
533
        }
534
        
535
        /**
536
         * Expand the given <code>fileToExpand</code> jar to the <code>tmpModuleFile</code> directory
537
         *
538
         * If <code>name</code> is null, the entire jar is expanded. If<code>name</code> is not null,
539
         * then only that path/file is expanded.
540
         *
541
         * @param fileToExpand file pointing at a .jar
542
         * @param tmpModuleDir directory in which to place the files
543
         * @param name filename inside of the jar to look for and expand
544
         * @param keepFullPath if true, will recreate entire directory structure in tmpModuleDir
545
         *            relating to <code>name</code>. if false will start directory structure at
546
         *            <code>name</code>
547
         * @throws UnsupportedOperationException if an entry would be extracted outside of tmpModuleDir (Zip slip attack)
548
         * <strong>Should</strong> expand entire jar if name is null
549
         * <strong>Should</strong> expand entire jar if name is empty string
550
         * <strong>Should</strong> expand directory with parent tree if name is directory and keepFullPath is true
551
         * <strong>Should</strong> expand directory without parent tree if name is directory and keepFullPath is false
552
         * <strong>Should</strong> expand file with parent tree if name is file and keepFullPath is true
553
         * <strong>Should</strong> throw exception for Zip slip attack
554
         */
555
        public static void expandJar(File fileToExpand, File tmpModuleDir, String name, boolean keepFullPath) throws IOException {
556
                JarFile jarFile = null;
1✔
557
                InputStream input = null;
1✔
558
                String docBase = tmpModuleDir.getAbsolutePath();
1✔
559
                try {
560
                        jarFile = new JarFile(fileToExpand);
1✔
561
                        Enumeration<JarEntry> jarEntries = jarFile.entries();
1✔
562
                        boolean foundName = (name == null);
1✔
563
                        
564
                        // loop over all of the elements looking for the match to 'name'
565
                        while (jarEntries.hasMoreElements()) {
1✔
566
                                JarEntry jarEntry = jarEntries.nextElement();
1✔
567
                                if (name == null || jarEntry.getName().startsWith(name)) {
1✔
568
                                        String entryName = jarEntry.getName();
1✔
569
                                        // trim out the name path from the name of the new file
570
                                        if (!keepFullPath && name != null) {
1✔
571
                                                entryName = entryName.replaceFirst(name, "");
1✔
572
                                        }
573
                                        
574
                                        // if it has a slash, it's in a directory
575
                                        int last = entryName.lastIndexOf('/');
1✔
576
                                        if (last >= 0) {
1✔
577
                                                File parent = new File(docBase, entryName.substring(0, last));
1✔
578
                                                if (!parent.toPath().normalize().startsWith(docBase)) {
1✔
579
                                                        throw new UnsupportedOperationException("Attempted to create directory '" + entryName + "' rejected as it attempts to write outside the chosen directory. This may be the result of a zip-slip style attack.");
1✔
580
                                                }
581
                                                parent.mkdirs();
1✔
582
                                                log.debug("Creating parent dirs: " + parent.getAbsolutePath());
1✔
583
                                        }
584
                                        // we don't want to "expand" directories or empty names
585
                                        if (entryName.endsWith("/") || "".equals(entryName)) {
1✔
586
                                                continue;
×
587
                                        }
588
                                        input = jarFile.getInputStream(jarEntry);
1✔
589
                                        expand(input, docBase, entryName);
1✔
590
                                        input.close();
1✔
591
                                        input = null;
1✔
592
                                        foundName = true;
1✔
593
                                }
594
                        }
1✔
595
                        if (!foundName) {
1✔
596
                                log.debug("Unable to find: " + name + " in file " + fileToExpand.getAbsolutePath());
1✔
597
                        }
598
                        
599
                }
600
                catch (IOException e) {
×
601
                        log.warn("Unable to delete tmpModuleFile on error", e);
×
602
                        throw e;
×
603
                }
604
                finally {
605
                        try {
606
                                input.close();
×
607
                        }
608
                        catch (Exception e) { /* pass */}
1✔
609
                        try {
610
                                jarFile.close();
1✔
611
                        }
612
                        catch (Exception e) { /* pass */}
1✔
613
                }
614
        }
1✔
615
        
616
        /**
617
         * Expand the given file in the given stream to a location (fileDir/name) The <code>input</code>
618
         * InputStream is not closed in this method
619
         *
620
         * @param input stream to read from
621
         * @param fileDir directory to copy to
622
         * @param name file/directory within the <code>fileDir</code> to which we expand
623
         *            <code>input</code>
624
         * @return File the file created by the expansion.
625
         * @throws IOException if an error occurred while copying
626
         */
627
        private static File expand(InputStream input, String fileDir, String name) throws IOException {
628
                log.debug("expanding: {}", name);
1✔
629
                
630
                File file = new File(fileDir, name);
1✔
631
                FileOutputStream outStream = null;
1✔
632
                try {
633
                        outStream = new FileOutputStream(file);
1✔
634
                        OpenmrsUtil.copyFile(input, outStream);
1✔
635
                }
636
                finally {
637
                        try {
638
                                outStream.close();
1✔
639
                        }
640
                        catch (Exception e) { /* pass */}
1✔
641
                }
642
                
643
                return file;
1✔
644
        }
645
        
646
        /**
647
         * Downloads the contents of a URL and copies them to a string (Borrowed from oreilly)
648
         *
649
         * @param url
650
         * @return InputStream of contents
651
         * <strong>Should</strong> return a valid input stream for old module urls
652
         */
653
        public static InputStream getURLStream(URL url) {
654
                InputStream in = null;
1✔
655
                try {
656
                        URLConnection uc = url.openConnection();
1✔
657
                        uc.setDefaultUseCaches(false);
1✔
658
                        uc.setUseCaches(false);
1✔
659
                        uc.setRequestProperty("Cache-Control", "max-age=0,no-cache");
1✔
660
                        uc.setRequestProperty("Pragma", "no-cache");
1✔
661
                        
662
                        log.debug("Logging an attempt to connect to: " + url);
1✔
663
                        
664
                        in = openConnectionCheckRedirects(uc);
×
665
                }
666
                catch (IOException io) {
1✔
667
                        log.warn("io while reading: " + url, io);
1✔
668
                }
×
669
                
670
                return in;
1✔
671
        }
672
        
673
        /**
674
         * Convenience method to follow http to https redirects. Will follow a total of 5 redirects,
675
         * then fail out due to foolishness on the url's part.
676
         *
677
         * @param c the {@link URLConnection} to open
678
         * @return an {@link InputStream} that is not necessarily at the same url, possibly at a 403
679
         *         redirect.
680
         * @throws IOException
681
         * @see #getURLStream(URL)
682
         */
683
        protected static InputStream openConnectionCheckRedirects(URLConnection c) throws IOException {
684
                boolean redir;
685
                int redirects = 0;
1✔
686
                InputStream in;
687
                do {
688
                        if (c instanceof HttpURLConnection) {
1✔
689
                                ((HttpURLConnection) c).setInstanceFollowRedirects(false);
1✔
690
                        }
691
                        // We want to open the input stream before getting headers
692
                        // because getHeaderField() et al swallow IOExceptions.
693
                        in = c.getInputStream();
×
694
                        redir = false;
×
695
                        if (c instanceof HttpURLConnection) {
×
696
                                HttpURLConnection http = (HttpURLConnection) c;
×
697
                                int stat = http.getResponseCode();
×
698
                                if (stat == 300 || stat == 301 || stat == 302 || stat == 303 || stat == 305 || stat == 307) {
×
699
                                        URL base = http.getURL();
×
700
                                        String loc = http.getHeaderField("Location");
×
701
                                        URL target = null;
×
702
                                        if (loc != null) {
×
703
                                                target = new URL(base, loc);
×
704
                                        }
705
                                        http.disconnect();
×
706
                                        // Redirection should be allowed only for HTTP and HTTPS
707
                                        // and should be limited to 5 redirects at most.
708
                                        if (target == null || !("http".equals(target.getProtocol()) || "https".equals(target.getProtocol()))
×
709
                                                || redirects >= 5) {
710
                                                throw new SecurityException("illegal URL redirect");
×
711
                                        }
712
                                        redir = true;
×
713
                                        c = target.openConnection();
×
714
                                        redirects++;
×
715
                                }
716
                        }
717
                } while (redir);
×
718
                return in;
×
719
        }
720
        
721
        /**
722
         * Downloads the contents of a URL and copies them to a string (Borrowed from oreilly)
723
         *
724
         * @param url
725
         * @return String contents of the URL
726
         * <strong>Should</strong> return an update rdf page for old https dev urls
727
         * <strong>Should</strong> return an update rdf page for old https module urls
728
         * <strong>Should</strong> return an update rdf page for module urls
729
         */
730
        public static String getURL(URL url) {
731
                InputStream in = null;
×
732
                ByteArrayOutputStream out = null;
×
733
                String output = "";
×
734
                try {
735
                        in = getURLStream(url);
×
736
                        if (in == null) {
×
737
                                // skip this module if updateURL is not defined
738
                                return "";
×
739
                        }
740
                        
741
                        out = new ByteArrayOutputStream();
×
742
                        OpenmrsUtil.copyFile(in, out);
×
743
                        output = out.toString(StandardCharsets.UTF_8.name());
×
744
                }
745
                catch (IOException io) {
×
746
                        log.warn("io while reading: " + url, io);
×
747
                }
748
                finally {
749
                        try {
750
                                in.close();
×
751
                        }
752
                        catch (Exception e) { /* pass */}
×
753
                        try {
754
                                out.close();
×
755
                        }
756
                        catch (Exception e) { /* pass */}
×
757
                }
758
                
759
                return output;
×
760
        }
761
        
762
        /**
763
         * Iterates over the modules and checks each update.rdf file for an update
764
         *
765
         * @return True if an update was found for one of the modules, false if none were found
766
         * @throws ModuleException
767
         */
768
        public static Boolean checkForModuleUpdates() throws ModuleException {
769
                
770
                Boolean updateFound = false;
×
771
                
772
                for (Module mod : ModuleFactory.getLoadedModules()) {
×
773
                        String updateURL = mod.getUpdateURL();
×
774
                        if (StringUtils.isNotEmpty(updateURL)) {
×
775
                                try {
776
                                        // get the contents pointed to by the url
777
                                        URL url = new URL(updateURL);
×
778
                                        if (!url.toString().endsWith(ModuleConstants.UPDATE_FILE_NAME)) {
×
779
                                                log.warn("Illegal url: " + url);
×
780
                                                continue;
×
781
                                        }
782
                                        String content = getURL(url);
×
783
                                        
784
                                        // skip empty or invalid updates
785
                                        if ("".equals(content)) {
×
786
                                                continue;
×
787
                                        }
788
                                        
789
                                        // process and parse the contents
790
                                        UpdateFileParser parser = new UpdateFileParser(content);
×
791
                                        parser.parse();
×
792
                                        
793
                                        log.debug("Update for mod: " + mod.getModuleId() + " compareVersion result: "
×
794
                                                + compareVersion(mod.getVersion(), parser.getCurrentVersion()));
×
795
                                        
796
                                        // check the update.rdf version against the installed version
797
                                        if (compareVersion(mod.getVersion(), parser.getCurrentVersion()) < 0) {
×
798
                                                if (mod.getModuleId().equals(parser.getModuleId())) {
×
799
                                                        mod.setDownloadURL(parser.getDownloadURL());
×
800
                                                        mod.setUpdateVersion(parser.getCurrentVersion());
×
801
                                                        updateFound = true;
×
802
                                                } else {
803
                                                        log.warn("Module id does not match in update.rdf:" + parser.getModuleId());
×
804
                                                }
805
                                        } else {
806
                                                mod.setDownloadURL(null);
×
807
                                                mod.setUpdateVersion(null);
×
808
                                        }
809
                                }
810
                                catch (ModuleException e) {
×
811
                                        log.warn("Unable to get updates from update.xml", e);
×
812
                                }
813
                                catch (MalformedURLException e) {
×
814
                                        log.warn("Unable to form a URL object out of: " + updateURL, e);
×
815
                                }
×
816
                        }
817
                }
×
818
                
819
                return updateFound;
×
820
        }
821
        
822
        /**
823
         * @return true/false whether the 'allow upload' or 'allow web admin' property has been turned
824
         *         on
825
         */
826
        public static Boolean allowAdmin() {
827
                
828
                Properties properties = Context.getRuntimeProperties();
×
829
                String prop = properties.getProperty(ModuleConstants.RUNTIMEPROPERTY_ALLOW_UPLOAD, null);
×
830
                if (prop == null) {
×
831
                        prop = properties.getProperty(ModuleConstants.RUNTIMEPROPERTY_ALLOW_ADMIN, "false");
×
832
                }
833
                
834
                return "true".equals(prop);
×
835
        }
836
        
837
        /**
838
         * @see ModuleUtil#refreshApplicationContext(AbstractRefreshableApplicationContext, boolean, Module)
839
         */
840
        public static AbstractRefreshableApplicationContext refreshApplicationContext(AbstractRefreshableApplicationContext ctx) {
841
                return refreshApplicationContext(ctx, false, null);
×
842
        }
843
        
844
        /**
845
         * Refreshes the given application context "properly" in OpenMRS. Will first shut down the
846
         * Context and destroy the classloader, then will refresh and set everything back up again.
847
         *
848
         * @param ctx Spring application context that needs refreshing.
849
         * @param isOpenmrsStartup if this refresh is being done at application startup.
850
         * @param startedModule the module that was just started and waiting on the context refresh.
851
         * @return AbstractRefreshableApplicationContext The newly refreshed application context.
852
         */
853
        public static AbstractRefreshableApplicationContext refreshApplicationContext(AbstractRefreshableApplicationContext ctx,
854
                boolean isOpenmrsStartup, Module startedModule) {
855
                //notify all started modules that we are about to refresh the context
856
                Set<Module> startedModules = new LinkedHashSet<>(ModuleFactory.getStartedModulesInOrder());
×
857
                for (Module module : startedModules) {
×
858
                        try {
859
                                if (module.getModuleActivator() != null) {
×
860
                                        Thread.currentThread().setContextClassLoader(ModuleFactory.getModuleClassLoader(module));
×
861
                                        module.getModuleActivator().willRefreshContext();
×
862
                                }
863
                        }
864
                        catch (Exception e) {
×
865
                                log.warn("Unable to call willRefreshContext() method in the module's activator", e);
×
866
                        }
×
867
                }
×
868
                
869
                OpenmrsClassLoader.saveState();
×
870
                SchedulerUtil.shutdown();
×
871
                ServiceContext.destroyInstance();
×
872
                
873
                try {
874
                        ctx.stop();
×
875
                        ctx.close();
×
876
                }
877
                catch (Exception e) {
×
878
                        log.warn("Exception while stopping and closing context: ", e);
×
879
                        // Spring seems to be trying to refresh the context instead of /just/ stopping
880
                        // pass
881
                }
×
882
                OpenmrsClassLoader.destroyInstance();
×
883
                ctx.setClassLoader(OpenmrsClassLoader.getInstance());
×
884
                Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
×
885
                
886
                ServiceContext.getInstance().startRefreshingContext();
×
887
                try {
888
                        ctx.refresh();
×
889
                }
890
                finally {
891
                        ServiceContext.getInstance().doneRefreshingContext();
×
892
                }
893
                
894
                ctx.setClassLoader(OpenmrsClassLoader.getInstance());
×
895
                Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
×
896
                
897
                OpenmrsClassLoader.restoreState();
×
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) {
×
921
                                                module.getModuleActivator().contextRefreshed();
×
922
                                                try {
923
                                                        //if it is system start up, call the started method for all started modules
924
                                                        if (isOpenmrsStartup) {
×
925
                                                                module.getModuleActivator().started();
×
926
                                                        }
927
                                                        //if refreshing the context after a user started or uploaded a new module
928
                                                        else if (!isOpenmrsStartup && module.equals(startedModule)) {
×
929
                                                                module.getModuleActivator().started();
×
930
                                                        }
931
                                                }
932
                                                catch (Exception e) {
×
933
                                                        log.warn("Unable to invoke started() method on the module's activator", e);
×
934
                                                        ModuleFactory.stopModule(module, true, true);
×
935
                                                }
×
936
                                        }
937
                                        
938
                                }
939
                                catch (Exception e) {
×
940
                                        log.warn("Unable to invoke method on the module's activator ", e);
×
941
                                }
×
942
                        }
×
943
                }
944
                finally {
945
                        Context.closeSessionWithCurrentUser();
×
946
                }
947
                
948
                return ctx;
×
949
        }
950
        
951
        /**
952
         * Looks at the &lt;moduleid&gt;.mandatory properties and at the currently started modules to make
953
         * sure that all mandatory modules have been started successfully.
954
         *
955
         * @throws ModuleException if a mandatory module isn't started
956
         * <strong>Should</strong> throw ModuleException if a mandatory module is not started
957
         */
958
        protected static void checkMandatoryModulesStarted() throws ModuleException {
959
                
960
                List<String> mandatoryModuleIds = getMandatoryModules();
1✔
961
                Set<String> startedModuleIds = ModuleFactory.getStartedModulesMap().keySet();
1✔
962
                
963
                mandatoryModuleIds.removeAll(startedModuleIds);
1✔
964
                
965
                // any module ids left in the list are not started
966
                if (!mandatoryModuleIds.isEmpty()) {
1✔
967
                        throw new MandatoryModuleException(mandatoryModuleIds);
1✔
968
                }
969
        }
1✔
970
        
971
        /**
972
         * Looks at the list of modules in {@link ModuleConstants#CORE_MODULES} to make sure that all
973
         * modules that are core to OpenMRS are started and have at least a minimum version that OpenMRS
974
         * needs.
975
         *
976
         * @throws ModuleException if a module that is core to OpenMRS is not started
977
         * <strong>Should</strong> throw ModuleException if a core module is not started
978
         */
979
        protected static void checkOpenmrsCoreModulesStarted() throws OpenmrsCoreModuleException {
980
                
981
                // if there is a property telling us to ignore required modules, drop out early
982
                if (ignoreCoreModules()) {
1✔
983
                        return;
1✔
984
                }
985
                
986
                // make a copy of the constant so we can modify the list
987
                Map<String, String> coreModules = new HashMap<>(ModuleConstants.CORE_MODULES);
×
988
                
989
                Collection<Module> startedModules = ModuleFactory.getStartedModulesMap().values();
×
990
                
991
                // loop through the current modules and test them
992
                for (Module mod : startedModules) {
×
993
                        String moduleId = mod.getModuleId();
×
994
                        if (coreModules.containsKey(moduleId)) {
×
995
                                String coreReqVersion = coreModules.get(moduleId);
×
996
                                if (compareVersion(mod.getVersion(), coreReqVersion) >= 0) {
×
997
                                        coreModules.remove(moduleId);
×
998
                                } else {
999
                                        log.debug("Module: " + moduleId + " is a core module and is started, but its version: "
×
1000
                                                + mod.getVersion() + " is not within the required version: " + coreReqVersion);
×
1001
                                }
1002
                        }
1003
                }
×
1004
                
1005
                // any module ids left in the list are not started
1006
                if (coreModules.size() > 0) {
×
1007
                        throw new OpenmrsCoreModuleException(coreModules);
×
1008
                }
1009
        }
×
1010
        
1011
        /**
1012
         * Uses the runtime properties to determine if the core modules should be enforced or not.
1013
         *
1014
         * @return true if the core modules list can be ignored.
1015
         */
1016
        public static boolean ignoreCoreModules() {
1017
                String ignoreCoreModules = Context.getRuntimeProperties().getProperty(ModuleConstants.IGNORE_CORE_MODULES_PROPERTY,
1✔
1018
                    "false");
1019
                return Boolean.parseBoolean(ignoreCoreModules);
1✔
1020
        }
1021
        
1022
        /**
1023
         * Returns all modules that are marked as mandatory. Currently this means there is a
1024
         * &lt;moduleid&gt;.mandatory=true global property.
1025
         *
1026
         * @return list of modules ids for mandatory modules
1027
         * <strong>Should</strong> return mandatory module ids
1028
         */
1029
        public static List<String> getMandatoryModules() {
1030
                
1031
                List<String> mandatoryModuleIds = new ArrayList<>();
1✔
1032
                
1033
                try {
1034
                        List<GlobalProperty> props = Context.getAdministrationService().getGlobalPropertiesBySuffix(".mandatory");
1✔
1035
                        
1036
                        for (GlobalProperty prop : props) {
1✔
1037
                                if ("true".equalsIgnoreCase(prop.getPropertyValue())) {
1✔
1038
                                        mandatoryModuleIds.add(prop.getProperty().replace(".mandatory", ""));
1✔
1039
                                }
1040
                        }
1✔
1041
                }
1042
                catch (Exception e) {
×
1043
                        log.warn("Unable to get the mandatory module list", e);
×
1044
                }
1✔
1045
                
1046
                return mandatoryModuleIds;
1✔
1047
        }
1048
        
1049
        /**
1050
         * <pre>
1051
         * Gets the module that should handle a path. The path you pass in should be a module id (in
1052
         * path format, i.e. /ui/springmvc, not ui.springmvc) followed by a resource. Something like
1053
         * the following:
1054
         *   /ui/springmvc/css/ui.css
1055
         *
1056
         * The first running module out of the following would be returned:
1057
         *   ui.springmvc.css
1058
         *   ui.springmvc
1059
         *   ui
1060
         * </pre>
1061
         *
1062
         * @param path
1063
         * @return the running module that matches the most of the given path
1064
         * <strong>Should</strong> handle ui springmvc css ui dot css when ui dot springmvc module is running
1065
         * <strong>Should</strong> handle ui springmvc css ui dot css when ui module is running
1066
         * <strong>Should</strong> return null for ui springmvc css ui dot css when no relevant module is running
1067
         */
1068
        public static Module getModuleForPath(String path) {
1069
                int ind = path.lastIndexOf('/');
1✔
1070
                if (ind <= 0) {
1✔
1071
                        throw new IllegalArgumentException(
×
1072
                                "Input must be /moduleId/resource. Input needs a / after the first character: " + path);
1073
                }
1074
                String moduleId = path.startsWith("/") ? path.substring(1, ind) : path.substring(0, ind);
1✔
1075
                moduleId = moduleId.replace('/', '.');
1✔
1076
                // iterate over progressively shorter module ids
1077
                while (true) {
1078
                        Module mod = ModuleFactory.getStartedModuleById(moduleId);
1✔
1079
                        if (mod != null) {
1✔
1080
                                return mod;
1✔
1081
                        }
1082
                        // try the next shorter module id
1083
                        ind = moduleId.lastIndexOf('.');
1✔
1084
                        if (ind < 0) {
1✔
1085
                                break;
1✔
1086
                        }
1087
                        moduleId = moduleId.substring(0, ind);
1✔
1088
                }
1✔
1089
                return null;
1✔
1090
        }
1091
        
1092
        /**
1093
         * Takes a global path and returns the local path within the specified module. For example
1094
         * calling this method with the path "/ui/springmvc/css/ui.css" and the ui.springmvc module, you
1095
         * would get "/css/ui.css".
1096
         *
1097
         * @param module
1098
         * @param path
1099
         * @return local path
1100
         * <strong>Should</strong> handle ui springmvc css ui dot css example
1101
         */
1102
        public static String getPathForResource(Module module, String path) {
1103
                if (path.startsWith("/")) {
1✔
1104
                        path = path.substring(1);
1✔
1105
                }
1106
                return path.substring(module.getModuleIdAsPath().length());
1✔
1107
        }
1108
        
1109
        /**
1110
         * This loops over all FILES in this jar to get the package names. If there is an empty
1111
         * directory in this jar it is not returned as a providedPackage.
1112
         *
1113
         * @param file jar file to look into
1114
         * @return list of strings of package names in this jar
1115
         */
1116
        public static Collection<String> getPackagesFromFile(File file) {
1117
                
1118
                // End early if we're given a non jar file
1119
                if (!file.getName().endsWith(".jar")) {
1✔
1120
                        return Collections.emptySet();
1✔
1121
                }
1122
                
1123
                Set<String> packagesProvided = new HashSet<>();
1✔
1124
                
1125
                JarFile jar = null;
1✔
1126
                try {
1127
                        jar = new JarFile(file);
1✔
1128
                        
1129
                        Enumeration<JarEntry> jarEntries = jar.entries();
1✔
1130
                        while (jarEntries.hasMoreElements()) {
1✔
1131
                                JarEntry jarEntry = jarEntries.nextElement();
1✔
1132
                                if (jarEntry.isDirectory()) {
1✔
1133
                                        // skip over directory entries, we only care about files
1134
                                        continue;
1✔
1135
                                }
1136
                                String name = jarEntry.getName();
1✔
1137
                                
1138
                                // Skip over some folders in the jar/omod
1139
                                if (name.startsWith("lib") || name.startsWith("META-INF") || name.startsWith("web/module")) {
1✔
1140
                                        continue;
1✔
1141
                                }
1142
                                
1143
                                Integer indexOfLastSlash = name.lastIndexOf("/");
1✔
1144
                                if (indexOfLastSlash <= 0) {
1✔
1145
                                        continue;
1✔
1146
                                }
1147
                                String packageName = name.substring(0, indexOfLastSlash);
1✔
1148
                                
1149
                                packageName = packageName.replaceAll("/", ".");
1✔
1150
                                
1151
                                if (packagesProvided.add(packageName) && log.isTraceEnabled()) {
1✔
1152
                                        log.trace("Adding module's jarentry with package: " + packageName);
×
1153
                                }
1154
                        }
1✔
1155
                        
1156
                        jar.close();
1✔
1157
                }
1158
                catch (IOException e) {
×
1159
                        log.error("Error while reading file: " + file.getAbsolutePath(), e);
×
1160
                }
1161
                finally {
1162
                        if (jar != null) {
1✔
1163
                                try {
1164
                                        jar.close();
1✔
1165
                                }
1166
                                catch (IOException e) {
×
1167
                                        // Ignore quietly
1168
                                }
1✔
1169
                        }
1170
                }
1171
                
1172
                return packagesProvided;
1✔
1173
        }
1174
        
1175
        /**
1176
         * Get a resource as from the module's api jar. Api jar should be in the omod's lib folder.
1177
         * 
1178
         * @param jarFile omod file loaded as jar
1179
         * @param moduleId id of the module
1180
         * @param version version of the module
1181
         * @param resource name of a resource from the api jar
1182
         * @return resource as an input stream or <code>null</code> if resource cannot be loaded
1183
         * <strong>Should</strong> load file from api as input stream
1184
         * <strong>Should</strong> return null if api is not found
1185
         * <strong>Should</strong> return null if file is not found in api
1186
         */
1187
        public static InputStream getResourceFromApi(JarFile jarFile, String moduleId, String version, String resource) {
1188
                String apiLocation = "lib/" + moduleId + "-api-" + version + ".jar";
1✔
1189
                return getResourceFromInnerJar(jarFile, apiLocation, resource);
1✔
1190
        }
1191
        
1192
        /**
1193
         * Load resource from a jar inside a jar.
1194
         * 
1195
         * @param outerJarFile jar file that contains a jar file
1196
         * @param innerJarFileLocation inner jar file location relative to the outer jar
1197
         * @param resource path to a resource relative to the inner jar
1198
         * @return resource from the inner jar as an input stream or <code>null</code> if resource cannot be loaded
1199
         */
1200
        private static InputStream getResourceFromInnerJar(JarFile outerJarFile, String innerJarFileLocation, String resource) {
1201
                File tempFile = null;
1✔
1202
                FileOutputStream tempOut = null;
1✔
1203
                JarFile innerJarFile = null;
1✔
1204
                InputStream innerInputStream = null;
1✔
1205
                try {
1206
                        tempFile = File.createTempFile("tempFile", "jar");
1✔
1207
                        tempOut = new FileOutputStream(tempFile);
1✔
1208
                        ZipEntry innerJarFileEntry = outerJarFile.getEntry(innerJarFileLocation);
1✔
1209
                        if (innerJarFileEntry != null) {
1✔
1210
                                IOUtils.copy(outerJarFile.getInputStream(innerJarFileEntry), tempOut);
1✔
1211
                                innerJarFile = new JarFile(tempFile);
1✔
1212
                                ZipEntry targetEntry = innerJarFile.getEntry(resource);
1✔
1213
                                if (targetEntry != null) {
1✔
1214
                                        // clone InputStream to make it work after the innerJarFile is closed
1215
                                        innerInputStream = innerJarFile.getInputStream(targetEntry);
1✔
1216
                                        byte[] byteArray = IOUtils.toByteArray(innerInputStream);
1✔
1217
                                        return new ByteArrayInputStream(byteArray);
1✔
1218
                                }
1219
                        }
1220
                }
1221
                catch (IOException e) {
×
1222
                        log.error("Unable to get '" + resource + "' from '" + innerJarFileLocation + "' of '" + outerJarFile.getName()
×
1223
                                + "'", e);
1224
                }
1225
                finally {
1226
                        IOUtils.closeQuietly(tempOut);
1✔
1227
                        IOUtils.closeQuietly(innerInputStream);
1✔
1228

1229
                        // close inner jar file before attempting to delete temporary file
1230
                        try {
1231
                                if (innerJarFile != null) {
1✔
1232
                                        innerJarFile.close();
1✔
1233
                                }
1234
                        }
1235
                        catch (IOException e) {
×
1236
                                log.warn("Unable to close inner jarfile: " + innerJarFile, e);
×
1237
                        }
1✔
1238

1239
                        // delete temporary file
1240
                        if (tempFile != null && !tempFile.delete()) {
1✔
1241
                                log.warn("Could not delete temporary jarfile: " + tempFile);
×
1242
                        }
1243
                }
1244
                return null;
1✔
1245
        }
1246
        
1247
        /**
1248
         * Gets the root folder of a module's sources during development
1249
         * 
1250
         * @param moduleId the module id
1251
         * @return the module's development folder is specified, else null
1252
         */
1253
        public static File getDevelopmentDirectory(String moduleId) {
1254
                String directory = System.getProperty(moduleId + ".development.directory");
1✔
1255
                if (StringUtils.isNotBlank(directory)) {
1✔
1256
                        return new File(directory);
×
1257
                }
1258
                
1259
                return null;
1✔
1260
        }
1261
}
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