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

openmrs / openmrs-core / 21724467624

05 Feb 2026 06:56PM UTC coverage: 63.83% (+0.09%) from 63.742%
21724467624

push

github

ibacher
Fix some serious errors in the ThreadSafeCircularFifoQueue (#5746)

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

93 existing lines in 4 files now uncovered.

22181 of 34750 relevant lines covered (63.83%)

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

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

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