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

openmrs / openmrs-core / 43293528472

12 Nov 2026 05:19PM UTC coverage: 66.969% (+0.2%) from 66.721%
43293528472

push

github

ibacher
Validate module ids and contain module paths (#6813)

38 of 42 new or added lines in 4 files covered. (90.48%)

391 existing lines in 8 files now uncovered.

26387 of 39402 relevant lines covered (66.97%)

0.67 hits per line

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

57.58
/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.nio.file.Path;
24
import java.util.ArrayList;
25
import java.util.Collection;
26
import java.util.Collections;
27
import java.util.Enumeration;
28
import java.util.HashSet;
29
import java.util.LinkedHashSet;
30
import java.util.List;
31
import java.util.Properties;
32
import java.util.Set;
33
import java.util.jar.JarEntry;
34
import java.util.jar.JarFile;
35
import java.util.regex.Matcher;
36
import java.util.regex.Pattern;
37
import java.util.zip.ZipEntry;
38
import org.openmrs.api.OpenmrsService;
39
import org.springframework.beans.PropertyValue;
40
import org.springframework.beans.factory.annotation.Autowired;
41
import org.springframework.beans.factory.config.BeanDefinition;
42
import org.springframework.beans.factory.config.BeanDefinitionHolder;
43
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
44
import org.springframework.beans.factory.config.RuntimeBeanReference;
45
import org.springframework.context.ConfigurableApplicationContext;
46
import org.springframework.core.annotation.AnnotationUtils;
47

48
import java.lang.reflect.Constructor;
49
import java.lang.reflect.Field;
50
import java.lang.reflect.Method;
51
import org.apache.commons.io.IOUtils;
52
import org.apache.commons.lang3.StringUtils;
53
import org.apache.commons.lang3.math.NumberUtils;
54
import org.openmrs.GlobalProperty;
55
import org.openmrs.api.AdministrationService;
56
import org.openmrs.api.context.Context;
57
import org.openmrs.api.context.ServiceContext;
58
import org.openmrs.scheduler.SchedulerUtil;
59
import org.openmrs.util.OpenmrsClassLoader;
60
import org.openmrs.util.OpenmrsConstants;
61
import org.openmrs.util.OpenmrsUtil;
62
import org.slf4j.Logger;
63
import org.slf4j.LoggerFactory;
64
import org.springframework.context.support.AbstractRefreshableApplicationContext;
65

66
/**
67
 * Utility methods for working and manipulating modules
68
 */
69
public class ModuleUtil {
70

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

162
                List<Module> modules = new ArrayList<>(ModuleFactory.getStartedModules());
1 ✔
163
                
164
                for (Module mod : modules) {
1 ✔
165
                        log.debug("stopping module: {}", mod.getModuleId());
1 ✔
166
                        
167
                        if (mod.isStarted()) {
1 ✔
168
                                ModuleFactory.stopModule(mod, true, true);
1 ✔
169
                        }
170
                }
1 ✔
171
                
172
                log.debug("done shutting down modules");
1 ✔
173
                
174
                // clean up the static variables just in case they weren't done before
175
                ModuleFactory.extensionMap.clear();
1 ✔
176
                ModuleFactory.loadedModules.invalidateAll();
1 ✔
177
                ModuleFactory.moduleClassLoaders.invalidateAll();
1 ✔
178
                ModuleFactory.startedModules.invalidateAll();
1 ✔
179
        }
1 ✔
180
        
181
        /**
182
         * Add the <code>inputStream</code> as a file in the modules repository
183
         *
184
         * @param inputStream <code>InputStream</code> to load
185
         * @return filename String of the file's name of the stream
186
         */
187
        public static File insertModuleFile(InputStream inputStream, String filename) {
188
                File folder = getModuleRepository();
1 ✔
189
                
190
                // check if module filename is already loaded
191
                if (OpenmrsUtil.folderContains(folder, filename)) {
×
192
                        throw new ModuleException(filename + " is already associated with a loaded module.");
×
193
                }
194

NEW
195
                File file = resolveWithinDirectory(folder, filename);
×
196

197
                try (FileOutputStream outputStream = new FileOutputStream(file)) {
×
198
                        OpenmrsUtil.copyFile(inputStream, outputStream);
×
199
                }
200
                catch (IOException e) {
×
201
                        throw new ModuleException("Can't create module file for " + filename, e);
×
202
                }
203
                finally {
204
                        try {
205
                                inputStream.close();
×
206
                        }
207
                        catch (Exception e) { /* pass */}
×
208
                }
209
                
210
                return file;
×
211
        }
212

213
        /**
214
         * Resolves <code>relativePath</code> against <code>baseDir</code> and verifies that the normalized
215
         * result is strictly inside <code>baseDir</code>. Use this for every path that is derived from
216
         * untrusted input, such as a module id, before deleting, creating or writing it.
217
         * <p>
218
         * <strong>Should</strong> return the file inside the base directory for a plain relative path<br/>
219
         * <strong>Should</strong> fail if the path resolves to the base directory itself<br/>
220
         * <strong>Should</strong> fail if the path resolves outside the base directory
221
         *
222
         * @param baseDir the directory the result must stay within
223
         * @param relativePath the path to resolve against <code>baseDir</code>
224
         * @return the normalized absolute file
225
         * @throws ModuleException if the resolved path is not strictly inside <code>baseDir</code>
226
         * @since 2.9.0
227
         */
228
        public static File resolveWithinDirectory(File baseDir, String relativePath) {
229
                Path base = baseDir.toPath().toAbsolutePath().normalize();
1 ✔
230
                Path resolved = new File(baseDir, relativePath).toPath().toAbsolutePath().normalize();
1 ✔
231
                if (resolved.equals(base) || !resolved.startsWith(base)) {
1 ✔
232
                        throw new ModuleException("Path '" + relativePath + "' resolves outside of " + base);
1 ✔
233
                }
234
                return resolved.toFile();
1 ✔
235
        }
236

237
        /**
238
         * Checks if the current OpenMRS version is in an array of versions.
239
         * <p>
240
         * This method calls {@link ModuleUtil#matchRequiredVersions(String, String)} internally.
241
         * </p>
242
         *
243
         * @param versions the openmrs versions to be checked against the current openmrs version
244
         * @return true if the current openmrs version is in versions otherwise false
245
         * <strong>Should</strong> return false when versions is null
246
         * <strong>Should</strong> return false when versions is empty
247
         * <strong>Should</strong> return true if current openmrs version matches one element in versions
248
         * <strong>Should</strong> return false if current openmrs version does not match any element in versions
249
         */
250
        public static boolean isOpenmrsVersionInVersions(String ...versions) {
251
                return isVersionInVersions(OpenmrsConstants.OPENMRS_VERSION_SHORT, versions);
1 ✔
252
        }
253

254
        /**
255
         * For testing of {@link #isOpenmrsVersionInVersions(String...)} only.
256
         * 
257
         * @param version the version
258
         * @param versions versions to match
259
         * @return true if version matches any value from versions
260
         */
261
        static boolean isVersionInVersions(String version, String ...versions) {
262
                if (versions == null || versions.length == 0) {
1 ✔
263
                        return false;
1 ✔
264
                }
265

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

451
        /**
452
         * Compare two version strings. Any version qualifiers are ignored in the comparison.
453
         *
454
         * @param versionA String like 1.9.2.0, may include a qualifier like "-SNAPSHOT", may be null
455
         * @param versionB String like 1.9.2.0, may include a qualifier like "-SNAPSHOT", may be null
456
         * @return the value <code>0</code> if versions are equal; a value less than <code>0</code> if first version is
457
         *                    before the second one; a value greater than <code>0</code> if first version is after the second one.
458
         */
459
        public static int compareVersionIgnoringQualifier(String versionA, String versionB) {
460
                return compareVersion(versionA, versionB, true);
1 ✔
461
        }
462

463
        private static int compareVersion(String versionA, String versionB, boolean ignoreQualifier) {
464
                try {
465
                        if (versionA == null || versionB == null) {
1 ✔
466
                                return 0;
1 ✔
467
                        }
468

469
                        List<String> versionANumbers = new ArrayList<>();
1 ✔
470
                        List<String> versionBNumbers = new ArrayList<>();
1 ✔
471
                        String qualifierSeparator = "-";
1 ✔
472

473
                        // strip off any qualifier e.g. "-SNAPSHOT"
474
                        int qualifierIndexA = versionA.indexOf(qualifierSeparator);
1 ✔
475
                        if (qualifierIndexA != -1) {
1 ✔
476
                                versionA = versionA.substring(0, qualifierIndexA);
1 ✔
477
                        }
478

479
                        // strip off any qualifier e.g. "-SNAPSHOT"
480
                        int qualifierIndexB = versionB.indexOf(qualifierSeparator);
1 ✔
481
                        if (qualifierIndexB != -1) {
1 ✔
482
                                versionB = versionB.substring(0, qualifierIndexB);
1 ✔
483
                        }
484

485
                        Collections.addAll(versionANumbers, versionA.split("\\."));
1 ✔
486
                        Collections.addAll(versionBNumbers, versionB.split("\\."));
1 ✔
487

488
                        // match the sizes of the lists
489
                        while (versionANumbers.size() < versionBNumbers.size()) {
1 ✔
490
                                versionANumbers.add("0");
1 ✔
491
                        }
492
                        while (versionBNumbers.size() < versionANumbers.size()) {
1 ✔
493
                                versionBNumbers.add("0");
1 ✔
494
                        }
495

496
                        for (int x = 0; x < versionANumbers.size(); x++) {
1 ✔
497
                                String verAPartString = versionANumbers.get(x).trim();
1 ✔
498
                                String verBPartString = versionBNumbers.get(x).trim();
1 ✔
499
                                Long verAPart = NumberUtils.toLong(verAPartString, 0);
1 ✔
500
                                Long verBPart = NumberUtils.toLong(verBPartString, 0);
1 ✔
501

502
                                int ret = verAPart.compareTo(verBPart);
1 ✔
503
                                if (ret != 0) {
1 ✔
504
                                        return ret;
1 ✔
505
                                }
506
                        }
507
                        
508
                        // At this point the version numbers are equal.
509
                        if (!ignoreQualifier) {
1 ✔
510
                                if (qualifierIndexA >= 0 && qualifierIndexB < 0) {
1 ✔
511
                                        return -1;
1 ✔
512
                                } else if (qualifierIndexA < 0 && qualifierIndexB >= 0) {
1 ✔
513
                                        return 1;
1 ✔
514
                                }
515
                        }
516
                }
517
                catch (NumberFormatException e) {
×
518
                        log.error("Error while converting a version/value to an integer: " + versionA + "/" + versionB, e);
×
519
                }
1 ✔
520
                
521
                // default return value if an error occurs or elements are equal
522
                return 0;
1 ✔
523
        }
524
        
525
        /**
526
         * Checks for qualifier version (i.e "-SNAPSHOT", "-ALPHA" etc. after maven version conventions)
527
         *
528
         * @param version String like 1.9.2-SNAPSHOT
529
         * @return true if version contains qualifier
530
         */
531
        public static boolean isVersionWithQualifier(String version) {
532
                Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.(\\d+))?(\\-([A-Za-z]+))").matcher(version);
1 ✔
533
                return matcher.matches();
1 ✔
534
        }
535
        
536
        /**
537
         * Gets the folder where modules are stored. ModuleExceptions are thrown on errors
538
         *
539
         * @return folder containing modules
540
         * <strong>Should</strong> use the runtime property as the first choice if specified
541
         * <strong>Should</strong> return the correct file if the runtime property is an absolute path
542
         */
543
        public static File getModuleRepository() {
544
                
545
                String folderName = Context.getRuntimeProperties().getProperty(ModuleConstants.REPOSITORY_FOLDER_RUNTIME_PROPERTY);
1 ✔
546
                if (StringUtils.isBlank(folderName)) {
1 ✔
547
                        AdministrationService as = Context.getAdministrationService();
1 ✔
548
                        folderName = as.getGlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY,
1 ✔
549
                            ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT);
550
                }
551
                // try to load the repository folder straight away.
552
                File folder = new File(folderName);
1 ✔
553
                
554
                // if the property wasn't a full path already, assume it was intended to be a folder in the
555
                // application directory
556
                if (!folder.exists()) {
1 ✔
557
                        folder = new File(OpenmrsUtil.getApplicationDataDirectory(), folderName);
1 ✔
558
                }
559
                
560
                // now create the modules folder if it doesn't exist
561
                if (!folder.exists()) {
1 ✔
562
                        log.warn("Module repository " + folder.getAbsolutePath() + " doesn't exist.  Creating directories now.");
1 ✔
563
                        folder.mkdirs();
1 ✔
564
                }
565
                
566
                if (!folder.isDirectory()) {
1 ✔
567
                        throw new ModuleException("Module repository is not a directory at: " + folder.getAbsolutePath());
×
568
                }
569
                
570
                return folder;
1 ✔
571
        }
572
        
573
        /**
574
         * Utility method to convert a {@link File} object to a local URL.
575
         *
576
         * @param file a file object
577
         * @return absolute URL that points to the given file
578
         * @throws MalformedURLException if file can't be represented as URL for some reason
579
         */
580
        public static URL file2url(final File file) throws MalformedURLException {
581
                if (file == null) {
1 ✔
582
                        return null;
1 ✔
583
                }
584
                try {
585
                        return file.getCanonicalFile().toURI().toURL();
1 ✔
586
                }
587
                catch (IOException | NoSuchMethodError ioe) {
1 ✔
588
                        throw new MalformedURLException("Cannot convert: " + file.getName() + " to url");
1 ✔
589
                }
590
        }
591
        
592
        /**
593
         * Expand the given <code>fileToExpand</code> jar to the <code>tmpModuleFile</code> directory
594
         *
595
         * If <code>name</code> is null, the entire jar is expanded. If<code>name</code> is not null,
596
         * then only that path/file is expanded.
597
         *
598
         * @param fileToExpand file pointing at a .jar
599
         * @param tmpModuleDir directory in which to place the files
600
         * @param name filename inside of the jar to look for and expand
601
         * @param keepFullPath if true, will recreate entire directory structure in tmpModuleDir
602
         *            relating to <code>name</code>. if false will start directory structure at
603
         *            <code>name</code>
604
         * @throws UnsupportedOperationException if an entry would be extracted outside of tmpModuleDir (Zip slip attack)
605
         * <strong>Should</strong> expand entire jar if name is null
606
         * <strong>Should</strong> expand entire jar if name is empty string
607
         * <strong>Should</strong> expand directory with parent tree if name is directory and keepFullPath is true
608
         * <strong>Should</strong> expand directory without parent tree if name is directory and keepFullPath is false
609
         * <strong>Should</strong> expand file with parent tree if name is file and keepFullPath is true
610
         * <strong>Should</strong> throw exception for Zip slip attack
611
         */
612
        public static void expandJar(File fileToExpand, File tmpModuleDir, String name, boolean keepFullPath) throws IOException {
613
                String docBase = tmpModuleDir.getAbsolutePath();
1 ✔
614
                log.debug("Expanding jar {}", fileToExpand);
1 ✔
615
                try (JarFile jarFile = new JarFile(fileToExpand)) {
1 ✔
616
                        Enumeration<JarEntry> jarEntries = jarFile.entries();
1 ✔
617
                        boolean foundName = (name == null);
1 ✔
618
                        
619
                        // loop over all of the elements looking for the match to 'name'
620
                        while (jarEntries.hasMoreElements()) {
1 ✔
621
                                JarEntry jarEntry = jarEntries.nextElement();
1 ✔
622
                                if (name == null || jarEntry.getName().startsWith(name)) {
1 ✔
623
                                        String entryName = jarEntry.getName();
1 ✔
624
                                        // trim out the name path from the name of the new file
625
                                        if (!keepFullPath && name != null) {
1 ✔
626
                                                entryName = entryName.replaceFirst(name, "");
1 ✔
627
                                        }
628
                                        
629
                                        // if it has a slash, it's in a directory
630
                                        int last = entryName.lastIndexOf('/');
1 ✔
631
                                        if (last >= 0) {
1 ✔
632
                                                File parent = new File(docBase, entryName.substring(0, last));
1 ✔
633
                                                if (!parent.toPath().normalize().startsWith(docBase)) {
1 ✔
634
                                                        throw new UnsupportedOperationException("Attempted to create directory '" + entryName + "' rejected as it attempts to write outside the chosen directory. This may be the result of a zip-slip style attack.");
1 ✔
635
                                                }
636
                                                parent.mkdirs();
1 ✔
637
                                                log.debug("Creating parent dirs: " + parent.getAbsolutePath());
1 ✔
638
                                        }
639
                                        // we don't want to "expand" directories or empty names
640
                                        if (entryName.endsWith("/") || "".equals(entryName)) {
1 ✔
641
                                                continue;
×
642
                                        }
643
                                        try(InputStream input = jarFile.getInputStream(jarEntry)) {
1 ✔
644
                                                expand(input, docBase, entryName);
1 ✔
645
                                        }
646
                                        foundName = true;
1 ✔
647
                                }
648
                        }
1 ✔
649
                        if (!foundName) {
1 ✔
650
                                log.debug("Unable to find: " + name + " in file " + fileToExpand.getAbsolutePath());
1 ✔
651
                        }
652
                        
653
                }
654
                catch (IOException e) {
×
655
                        log.warn("Unable to delete tmpModuleFile on error", e);
×
656
                        throw e;
×
657
                }
1 ✔
658
        }
1 ✔
659
        
660
        /**
661
         * Expand the given file in the given stream to a location (fileDir/name) The <code>input</code>
662
         * InputStream is not closed in this method
663
         *
664
         * @param input stream to read from
665
         * @param fileDir directory to copy to
666
         * @param name file/directory within the <code>fileDir</code> to which we expand
667
         *            <code>input</code>
668
         * @return File the file created by the expansion.
669
         * @throws IOException if an error occurred while copying
670
         */
671
        private static void expand(InputStream input, String fileDir, String name) throws IOException {
672
                log.debug("expanding: {}", name);
1 ✔
673

674
                File file = new File(fileDir, name);
1 ✔
675

676
                if (!file.toPath().normalize().startsWith(fileDir)) {
1 ✔
677
                        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.");
×
678
                }
679
                
680
                try (FileOutputStream outStream = new FileOutputStream(file)) {
1 ✔
681
                        OpenmrsUtil.copyFile(input, outStream);
1 ✔
682
                }
683
        }
1 ✔
684
        
685
        /**
686
         * Downloads the contents of a URL and copies them to a string (Borrowed from oreilly)
687
         *
688
         * @param url
689
         * @return InputStream of contents
690
         * <strong>Should</strong> return a valid input stream for old module urls
691
         */
692
        public static InputStream getURLStream(URL url) {
693
                InputStream in = null;
×
694
                try {
695
                        URLConnection uc = url.openConnection();
×
696
                        uc.setDefaultUseCaches(false);
×
697
                        uc.setUseCaches(false);
×
698
                        uc.setRequestProperty("Cache-Control", "max-age=0,no-cache");
×
699
                        uc.setRequestProperty("Pragma", "no-cache");
×
700
                        
701
                        log.debug("Logging an attempt to connect to: " + url);
×
702
                        
703
                        in = openConnectionCheckRedirects(uc);
×
704
                }
705
                catch (IOException io) {
×
706
                        log.warn("io while reading: " + url, io);
×
707
                }
×
708
                
709
                return in;
×
710
        }
711
        
712
        /**
713
         * Convenience method to follow http to https redirects. Will follow a total of 5 redirects, then
714
         * fail out due to foolishness on the url's part. Once a connection in the chain uses https, a
715
         * redirect to a non-https url is refused.
716
         * <p>
717
         * <strong>Should</strong> follow http redirects<br/>
718
         * <strong>Should</strong> refuse a redirect from https to http
719
         *
720
         * @param c the {@link URLConnection} to open
721
         * @return an {@link InputStream} that is not necessarily at the same url, possibly at a 403
722
         *         redirect.
723
         * @throws IOException
724
         * @see #getURLStream(URL)
725
         */
726
        protected static InputStream openConnectionCheckRedirects(URLConnection c) throws IOException {
727
                boolean redir;
728
                int redirects = 0;
1 ✔
729
                boolean secure = "https".equals(c.getURL().getProtocol());
1 ✔
730
                InputStream in;
731
                do {
732
                        if (c instanceof HttpURLConnection) {
1 ✔
733
                                ((HttpURLConnection) c).setInstanceFollowRedirects(false);
1 ✔
734
                        }
735
                        // We want to open the input stream before getting headers
736
                        // because getHeaderField() et al swallow IOExceptions.
737
                        in = c.getInputStream();
1 ✔
738
                        redir = false;
1 ✔
739
                        if (c instanceof HttpURLConnection) {
1 ✔
740
                                HttpURLConnection http = (HttpURLConnection) c;
1 ✔
741
                                int stat = http.getResponseCode();
1 ✔
742
                                if (stat == 300 || stat == 301 || stat == 302 || stat == 303 || stat == 305 || stat == 307) {
1 ✔
743
                                        URL base = http.getURL();
1 ✔
744
                                        String loc = http.getHeaderField("Location");
1 ✔
745
                                        URL target = null;
1 ✔
746
                                        if (loc != null) {
1 ✔
747
                                                target = new URL(base, loc);
1 ✔
748
                                        }
749
                                        http.disconnect();
1 ✔
750
                                        // Redirection should be allowed only for HTTP and HTTPS
751
                                        // and should be limited to 5 redirects at most.
752
                                        if (target == null || !("http".equals(target.getProtocol()) || "https".equals(target.getProtocol()))
1 ✔
753
                                                || redirects >= 5) {
754
                                                throw new SecurityException("illegal URL redirect");
×
755
                                        }
756
                                        if (secure && !"https".equals(target.getProtocol())) {
1 ✔
757
                                                throw new SecurityException("illegal URL redirect from https to " + target.getProtocol());
1 ✔
758
                                        }
759
                                        secure = secure || "https".equals(target.getProtocol());
1 ✔
760
                                        redir = true;
1 ✔
761
                                        c = target.openConnection();
1 ✔
762
                                        redirects++;
1 ✔
763
                                }
764
                        }
765
                } while (redir);
1 ✔
766
                return in;
1 ✔
767
        }
768
        
769
        /**
770
         * Downloads the contents of a URL and copies them to a string (Borrowed from oreilly)
771
         *
772
         * @param url
773
         * @return String contents of the URL
774
         * <strong>Should</strong> return an update rdf page for old https dev urls
775
         * <strong>Should</strong> return an update rdf page for old https module urls
776
         * <strong>Should</strong> return an update rdf page for module urls
777
         */
778
        public static String getURL(URL url) {
779
                InputStream in = null;
×
780
                ByteArrayOutputStream out = null;
×
781
                String output = "";
×
782
                try {
783
                        in = getURLStream(url);
×
784
                        if (in == null) {
×
785
                                // skip this module if updateURL is not defined
786
                                return "";
×
787
                        }
788
                        
789
                        out = new ByteArrayOutputStream();
×
790
                        OpenmrsUtil.copyFile(in, out);
×
791
                        output = out.toString(StandardCharsets.UTF_8.name());
×
792
                }
793
                catch (IOException io) {
×
794
                        log.warn("io while reading: " + url, io);
×
795
                }
796
                finally {
797
                        try {
798
                                in.close();
×
799
                        }
800
                        catch (Exception e) { /* pass */}
×
801
                        try {
802
                                out.close();
×
803
                        }
804
                        catch (Exception e) { /* pass */}
×
805
                }
806
                
807
                return output;
×
808
        }
809
        
810
        /**
811
         * Iterates over the modules and checks each update.rdf file for an update
812
         *
813
         * @return True if an update was found for one of the modules, false if none were found
814
         * @throws ModuleException
815
         */
816
        public static Boolean checkForModuleUpdates() throws ModuleException {
817
                
818
                Boolean updateFound = false;
×
819
                
820
                for (Module mod : ModuleFactory.getLoadedModules()) {
×
821
                        String updateURL = mod.getUpdateURL();
×
822
                        if (StringUtils.isNotEmpty(updateURL)) {
×
823
                                try {
824
                                        // get the contents pointed to by the url
825
                                        URL url = new URL(updateURL);
×
826
                                        if (!url.toString().endsWith(ModuleConstants.UPDATE_FILE_NAME)) {
×
827
                                                log.warn("Illegal url: " + url);
×
828
                                                continue;
×
829
                                        }
830
                                        String content = getURL(url);
×
831
                                        
832
                                        // skip empty or invalid updates
833
                                        if ("".equals(content)) {
×
834
                                                continue;
×
835
                                        }
836
                                        
837
                                        // process and parse the contents
838
                                        UpdateFileParser parser = new UpdateFileParser(content);
×
839
                                        parser.parse();
×
840
                                        
841
                                        log.debug("Update for mod: " + mod.getModuleId() + " compareVersion result: "
×
842
                                                + compareVersion(mod.getVersion(), parser.getCurrentVersion()));
×
843
                                        
844
                                        // check the update.rdf version against the installed version
845
                                        if (compareVersion(mod.getVersion(), parser.getCurrentVersion()) < 0) {
×
846
                                                if (mod.getModuleId().equals(parser.getModuleId())) {
×
847
                                                        mod.setDownloadURL(parser.getDownloadURL());
×
848
                                                        mod.setUpdateVersion(parser.getCurrentVersion());
×
849
                                                        updateFound = true;
×
850
                                                } else {
851
                                                        log.warn("Module id does not match in update.rdf:" + parser.getModuleId());
×
852
                                                }
853
                                        } else {
854
                                                mod.setDownloadURL(null);
×
855
                                                mod.setUpdateVersion(null);
×
856
                                        }
857
                                }
858
                                catch (ModuleException e) {
×
859
                                        log.warn("Unable to get updates from update.xml", e);
×
860
                                }
861
                                catch (MalformedURLException e) {
×
862
                                        log.warn("Unable to form a URL object out of: " + updateURL, e);
×
863
                                }
×
864
                        }
865
                }
×
866
                
867
                return updateFound;
×
868
        }
869
        
870
        /**
871
         * @return true/false whether the 'allow upload' or 'allow web admin' property has been turned
872
         *         on
873
         */
874
        public static Boolean allowAdmin() {
875
                
876
                Properties properties = Context.getRuntimeProperties();
×
877
                String prop = properties.getProperty(ModuleConstants.RUNTIMEPROPERTY_ALLOW_UPLOAD, null);
×
878
                if (prop == null) {
×
879
                        prop = properties.getProperty(ModuleConstants.RUNTIMEPROPERTY_ALLOW_ADMIN, "false");
×
880
                }
881
                
882
                return "true".equals(prop);
×
883
        }
884
        
885
        /**
886
         * @see ModuleUtil#refreshApplicationContext(AbstractRefreshableApplicationContext, boolean, Module)
887
         */
888
        public static AbstractRefreshableApplicationContext refreshApplicationContext(AbstractRefreshableApplicationContext ctx) {
889
                return refreshApplicationContext(ctx, false, null);
×
890
        }
891
        
892
        /**
893
         * Refreshes the given application context "properly" in OpenMRS. Will first shut down the
894
         * Context and destroy the classloader, then will refresh and set everything back up again.
895
         *
896
         * @param ctx Spring application context that needs refreshing.
897
         * @param isOpenmrsStartup if this refresh is being done at application startup.
898
         * @param startedModule the module that was just started and waiting on the context refresh.
899
         * @return AbstractRefreshableApplicationContext The newly refreshed application context.
900
         */
901
        public static AbstractRefreshableApplicationContext refreshApplicationContext(AbstractRefreshableApplicationContext ctx,
902
                boolean isOpenmrsStartup, Module startedModule) {
903
                //notify all started modules that we are about to refresh the context
904
                Set<Module> startedModules = new LinkedHashSet<>(ModuleFactory.getStartedModulesInOrder());
×
905
                for (Module module : startedModules) {
×
906
                        try {
907
                                if (module.getModuleActivator() != null) {
×
908
                                        log.debug("Run module willRefreshContext: {}", module.getModuleId());
×
909
                                        Thread.currentThread().setContextClassLoader(ModuleFactory.getModuleClassLoader(module));
×
910
                                        module.getModuleActivator().willRefreshContext();
×
911
                                }
912
                        }
913
                        catch (Error e) {
×
914
                                log.warn("Unable to call willRefreshContext() method in the module's activator", e);
×
915
                        }
×
916
                }
×
917
                
918
                ServiceContext.destroyInstance();
×
919
                
920
                try {
921
                        ctx.stop();
×
922
                        ctx.close();
×
923
                }
924
                catch (Exception e) {
×
925
                        log.warn("Exception while stopping and closing context: ", e);
×
926
                        // Spring seems to be trying to refresh the context instead of /just/ stopping
927
                        // pass
928
                }
×
929
                OpenmrsClassLoader.destroyInstance();
×
930
                ctx.setClassLoader(OpenmrsClassLoader.getInstance());
×
931
                Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
×
932
                
933
                log.debug("Refreshing context");
×
934
                ServiceContext.getInstance().startRefreshingContext();
×
935
                try {
936
                        ctx.refresh();
×
937
                        // TRUNK-6421: warn if XML-declared services also use annotations like @Autowired
938
                        logWarningsForAnnotatedXmlServices(ctx);
×
939
                        
940
                }
941
                finally {
942
                        ServiceContext.getInstance().doneRefreshingContext();
×
943
                }
944
                log.debug("Done refreshing context");
×
945
                
946
                ctx.setClassLoader(OpenmrsClassLoader.getInstance());
×
947
                Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
×
948
                
949
                OpenmrsClassLoader.setThreadsToNewClassLoader();
×
950
                
951
                // reload the advice points that were lost when refreshing Spring
952
                log.debug("Reloading advice for all started modules: {}", startedModules.size());
×
953
                
954
                try {
955
                        //The call backs in this block may need lazy loading of objects
956
                        //which will fail because we use an OpenSessionInViewFilter whose opened session
957
                        //was closed when the application context was refreshed as above.
958
                        //So we need to open another session now. TRUNK-3739
959
                        Context.openSessionWithCurrentUser();
×
960
                        for (Module module : startedModules) {
×
961
                                if (!module.isStarted()) {
×
962
                                        continue;
×
963
                                }
964
                                
965
                                ModuleFactory.loadAdvice(module);
×
966
                                try {
967
                                        ModuleFactory.passDaemonToken(module);
×
968
                                        
969
                                        if (module.getModuleActivator() != null) {
×
970
                                                log.debug("Run module contextRefreshed: {}", module.getModuleId());
×
971
                                                module.getModuleActivator().contextRefreshed();
×
972
                                                try {
973
                                                        //if it is system start up, call the started method for all started modules
974
                                                        if (isOpenmrsStartup) {
×
975
                                                                log.debug("Run module started: {}", module.getModuleId());
×
976
                                                                module.getModuleActivator().started();
×
977
                                                        }
978
                                                        //if refreshing the context after a user started or uploaded a new module
979
                                                        else if (!isOpenmrsStartup && module.equals(startedModule)) {
×
980
                                                                log.debug("Run module started: {}", module.getModuleId());
×
981
                                                                module.getModuleActivator().started();
×
982
                                                        }
983
                                                        log.debug("Done running module started: {}", module.getModuleId());
×
984
                                                }
985
                                                catch (Error e) {
×
986
                                                        log.warn("Unable to invoke started() method on the module's activator", e);
×
987
                                                        ModuleFactory.stopModule(module, true, true);
×
988
                                                }
×
989
                                        }
990
                                        
991
                                }
992
                                catch (Error e) {
×
993
                                        log.warn("Unable to invoke method on the module's activator ", e);
×
994
                                }
×
995
                        }
×
996
                }
997
                finally {
998
                        Context.closeSessionWithCurrentUser();
×
999
                }
1000
                
1001
                return ctx;
×
1002
        }
1003
        
1004
        private static void logWarningsForAnnotatedXmlServices(AbstractRefreshableApplicationContext ctx) {
1005
                ConfigurableListableBeanFactory factory = ctx.getBeanFactory();
×
1006

1007
                for (String beanName : factory.getBeanDefinitionNames()) {
×
1008
                        BeanDefinition def = factory.getBeanDefinition(beanName);
×
1009
                        String beanClassName = def.getBeanClassName();
×
1010

1011
                        if ("org.springframework.transaction.interceptor.TransactionProxyFactoryBean".equals(beanClassName)) {
×
1012
                                PropertyValue target = def.getPropertyValues().getPropertyValue("target");
×
1013
                                if (target != null) {
×
1014
                                        if (target.getValue() instanceof BeanDefinitionHolder) {
×
1015
                                                def = ((BeanDefinitionHolder) target.getValue()).getBeanDefinition();
×
1016
                                                beanClassName = def.getBeanClassName();
×
1017
                                        } else if (target.getValue() instanceof RuntimeBeanReference) {
×
1018
                                                beanName = ((RuntimeBeanReference) target.getValue()).getBeanName();
×
1019
                                                def = factory.getBeanDefinition(beanName);
×
1020
                                                beanClassName = def.getBeanClassName();
×
1021
                                        }
1022
                                }
1023
                        } else {
1024
                                continue;
1025
                        }
1026
                        
1027
                        if (beanClassName == null) {
×
1028
                                log.debug("No classname for bean {}", beanName);
×
1029
                                continue;
×
1030
                        }
1031
                        
1032
                        int proxySuffix = beanClassName.indexOf("$$");
×
1033
                        if (proxySuffix != -1) {
×
1034
                                // Get rid of proxy suffix
1035
                                beanClassName = beanClassName.substring(0, proxySuffix);
×
1036
                        }
1037

1038
                        Class<?> beanClass;
1039
                        try {
1040
                                beanClass = OpenmrsClassLoader.getInstance().loadClass(beanClassName);
×
1041
                        }
1042
                        catch (ClassNotFoundException e) {
×
1043
                                log.debug("Unable to load class {} for bean {}", beanClassName, beanName, e);
×
1044
                                continue;
×
1045
                        }
×
1046

1047
                        boolean hasAutowired = false;
×
1048
                        
1049
                        for (Field field : beanClass.getDeclaredFields()) {
×
1050
                                if (AnnotationUtils.getAnnotation(field, Autowired.class) != null) {
×
1051
                                        hasAutowired = true;
×
1052
                                        break;
×
1053
                                }
1054
                        }
1055
                        
1056
                        if (!hasAutowired) {
×
1057
                                for (Constructor<?> ctor : beanClass.getDeclaredConstructors()) {
×
1058
                                        if (AnnotationUtils.getAnnotation(ctor, Autowired.class) != null) {
×
1059
                                                hasAutowired = true;
×
1060
                                                break;
×
1061
                                        }
1062
                                }
1063
                        }
1064
                        
1065
                        if (!hasAutowired) {
×
1066
                                for (Method method : beanClass.getDeclaredMethods()) {
×
1067
                                        if (AnnotationUtils.getAnnotation(method, Autowired.class) != null) {
×
1068
                                                hasAutowired = true;
×
1069
                                                break;
×
1070
                                        }
1071
                                }
1072
                        }
1073

1074
                        if (!hasAutowired) {
×
1075
                                continue;
×
1076
                        }
1077
                        
1078
                        log.warn("Service bean '{}' ({}) appears to be declared via XML " +
×
1079
                                        "and also uses @Autowired annotations. This combination can lead to " +
1080
                                        "slow context refresh when mixing XML-declared services with " +
1081
                                        "annotation-based injection. Please remove @Autowired annotations from the bean. See TRUNK-6363.",
1082
                                beanName, beanClassName);
1083
                }
1084
        }
×
1085
        
1086
        /**
1087
         * Looks at the &lt;moduleid&gt;.mandatory properties and at the currently started modules to make
1088
         * sure that all mandatory modules have been started successfully.
1089
         *
1090
         * @throws ModuleException if a mandatory module isn't started
1091
         * <strong>Should</strong> throw ModuleException if a mandatory module is not started
1092
         */
1093
        protected static void checkMandatoryModulesStarted() throws ModuleException {
1094
                
1095
                List<String> mandatoryModuleIds = getMandatoryModules();
1 ✔
1096
                Set<String> startedModuleIds = ModuleFactory.getStartedModulesMap().keySet();
1 ✔
1097
                
1098
                mandatoryModuleIds.removeAll(startedModuleIds);
1 ✔
1099
                
1100
                // any module ids left in the list are not started
1101
                if (!mandatoryModuleIds.isEmpty()) {
1 ✔
1102
                        throw new MandatoryModuleException(mandatoryModuleIds);
1 ✔
1103
                }
1104
        }
1 ✔
1105
        
1106
        /**
1107
         * Returns all modules that are marked as mandatory. Currently this means there is a
1108
         * &lt;moduleid&gt;.mandatory=true global property.
1109
         *
1110
         * @return list of modules ids for mandatory modules
1111
         * <strong>Should</strong> return mandatory module ids
1112
         */
1113
        public static List<String> getMandatoryModules() {
1114
                
1115
                List<String> mandatoryModuleIds = new ArrayList<>();
1 ✔
1116
                
1117
                try {
1118
                        List<GlobalProperty> props = Context.getAdministrationService().getGlobalPropertiesBySuffix(".mandatory");
1 ✔
1119
                        
1120
                        for (GlobalProperty prop : props) {
1 ✔
1121
                                if ("true".equalsIgnoreCase(prop.getPropertyValue())) {
1 ✔
1122
                                        mandatoryModuleIds.add(prop.getProperty().replace(".mandatory", ""));
1 ✔
1123
                                }
1124
                        }
1 ✔
1125
                }
1126
                catch (Exception e) {
×
1127
                        log.warn("Unable to get the mandatory module list", e);
×
1128
                }
1 ✔
1129
                
1130
                return mandatoryModuleIds;
1 ✔
1131
        }
1132
        
1133
        /**
1134
         * <pre>
1135
         * Gets the module that should handle a path. The path you pass in should be a module id (in
1136
         * path format, i.e. /ui/springmvc, not ui.springmvc) followed by a resource. Something like
1137
         * the following:
1138
         *   /ui/springmvc/css/ui.css
1139
         *
1140
         * The first running module out of the following would be returned:
1141
         *   ui.springmvc.css
1142
         *   ui.springmvc
1143
         *   ui
1144
         * </pre>
1145
         *
1146
         * @param path
1147
         * @return the running module that matches the most of the given path
1148
         * <strong>Should</strong> handle ui springmvc css ui dot css when ui dot springmvc module is running
1149
         * <strong>Should</strong> handle ui springmvc css ui dot css when ui module is running
1150
         * <strong>Should</strong> return null for ui springmvc css ui dot css when no relevant module is running
1151
         */
1152
        public static Module getModuleForPath(String path) {
1153
                int ind = path.lastIndexOf('/');
1 ✔
1154
                if (ind <= 0) {
1 ✔
1155
                        throw new IllegalArgumentException(
×
1156
                                "Input must be /moduleId/resource. Input needs a / after the first character: " + path);
1157
                }
1158
                String moduleId = path.startsWith("/") ? path.substring(1, ind) : path.substring(0, ind);
1 ✔
1159
                moduleId = moduleId.replace('/', '.');
1 ✔
1160
                // iterate over progressively shorter module ids
1161
                while (true) {
1162
                        Module mod = ModuleFactory.getStartedModuleById(moduleId);
1 ✔
1163
                        if (mod != null) {
1 ✔
1164
                                return mod;
1 ✔
1165
                        }
1166
                        // try the next shorter module id
1167
                        ind = moduleId.lastIndexOf('.');
1 ✔
1168
                        if (ind < 0) {
1 ✔
1169
                                break;
1 ✔
1170
                        }
1171
                        moduleId = moduleId.substring(0, ind);
1 ✔
1172
                }
1 ✔
1173
                return null;
1 ✔
1174
        }
1175
        
1176
        /**
1177
         * Takes a global path and returns the local path within the specified module. For example
1178
         * calling this method with the path "/ui/springmvc/css/ui.css" and the ui.springmvc module, you
1179
         * would get "/css/ui.css".
1180
         *
1181
         * @param module
1182
         * @param path
1183
         * @return local path
1184
         * <strong>Should</strong> handle ui springmvc css ui dot css example
1185
         */
1186
        public static String getPathForResource(Module module, String path) {
1187
                if (path.startsWith("/")) {
1 ✔
1188
                        path = path.substring(1);
1 ✔
1189
                }
1190
                return path.substring(module.getModuleIdAsPath().length());
1 ✔
1191
        }
1192
        
1193
        /**
1194
         * This loops over all FILES in this jar to get the package names. If there is an empty
1195
         * directory in this jar it is not returned as a providedPackage.
1196
         *
1197
         * @param file jar file to look into
1198
         * @return list of strings of package names in this jar
1199
         */
1200
        public static Collection<String> getPackagesFromFile(File file) {
1201
                
1202
                // End early if we're given a non jar file
1203
                if (!file.getName().endsWith(".jar")) {
1 ✔
1204
                        return Collections.emptySet();
1 ✔
1205
                }
1206
                
1207
                Set<String> packagesProvided = new HashSet<>();
1 ✔
1208
                
1209
                JarFile jar = null;
1 ✔
1210
                try {
1211
                        jar = new JarFile(file);
1 ✔
1212
                        
1213
                        Enumeration<JarEntry> jarEntries = jar.entries();
1 ✔
1214
                        while (jarEntries.hasMoreElements()) {
1 ✔
1215
                                JarEntry jarEntry = jarEntries.nextElement();
1 ✔
1216
                                if (jarEntry.isDirectory()) {
1 ✔
1217
                                        // skip over directory entries, we only care about files
1218
                                        continue;
1 ✔
1219
                                }
1220
                                String name = jarEntry.getName();
1 ✔
1221
                                
1222
                                // Skip over some folders in the jar/omod
1223
                                if (name.startsWith("lib") || name.startsWith("META-INF") || name.startsWith("web/module")) {
1 ✔
1224
                                        continue;
1 ✔
1225
                                }
1226
                                
1227
                                Integer indexOfLastSlash = name.lastIndexOf("/");
1 ✔
1228
                                if (indexOfLastSlash <= 0) {
1 ✔
1229
                                        continue;
1 ✔
1230
                                }
1231
                                String packageName = name.substring(0, indexOfLastSlash);
1 ✔
1232
                                
1233
                                packageName = packageName.replaceAll("/", ".");
1 ✔
1234
                                
1235
                                if (packagesProvided.add(packageName) && log.isTraceEnabled()) {
1 ✔
1236
                                        log.trace("Adding module's jarentry with package: " + packageName);
×
1237
                                }
1238
                        }
1 ✔
1239
                        
1240
                        jar.close();
1 ✔
1241
                }
1242
                catch (IOException e) {
×
1243
                        log.error("Error while reading file: " + file.getAbsolutePath(), e);
×
1244
                }
1245
                finally {
1246
                        if (jar != null) {
1 ✔
1247
                                try {
1248
                                        jar.close();
1 ✔
1249
                                }
1250
                                catch (IOException e) {
×
1251
                                        // Ignore quietly
1252
                                }
1 ✔
1253
                        }
1254
                }
1255
                
1256
                return packagesProvided;
1 ✔
1257
        }
1258
        
1259
        /**
1260
         * Get a resource as from the module's api jar. Api jar should be in the omod's lib folder.
1261
         * 
1262
         * @param jarFile omod file loaded as jar
1263
         * @param moduleId id of the module
1264
         * @param version version of the module
1265
         * @param resource name of a resource from the api jar
1266
         * @return resource as an input stream or <code>null</code> if resource cannot be loaded
1267
         * <strong>Should</strong> load file from api as input stream
1268
         * <strong>Should</strong> return null if api is not found
1269
         * <strong>Should</strong> return null if file is not found in api
1270
         */
1271
        public static InputStream getResourceFromApi(JarFile jarFile, String moduleId, String version, String resource) {
1272
                String apiLocation = "lib/" + moduleId + "-api-" + version + ".jar";
1 ✔
1273
                return getResourceFromInnerJar(jarFile, apiLocation, resource);
1 ✔
1274
        }
1275
        
1276
        /**
1277
         * Load resource from a jar inside a jar.
1278
         * 
1279
         * @param outerJarFile jar file that contains a jar file
1280
         * @param innerJarFileLocation inner jar file location relative to the outer jar
1281
         * @param resource path to a resource relative to the inner jar
1282
         * @return resource from the inner jar as an input stream or <code>null</code> if resource cannot be loaded
1283
         */
1284
        private static InputStream getResourceFromInnerJar(JarFile outerJarFile, String innerJarFileLocation, String resource) {
1285
                File tempFile = null;
1 ✔
1286
                FileOutputStream tempOut = null;
1 ✔
1287
                JarFile innerJarFile = null;
1 ✔
1288
                InputStream innerInputStream = null;
1 ✔
1289
                try {
1290
                        tempFile = File.createTempFile("tempFile", "jar");
1 ✔
1291
                        tempOut = new FileOutputStream(tempFile);
1 ✔
1292
                        ZipEntry innerJarFileEntry = outerJarFile.getEntry(innerJarFileLocation);
1 ✔
1293
                        if (innerJarFileEntry != null) {
1 ✔
1294
                                IOUtils.copy(outerJarFile.getInputStream(innerJarFileEntry), tempOut);
1 ✔
1295
                                innerJarFile = new JarFile(tempFile);
1 ✔
1296
                                ZipEntry targetEntry = innerJarFile.getEntry(resource);
1 ✔
1297
                                if (targetEntry != null) {
1 ✔
1298
                                        // clone InputStream to make it work after the innerJarFile is closed
1299
                                        innerInputStream = innerJarFile.getInputStream(targetEntry);
1 ✔
1300
                                        byte[] byteArray = IOUtils.toByteArray(innerInputStream);
1 ✔
1301
                                        return new ByteArrayInputStream(byteArray);
1 ✔
1302
                                }
1303
                        }
1304
                }
1305
                catch (IOException e) {
×
1306
                        log.error("Unable to get '" + resource + "' from '" + innerJarFileLocation + "' of '" + outerJarFile.getName()
×
1307
                                + "'", e);
1308
                }
1309
                finally {
1310
                        IOUtils.closeQuietly(tempOut);
1 ✔
1311
                        IOUtils.closeQuietly(innerInputStream);
1 ✔
1312

1313
                        // close inner jar file before attempting to delete temporary file
1314
                        try {
1315
                                if (innerJarFile != null) {
1 ✔
1316
                                        innerJarFile.close();
1 ✔
1317
                                }
1318
                        }
1319
                        catch (IOException e) {
×
1320
                                log.warn("Unable to close inner jarfile: " + innerJarFile, e);
×
1321
                        }
1 ✔
1322

1323
                        // delete temporary file
1324
                        if (tempFile != null && !tempFile.delete()) {
1 ✔
1325
                                log.warn("Could not delete temporary jarfile: " + tempFile);
×
1326
                        }
1327
                }
1328
                return null;
1 ✔
1329
        }
1330
        
1331
        /**
1332
         * Gets the root folder of a module's sources during development
1333
         * 
1334
         * @param moduleId the module id
1335
         * @return the module's development folder is specified, else null
1336
         */
1337
        public static File getDevelopmentDirectory(String moduleId) {
1338
                String directory = System.getProperty(moduleId + ".development.directory");
1 ✔
1339
                if (StringUtils.isNotBlank(directory)) {
1 ✔
1340
                        return new File(directory);
×
1341
                }
1342
                
1343
                return null;
1 ✔
1344
        }
1345
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc