• 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

93.82
/api/src/main/java/org/openmrs/module/ModuleFileParser.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 javax.xml.parsers.DocumentBuilder;
13
import javax.xml.parsers.DocumentBuilderFactory;
14
import javax.xml.parsers.ParserConfigurationException;
15
import java.io.ByteArrayOutputStream;
16
import java.io.File;
17
import java.io.FileOutputStream;
18
import java.io.IOException;
19
import java.io.InputStream;
20
import java.io.StringReader;
21
import java.nio.charset.StandardCharsets;
22
import java.util.ArrayList;
23
import java.util.Collection;
24
import java.util.HashMap;
25
import java.util.HashSet;
26
import java.util.IdentityHashMap;
27
import java.util.List;
28
import java.util.Map;
29
import java.util.Objects;
30
import java.util.Set;
31
import java.util.jar.JarFile;
32
import java.util.regex.Matcher;
33
import java.util.regex.Pattern;
34
import java.util.zip.ZipEntry;
35

36
import org.apache.commons.lang3.StringUtils;
37
import org.openmrs.GlobalProperty;
38
import org.openmrs.Privilege;
39
import org.openmrs.api.context.Context;
40
import org.openmrs.customdatatype.CustomDatatype;
41
import org.openmrs.messagesource.MessageSourceService;
42
import org.openmrs.util.OpenmrsClassLoader;
43
import org.openmrs.util.OpenmrsUtil;
44
import org.slf4j.Logger;
45
import org.slf4j.LoggerFactory;
46
import org.w3c.dom.Attr;
47
import org.w3c.dom.Document;
48
import org.w3c.dom.Element;
49
import org.w3c.dom.Node;
50
import org.w3c.dom.NodeList;
51
import org.xml.sax.InputSource;
52

53
import static org.openmrs.util.XmlUtils.createDocumentBuilder;
54

55
/**
56
 * This class will parse an OpenMRS module, specifically its {@code config.xml} file into a {@link org.openmrs.module.Module} object.
57
 * <p>Typical usage is:
58
 * <ol>
59
 * <li>Create a {@code ModuleFileParser} with {@link #ModuleFileParser(MessageSourceService)}.
60
 * <li>Parse the module by passing the file to {@link #parse(File)}.</li>
61
 * </ol>
62
 * Note that the parser does not validate the {@code config.xml} file against the document type definition's (DTD).
63
 */
64
public class ModuleFileParser {
65
        
66
        private static final Logger log = LoggerFactory.getLogger(ModuleFileParser.class);
1 ✔
67

68
        private static final String MODULE_CONFIG_XML_FILENAME = "config.xml";
69

70
        private static final String OPENMRS_MODULE_FILE_EXTENSION = ".omod";
71
        
72
        //https://resources.openmrs.org/doctype/config-1.5.dtd
73
        private static final Pattern OPENMRS_DTD_SYSTEM_ID_PATTERN = Pattern.compile("https?://resources.openmrs.org/doctype/(?<config>config-[0-9.]+\\.dtd)");
1 ✔
74
        
75
        private static final Pattern MODULE_ID_SEGMENT_PATTERN = Pattern.compile("[A-Za-z0-9_-]+");
1 ✔
76
        
77
        /**
78
         * List out all of the possible version numbers for config files that openmrs has DTDs for.
79
         * These are usually stored at http://resources.openmrs.org/doctype/config-x.x.dt
80
         */
81
        private static List<String> validConfigVersions = new ArrayList<>();
1 ✔
82
        
83
        static {
84
                validConfigVersions.add("1.0");
1 ✔
85
                validConfigVersions.add("1.1");
1 ✔
86
                validConfigVersions.add("1.2");
1 ✔
87
                validConfigVersions.add("1.3");
1 ✔
88
                validConfigVersions.add("1.4");
1 ✔
89
                validConfigVersions.add("1.5");
1 ✔
90
                validConfigVersions.add("1.6");
1 ✔
91
                validConfigVersions.add("1.7");
1 ✔
92
                validConfigVersions.add("2.0");
1 ✔
93
        }
1 ✔
94
        
95
        // TODO - remove this field once ModuleFileParser(File), ModuleFileParser(InputStream) are removed.
96
        // There is no need to keep the file as state since moduleFileParser.parse(File) does not need it.
97
        // this is also why all private methods that need access to the file for parsing or error message get it as a parameter
98
        private File moduleFile;
99

100
        private MessageSourceService messageSourceService;
101

102
        /**
103
         * Creates a ModuleFileParser.
104
         *
105
         * @param messageSourceService the message source used for error messages
106
         * @since 2.2.0
107
         */
108
        public ModuleFileParser(MessageSourceService messageSourceService) {
1 ✔
109
                this.messageSourceService = Objects.requireNonNull(messageSourceService, "messageSourceService must not be null");
1 ✔
110
        }
1 ✔
111
        
112
        /**
113
         * Constructor
114
         *
115
         * @param moduleFile the module (jar)file that will be parsed
116
         * @deprecated since 2.2.0 use {@link #ModuleFileParser(MessageSourceService)}
117
         */
118
        @Deprecated
119
        public ModuleFileParser(File moduleFile) {
1 ✔
120
                this.messageSourceService = Context.getMessageSourceService();
1 ✔
121
                validateFileIsNotNull(moduleFile);
1 ✔
122
                validateFileHasModuleFileExtension(moduleFile);
×
UNCOV
123
                this.moduleFile = moduleFile;
×
UNCOV
124
        }
×
125

126
        private void validateFileIsNotNull(File moduleFile) {
127
                if (moduleFile == null) {
1 ✔
128
                        throw new ModuleException(messageSourceService.getMessage("Module.error.fileCannotBeNull"));
1 ✔
129
                }
130
        }
1 ✔
131

132
        private void validateFileHasModuleFileExtension(File moduleFile) {
133
                if (!moduleFile.getName().endsWith(OPENMRS_MODULE_FILE_EXTENSION)) {
1 ✔
134
                        throw new ModuleException(messageSourceService.getMessage("Module.error.invalidFileExtension"),
1 ✔
135
                                moduleFile.getName());
1 ✔
136
                }
137
        }
1 ✔
138

139
        /**
140
         * Convenience constructor to parse the given inputStream file into an omod. <br>
141
         * This copies the stream into a temporary file just so things can be parsed.<br>
142
         *
143
         * @param inputStream the inputStream pointing to an omod file
144
         * @deprecated since 2.2.0 use {@link #ModuleFileParser(MessageSourceService)}
145
         */
146
        @Deprecated
147
        public ModuleFileParser(InputStream inputStream) {
1 ✔
148
                this.messageSourceService = Context.getMessageSourceService();
1 ✔
149
                this.moduleFile = createTempFile("moduleUpgrade", OPENMRS_MODULE_FILE_EXTENSION);
1 ✔
UNCOV
150
                copyInputStreamToFile(inputStream, this.moduleFile);
×
UNCOV
151
        }
×
152

153
        /**
154
         * Parses the given {@code InputStream} of an OpenMRS module into a {@code Module}.
155
         * This copies the stream into a temporary file and close given {@code InputStream}.
156
         *
157
         * @param inputStream the inputStream pointing to an omod file
158
         * @since 2.2.0
159
         */
160
        public Module parse(InputStream inputStream) {
161
                File moduleFile = createTempFile("moduleUpgrade", OPENMRS_MODULE_FILE_EXTENSION);
1 ✔
162
                copyInputStreamToFile(inputStream, moduleFile);
1 ✔
163
                return parse(moduleFile);
1 ✔
164
        }
165

166
        private File createTempFile(String prefix, String suffix) {
167
                File file;
168
                try {
169
                        file = File.createTempFile(prefix, suffix);
1 ✔
170
                }
UNCOV
171
                catch (IOException e) {
×
UNCOV
172
                        throw new ModuleException(messageSourceService.getMessage("Module.error.cannotCreateFile"), e);
×
173
                }
1 ✔
174
                return file;
1 ✔
175
        }
176

177
        private void copyInputStreamToFile(InputStream inputStream, File file) {
178
                try (FileOutputStream outputStream = new FileOutputStream(file)) {
1 ✔
179
                        OpenmrsUtil.copyFile(inputStream, outputStream);
1 ✔
180
                }
181
                catch (IOException e) {
1 ✔
182
                        throw new ModuleException(messageSourceService.getMessage("Module.error.cannotCreateFile"), e);
1 ✔
183
                }
184
                finally {
185
                        try {
186
                                inputStream.close();
1 ✔
187
                        }
188
                        catch (Exception e) { /* pass */}
1 ✔
189
                }
190
        }
1 ✔
191

192
        /**
193
         * This constructor was created for testing purposes and is now deprecated.
194
         * DO NOT USE.
195
         *
196
         * @deprecated since 2.2.0 use {@link #ModuleFileParser(MessageSourceService)}
197
         */
198
        @Deprecated
199
        ModuleFileParser() {
1 ✔
200
        }
1 ✔
201

202
        /**
203
         * Get the module.
204
         * If you use this method only do so together with {@link #ModuleFileParser(File)} or {@link #ModuleFileParser(InputStream)}.
205
         * Best use {@link #ModuleFileParser(MessageSourceService)} and {@link #parse(File)}
206
         * since this method is deprecated.
207
         *
208
         * @return new module object
209
         * @deprecated since 2.2.0 use {@link #parse(File)}
210
         */
211
        @Deprecated
212
        public Module parse() throws ModuleException {
UNCOV
213
                return parse(this.moduleFile);
×
214
        }
215

216
        /**
217
         * Get the module from an OpenMRS module file.
218
         * 
219
         * @param moduleFile the module file to be parsed
220
         * @return new module object
221
         * @since 2.2.0
222
         */
223
        public Module parse(File moduleFile) {
224
                validateFileIsNotNull(moduleFile);
1 ✔
225
                validateFileHasModuleFileExtension(moduleFile);
1 ✔
226
                return createModule(getModuleConfigXml(moduleFile), moduleFile);
1 ✔
227
        }
228

229
        private Document getModuleConfigXml(File moduleFile) {
230
                Document config;
231
                try (JarFile jarfile = new JarFile(moduleFile)) {
1 ✔
232
                        ZipEntry configEntry = getConfigXmlZipEntry(jarfile, moduleFile);
1 ✔
233
                        config = parseConfigXml(jarfile, configEntry, moduleFile);
1 ✔
234
                }
235
                catch (IOException e) {
1 ✔
236
                        throw new ModuleException(messageSourceService.getMessage("Module.error.cannotGetJarFile"),
1 ✔
237
                                moduleFile.getName(), e);
1 ✔
238
                }
1 ✔
239
                return config;
1 ✔
240
        }
241

242
        private ZipEntry getConfigXmlZipEntry(JarFile jarfile, File moduleFile) {
243
                ZipEntry config = jarfile.getEntry(MODULE_CONFIG_XML_FILENAME);
1 ✔
244
                if (config == null) {
1 ✔
245
                        throw new ModuleException(messageSourceService.getMessage("Module.error.noConfigFile"),
1 ✔
246
                                moduleFile.getName());
1 ✔
247
                }
248
                return config;
1 ✔
249
        }
250

251
        private Document parseConfigXml(JarFile jarfile, ZipEntry configEntry, File moduleFile) {
252
                Document config;
253
                try (InputStream configStream = jarfile.getInputStream(configEntry)) {
1 ✔
254
                        config = parseConfigXmlStream(configStream, moduleFile);
1 ✔
255
                }
256
                catch (IOException e) {
×
UNCOV
257
                        throw new ModuleException(messageSourceService.getMessage(
×
UNCOV
258
                                "Module.error.cannotGetConfigFileStream"), moduleFile.getName(), e);
×
259
                }
1 ✔
260
                return config;
1 ✔
261
        }
262

263
        private Document parseConfigXmlStream(InputStream configStream, File moduleFile) {
264
                Document config;
265
                try {
266
                        DocumentBuilder db = newDocumentBuilder();
1 ✔
267
                        config = db.parse(configStream);
1 ✔
268
                }
269
                catch (Exception e) {
1 ✔
270
                        log.error("Error parsing " + MODULE_CONFIG_XML_FILENAME + ": " + configStream.toString(), e);
1 ✔
271

272
                        String output = "";
1 ✔
273
                        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
1 ✔
274
                                // Now copy bytes from the URL to the output stream
275
                                byte[] buffer = new byte[4096];
1 ✔
276
                                int bytesRead;
UNCOV
277
                                while ((bytesRead = configStream.read(buffer)) != -1) {
×
278
                                        out.write(buffer, 0, bytesRead);
×
279
                                }
UNCOV
280
                                output = out.toString(StandardCharsets.UTF_8.name());
×
281
                        }
282
                        catch (Exception e2) {
1 ✔
283
                                log.warn("Another error parsing " + MODULE_CONFIG_XML_FILENAME, e2);
1 ✔
UNCOV
284
                        }
×
285

286
                        log.error("{} content: {}", MODULE_CONFIG_XML_FILENAME, output);
1 ✔
287
                        throw new ModuleException(messageSourceService.getMessage("Module.error.cannotParseConfigFile"),
1 ✔
288
                                moduleFile.getName(), e);
1 ✔
289
                }
1 ✔
290
                return config;
1 ✔
291
        }
292

293
        private DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
294
                DocumentBuilder db = createDocumentBuilder();;
1 ✔
295

296
                // When asked to resolve external entities (such as a
297
                // DTD) we return an InputSource
298
                // with no data at the end, causing the parser to ignore
299
                // the DTD.
300
                db.setEntityResolver((publicId, systemId) -> {
1 ✔
UNCOV
301
                        Matcher dtdMatcher = OPENMRS_DTD_SYSTEM_ID_PATTERN.matcher(systemId);
×
UNCOV
302
                        if (dtdMatcher.matches()) {
×
UNCOV
303
                                String dtdFile = dtdMatcher.group("config");
×
UNCOV
304
                                return new InputSource(OpenmrsClassLoader.getInstance().getResourceAsStream("org/openmrs/module/dtd/" + dtdFile));
×
305
                        }
UNCOV
306
                        return new InputSource(new StringReader(""));
×
307
                });
308
                
309
                return db;
1 ✔
310
        }
311

312
        private Module createModule(Document config, File moduleFile) {
313
                Element configRoot = config.getDocumentElement();
1 ✔
314

315
                String configVersion = ensureValidModuleConfigVersion(configRoot, moduleFile);
1 ✔
316
                
317
                String name = ensureNonEmptyName(configRoot, moduleFile);
1 ✔
318
                String moduleId = ensureValidId(configRoot, name);
1 ✔
319
                String packageName = ensureNonEmptyPackage(configRoot, name);
1 ✔
320
                
321
                String author = getElementTrimmed(configRoot, "author");
1 ✔
322
                String desc = getElementTrimmed(configRoot, "description");
1 ✔
323
                String version = getElementTrimmed(configRoot, "version");
1 ✔
324

325
                Module module = new Module(name, moduleId, packageName, author, desc, version, configVersion);
1 ✔
326

327
                module.setActivatorName(getElementTrimmed(configRoot, "activator"));
1 ✔
328
                module.setRequireDatabaseVersion(getElementTrimmed(configRoot, "require_database_version"));
1 ✔
329
                module.setRequireOpenmrsVersion(getElementTrimmed(configRoot, "require_version"));
1 ✔
330
                module.setUpdateURL(getElementTrimmed(configRoot, "updateURL"));
1 ✔
331

332
                module.setRequiredModulesMap(extractRequiredModules(configRoot));
1 ✔
333
                module.setAwareOfModulesMap(extractAwareOfModules(configRoot));
1 ✔
334
                module.setStartBeforeModulesMap(extractStartBeforeModules(configRoot));
1 ✔
335
                module.setAdvicePoints(extractAdvice(configRoot, module));
1 ✔
336
                module.setExtensionNames(extractExtensions(configRoot));
1 ✔
337
                module.setPrivileges(extractPrivileges(configRoot));
1 ✔
338
                module.setGlobalProperties(extractGlobalProperties(configRoot));
1 ✔
339
                module.setMappingFiles(extractMappingFiles(configRoot));
1 ✔
340
                module.setPackagesWithMappedClasses(extractPackagesWithMappedClasses(configRoot));
1 ✔
341
                module.setMandatory(extractMandatory(configRoot, configVersion));
1 ✔
342
                module.setConditionalResources(extractConditionalResources(configRoot));
1 ✔
343

344
                module.setConfig(config);
1 ✔
345
                module.setFile(moduleFile);
1 ✔
346

347
                return module;
1 ✔
348
        }
349

350
        private String ensureValidModuleConfigVersion(Element configRoot, File moduleFile) {
351
                String configVersion = configRoot.getAttribute("configVersion").trim();
1 ✔
352
                validateModuleConfigVersion(configVersion, moduleFile);
1 ✔
353
                return configVersion;
1 ✔
354
        }
355

356
        private void validateModuleConfigVersion(String version, File moduleFile) {
357
                if (!validConfigVersions.contains(version)) {
1 ✔
358
                        throw new ModuleException(Context.getMessageSourceService().getMessage("Module.error.invalidConfigVersion",
1 ✔
359
                                new Object[] { version, String.join(", ", validConfigVersions) }, Context.getLocale()),
1 ✔
360
                                moduleFile.getName());
1 ✔
361
                }
362
        }
1 ✔
363

364
        private String ensureNonEmptyName(Element configRoot, File moduleFile) {
365
                return getTrimmedElementOrFail(configRoot, "name", "Module.error.nameCannotBeEmpty", moduleFile.getName());
1 ✔
366
        }
367

368
        private String ensureValidId(Element configRoot, String name) {
369
                String moduleId = getTrimmedElementOrFail(configRoot, "id", "Module.error.idCannotBeEmpty", name);
1 ✔
370
                if (!isValidModuleId(moduleId)) {
1 ✔
371
                        throw new ModuleException(messageSourceService.getMessage("Module.error.idInvalid") + ": " + moduleId, name);
1 ✔
372
                }
373
                return moduleId;
1 ✔
374
        }
375

376
        private static boolean isValidModuleId(String moduleId) {
377
                if (moduleId.startsWith("_") || moduleId.startsWith("-")) {
1 ✔
378
                        return false;
1 ✔
379
                }
380
                for (String segment : moduleId.split("\\.", -1)) {
1 ✔
381
                        if (!MODULE_ID_SEGMENT_PATTERN.matcher(segment).matches()) {
1 ✔
382
                                return false;
1 ✔
383
                        }
384
                }
385
                return true;
1 ✔
386
        }
387

388
        private String ensureNonEmptyPackage(Element configRoot, String name) {
389
                return getTrimmedElementOrFail(configRoot, "package", "Module.error.packageCannotBeEmpty", name);
1 ✔
390
        }
391

392
        /**
393
         * load in required modules list
394
         *
395
         * @return map from module package name to required version
396
         * @since 1.5
397
         */
398
        private Map<String, String> extractRequiredModules(Element configRoot) {
399
                return extractModulesWithVersionAttribute(configRoot, "require_module", "require_modules");
1 ✔
400
        }
401
        
402
        /**
403
         * load in list of modules we are aware of.
404
         *
405
         * @return map from module package name to aware of version
406
         * @since 1.9
407
         */
408
        private Map<String, String> extractAwareOfModules(Element configRoot) {
409
                return extractModulesWithVersionAttribute(configRoot, "aware_of_module", "aware_of_modules");
1 ✔
410
        }
411
        
412
        private Map<String, String> extractStartBeforeModules(Element configRoot) {
413
                Map<String, String> result = extractModulesWithVersionAttribute(configRoot, "module", "start_before_modules");
1 ✔
414
                result.putAll(extractModulesWithVersionAttribute(configRoot, "start_before_module", "start_before_modules"));
1 ✔
415
                return result;
1 ✔
416
        }
417

418
        private Map<String, String> extractModulesWithVersionAttribute(Element configRoot, String elementName,
419
                String elementParentName) {
420
                
421
                NodeList parents = configRoot.getElementsByTagName(elementParentName);
1 ✔
422
                
423
                Map<String, String> result = new HashMap<>();
1 ✔
424
                if (parents.getLength() == 0) {
1 ✔
425
                        return result;
1 ✔
426
                }
427
                
428
                Element firstParent = (Element) parents.item(0);
1 ✔
429
                NodeList children = firstParent.getElementsByTagName(elementName);
1 ✔
430
                
431
                int i = 0;
1 ✔
432
                while (i < children.getLength()) {
1 ✔
433
                        Element child = (Element) children.item(i);
1 ✔
434
                        Attr versionAttribute = child.getAttributeNode("version");
1 ✔
435
                        String version = versionAttribute == null ? null : versionAttribute.getValue();
1 ✔
436
                        result.put(child.getTextContent().trim(), version);
1 ✔
437
                        i++;
1 ✔
438
                }
1 ✔
439
                return result;
1 ✔
440
        }
441

442
        private List<AdvicePoint> extractAdvice(Element configRoot, Module module) {
443

444
                List<AdvicePoint> result = new ArrayList<>();
1 ✔
445

446
                NodeList advice = configRoot.getElementsByTagName("advice");
1 ✔
447
                if (advice.getLength() == 0) {
1 ✔
448
                        return result;
1 ✔
449
                }
450

451
                log.debug("# advice: {}", advice.getLength());
1 ✔
452
                int i = 0;
1 ✔
453
                while (i < advice.getLength()) {
1 ✔
454
                        Element element = (Element) advice.item(i);
1 ✔
455
                        String point = getElementTrimmed(element, "point");
1 ✔
456
                        String adviceClass = getElementTrimmed(element, "class");
1 ✔
457
                        log.debug("advice point: {}, class: {}", point, adviceClass);
1 ✔
458

459
                        if (point.isEmpty() || adviceClass.isEmpty()) {
1 ✔
460
                                log.warn("'point' and 'class' are required for advice. Given '{}' and '{}'", point, adviceClass);
1 ✔
461
                        } else {
462
                                result.add(new AdvicePoint(module, point, adviceClass));
1 ✔
463
                        }
464
                        i++;
1 ✔
465
                }
1 ✔
466

467
                return result;
1 ✔
468
        }
469

470
        private Map<String, String> extractExtensions(Element configRoot) {
471

472
                Map<String, String> result = new IdentityHashMap<>();
1 ✔
473

474
                NodeList extensions = configRoot.getElementsByTagName("extension");
1 ✔
475
                if (extensions.getLength() == 0) {
1 ✔
476
                        return result;
1 ✔
477
                }
478

479
                log.debug("# extensions: {}", extensions.getLength());
1 ✔
480
                int i = 0;
1 ✔
481
                while (i < extensions.getLength()) {
1 ✔
482
                        Element element = (Element) extensions.item(i);
1 ✔
483
                        String point = getElementTrimmed(element, "point");
1 ✔
484
                        String extClass = getElementTrimmed(element, "class");
1 ✔
485
                        log.debug("extension point: {}, class: {}", point, extClass);
1 ✔
486

487
                        if (point.isEmpty() || extClass.isEmpty()) {
1 ✔
488
                                log.warn("'point' and 'class' are required for extensions. Given '{}' and '{}'", point, extClass);
1 ✔
489
                        } else if (point.contains(Extension.EXTENSION_ID_SEPARATOR)) {
1 ✔
490
                                log.warn("Point id contains illegal character: '{}'", Extension.EXTENSION_ID_SEPARATOR);
1 ✔
491
                        } else {
492
                                result.put(point, extClass);
1 ✔
493
                        }
494
                        i++;
1 ✔
495
                }
1 ✔
496
                return result;
1 ✔
497
        }
498

499
        private List<Privilege> extractPrivileges(Element configRoot) {
500

501
                List<Privilege> result = new ArrayList<>();
1 ✔
502

503
                NodeList privileges = configRoot.getElementsByTagName("privilege");
1 ✔
504
                if (privileges.getLength() == 0) {
1 ✔
505
                        return result;
1 ✔
506
                }
507

508
                log.debug("# privileges: {}", privileges.getLength());
1 ✔
509
                int i = 0;
1 ✔
510
                while (i < privileges.getLength()) {
1 ✔
511
                        Element element = (Element) privileges.item(i);
1 ✔
512
                        String name = getElementTrimmed(element, "name");
1 ✔
513
                        String description = getElementTrimmed(element, "description");
1 ✔
514
                        log.debug("extension name: {}, description: {}", name, description);
1 ✔
515

516
                        if (name.isEmpty() || description.isEmpty()) {
1 ✔
517
                                log.warn("'name' and 'description' are required for privilege. Given '{}' and '{}'", name, description);
1 ✔
518
                        } else {
519
                                result.add(new Privilege(name, description));
1 ✔
520
                        }
521
                        i++;
1 ✔
522
                }
1 ✔
523
                return result;
1 ✔
524
        }
525
        
526
        private List<GlobalProperty> extractGlobalProperties(Element configRoot) {
527
                
528
                List<GlobalProperty> result = new ArrayList<>();
1 ✔
529
                
530
                NodeList propNodes = configRoot.getElementsByTagName("globalProperty");
1 ✔
531
                if (propNodes.getLength() == 0) {
1 ✔
532
                        return result;
1 ✔
533
                }
534
                
535
                log.debug("# global properties: {}", propNodes.getLength());
1 ✔
536
                int i = 0;
1 ✔
537
                while (i < propNodes.getLength()) {
1 ✔
538
                        Element gpElement = (Element) propNodes.item(i);
1 ✔
539
                        GlobalProperty globalProperty = extractGlobalProperty(gpElement);
1 ✔
540
                        
541
                        if (globalProperty != null) {
1 ✔
542
                                result.add(globalProperty);
1 ✔
543
                        }
544
                        
545
                        i++;
1 ✔
546
                }
1 ✔
547
                
548
                return result;
1 ✔
549
        }
550

551
        private GlobalProperty extractGlobalProperty(Element element) {
552
                String property = getElementTrimmed(element, "property");
1 ✔
553
                String defaultValue = getElementTrimmed(element, "defaultValue");
1 ✔
554
                String description = removeTabsAndTrim(getElementTrimmed(element, "description"));
1 ✔
555
                String datatypeClassname = getElementTrimmed(element, "datatypeClassname");
1 ✔
556
                String datatypeConfig = getElementTrimmed(element, "datatypeConfig");
1 ✔
557
                String viewPrivilege = removeTabsAndTrim(getElementTrimmed(element, "viewPrivilege"));
1 ✔
558
                String editPrivilege = removeTabsAndTrim(getElementTrimmed(element, "editPrivilege"));
1 ✔
559
                String deletePrivilege = removeTabsAndTrim(getElementTrimmed(element, "deletePrivilege"));
1 ✔
560
                
561
                log.debug("property: {}, defaultValue: {}", property, defaultValue);
1 ✔
562
                log.debug("description: {}, datatypeClassname: {}", description, datatypeClassname);
1 ✔
563
                log.debug("datatypeConfig: {}", datatypeConfig);
1 ✔
564
                log.debug("viewPrivilege: {}, editPrivilege: {}, deletePrivilege: {}", viewPrivilege, editPrivilege, deletePrivilege);
1 ✔
565

566
                return createGlobalProperty(property, defaultValue, description, datatypeClassname,
1 ✔
567
                        datatypeConfig, viewPrivilege, editPrivilege, deletePrivilege);
568
        }
569

570
        private String removeTabsAndTrim(String string) {
571
                return string.replaceAll("        ", "").trim();
1 ✔
572
        }
573

574
        private GlobalProperty createGlobalProperty(String property, String defaultValue, String description,
575
                String datatypeClassname, String datatypeConfig, String viewPrivilege, String editPrivilege, String deletePrivilege) {
576

577
                GlobalProperty globalProperty = null;
1 ✔
578
                if (property.isEmpty()) {
1 ✔
579
                        log.warn("'property' is required for global properties. Given '{}'", property);
1 ✔
580
                        return globalProperty;
1 ✔
581
                }
582

583
                if (!datatypeClassname.isEmpty()) {
1 ✔
584
                        globalProperty = createGlobalPropertyWithDatatype(property, defaultValue, description, datatypeClassname,
1 ✔
585
                                datatypeConfig);
586
                } else {
587
                        globalProperty = new GlobalProperty(property, defaultValue, description);
1 ✔
588
                }
589
                
590
                if (!viewPrivilege.isEmpty()) {
1 ✔
591
                        globalProperty.setViewPrivilege(new Privilege(viewPrivilege));
1 ✔
592
                }
593
                if (!editPrivilege.isEmpty()) {
1 ✔
594
                        globalProperty.setEditPrivilege(new Privilege(editPrivilege));
1 ✔
595
                }
596
                if (!deletePrivilege.isEmpty()) {
1 ✔
597
                        globalProperty.setDeletePrivilege(new Privilege(deletePrivilege));
1 ✔
598
                }
599
                
600
                return globalProperty;
1 ✔
601
        }
602

603
        private GlobalProperty createGlobalPropertyWithDatatype(String property, String defaultValue, String description,
604
                String datatypeClassname, String datatypeConfig) {
605
                GlobalProperty globalProperty = null;
1 ✔
606
                try {
607
                        Class<CustomDatatype<?>> datatypeClazz = (Class<CustomDatatype<?>>) Class.forName(datatypeClassname)
1 ✔
608
                                .asSubclass(CustomDatatype.class);
1 ✔
609
                        globalProperty = new GlobalProperty(property, defaultValue, description, datatypeClazz, datatypeConfig);
1 ✔
610
                }
611
                catch (ClassCastException ex) {
1 ✔
612
                        log.error("The class specified by 'datatypeClassname' (" + datatypeClassname
1 ✔
613
                                + ") must be a subtype of 'org.openmrs.customdatatype.CustomDatatype<?>'.", ex);
614
                }
615
                catch (ClassNotFoundException ex) {
1 ✔
616
                        log.error("The class specified by 'datatypeClassname' (" + datatypeClassname
1 ✔
617
                                + ") could not be found.", ex);
618
                }
1 ✔
619
                return globalProperty;
1 ✔
620
        }
621

622
        private List<String> extractMappingFiles(Element configRoot) {
623
                List<String> result = new ArrayList<>();
1 ✔
624
                splitTagContentByWhitespace(configRoot, "mappingFiles", result);
1 ✔
625
                return result;
1 ✔
626
        }
627

628
        private Set<String> extractPackagesWithMappedClasses(Element configRoot) {
629
                Set<String> result = new HashSet<>();
1 ✔
630
                splitTagContentByWhitespace(configRoot, "packagesWithMappedClasses", result);
1 ✔
631
                return result;
1 ✔
632
        }
633

634
        private Collection<String> splitTagContentByWhitespace(Element rootNode, String tag, Collection<String> result) {
635
                String content = getElement(rootNode, tag);
1 ✔
636
                for (String s : content.split("\\s")) {
1 ✔
637
                        String s2 = s.trim();
1 ✔
638
                        if (s2.length() > 0) {
1 ✔
639
                                result.add(s2);
1 ✔
640
                        }
641
                }
642
                return result;
1 ✔
643
        }
644
        
645
        private String getTrimmedElementOrFail(Element rootNode, String elementName, String errorMessageKey, String moduleName) {
646
                String element = getElementTrimmed(rootNode, elementName);
1 ✔
647
                if (element == null || element.length() == 0) {
1 ✔
648
                        throw new ModuleException(messageSourceService.getMessage(errorMessageKey),
1 ✔
649
                                moduleName);
650
                }
651
                return element;
1 ✔
652
        }
653

654
        private String getElementTrimmed(Element element, String name) {
655
                return getElement(element, name).trim();
1 ✔
656
        }
657

658
        private String getElement(Element root, String tag) {
659
                if (root.getElementsByTagName(tag).getLength() > 0) {
1 ✔
660
                        return root.getElementsByTagName(tag).item(0).getTextContent();
1 ✔
661
                }
662
                return "";
1 ✔
663
        }
664

665
        /**
666
         * Looks for the "<mandatory>" element in the config file and returns true if the value is
667
         * exactly "true".
668
         */
669
        private boolean extractMandatory(Element configRoot, String configVersion) {
670
                if (Double.parseDouble(configVersion) >= 1.3) {
1 ✔
671
                        String mandatory = getElementTrimmed(configRoot, "mandatory");
1 ✔
672
                        return "true".equalsIgnoreCase(mandatory);
1 ✔
673
                }
674

675
                // this module has an older config file
676
                return false;
1 ✔
677
        }
678

679
        /**
680
         * Parses conditionalResources tag.
681
         *
682
         * <strong>Should</strong> parse openmrsVersion and modules
683
         * <strong>Should</strong> parse conditionalResource with whitespace
684
         * <strong>Should</strong> throw exception if multiple conditionalResources tags found
685
         * <strong>Should</strong> throw exception if conditionalResources contains invalid tag
686
         * <strong>Should</strong> throw exception if path is blank
687
         */
688
        List<ModuleConditionalResource> extractConditionalResources(Element configRoot) {
689
                List<ModuleConditionalResource> conditionalResources = new ArrayList<>();
1 ✔
690

691
                NodeList parentConditionalResources = configRoot.getElementsByTagName("conditionalResources");
1 ✔
692

693
                if (parentConditionalResources.getLength() == 0) {
1 ✔
694
                        return new ArrayList<>();
1 ✔
695
                } else if (parentConditionalResources.getLength() > 1) {
1 ✔
696
                        throw new IllegalArgumentException("Found multiple conditionalResources tags. There can be only one.");
1 ✔
697
                }
698

699
                NodeList conditionalResourcesNode = parentConditionalResources.item(0).getChildNodes();
1 ✔
700

701
                for (int i = 0; i < conditionalResourcesNode.getLength(); i++) {
1 ✔
702
                        Node conditionalResourceNode = conditionalResourcesNode.item(i);
1 ✔
703

704
                        if ("#text".equals(conditionalResourceNode.getNodeName())) {
1 ✔
705
                                //ignore text and whitespace in particular
706
                                continue;
1 ✔
707
                        }
708

709
                        if (!"conditionalResource".equals(conditionalResourceNode.getNodeName())) {
1 ✔
710
                                throw new IllegalArgumentException("Found the " + conditionalResourceNode.getNodeName()
1 ✔
711
                                        + " node under conditionalResources. Only conditionalResource is allowed.");
712
                        }
713

714
                        NodeList resourceElements = conditionalResourceNode.getChildNodes();
1 ✔
715

716
                        ModuleConditionalResource resource = new ModuleConditionalResource();
1 ✔
717
                        conditionalResources.add(resource);
1 ✔
718

719
                        for (int j = 0; j < resourceElements.getLength(); j++) {
1 ✔
720
                                Node resourceElement = resourceElements.item(j);
1 ✔
721

722
                                if ("path".equals(resourceElement.getNodeName())) {
1 ✔
723
                                        if (StringUtils.isBlank(resourceElement.getTextContent())) {
1 ✔
724
                                                throw new IllegalArgumentException("The path of a conditional resource must not be blank");
1 ✔
725
                                        }
726
                                        resource.setPath(resourceElement.getTextContent());
1 ✔
727
                                } else if ("openmrsVersion".equals(resourceElement.getNodeName())) {
1 ✔
728
                                        if (StringUtils.isBlank(resource.getOpenmrsPlatformVersion())) {
1 ✔
729
                                                resource.setOpenmrsPlatformVersion(resourceElement.getTextContent());
1 ✔
730
                                        }
731
                                } else if ("openmrsPlatformVersion".equals(resourceElement.getNodeName())) {
1 ✔
UNCOV
732
                                        resource.setOpenmrsPlatformVersion(resourceElement.getTextContent());
×
733
                                } else if ("modules".equals(resourceElement.getNodeName())) {
1 ✔
734
                                        NodeList modulesNode = resourceElement.getChildNodes();
1 ✔
735
                                        for (int k = 0; k < modulesNode.getLength(); k++) {
1 ✔
736
                                                Node moduleNode = modulesNode.item(k);
1 ✔
737
                                                if ("module".equals(moduleNode.getNodeName())) {
1 ✔
738
                                                        NodeList moduleElements = moduleNode.getChildNodes();
1 ✔
739

740
                                                        ModuleConditionalResource.ModuleAndVersion module = new ModuleConditionalResource.ModuleAndVersion();
1 ✔
741
                                                        resource.getModules().add(module);
1 ✔
742
                                                        for (int m = 0; m < moduleElements.getLength(); m++) {
1 ✔
743
                                                                Node moduleElement = moduleElements.item(m);
1 ✔
744

745
                                                                if ("moduleId".equals(moduleElement.getNodeName())) {
1 ✔
746
                                                                        module.setModuleId(moduleElement.getTextContent());
1 ✔
747
                                                                } else if ("version".equals(moduleElement.getNodeName())) {
1 ✔
748
                                                                        module.setVersion(moduleElement.getTextContent());
1 ✔
749
                                                                }
750
                                                        }
751
                                                }
752
                                        }
753
                                }
754
                        }
755
                }
756

757
                return conditionalResources;
1 ✔
758
        }
759
}
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