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

openmrs / openmrs-core / 8603130860

08 Apr 2024 03:57PM UTC coverage: 64.68% (-0.01%) from 64.691%
8603130860

push

github

web-flow
TRUNK-6226: Fix potential zip-slips (#4613)

1 of 5 new or added lines in 2 files covered. (20.0%)

5 existing lines in 3 files now uncovered.

22761 of 35190 relevant lines covered (64.68%)

0.65 hits per line

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

58.31
/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.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.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 = compareVersion(version, lowerBound);
1✔
326
                                        
327
                                        int upperReturn = compareVersion(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 (compareVersion(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
         * Compares <code>version</code> to <code>value</code> version and value are strings like
396
         * 1.9.2.0 Returns <code>0</code> if either <code>version</code> or <code>value</code> is null.
397
         *
398
         * @param version String like 1.9.2.0
399
         * @param value String like 1.9.2.0
400
         * @return the value <code>0</code> if <code>version</code> is equal to the argument
401
         *         <code>value</code>; a value less than <code>0</code> if <code>version</code> is
402
         *         numerically less than the argument <code>value</code>; and a value greater than
403
         *         <code>0</code> if <code>version</code> is numerically greater than the argument
404
         *         <code>value</code>
405
         * <strong>Should</strong> correctly comparing two version numbers
406
         * <strong>Should</strong> treat SNAPSHOT as earliest version
407
         */
408
        public static int compareVersion(String version, String value) {
409
                try {
410
                        if (version == null || value == null) {
1✔
411
                                return 0;
×
412
                        }
413
                        
414
                        List<String> versions = new ArrayList<>();
1✔
415
                        List<String> values = new ArrayList<>();
1✔
416
                        String separator = "-";
1✔
417
                        
418
                        // strip off any qualifier e.g. "-SNAPSHOT"
419
                        int qualifierIndex = version.indexOf(separator);
1✔
420
                        if (qualifierIndex != -1) {
1✔
421
                                version = version.substring(0, qualifierIndex);
1✔
422
                        }
423
                        
424
                        qualifierIndex = value.indexOf(separator);
1✔
425
                        if (qualifierIndex != -1) {
1✔
426
                                value = value.substring(0, qualifierIndex);
1✔
427
                        }
428
                        
429
                        Collections.addAll(versions, version.split("\\."));
1✔
430
                        Collections.addAll(values, value.split("\\."));
1✔
431
                        
432
                        // match the sizes of the lists
433
                        while (versions.size() < values.size()) {
1✔
434
                                versions.add("0");
1✔
435
                        }
436
                        while (values.size() < versions.size()) {
1✔
437
                                values.add("0");
1✔
438
                        }
439
                        
440
                        for (int x = 0; x < versions.size(); x++) {
1✔
441
                                String verNum = versions.get(x).trim();
1✔
442
                                String valNum = values.get(x).trim();
1✔
443
                                Long ver = NumberUtils.toLong(verNum, 0);
1✔
444
                                Long val = NumberUtils.toLong(valNum, 0);
1✔
445
                                
446
                                int ret = ver.compareTo(val);
1✔
447
                                if (ret != 0) {
1✔
448
                                        return ret;
1✔
449
                                }
450
                        }
451
                }
452
                catch (NumberFormatException e) {
×
453
                        log.error("Error while converting a version/value to an integer: " + version + "/" + value, e);
×
454
                }
1✔
455
                
456
                // default return value if an error occurs or elements are equal
457
                return 0;
1✔
458
        }
459
        
460
        /**
461
         * Checks for qualifier version (i.e "-SNAPSHOT", "-ALPHA" etc. after maven version conventions)
462
         *
463
         * @param version String like 1.9.2-SNAPSHOT
464
         * @return true if version contains qualifier
465
         */
466
        public static boolean isVersionWithQualifier(String version) {
467
                Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.(\\d+))?(\\-([A-Za-z]+))").matcher(version);
1✔
468
                return matcher.matches();
1✔
469
        }
470
        
471
        /**
472
         * Gets the folder where modules are stored. ModuleExceptions are thrown on errors
473
         *
474
         * @return folder containing modules
475
         * <strong>Should</strong> use the runtime property as the first choice if specified
476
         * <strong>Should</strong> return the correct file if the runtime property is an absolute path
477
         */
478
        public static File getModuleRepository() {
479
                
480
                String folderName = Context.getRuntimeProperties().getProperty(ModuleConstants.REPOSITORY_FOLDER_RUNTIME_PROPERTY);
1✔
481
                if (StringUtils.isBlank(folderName)) {
1✔
482
                        AdministrationService as = Context.getAdministrationService();
1✔
483
                        folderName = as.getGlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY,
1✔
484
                            ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT);
485
                }
486
                // try to load the repository folder straight away.
487
                File folder = new File(folderName);
1✔
488
                
489
                // if the property wasn't a full path already, assume it was intended to be a folder in the
490
                // application directory
491
                if (!folder.exists()) {
1✔
492
                        folder = new File(OpenmrsUtil.getApplicationDataDirectory(), folderName);
1✔
493
                }
494
                
495
                // now create the modules folder if it doesn't exist
496
                if (!folder.exists()) {
1✔
497
                        log.warn("Module repository " + folder.getAbsolutePath() + " doesn't exist.  Creating directories now.");
1✔
498
                        folder.mkdirs();
1✔
499
                }
500
                
501
                if (!folder.isDirectory()) {
1✔
502
                        throw new ModuleException("Module repository is not a directory at: " + folder.getAbsolutePath());
×
503
                }
504
                
505
                return folder;
1✔
506
        }
507
        
508
        /**
509
         * Utility method to convert a {@link File} object to a local URL.
510
         *
511
         * @param file a file object
512
         * @return absolute URL that points to the given file
513
         * @throws MalformedURLException if file can't be represented as URL for some reason
514
         */
515
        public static URL file2url(final File file) throws MalformedURLException {
516
                if (file == null) {
1✔
517
                        return null;
1✔
518
                }
519
                try {
520
                        return file.getCanonicalFile().toURI().toURL();
1✔
521
                }
522
                catch (IOException | NoSuchMethodError ioe) {
1✔
523
                        throw new MalformedURLException("Cannot convert: " + file.getName() + " to url");
1✔
524
                }
525
        }
526
        
527
        /**
528
         * Expand the given <code>fileToExpand</code> jar to the <code>tmpModuleFile</code> directory
529
         *
530
         * If <code>name</code> is null, the entire jar is expanded. If<code>name</code> is not null,
531
         * then only that path/file is expanded.
532
         *
533
         * @param fileToExpand file pointing at a .jar
534
         * @param tmpModuleDir directory in which to place the files
535
         * @param name filename inside of the jar to look for and expand
536
         * @param keepFullPath if true, will recreate entire directory structure in tmpModuleDir
537
         *            relating to <code>name</code>. if false will start directory structure at
538
         *            <code>name</code>
539
         * <strong>Should</strong> expand entire jar if name is null
540
         * <strong>Should</strong> expand entire jar if name is empty string
541
         * <strong>Should</strong> expand directory with parent tree if name is directory and keepFullPath is true
542
         * <strong>Should</strong> expand directory without parent tree if name is directory and keepFullPath is false
543
         * <strong>Should</strong> expand file with parent tree if name is file and keepFullPath is true
544
         */
545
        public static void expandJar(File fileToExpand, File tmpModuleDir, String name, boolean keepFullPath) throws IOException {
546
                String docBase = tmpModuleDir.getAbsolutePath();
1✔
547
                try (JarFile jarFile = new JarFile(fileToExpand)) {
1✔
548
                        Enumeration<JarEntry> jarEntries = jarFile.entries();
1✔
549
                        boolean foundName = (name == null);
1✔
550
                        
551
                        // loop over all of the elements looking for the match to 'name'
552
                        while (jarEntries.hasMoreElements()) {
1✔
553
                                JarEntry jarEntry = jarEntries.nextElement();
1✔
554
                                if (name == null || jarEntry.getName().startsWith(name)) {
1✔
555
                                        String entryName = jarEntry.getName();
1✔
556
                                        // trim out the name path from the name of the new file
557
                                        if (!keepFullPath && name != null) {
1✔
558
                                                entryName = entryName.replaceFirst(name, "");
1✔
559
                                        }
560
                                        
561
                                        // if it has a slash, it's in a directory
562
                                        int last = entryName.lastIndexOf('/');
1✔
563
                                        if (last >= 0) {
1✔
564
                                                File parent = new File(docBase, entryName.substring(0, last));
1✔
565
                                                parent.mkdirs();
1✔
566
                                                log.debug("Creating parent dirs: " + parent.getAbsolutePath());
1✔
567
                                        }
568
                                        // we don't want to "expand" directories or empty names
569
                                        if (entryName.endsWith("/") || "".equals(entryName)) {
1✔
570
                                                continue;
×
571
                                        }
572
                                        try(InputStream input = jarFile.getInputStream(jarEntry)) {
1✔
573
                                                expand(input, docBase, entryName);
1✔
574
                                        }
575
                                        foundName = true;
1✔
576
                                }
577
                        }
1✔
578
                        if (!foundName) {
1✔
579
                                log.debug("Unable to find: " + name + " in file " + fileToExpand.getAbsolutePath());
1✔
580
                        }
581
                        
582
                }
583
                catch (IOException e) {
×
584
                        log.warn("Unable to delete tmpModuleFile on error", e);
×
585
                        throw e;
×
586
                }
1✔
587
        }
1✔
588
        
589
        /**
590
         * Expand the given file in the given stream to a location (fileDir/name) The <code>input</code>
591
         * InputStream is not closed in this method
592
         *
593
         * @param input stream to read from
594
         * @param fileDir directory to copy to
595
         * @param name file/directory within the <code>fileDir</code> to which we expand
596
         *            <code>input</code>
597
         * @return File the file created by the expansion.
598
         * @throws IOException if an error occurred while copying
599
         */
600
        private static void expand(InputStream input, String fileDir, String name) throws IOException {
601
                log.debug("expanding: {}", name);
1✔
602

603
                File file = new File(fileDir, name);
1✔
604

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

1197
                        // close inner jar file before attempting to delete temporary file
1198
                        try {
1199
                                if (innerJarFile != null) {
1✔
1200
                                        innerJarFile.close();
1✔
1201
                                }
1202
                        }
1203
                        catch (IOException e) {
×
1204
                                log.warn("Unable to close inner jarfile: " + innerJarFile, e);
×
1205
                        }
1✔
1206

1207
                        // delete temporary file
1208
                        if (tempFile != null && !tempFile.delete()) {
1✔
1209
                                log.warn("Could not delete temporary jarfile: " + tempFile);
×
1210
                        }
1211
                }
1212
                return null;
1✔
1213
        }
1214
        
1215
        /**
1216
         * Gets the root folder of a module's sources during development
1217
         * 
1218
         * @param moduleId the module id
1219
         * @return the module's development folder is specified, else null
1220
         */
1221
        public static File getDevelopmentDirectory(String moduleId) {
1222
                String directory = System.getProperty(moduleId + ".development.directory");
1✔
1223
                if (StringUtils.isNotBlank(directory)) {
1✔
1224
                        return new File(directory);
×
1225
                }
1226
                
1227
                return null;
1✔
1228
        }
1229
}
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

© 2025 Coveralls, Inc