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

openmrs / openmrs-core / 43295168256

12 Nov 2026 03:43PM UTC coverage: 68.956% (+0.02%) from 68.932%
43295168256

push

github

ibacher
Restrict PersonAttribute hydration and type formats to permitted classes (#6799)

19 of 19 new or added lines in 2 files covered. (100.0%)

385 existing lines in 7 files now uncovered.

26426 of 38323 relevant lines covered (68.96%)

0.69 hits per line

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

93.64
/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
        /**
76
         * List out all of the possible version numbers for config files that openmrs has DTDs for.
77
         * These are usually stored at http://resources.openmrs.org/doctype/config-x.x.dt
78
         */
79
        private static List<String> validConfigVersions = new ArrayList<>();
1 ✔
80
        
81
        static {
82
                validConfigVersions.add("1.0");
1 ✔
83
                validConfigVersions.add("1.1");
1 ✔
84
                validConfigVersions.add("1.2");
1 ✔
85
                validConfigVersions.add("1.3");
1 ✔
86
                validConfigVersions.add("1.4");
1 ✔
87
                validConfigVersions.add("1.5");
1 ✔
88
                validConfigVersions.add("1.6");
1 ✔
89
                validConfigVersions.add("1.7");
1 ✔
90
                validConfigVersions.add("2.0");
1 ✔
91
        }
1 ✔
92
        
93
        // TODO - remove this field once ModuleFileParser(File), ModuleFileParser(InputStream) are removed.
94
        // There is no need to keep the file as state since moduleFileParser.parse(File) does not need it.
95
        // this is also why all private methods that need access to the file for parsing or error message get it as a parameter
96
        private File moduleFile;
97

98
        private MessageSourceService messageSourceService;
99

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

291
        private DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
292
                DocumentBuilder db = createDocumentBuilder();;
1 ✔
293

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

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

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

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

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

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

342
                module.setConfig(config);
1 ✔
343
                module.setFile(moduleFile);
1 ✔
344

345
                return module;
1 ✔
346
        }
347

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

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

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

366
        private String ensureNonEmptyId(Element configRoot, String name) {
367
                return getTrimmedElementOrFail(configRoot, "id", "Module.error.idCannotBeEmpty", name);
1 ✔
368
        }
369

370
        private String ensureNonEmptyPackage(Element configRoot, String name) {
371
                return getTrimmedElementOrFail(configRoot, "package", "Module.error.packageCannotBeEmpty", name);
1 ✔
372
        }
373

374
        /**
375
         * load in required modules list
376
         *
377
         * @return map from module package name to required version
378
         * @since 1.5
379
         */
380
        private Map<String, String> extractRequiredModules(Element configRoot) {
381
                return extractModulesWithVersionAttribute(configRoot, "require_module", "require_modules");
1 ✔
382
        }
383
        
384
        /**
385
         * load in list of modules we are aware of.
386
         *
387
         * @return map from module package name to aware of version
388
         * @since 1.9
389
         */
390
        private Map<String, String> extractAwareOfModules(Element configRoot) {
391
                return extractModulesWithVersionAttribute(configRoot, "aware_of_module", "aware_of_modules");
1 ✔
392
        }
393
        
394
        private Map<String, String> extractStartBeforeModules(Element configRoot) {
395
                Map<String, String> result = extractModulesWithVersionAttribute(configRoot, "module", "start_before_modules");
1 ✔
396
                result.putAll(extractModulesWithVersionAttribute(configRoot, "start_before_module", "start_before_modules"));
1 ✔
397
                return result;
1 ✔
398
        }
399

400
        private Map<String, String> extractModulesWithVersionAttribute(Element configRoot, String elementName,
401
                String elementParentName) {
402
                
403
                NodeList parents = configRoot.getElementsByTagName(elementParentName);
1 ✔
404
                
405
                Map<String, String> result = new HashMap<>();
1 ✔
406
                if (parents.getLength() == 0) {
1 ✔
407
                        return result;
1 ✔
408
                }
409
                
410
                Element firstParent = (Element) parents.item(0);
1 ✔
411
                NodeList children = firstParent.getElementsByTagName(elementName);
1 ✔
412
                
413
                int i = 0;
1 ✔
414
                while (i < children.getLength()) {
1 ✔
415
                        Element child = (Element) children.item(i);
1 ✔
416
                        Attr versionAttribute = child.getAttributeNode("version");
1 ✔
417
                        String version = versionAttribute == null ? null : versionAttribute.getValue();
1 ✔
418
                        result.put(child.getTextContent().trim(), version);
1 ✔
419
                        i++;
1 ✔
420
                }
1 ✔
421
                return result;
1 ✔
422
        }
423

424
        private List<AdvicePoint> extractAdvice(Element configRoot, Module module) {
425

426
                List<AdvicePoint> result = new ArrayList<>();
1 ✔
427

428
                NodeList advice = configRoot.getElementsByTagName("advice");
1 ✔
429
                if (advice.getLength() == 0) {
1 ✔
430
                        return result;
1 ✔
431
                }
432

433
                log.debug("# advice: {}", advice.getLength());
1 ✔
434
                int i = 0;
1 ✔
435
                while (i < advice.getLength()) {
1 ✔
436
                        Element element = (Element) advice.item(i);
1 ✔
437
                        String point = getElementTrimmed(element, "point");
1 ✔
438
                        String adviceClass = getElementTrimmed(element, "class");
1 ✔
439
                        log.debug("advice point: {}, class: {}", point, adviceClass);
1 ✔
440

441
                        if (point.isEmpty() || adviceClass.isEmpty()) {
1 ✔
442
                                log.warn("'point' and 'class' are required for advice. Given '{}' and '{}'", point, adviceClass);
1 ✔
443
                        } else {
444
                                result.add(new AdvicePoint(module, point, adviceClass));
1 ✔
445
                        }
446
                        i++;
1 ✔
447
                }
1 ✔
448

449
                return result;
1 ✔
450
        }
451

452
        private Map<String, String> extractExtensions(Element configRoot) {
453

454
                Map<String, String> result = new IdentityHashMap<>();
1 ✔
455

456
                NodeList extensions = configRoot.getElementsByTagName("extension");
1 ✔
457
                if (extensions.getLength() == 0) {
1 ✔
458
                        return result;
1 ✔
459
                }
460

461
                log.debug("# extensions: {}", extensions.getLength());
1 ✔
462
                int i = 0;
1 ✔
463
                while (i < extensions.getLength()) {
1 ✔
464
                        Element element = (Element) extensions.item(i);
1 ✔
465
                        String point = getElementTrimmed(element, "point");
1 ✔
466
                        String extClass = getElementTrimmed(element, "class");
1 ✔
467
                        log.debug("extension point: {}, class: {}", point, extClass);
1 ✔
468

469
                        if (point.isEmpty() || extClass.isEmpty()) {
1 ✔
470
                                log.warn("'point' and 'class' are required for extensions. Given '{}' and '{}'", point, extClass);
1 ✔
471
                        } else if (point.contains(Extension.EXTENSION_ID_SEPARATOR)) {
1 ✔
472
                                log.warn("Point id contains illegal character: '{}'", Extension.EXTENSION_ID_SEPARATOR);
1 ✔
473
                        } else {
474
                                result.put(point, extClass);
1 ✔
475
                        }
476
                        i++;
1 ✔
477
                }
1 ✔
478
                return result;
1 ✔
479
        }
480

481
        private List<Privilege> extractPrivileges(Element configRoot) {
482

483
                List<Privilege> result = new ArrayList<>();
1 ✔
484

485
                NodeList privileges = configRoot.getElementsByTagName("privilege");
1 ✔
486
                if (privileges.getLength() == 0) {
1 ✔
487
                        return result;
1 ✔
488
                }
489

490
                log.debug("# privileges: {}", privileges.getLength());
1 ✔
491
                int i = 0;
1 ✔
492
                while (i < privileges.getLength()) {
1 ✔
493
                        Element element = (Element) privileges.item(i);
1 ✔
494
                        String name = getElementTrimmed(element, "name");
1 ✔
495
                        String description = getElementTrimmed(element, "description");
1 ✔
496
                        log.debug("extension name: {}, description: {}", name, description);
1 ✔
497

498
                        if (name.isEmpty() || description.isEmpty()) {
1 ✔
499
                                log.warn("'name' and 'description' are required for privilege. Given '{}' and '{}'", name, description);
1 ✔
500
                        } else {
501
                                result.add(new Privilege(name, description));
1 ✔
502
                        }
503
                        i++;
1 ✔
504
                }
1 ✔
505
                return result;
1 ✔
506
        }
507
        
508
        private List<GlobalProperty> extractGlobalProperties(Element configRoot) {
509
                
510
                List<GlobalProperty> result = new ArrayList<>();
1 ✔
511
                
512
                NodeList propNodes = configRoot.getElementsByTagName("globalProperty");
1 ✔
513
                if (propNodes.getLength() == 0) {
1 ✔
514
                        return result;
1 ✔
515
                }
516
                
517
                log.debug("# global properties: {}", propNodes.getLength());
1 ✔
518
                int i = 0;
1 ✔
519
                while (i < propNodes.getLength()) {
1 ✔
520
                        Element gpElement = (Element) propNodes.item(i);
1 ✔
521
                        GlobalProperty globalProperty = extractGlobalProperty(gpElement);
1 ✔
522
                        
523
                        if (globalProperty != null) {
1 ✔
524
                                result.add(globalProperty);
1 ✔
525
                        }
526
                        
527
                        i++;
1 ✔
528
                }
1 ✔
529
                
530
                return result;
1 ✔
531
        }
532

533
        private GlobalProperty extractGlobalProperty(Element element) {
534
                String property = getElementTrimmed(element, "property");
1 ✔
535
                String defaultValue = getElementTrimmed(element, "defaultValue");
1 ✔
536
                String description = removeTabsAndTrim(getElementTrimmed(element, "description"));
1 ✔
537
                String datatypeClassname = getElementTrimmed(element, "datatypeClassname");
1 ✔
538
                String datatypeConfig = getElementTrimmed(element, "datatypeConfig");
1 ✔
539
                String viewPrivilege = removeTabsAndTrim(getElementTrimmed(element, "viewPrivilege"));
1 ✔
540
                String editPrivilege = removeTabsAndTrim(getElementTrimmed(element, "editPrivilege"));
1 ✔
541
                String deletePrivilege = removeTabsAndTrim(getElementTrimmed(element, "deletePrivilege"));
1 ✔
542
                
543
                log.debug("property: {}, defaultValue: {}", property, defaultValue);
1 ✔
544
                log.debug("description: {}, datatypeClassname: {}", description, datatypeClassname);
1 ✔
545
                log.debug("datatypeConfig: {}", datatypeConfig);
1 ✔
546
                log.debug("viewPrivilege: {}, editPrivilege: {}, deletePrivilege: {}", viewPrivilege, editPrivilege, deletePrivilege);
1 ✔
547

548
                return createGlobalProperty(property, defaultValue, description, datatypeClassname,
1 ✔
549
                        datatypeConfig, viewPrivilege, editPrivilege, deletePrivilege);
550
        }
551

552
        private String removeTabsAndTrim(String string) {
553
                return string.replaceAll("        ", "").trim();
1 ✔
554
        }
555

556
        private GlobalProperty createGlobalProperty(String property, String defaultValue, String description,
557
                String datatypeClassname, String datatypeConfig, String viewPrivilege, String editPrivilege, String deletePrivilege) {
558

559
                GlobalProperty globalProperty = null;
1 ✔
560
                if (property.isEmpty()) {
1 ✔
561
                        log.warn("'property' is required for global properties. Given '{}'", property);
1 ✔
562
                        return globalProperty;
1 ✔
563
                }
564

565
                if (!datatypeClassname.isEmpty()) {
1 ✔
566
                        globalProperty = createGlobalPropertyWithDatatype(property, defaultValue, description, datatypeClassname,
1 ✔
567
                                datatypeConfig);
568
                } else {
569
                        globalProperty = new GlobalProperty(property, defaultValue, description);
1 ✔
570
                }
571
                
572
                if (!viewPrivilege.isEmpty()) {
1 ✔
573
                        globalProperty.setViewPrivilege(new Privilege(viewPrivilege));
1 ✔
574
                }
575
                if (!editPrivilege.isEmpty()) {
1 ✔
576
                        globalProperty.setEditPrivilege(new Privilege(editPrivilege));
1 ✔
577
                }
578
                if (!deletePrivilege.isEmpty()) {
1 ✔
579
                        globalProperty.setDeletePrivilege(new Privilege(deletePrivilege));
1 ✔
580
                }
581
                
582
                return globalProperty;
1 ✔
583
        }
584

585
        private GlobalProperty createGlobalPropertyWithDatatype(String property, String defaultValue, String description,
586
                String datatypeClassname, String datatypeConfig) {
587
                GlobalProperty globalProperty = null;
1 ✔
588
                try {
589
                        Class<CustomDatatype<?>> datatypeClazz = (Class<CustomDatatype<?>>) Class.forName(datatypeClassname)
1 ✔
590
                                .asSubclass(CustomDatatype.class);
1 ✔
591
                        globalProperty = new GlobalProperty(property, defaultValue, description, datatypeClazz, datatypeConfig);
1 ✔
592
                }
593
                catch (ClassCastException ex) {
1 ✔
594
                        log.error("The class specified by 'datatypeClassname' (" + datatypeClassname
1 ✔
595
                                + ") must be a subtype of 'org.openmrs.customdatatype.CustomDatatype<?>'.", ex);
596
                }
597
                catch (ClassNotFoundException ex) {
1 ✔
598
                        log.error("The class specified by 'datatypeClassname' (" + datatypeClassname
1 ✔
599
                                + ") could not be found.", ex);
600
                }
1 ✔
601
                return globalProperty;
1 ✔
602
        }
603

604
        private List<String> extractMappingFiles(Element configRoot) {
605
                List<String> result = new ArrayList<>();
1 ✔
606
                splitTagContentByWhitespace(configRoot, "mappingFiles", result);
1 ✔
607
                return result;
1 ✔
608
        }
609

610
        private Set<String> extractPackagesWithMappedClasses(Element configRoot) {
611
                Set<String> result = new HashSet<>();
1 ✔
612
                splitTagContentByWhitespace(configRoot, "packagesWithMappedClasses", result);
1 ✔
613
                return result;
1 ✔
614
        }
615

616
        private Collection<String> splitTagContentByWhitespace(Element rootNode, String tag, Collection<String> result) {
617
                String content = getElement(rootNode, tag);
1 ✔
618
                for (String s : content.split("\\s")) {
1 ✔
619
                        String s2 = s.trim();
1 ✔
620
                        if (s2.length() > 0) {
1 ✔
621
                                result.add(s2);
1 ✔
622
                        }
623
                }
624
                return result;
1 ✔
625
        }
626
        
627
        private String getTrimmedElementOrFail(Element rootNode, String elementName, String errorMessageKey, String moduleName) {
628
                String element = getElementTrimmed(rootNode, elementName);
1 ✔
629
                if (element == null || element.length() == 0) {
1 ✔
630
                        throw new ModuleException(messageSourceService.getMessage(errorMessageKey),
1 ✔
631
                                moduleName);
632
                }
633
                return element;
1 ✔
634
        }
635

636
        private String getElementTrimmed(Element element, String name) {
637
                return getElement(element, name).trim();
1 ✔
638
        }
639

640
        private String getElement(Element root, String tag) {
641
                if (root.getElementsByTagName(tag).getLength() > 0) {
1 ✔
642
                        return root.getElementsByTagName(tag).item(0).getTextContent();
1 ✔
643
                }
644
                return "";
1 ✔
645
        }
646

647
        /**
648
         * Looks for the "<mandatory>" element in the config file and returns true if the value is
649
         * exactly "true".
650
         */
651
        private boolean extractMandatory(Element configRoot, String configVersion) {
652
                if (Double.parseDouble(configVersion) >= 1.3) {
1 ✔
653
                        String mandatory = getElementTrimmed(configRoot, "mandatory");
1 ✔
654
                        return "true".equalsIgnoreCase(mandatory);
1 ✔
655
                }
656

657
                // this module has an older config file
658
                return false;
1 ✔
659
        }
660

661
        /**
662
         * Parses conditionalResources tag.
663
         *
664
         * <strong>Should</strong> parse openmrsVersion and modules
665
         * <strong>Should</strong> parse conditionalResource with whitespace
666
         * <strong>Should</strong> throw exception if multiple conditionalResources tags found
667
         * <strong>Should</strong> throw exception if conditionalResources contains invalid tag
668
         * <strong>Should</strong> throw exception if path is blank
669
         */
670
        List<ModuleConditionalResource> extractConditionalResources(Element configRoot) {
671
                List<ModuleConditionalResource> conditionalResources = new ArrayList<>();
1 ✔
672

673
                NodeList parentConditionalResources = configRoot.getElementsByTagName("conditionalResources");
1 ✔
674

675
                if (parentConditionalResources.getLength() == 0) {
1 ✔
676
                        return new ArrayList<>();
1 ✔
677
                } else if (parentConditionalResources.getLength() > 1) {
1 ✔
678
                        throw new IllegalArgumentException("Found multiple conditionalResources tags. There can be only one.");
1 ✔
679
                }
680

681
                NodeList conditionalResourcesNode = parentConditionalResources.item(0).getChildNodes();
1 ✔
682

683
                for (int i = 0; i < conditionalResourcesNode.getLength(); i++) {
1 ✔
684
                        Node conditionalResourceNode = conditionalResourcesNode.item(i);
1 ✔
685

686
                        if ("#text".equals(conditionalResourceNode.getNodeName())) {
1 ✔
687
                                //ignore text and whitespace in particular
688
                                continue;
1 ✔
689
                        }
690

691
                        if (!"conditionalResource".equals(conditionalResourceNode.getNodeName())) {
1 ✔
692
                                throw new IllegalArgumentException("Found the " + conditionalResourceNode.getNodeName()
1 ✔
693
                                        + " node under conditionalResources. Only conditionalResource is allowed.");
694
                        }
695

696
                        NodeList resourceElements = conditionalResourceNode.getChildNodes();
1 ✔
697

698
                        ModuleConditionalResource resource = new ModuleConditionalResource();
1 ✔
699
                        conditionalResources.add(resource);
1 ✔
700

701
                        for (int j = 0; j < resourceElements.getLength(); j++) {
1 ✔
702
                                Node resourceElement = resourceElements.item(j);
1 ✔
703

704
                                if ("path".equals(resourceElement.getNodeName())) {
1 ✔
705
                                        if (StringUtils.isBlank(resourceElement.getTextContent())) {
1 ✔
706
                                                throw new IllegalArgumentException("The path of a conditional resource must not be blank");
1 ✔
707
                                        }
708
                                        resource.setPath(resourceElement.getTextContent());
1 ✔
709
                                } else if ("openmrsVersion".equals(resourceElement.getNodeName())) {
1 ✔
710
                                        if (StringUtils.isBlank(resource.getOpenmrsPlatformVersion())) {
1 ✔
711
                                                resource.setOpenmrsPlatformVersion(resourceElement.getTextContent());
1 ✔
712
                                        }
713
                                } else if ("openmrsPlatformVersion".equals(resourceElement.getNodeName())) {
1 ✔
UNCOV
714
                                        resource.setOpenmrsPlatformVersion(resourceElement.getTextContent());
×
715
                                } else if ("modules".equals(resourceElement.getNodeName())) {
1 ✔
716
                                        NodeList modulesNode = resourceElement.getChildNodes();
1 ✔
717
                                        for (int k = 0; k < modulesNode.getLength(); k++) {
1 ✔
718
                                                Node moduleNode = modulesNode.item(k);
1 ✔
719
                                                if ("module".equals(moduleNode.getNodeName())) {
1 ✔
720
                                                        NodeList moduleElements = moduleNode.getChildNodes();
1 ✔
721

722
                                                        ModuleConditionalResource.ModuleAndVersion module = new ModuleConditionalResource.ModuleAndVersion();
1 ✔
723
                                                        resource.getModules().add(module);
1 ✔
724
                                                        for (int m = 0; m < moduleElements.getLength(); m++) {
1 ✔
725
                                                                Node moduleElement = moduleElements.item(m);
1 ✔
726

727
                                                                if ("moduleId".equals(moduleElement.getNodeName())) {
1 ✔
728
                                                                        module.setModuleId(moduleElement.getTextContent());
1 ✔
729
                                                                } else if ("version".equals(moduleElement.getNodeName())) {
1 ✔
730
                                                                        module.setVersion(moduleElement.getTextContent());
1 ✔
731
                                                                }
732
                                                        }
733
                                                }
734
                                        }
735
                                }
736
                        }
737
                }
738

739
                return conditionalResources;
1 ✔
740
        }
741
}
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