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

openmrs / openmrs-core / 21885081110

10 Feb 2026 10:36PM UTC coverage: 65.419% (+0.1%) from 65.317%
21885081110

push

github

dkayiwa
TRUNK-6542 Editing observations should copy reference ranges

11 of 11 new or added lines in 1 file covered. (100.0%)

110 existing lines in 6 files now uncovered.

23798 of 36378 relevant lines covered (65.42%)

0.65 hits per line

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

59.82
/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
         * @throws UnsupportedOperationException if an entry would be extracted outside of tmpModuleDir (Zip slip attack)
568
         * <strong>Should</strong> expand entire jar if name is null
569
         * <strong>Should</strong> expand entire jar if name is empty string
570
         * <strong>Should</strong> expand directory with parent tree if name is directory and keepFullPath is true
571
         * <strong>Should</strong> expand directory without parent tree if name is directory and keepFullPath is false
572
         * <strong>Should</strong> expand file with parent tree if name is file and keepFullPath is true
573
         * <strong>Should</strong> throw exception for Zip slip attack
574
         */
575
        public static void expandJar(File fileToExpand, File tmpModuleDir, String name, boolean keepFullPath) throws IOException {
576
                String docBase = tmpModuleDir.getAbsolutePath();
1✔
577
                try (JarFile jarFile = new JarFile(fileToExpand)) {
1✔
578
                        Enumeration<JarEntry> jarEntries = jarFile.entries();
1✔
579
                        boolean foundName = (name == null);
1✔
580
                        
581
                        // loop over all of the elements looking for the match to 'name'
582
                        while (jarEntries.hasMoreElements()) {
1✔
583
                                JarEntry jarEntry = jarEntries.nextElement();
1✔
584
                                if (name == null || jarEntry.getName().startsWith(name)) {
1✔
585
                                        String entryName = jarEntry.getName();
1✔
586
                                        // trim out the name path from the name of the new file
587
                                        if (!keepFullPath && name != null) {
1✔
588
                                                entryName = entryName.replaceFirst(name, "");
1✔
589
                                        }
590
                                        
591
                                        // if it has a slash, it's in a directory
592
                                        int last = entryName.lastIndexOf('/');
1✔
593
                                        if (last >= 0) {
1✔
594
                                                File parent = new File(docBase, entryName.substring(0, last));
1✔
595
                                                if (!parent.toPath().normalize().startsWith(docBase)) {
1✔
596
                                                        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✔
597
                                                }
598
                                                parent.mkdirs();
1✔
599
                                                log.debug("Creating parent dirs: " + parent.getAbsolutePath());
1✔
600
                                        }
601
                                        // we don't want to "expand" directories or empty names
602
                                        if (entryName.endsWith("/") || "".equals(entryName)) {
1✔
UNCOV
603
                                                continue;
×
604
                                        }
605
                                        try(InputStream input = jarFile.getInputStream(jarEntry)) {
1✔
606
                                                expand(input, docBase, entryName);
1✔
607
                                        }
608
                                        foundName = true;
1✔
609
                                }
610
                        }
1✔
611
                        if (!foundName) {
1✔
612
                                log.debug("Unable to find: " + name + " in file " + fileToExpand.getAbsolutePath());
1✔
613
                        }
614
                        
615
                }
UNCOV
616
                catch (IOException e) {
×
UNCOV
617
                        log.warn("Unable to delete tmpModuleFile on error", e);
×
UNCOV
618
                        throw e;
×
619
                }
1✔
620
        }
1✔
621
        
622
        /**
623
         * Expand the given file in the given stream to a location (fileDir/name) The <code>input</code>
624
         * InputStream is not closed in this method
625
         *
626
         * @param input stream to read from
627
         * @param fileDir directory to copy to
628
         * @param name file/directory within the <code>fileDir</code> to which we expand
629
         *            <code>input</code>
630
         * @return File the file created by the expansion.
631
         * @throws IOException if an error occurred while copying
632
         */
633
        private static void expand(InputStream input, String fileDir, String name) throws IOException {
634
                log.debug("expanding: {}", name);
1✔
635

636
                File file = new File(fileDir, name);
1✔
637

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

1187
                        // close inner jar file before attempting to delete temporary file
1188
                        try {
1189
                                if (innerJarFile != null) {
1✔
1190
                                        innerJarFile.close();
1✔
1191
                                }
1192
                        }
UNCOV
1193
                        catch (IOException e) {
×
1194
                                log.warn("Unable to close inner jarfile: " + innerJarFile, e);
×
1195
                        }
1✔
1196

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