source: josm/trunk/src/org/openstreetmap/josm/data/validation/tests/ConditionalKeys.java@ 16154

Last change on this file since 16154 was 16154, checked in by Don-vip, 4 years ago

see #17533 - see #18455 - partial revert of r15640, causing untagged nodes to be skipped entirely

  • Property svn:eol-style set to native
File size: 10.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.validation.tests;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.util.ArrayList;
7import java.util.Arrays;
8import java.util.Collection;
9import java.util.HashSet;
10import java.util.List;
11import java.util.Set;
12import java.util.regex.Matcher;
13import java.util.regex.Pattern;
14
15import org.openstreetmap.josm.data.osm.OsmPrimitive;
16import org.openstreetmap.josm.data.validation.Severity;
17import org.openstreetmap.josm.data.validation.Test;
18import org.openstreetmap.josm.data.validation.TestError;
19import org.openstreetmap.josm.tools.Logging;
20import org.openstreetmap.josm.tools.SubclassFilteredCollection;
21
22/**
23 * Checks for <a href="http://wiki.openstreetmap.org/wiki/Conditional_restrictions">conditional restrictions</a>
24 * @since 6605
25 */
26public class ConditionalKeys extends Test.TagTest {
27
28 private final OpeningHourTest openingHourTest = new OpeningHourTest();
29 private static final Set<String> RESTRICTION_TYPES = new HashSet<>(Arrays.asList("oneway", "toll", "noexit", "maxspeed", "minspeed",
30 "maxstay", "maxweight", "maxaxleload", "maxheight", "maxwidth", "maxlength", "overtaking", "maxgcweight", "maxgcweightrating",
31 "fee", "restriction", "interval", "duration"));
32 private static final Set<String> RESTRICTION_VALUES = new HashSet<>(Arrays.asList("yes", "official", "designated", "destination",
33 "delivery", "customers", "permissive", "private", "agricultural", "forestry", "no"));
34 private static final Set<String> TRANSPORT_MODES = new HashSet<>(Arrays.asList("access", "foot", "ski", "inline_skates", "ice_skates",
35 "horse", "vehicle", "bicycle", "carriage", "trailer", "caravan", "motor_vehicle", "motorcycle", "moped", "mofa",
36 "motorcar", "motorhome", "psv", "bus", "taxi", "tourist_bus", "goods", "hgv", "agricultural", "atv", "snowmobile",
37 "hgv_articulated", "ski:nordic", "ski:alpine", "ski:telemark", "coach", "golf_cart"
38 /*,"minibus","share_taxi","hov","car_sharing","emergency","hazmat","disabled"*/));
39
40 private static final Pattern CONDITIONAL_PATTERN;
41 static {
42 final String part = Pattern.compile("([^@\\p{Space}][^@]*?)"
43 + "\\s*@\\s*" + "(\\([^)\\p{Space}][^)]+?\\)|[^();\\p{Space}][^();]*?)\\s*").toString();
44 CONDITIONAL_PATTERN = Pattern.compile('(' + part + ")(;\\s*" + part + ")*");
45 }
46
47 /**
48 * Constructs a new {@code ConditionalKeys}.
49 */
50 public ConditionalKeys() {
51 super(tr("Conditional Keys"), tr("Tests for the correct usage of ''*:conditional'' tags."));
52 }
53
54 @Override
55 public void initialize() throws Exception {
56 super.initialize();
57 openingHourTest.initialize();
58 }
59
60 /**
61 * Check if the key is a key for an access restriction
62 * @param part The key (or the restriction part of it, e.g. for lanes)
63 * @return <code>true</code> if it is a restriction
64 */
65 public static boolean isRestrictionType(String part) {
66 return RESTRICTION_TYPES.contains(part);
67 }
68
69 /**
70 * Check if the value is a valid restriction value
71 * @param part The value
72 * @return <code>true</code> for allowed restriction values
73 */
74 public static boolean isRestrictionValue(String part) {
75 return RESTRICTION_VALUES.contains(part);
76 }
77
78 /**
79 * Checks if the key denotes a
80 * <a href="http://wiki.openstreetmap.org/wiki/Key:access#Transport_mode_restrictions">transport access mode restriction</a>
81 * @param part The key (or the restriction part of it, e.g. for lanes)
82 * @return <code>true</code> if it is a restriction
83 */
84 public static boolean isTransportationMode(String part) {
85 return TRANSPORT_MODES.contains(part);
86 }
87
88 /**
89 * Check if a key part is a valid direction
90 * @param part The part of the key
91 * @return <code>true</code> if it is a direction
92 */
93 public static boolean isDirection(String part) {
94 return "forward".equals(part) || "backward".equals(part);
95 }
96
97 /**
98 * Checks if a given key is a valid access key
99 * @param key The conditional key
100 * @return <code>true</code> if the key is valid
101 */
102 public boolean isKeyValid(String key) {
103 // <restriction-type>[:<transportation mode>][:<direction>]:conditional
104 // -- or -- <transportation mode> [:<direction>]:conditional
105 if (!key.endsWith(":conditional")) {
106 return false;
107 }
108 final String[] parts = key.replace(":conditional", "").split(":");
109 return isKeyValid3Parts(parts) || isKeyValid1Part(parts) || isKeyValid2Parts(parts);
110 }
111
112 private static boolean isKeyValid3Parts(String... parts) {
113 return parts.length == 3 && isRestrictionType(parts[0]) && isTransportationMode(parts[1]) && isDirection(parts[2]);
114 }
115
116 private static boolean isKeyValid2Parts(String... parts) {
117 return parts.length == 2 && ((isRestrictionType(parts[0]) && (isTransportationMode(parts[1]) || isDirection(parts[1])))
118 || (isTransportationMode(parts[0]) && isDirection(parts[1])));
119 }
120
121 private static boolean isKeyValid1Part(String... parts) {
122 return parts.length == 1 && (isRestrictionType(parts[0]) || isTransportationMode(parts[0]));
123 }
124
125 /**
126 * Check if a value is valid
127 * @param key The key the value is for
128 * @param value The value
129 * @return <code>true</code> if it is valid
130 */
131 public boolean isValueValid(String key, String value) {
132 return validateValue(key, value) == null;
133 }
134
135 static class ConditionalParsingException extends RuntimeException {
136 ConditionalParsingException(String message) {
137 super(message);
138 }
139 }
140
141 /**
142 * A conditional value is a value for the access restriction tag that depends on conditions (time, ...)
143 */
144 public static class ConditionalValue {
145 /**
146 * The value the tag should have if the condition matches
147 */
148 public final String restrictionValue;
149 /**
150 * The conditions for {@link #restrictionValue}
151 */
152 public final Collection<String> conditions;
153
154 /**
155 * Create a new {@link ConditionalValue}
156 * @param restrictionValue The value the tag should have if the condition matches
157 * @param conditions The conditions for that value
158 */
159 public ConditionalValue(String restrictionValue, Collection<String> conditions) {
160 this.restrictionValue = restrictionValue;
161 this.conditions = conditions;
162 }
163
164 /**
165 * Parses the condition values as string.
166 * @param value value, must match {@code <restriction-value> @ <condition>[;<restriction-value> @ <condition>]} pattern
167 * @return list of {@code ConditionalValue}s
168 * @throws ConditionalParsingException if {@code value} does not match expected pattern
169 */
170 public static List<ConditionalValue> parse(String value) {
171 // <restriction-value> @ <condition>[;<restriction-value> @ <condition>]
172 final List<ConditionalValue> r = new ArrayList<>();
173 final Matcher m = CONDITIONAL_PATTERN.matcher(value);
174 if (!m.matches()) {
175 throw new ConditionalParsingException(tr("Does not match pattern ''restriction value @ condition''"));
176 } else {
177 int i = 2;
178 while (i + 1 <= m.groupCount() && m.group(i + 1) != null) {
179 final String restrictionValue = m.group(i);
180 final String[] conditions = m.group(i + 1).replace("(", "").replace(")", "").split("\\s+(AND|and)\\s+");
181 r.add(new ConditionalValue(restrictionValue, Arrays.asList(conditions)));
182 i += 3;
183 }
184 }
185 return r;
186 }
187 }
188
189 /**
190 * Validate a key/value pair
191 * @param key The key
192 * @param value The value
193 * @return The error message for that value or <code>null</code> to indicate valid
194 */
195 public String validateValue(String key, String value) {
196 try {
197 for (final ConditionalValue conditional : ConditionalValue.parse(value)) {
198 // validate restriction value
199 if (isTransportationMode(key.split(":")[0]) && !isRestrictionValue(conditional.restrictionValue)) {
200 return tr("{0} is not a valid restriction value", conditional.restrictionValue);
201 }
202 // validate opening hour if the value contains an hour (heuristic)
203 for (final String condition : conditional.conditions) {
204 if (condition.matches(".*[0-9]:[0-9]{2}.*")) {
205 final List<TestError> errors = openingHourTest.checkOpeningHourSyntax("", condition);
206 if (!errors.isEmpty()) {
207 return errors.get(0).getDescription();
208 }
209 }
210 }
211 }
212 } catch (ConditionalParsingException ex) {
213 Logging.debug(ex);
214 return ex.getMessage();
215 }
216 return null;
217 }
218
219 /**
220 * Validate a primitive
221 * @param p The primitive
222 * @return The errors for that primitive or an empty list if there are no errors.
223 */
224 public List<TestError> validatePrimitive(OsmPrimitive p) {
225 final List<TestError> errors = new ArrayList<>();
226 for (final String key : SubclassFilteredCollection.filter(p.keySet(),
227 Pattern.compile(":conditional(:.*)?$").asPredicate())) {
228 if (!isKeyValid(key)) {
229 errors.add(TestError.builder(this, Severity.WARNING, 3201)
230 .message(tr("Wrong syntax in {0} key", key))
231 .primitives(p)
232 .build());
233 continue;
234 }
235 final String value = p.get(key);
236 final String error = validateValue(key, value);
237 if (error != null) {
238 errors.add(TestError.builder(this, Severity.WARNING, 3202)
239 .message(tr("Error in {0} value: {1}", key, error))
240 .primitives(p)
241 .build());
242 }
243 }
244 return errors;
245 }
246
247 @Override
248 public void check(OsmPrimitive p) {
249 if (p.isTagged()) {
250 errors.addAll(validatePrimitive(p));
251 }
252 }
253}
Note: See TracBrowser for help on using the repository browser.