1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
// SPDX-License-Identifier: BSD-3-Clause
package org.islandoftex.texplate.util;
import io.vavr.control.Try;
import org.islandoftex.texplate.exceptions.InvalidKeySetException;
import org.islandoftex.texplate.model.Template;
import java.util.Map;
/**
* Helper methods for validation.
*
* @version 1.0
* @since 1.0
*/
public class ValidatorUtils {
/**
* Validates the data map based on the template requirements.
*
* @param template The template.
* @param map The data map.
* @return A boolean value indicating whether the data map is valid.
*/
private static boolean validateRequirements(Template template,
Map<String, String> map) {
return template.getRequirements().isEmpty() ||
template.getRequirements().containsAll(map.keySet());
}
/**
* Validates the template pattern and the data map and throws an exception
* in case of failure.
*
* @param template The template.
* @param map The data map.
* @return The data map.
* @throws InvalidKeySetException There are invalid keys in the map.
*/
private static Map<String, String> checkValidation(Template template,
Map<String, String> map)
throws InvalidKeySetException {
// for starters, we try to validate
// the template requirements
if (validateRequirements(template, map)) {
// everything is validated, so
// we simply return the map
return map;
} else {
// the requirements were missing,
// so an exception is thrown
throw new InvalidKeySetException("The provided map does not "
+ "contain all the keys required by the chosen "
+ "template. Make sure to define such keys and try "
+ "again. Check the user manual for further details.");
}
}
/**
* Validates the template pattern and the data map.
*
* @param template The template.
* @param map The data map.
* @return The data map, enclosed in a Try object.
*/
public static Try<Map<String, String>> validate(Template template,
Map<String, String> map) {
return Try.of(() -> checkValidation(template, map));
}
}
|