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

openmrs / openmrs-core / 21752216547

21 Aug 2025 11:52AM UTC coverage: 63.694% (-0.08%) from 63.778%
21752216547

push

github

rkorytkowski
TRUNK-6318: Back-port LocalStorageServcie and StreamDataService fixes

(cherry picked from commit 658a3df03)
(cherry picked from commit f7d12ffc9)
(cherry picked from commit 4fac7d80e)

48 of 68 new or added lines in 3 files covered. (70.59%)

282 existing lines in 9 files now uncovered.

21840 of 34289 relevant lines covered (63.69%)

0.64 hits per line

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

58.41
/api/src/main/java/org/openmrs/module/ModuleUtil.java
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
3
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
4
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
5
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
6
 *
7
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
8
 * graphic logo is a trademark of OpenMRS Inc.
9
 */
10
package org.openmrs.module;
11

12
import java.io.ByteArrayInputStream;
13
import java.io.ByteArrayOutputStream;
14
import java.io.File;
15
import java.io.FileOutputStream;
16
import java.io.IOException;
17
import java.io.InputStream;
18
import java.net.HttpURLConnection;
19
import java.net.MalformedURLException;
20
import java.net.URL;
21
import java.net.URLConnection;
22
import java.nio.charset.StandardCharsets;
23
import java.util.ArrayList;
24
import java.util.Collection;
25
import java.util.Collections;
26
import java.util.Enumeration;
27
import java.util.HashMap;
28
import java.util.HashSet;
29
import java.util.LinkedHashSet;
30
import java.util.List;
31
import java.util.Map;
32
import java.util.Properties;
33
import java.util.Set;
34
import java.util.jar.JarEntry;
35
import java.util.jar.JarFile;
36
import java.util.regex.Matcher;
37
import java.util.regex.Pattern;
38
import java.util.zip.ZipEntry;
39

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

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

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

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

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

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

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

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

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