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

openmrs / openmrs-core / 13458255713

21 Feb 2025 01:54PM UTC coverage: 64.844% (+0.009%) from 64.835%
13458255713

push

github

web-flow
TRUNK-5208 ModuleUtil compareVersions should sort a SNAPSHOT version as "less than" (#4929)

* TRUNK-5208 compareVersion orders SNAPSHOT version before regular one

That means a version string like "1.2.3-SNAPSHOT" is ordered before
version string "1.2.3".

Also update javadoc and give more descriptive names to variables.

* TRUNK-5208 add test case that shows matchRequiredVersions behaviour

* TRUNK-5208 refactor: remove redundant "snapshot" from names

32 of 33 new or added lines in 1 file covered. (96.97%)

1 existing line in 1 file now uncovered.

23176 of 35741 relevant lines covered (64.84%)

0.65 hits per line

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

59.19
/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 {
71
                
72
                String moduleListString = props.getProperty(ModuleConstants.RUNTIMEPROPERTY_MODULE_LIST_TO_LOAD);
1✔
73
                
74
                if (moduleListString == null || moduleListString.isEmpty()) {
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.clear();
1✔
168
                ModuleFactory.loadedModules.invalidateAll();
1✔
169
                ModuleFactory.moduleClassLoaders.invalidateAll();
1✔
170
                ModuleFactory.startedModules.invalidateAll();
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
                try (FileOutputStream outputStream = new FileOutputStream(file)) {
×
190
                        OpenmrsUtil.copyFile(inputStream, outputStream);
×
191
                }
192
                catch (IOException e) {
×
193
                        throw new ModuleException("Can't create module file for " + filename, e);
×
194
                }
195
                finally {
196
                        try {
197
                                inputStream.close();
×
198
                        }
199
                        catch (Exception e) { /* pass */}
×
200
                }
201
                
202
                return file;
×
203
        }
204

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

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

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

420
        private static int compareVersion(String versionA, String versionB, boolean ignoreQualifier) {
421
                try {
422
                        if (versionA == null || versionB == null) {
1✔
423
                                return 0;
1✔
424
                        }
425

426
                        List<String> versionANumbers = new ArrayList<>();
1✔
427
                        List<String> versionBNumbers = new ArrayList<>();
1✔
428
                        String qualifierSeparator = "-";
1✔
429

430
                        // strip off any qualifier e.g. "-SNAPSHOT"
431
                        int qualifierIndexA = versionA.indexOf(qualifierSeparator);
1✔
432
                        if (qualifierIndexA != -1) {
1✔
433
                                versionA = versionA.substring(0, qualifierIndexA);
1✔
434
                        }
435

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

442
                        Collections.addAll(versionANumbers, versionA.split("\\."));
1✔
443
                        Collections.addAll(versionBNumbers, versionB.split("\\."));
1✔
444

445
                        // match the sizes of the lists
446
                        while (versionANumbers.size() < versionBNumbers.size()) {
1✔
447
                                versionANumbers.add("0");
1✔
448
                        }
449
                        while (versionBNumbers.size() < versionANumbers.size()) {
1✔
450
                                versionBNumbers.add("0");
1✔
451
                        }
452

453
                        for (int x = 0; x < versionANumbers.size(); x++) {
1✔
454
                                String verAPartString = versionANumbers.get(x).trim();
1✔
455
                                String verBPartString = versionBNumbers.get(x).trim();
1✔
456
                                Long verAPart = NumberUtils.toLong(verAPartString, 0);
1✔
457
                                Long verBPart = NumberUtils.toLong(verBPartString, 0);
1✔
458

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

625
                File file = new File(fileDir, name);
1✔
626

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

1219
                        // close inner jar file before attempting to delete temporary file
1220
                        try {
1221
                                if (innerJarFile != null) {
1✔
1222
                                        innerJarFile.close();
1✔
1223
                                }
1224
                        }
1225
                        catch (IOException e) {
×
1226
                                log.warn("Unable to close inner jarfile: " + innerJarFile, e);
×
1227
                        }
1✔
1228

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