source: josm/trunk/src/org/openstreetmap/josm/data/validation/tests/MapCSSTagChecker.java@ 8318

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

fix various Sonar issues:

  • squid:S1068: Unused private fields should be removed
  • squid:S1155: Collection.isEmpty() should be used to test for emptiness
  • squid:S1185: Overriding methods should do more than simply call the same method in the super class
  • squid:S1694: An abstract class should have both abstract and concrete methods
  • squid:S1905: Redundant casts should not be used
  • squid:S2065: Fields in non-serializable classes should not be "transient"
  • squid:S2583: Conditions should not unconditionally evaluate to "TRUE" or to "FALSE"
  • squid:ModifiersOrderCheck: Modifiers should be declared in the correct order
  • Property svn:eol-style set to native
File size: 33.7 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.io.BufferedReader;
7import java.io.IOException;
8import java.io.InputStream;
9import java.io.Reader;
10import java.text.MessageFormat;
11import java.util.ArrayList;
12import java.util.Arrays;
13import java.util.Collection;
14import java.util.Collections;
15import java.util.HashMap;
16import java.util.HashSet;
17import java.util.Iterator;
18import java.util.LinkedHashMap;
19import java.util.LinkedHashSet;
20import java.util.LinkedList;
21import java.util.List;
22import java.util.Map;
23import java.util.Set;
24import java.util.regex.Matcher;
25import java.util.regex.Pattern;
26
27import org.openstreetmap.josm.Main;
28import org.openstreetmap.josm.command.ChangePropertyCommand;
29import org.openstreetmap.josm.command.ChangePropertyKeyCommand;
30import org.openstreetmap.josm.command.Command;
31import org.openstreetmap.josm.command.DeleteCommand;
32import org.openstreetmap.josm.command.SequenceCommand;
33import org.openstreetmap.josm.data.osm.DataSet;
34import org.openstreetmap.josm.data.osm.OsmPrimitive;
35import org.openstreetmap.josm.data.osm.OsmUtils;
36import org.openstreetmap.josm.data.osm.Tag;
37import org.openstreetmap.josm.data.validation.FixableTestError;
38import org.openstreetmap.josm.data.validation.Severity;
39import org.openstreetmap.josm.data.validation.Test;
40import org.openstreetmap.josm.data.validation.TestError;
41import org.openstreetmap.josm.gui.mappaint.Environment;
42import org.openstreetmap.josm.gui.mappaint.Keyword;
43import org.openstreetmap.josm.gui.mappaint.MultiCascade;
44import org.openstreetmap.josm.gui.mappaint.mapcss.Condition;
45import org.openstreetmap.josm.gui.mappaint.mapcss.Condition.ClassCondition;
46import org.openstreetmap.josm.gui.mappaint.mapcss.Expression;
47import org.openstreetmap.josm.gui.mappaint.mapcss.Instruction;
48import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule;
49import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule.Declaration;
50import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
51import org.openstreetmap.josm.gui.mappaint.mapcss.Selector;
52import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.AbstractSelector;
53import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector;
54import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser;
55import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException;
56import org.openstreetmap.josm.gui.preferences.SourceEntry;
57import org.openstreetmap.josm.gui.preferences.validator.ValidatorPreference;
58import org.openstreetmap.josm.gui.preferences.validator.ValidatorTagCheckerRulesPreference;
59import org.openstreetmap.josm.io.CachedFile;
60import org.openstreetmap.josm.io.IllegalDataException;
61import org.openstreetmap.josm.io.UTFInputStreamReader;
62import org.openstreetmap.josm.tools.CheckParameterUtil;
63import org.openstreetmap.josm.tools.MultiMap;
64import org.openstreetmap.josm.tools.Predicate;
65import org.openstreetmap.josm.tools.Utils;
66
67/**
68 * MapCSS-based tag checker/fixer.
69 * @since 6506
70 */
71public class MapCSSTagChecker extends Test.TagTest {
72
73 /**
74 * A grouped MapCSSRule with multiple selectors for a single declaration.
75 * @see MapCSSRule
76 */
77 public static class GroupedMapCSSRule {
78 /** MapCSS selectors **/
79 public final List<Selector> selectors;
80 /** MapCSS declaration **/
81 public final Declaration declaration;
82
83 /**
84 * Constructs a new {@code GroupedMapCSSRule}.
85 * @param selectors MapCSS selectors
86 * @param declaration MapCSS declaration
87 */
88 public GroupedMapCSSRule(List<Selector> selectors, Declaration declaration) {
89 this.selectors = selectors;
90 this.declaration = declaration;
91 }
92
93 @Override
94 public int hashCode() {
95 final int prime = 31;
96 int result = 1;
97 result = prime * result + ((declaration == null) ? 0 : declaration.hashCode());
98 result = prime * result + ((selectors == null) ? 0 : selectors.hashCode());
99 return result;
100 }
101
102 @Override
103 public boolean equals(Object obj) {
104 if (this == obj)
105 return true;
106 if (obj == null)
107 return false;
108 if (!(obj instanceof GroupedMapCSSRule))
109 return false;
110 GroupedMapCSSRule other = (GroupedMapCSSRule) obj;
111 if (declaration == null) {
112 if (other.declaration != null)
113 return false;
114 } else if (!declaration.equals(other.declaration))
115 return false;
116 if (selectors == null) {
117 if (other.selectors != null)
118 return false;
119 } else if (!selectors.equals(other.selectors))
120 return false;
121 return true;
122 }
123
124 @Override
125 public String toString() {
126 return "GroupedMapCSSRule [selectors=" + selectors + ", declaration=" + declaration + "]";
127 }
128 }
129
130 /**
131 * The preference key for tag checker source entries.
132 * @since 6670
133 */
134 public static final String ENTRIES_PREF_KEY = "validator." + MapCSSTagChecker.class.getName() + ".entries";
135
136 /**
137 * Constructs a new {@code MapCSSTagChecker}.
138 */
139 public MapCSSTagChecker() {
140 super(tr("Tag checker (MapCSS based)"), tr("This test checks for errors in tag keys and values."));
141 }
142
143 /**
144 * Represents a fix to a validation test. The fixing {@link Command} can be obtained by {@link #createCommand(OsmPrimitive, Selector)}.
145 */
146 abstract static class FixCommand {
147 /**
148 * Creates the fixing {@link Command} for the given primitive. The {@code matchingSelector} is used to
149 * evaluate placeholders (cf. {@link org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker.TagCheck#insertArguments(Selector, String, OsmPrimitive)}).
150 */
151 abstract Command createCommand(final OsmPrimitive p, final Selector matchingSelector);
152
153 private static void checkObject(final Object obj) {
154 CheckParameterUtil.ensureThat(obj instanceof Expression || obj instanceof String, "instance of Exception or String expected, but got " + obj);
155 }
156
157 /**
158 * Evaluates given object as {@link Expression} or {@link String} on the matched {@link OsmPrimitive} and {@code matchingSelector}.
159 */
160 private static String evaluateObject(final Object obj, final OsmPrimitive p, final Selector matchingSelector) {
161 final String s;
162 if (obj instanceof Expression) {
163 s = (String) ((Expression) obj).evaluate(new Environment().withPrimitive(p));
164 } else if (obj instanceof String) {
165 s = (String) obj;
166 } else {
167 return null;
168 }
169 return TagCheck.insertArguments(matchingSelector, s, p);
170 }
171
172 /**
173 * Creates a fixing command which executes a {@link ChangePropertyCommand} on the specified tag.
174 */
175 static FixCommand fixAdd(final Object obj) {
176 checkObject(obj);
177 return new FixCommand() {
178 @Override
179 Command createCommand(OsmPrimitive p, Selector matchingSelector) {
180 final Tag tag = Tag.ofString(evaluateObject(obj, p, matchingSelector));
181 return new ChangePropertyCommand(p, tag.getKey(), tag.getValue());
182 }
183
184 @Override
185 public String toString() {
186 return "fixAdd: " + obj;
187 }
188 };
189
190 }
191
192 /**
193 * Creates a fixing command which executes a {@link ChangePropertyCommand} to delete the specified key.
194 */
195 static FixCommand fixRemove(final Object obj) {
196 checkObject(obj);
197 return new FixCommand() {
198 @Override
199 Command createCommand(OsmPrimitive p, Selector matchingSelector) {
200 final String key = evaluateObject(obj, p, matchingSelector);
201 return new ChangePropertyCommand(p, key, "");
202 }
203
204 @Override
205 public String toString() {
206 return "fixRemove: " + obj;
207 }
208 };
209 }
210
211 /**
212 * Creates a fixing command which executes a {@link ChangePropertyKeyCommand} on the specified keys.
213 */
214 static FixCommand fixChangeKey(final String oldKey, final String newKey) {
215 return new FixCommand() {
216 @Override
217 Command createCommand(OsmPrimitive p, Selector matchingSelector) {
218 return new ChangePropertyKeyCommand(p, oldKey, newKey);
219 }
220
221 @Override
222 public String toString() {
223 return "fixChangeKey: " + oldKey + " => " + newKey;
224 }
225 };
226 }
227 }
228
229 final MultiMap<String, TagCheck> checks = new MultiMap<>();
230
231 static class TagCheck implements Predicate<OsmPrimitive> {
232 protected final GroupedMapCSSRule rule;
233 protected final List<FixCommand> fixCommands = new ArrayList<>();
234 protected final List<String> alternatives = new ArrayList<>();
235 protected final Map<Instruction.AssignmentInstruction, Severity> errors = new HashMap<>();
236 protected final Map<String, Boolean> assertions = new HashMap<>();
237 protected final Set<String> setClassExpressions = new HashSet<>();
238 protected boolean deletion = false;
239
240 TagCheck(GroupedMapCSSRule rule) {
241 this.rule = rule;
242 }
243
244 private static final String POSSIBLE_THROWS = possibleThrows();
245
246 static final String possibleThrows() {
247 StringBuffer sb = new StringBuffer();
248 for (Severity s : Severity.values()) {
249 if (sb.length() > 0) {
250 sb.append('/');
251 }
252 sb.append("throw")
253 .append(s.name().charAt(0))
254 .append(s.name().substring(1).toLowerCase());
255 }
256 return sb.toString();
257 }
258
259 static TagCheck ofMapCSSRule(final GroupedMapCSSRule rule) throws IllegalDataException {
260 final TagCheck check = new TagCheck(rule);
261 for (Instruction i : rule.declaration.instructions) {
262 if (i instanceof Instruction.AssignmentInstruction) {
263 final Instruction.AssignmentInstruction ai = (Instruction.AssignmentInstruction) i;
264 if (ai.isSetInstruction) {
265 check.setClassExpressions.add(ai.key);
266 continue;
267 }
268 final String val = ai.val instanceof Expression
269 ? (String) ((Expression) ai.val).evaluate(new Environment())
270 : ai.val instanceof String
271 ? (String) ai.val
272 : ai.val instanceof Keyword
273 ? ((Keyword) ai.val).val
274 : null;
275 if (ai.key.startsWith("throw")) {
276 try {
277 final Severity severity = Severity.valueOf(ai.key.substring("throw".length()).toUpperCase());
278 check.errors.put(ai, severity);
279 } catch (IllegalArgumentException e) {
280 Main.warn("Unsupported "+ai.key+" instruction. Allowed instructions are "+POSSIBLE_THROWS);
281 }
282 } else if ("fixAdd".equals(ai.key)) {
283 check.fixCommands.add(FixCommand.fixAdd(ai.val));
284 } else if ("fixRemove".equals(ai.key)) {
285 CheckParameterUtil.ensureThat(!(ai.val instanceof String) || !(val != null && val.contains("=")),
286 "Unexpected '='. Please only specify the key to remove!");
287 check.fixCommands.add(FixCommand.fixRemove(ai.val));
288 } else if ("fixChangeKey".equals(ai.key) && val != null) {
289 CheckParameterUtil.ensureThat(val.contains("=>"), "Separate old from new key by '=>'!");
290 final String[] x = val.split("=>", 2);
291 check.fixCommands.add(FixCommand.fixChangeKey(Tag.removeWhiteSpaces(x[0]), Tag.removeWhiteSpaces(x[1])));
292 } else if ("fixDeleteObject".equals(ai.key) && val != null) {
293 CheckParameterUtil.ensureThat(val.equals("this"), "fixDeleteObject must be followed by 'this'");
294 check.deletion = true;
295 } else if ("suggestAlternative".equals(ai.key) && val != null) {
296 check.alternatives.add(val);
297 } else if ("assertMatch".equals(ai.key) && val != null) {
298 check.assertions.put(val, true);
299 } else if ("assertNoMatch".equals(ai.key) && val != null) {
300 check.assertions.put(val, false);
301 } else {
302 throw new IllegalDataException("Cannot add instruction " + ai.key + ": " + ai.val + "!");
303 }
304 }
305 }
306 if (check.errors.isEmpty() && check.setClassExpressions.isEmpty()) {
307 throw new IllegalDataException(
308 "No "+POSSIBLE_THROWS+" given! You should specify a validation error message for " + rule.selectors);
309 } else if (check.errors.size() > 1) {
310 throw new IllegalDataException(
311 "More than one "+POSSIBLE_THROWS+" given! You should specify a single validation error message for "
312 + rule.selectors);
313 }
314 return check;
315 }
316
317 static List<TagCheck> readMapCSS(Reader css) throws ParseException {
318 CheckParameterUtil.ensureParameterNotNull(css, "css");
319 return readMapCSS(new MapCSSParser(css));
320 }
321
322 static List<TagCheck> readMapCSS(MapCSSParser css) throws ParseException {
323 CheckParameterUtil.ensureParameterNotNull(css, "css");
324 final MapCSSStyleSource source = new MapCSSStyleSource("");
325 css.sheet(source);
326 assert source.getErrors().isEmpty();
327 // Ignore "meta" rule(s) from external rules of JOSM wiki
328 removeMetaRules(source);
329 // group rules with common declaration block
330 Map<Declaration, List<Selector>> g = new LinkedHashMap<>();
331 for (MapCSSRule rule : source.rules) {
332 if (!g.containsKey(rule.declaration)) {
333 List<Selector> sels = new ArrayList<>();
334 sels.add(rule.selector);
335 g.put(rule.declaration, sels);
336 } else {
337 g.get(rule.declaration).add(rule.selector);
338 }
339 }
340 List<TagCheck> result = new ArrayList<>();
341 for (Map.Entry<Declaration, List<Selector>> map : g.entrySet()) {
342 try {
343 result.add(TagCheck.ofMapCSSRule(
344 new GroupedMapCSSRule(map.getValue(), map.getKey())));
345 } catch (IllegalDataException e) {
346 Main.error("Cannot add MapCss rule: "+e.getMessage());
347 }
348 }
349 return result;
350 }
351
352 private static void removeMetaRules(MapCSSStyleSource source) {
353 for (Iterator<MapCSSRule> it = source.rules.iterator(); it.hasNext(); ) {
354 MapCSSRule x = it.next();
355 if (x.selector instanceof GeneralSelector) {
356 GeneralSelector gs = (GeneralSelector) x.selector;
357 if ("meta".equals(gs.base) && gs.getConditions().isEmpty()) {
358 it.remove();
359 }
360 }
361 }
362 }
363
364 @Override
365 public boolean evaluate(OsmPrimitive primitive) {
366 // Tests whether the primitive contains a deprecated tag which is represented by this MapCSSTagChecker.
367 return whichSelectorMatchesPrimitive(primitive) != null;
368 }
369
370 Selector whichSelectorMatchesPrimitive(OsmPrimitive primitive) {
371 return whichSelectorMatchesEnvironment(new Environment().withPrimitive(primitive));
372 }
373
374 Selector whichSelectorMatchesEnvironment(Environment env) {
375 for (Selector i : rule.selectors) {
376 env.clearSelectorMatchingInformation();
377 if (i.matches(env)) {
378 return i;
379 }
380 }
381 return null;
382 }
383
384 /**
385 * Determines the {@code index}-th key/value/tag (depending on {@code type}) of the
386 * {@link org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector}.
387 */
388 static String determineArgument(Selector.GeneralSelector matchingSelector, int index, String type, OsmPrimitive p) {
389 try {
390 final Condition c = matchingSelector.getConditions().get(index);
391 final Tag tag = c instanceof Condition.KeyCondition
392 ? ((Condition.KeyCondition) c).asTag(p)
393 : c instanceof Condition.SimpleKeyValueCondition
394 ? ((Condition.SimpleKeyValueCondition) c).asTag()
395 : c instanceof Condition.KeyValueCondition
396 ? ((Condition.KeyValueCondition) c).asTag()
397 : null;
398 if (tag == null) {
399 return null;
400 } else if ("key".equals(type)) {
401 return tag.getKey();
402 } else if ("value".equals(type)) {
403 return tag.getValue();
404 } else if ("tag".equals(type)) {
405 return tag.toString();
406 }
407 } catch (IndexOutOfBoundsException ignore) {
408 if (Main.isDebugEnabled()) {
409 Main.debug(ignore.getMessage());
410 }
411 }
412 return null;
413 }
414
415 /**
416 * Replaces occurrences of <code>{i.key}</code>, <code>{i.value}</code>, <code>{i.tag}</code> in {@code s} by the corresponding
417 * key/value/tag of the {@code index}-th {@link Condition} of {@code matchingSelector}.
418 */
419 static String insertArguments(Selector matchingSelector, String s, OsmPrimitive p) {
420 if (s != null && matchingSelector instanceof Selector.ChildOrParentSelector) {
421 return insertArguments(((Selector.ChildOrParentSelector)matchingSelector).right, s, p);
422 } else if (s == null || !(matchingSelector instanceof GeneralSelector)) {
423 return s;
424 }
425 final Matcher m = Pattern.compile("\\{(\\d+)\\.(key|value|tag)\\}").matcher(s);
426 final StringBuffer sb = new StringBuffer();
427 while (m.find()) {
428 final String argument = determineArgument((Selector.GeneralSelector) matchingSelector, Integer.parseInt(m.group(1)), m.group(2), p);
429 try {
430 // Perform replacement with null-safe + regex-safe handling
431 m.appendReplacement(sb, String.valueOf(argument).replace("^(", "").replace(")$", ""));
432 } catch (IndexOutOfBoundsException | IllegalArgumentException e) {
433 Main.error(tr("Unable to replace argument {0} in {1}: {2}", argument, sb, e.getMessage()));
434 }
435 }
436 m.appendTail(sb);
437 return sb.toString();
438 }
439
440 /**
441 * Constructs a fix in terms of a {@link org.openstreetmap.josm.command.Command} for the {@link OsmPrimitive}
442 * if the error is fixable, or {@code null} otherwise.
443 *
444 * @param p the primitive to construct the fix for
445 * @return the fix or {@code null}
446 */
447 Command fixPrimitive(OsmPrimitive p) {
448 if (fixCommands.isEmpty() && !deletion) {
449 return null;
450 }
451 final Selector matchingSelector = whichSelectorMatchesPrimitive(p);
452 Collection<Command> cmds = new LinkedList<>();
453 for (FixCommand fixCommand : fixCommands) {
454 cmds.add(fixCommand.createCommand(p, matchingSelector));
455 }
456 if (deletion) {
457 cmds.add(new DeleteCommand(p));
458 }
459 return new SequenceCommand(tr("Fix of {0}", getDescriptionForMatchingSelector(p, matchingSelector)), cmds);
460 }
461
462 /**
463 * Constructs a (localized) message for this deprecation check.
464 *
465 * @return a message
466 */
467 String getMessage(OsmPrimitive p) {
468 if (errors.isEmpty()) {
469 // Return something to avoid NPEs
470 return rule.declaration.toString();
471 } else {
472 final Object val = errors.keySet().iterator().next().val;
473 return String.valueOf(
474 val instanceof Expression
475 ? ((Expression) val).evaluate(new Environment().withPrimitive(p))
476 : val
477 );
478 }
479 }
480
481 /**
482 * Constructs a (localized) description for this deprecation check.
483 *
484 * @return a description (possibly with alternative suggestions)
485 * @see #getDescriptionForMatchingSelector
486 */
487 String getDescription(OsmPrimitive p) {
488 if (alternatives.isEmpty()) {
489 return getMessage(p);
490 } else {
491 /* I18N: {0} is the test error message and {1} is an alternative */
492 return tr("{0}, use {1} instead", getMessage(p), Utils.join(tr(" or "), alternatives));
493 }
494 }
495
496 /**
497 * Constructs a (localized) description for this deprecation check
498 * where any placeholders are replaced by values of the matched selector.
499 *
500 * @return a description (possibly with alternative suggestions)
501 */
502 String getDescriptionForMatchingSelector(OsmPrimitive p, Selector matchingSelector) {
503 return insertArguments(matchingSelector, getDescription(p), p);
504 }
505
506 Severity getSeverity() {
507 return errors.isEmpty() ? null : errors.values().iterator().next();
508 }
509
510 @Override
511 public String toString() {
512 return getDescription(null);
513 }
514
515 /**
516 * Constructs a {@link TestError} for the given primitive, or returns null if the primitive does not give rise to an error.
517 *
518 * @param p the primitive to construct the error for
519 * @return an instance of {@link TestError}, or returns null if the primitive does not give rise to an error.
520 */
521 TestError getErrorForPrimitive(OsmPrimitive p) {
522 final Environment env = new Environment().withPrimitive(p);
523 return getErrorForPrimitive(p, whichSelectorMatchesEnvironment(env), env);
524 }
525
526 TestError getErrorForPrimitive(OsmPrimitive p, Selector matchingSelector, Environment env) {
527 if (matchingSelector != null && !errors.isEmpty()) {
528 final Command fix = fixPrimitive(p);
529 final String description = getDescriptionForMatchingSelector(p, matchingSelector);
530 final List<OsmPrimitive> primitives;
531 if (env.child != null) {
532 primitives = Arrays.asList(p, env.child);
533 } else {
534 primitives = Collections.singletonList(p);
535 }
536 if (fix != null) {
537 return new FixableTestError(null, getSeverity(), description, null, matchingSelector.toString(), 3000, primitives, fix);
538 } else {
539 return new TestError(null, getSeverity(), description, null, matchingSelector.toString(), 3000, primitives);
540 }
541 } else {
542 return null;
543 }
544 }
545
546 /**
547 * Returns the set of tagchecks on which this check depends on.
548 * @param schecks the collection of tagcheks to search in
549 * @return the set of tagchecks on which this check depends on
550 * @since 7881
551 */
552 public Set<TagCheck> getTagCheckDependencies(Collection<TagCheck> schecks) {
553 Set<TagCheck> result = new HashSet<MapCSSTagChecker.TagCheck>();
554 Set<String> classes = getClassesIds();
555 if (schecks != null && !classes.isEmpty()) {
556 for (TagCheck tc : schecks) {
557 if (this.equals(tc)) {
558 continue;
559 }
560 for (String id : tc.setClassExpressions) {
561 if (classes.contains(id)) {
562 result.add(tc);
563 break;
564 }
565 }
566 }
567 }
568 return result;
569 }
570
571 /**
572 * Returns the list of ids of all MapCSS classes referenced in the rule selectors.
573 * @return the list of ids of all MapCSS classes referenced in the rule selectors
574 * @since 7881
575 */
576 public Set<String> getClassesIds() {
577 Set<String> result = new HashSet<>();
578 for (Selector s : rule.selectors) {
579 if (s instanceof AbstractSelector) {
580 for (Condition c : ((AbstractSelector)s).getConditions()) {
581 if (c instanceof ClassCondition) {
582 result.add(((ClassCondition) c).id);
583 }
584 }
585 }
586 }
587 return result;
588 }
589 }
590
591 static class MapCSSTagCheckerAndRule extends MapCSSTagChecker {
592 public final GroupedMapCSSRule rule;
593
594 MapCSSTagCheckerAndRule(GroupedMapCSSRule rule) {
595 this.rule = rule;
596 }
597
598 @Override
599 public boolean equals(Object obj) {
600 return super.equals(obj)
601 || (obj instanceof TagCheck && rule.equals(((TagCheck) obj).rule))
602 || (obj instanceof GroupedMapCSSRule && rule.equals(obj));
603 }
604
605 @Override
606 public int hashCode() {
607 final int prime = 31;
608 int result = super.hashCode();
609 result = prime * result + ((rule == null) ? 0 : rule.hashCode());
610 return result;
611 }
612
613 @Override
614 public String toString() {
615 return "MapCSSTagCheckerAndRule [rule=" + rule + "]";
616 }
617 }
618
619 /**
620 * Obtains all {@link TestError}s for the {@link OsmPrimitive} {@code p}.
621 * @param p The OSM primitive
622 * @param includeOtherSeverity if {@code true}, errors of severity {@link Severity#OTHER} (info) will also be returned
623 * @return all errors for the given primitive, with or without those of "info" severity
624 */
625 public synchronized Collection<TestError> getErrorsForPrimitive(OsmPrimitive p, boolean includeOtherSeverity) {
626 return getErrorsForPrimitive(p, includeOtherSeverity, checks.values());
627 }
628
629 private static Collection<TestError> getErrorsForPrimitive(OsmPrimitive p, boolean includeOtherSeverity,
630 Collection<Set<TagCheck>> checksCol) {
631 final List<TestError> r = new ArrayList<>();
632 final Environment env = new Environment(p, new MultiCascade(), Environment.DEFAULT_LAYER, null);
633 for (Set<TagCheck> schecks : checksCol) {
634 for (TagCheck check : schecks) {
635 if (Severity.OTHER.equals(check.getSeverity()) && !includeOtherSeverity) {
636 continue;
637 }
638 final Selector selector = check.whichSelectorMatchesEnvironment(env);
639 if (selector != null) {
640 check.rule.declaration.execute(env);
641 final TestError error = check.getErrorForPrimitive(p, selector, env);
642 if (error != null) {
643 error.setTester(new MapCSSTagCheckerAndRule(check.rule));
644 r.add(error);
645 }
646 }
647 }
648 }
649 return r;
650 }
651
652 /**
653 * Visiting call for primitives.
654 *
655 * @param p The primitive to inspect.
656 */
657 @Override
658 public void check(OsmPrimitive p) {
659 errors.addAll(getErrorsForPrimitive(p, ValidatorPreference.PREF_OTHER.get()));
660 }
661
662 /**
663 * Adds a new MapCSS config file from the given URL.
664 * @param url The unique URL of the MapCSS config file
665 * @throws ParseException if the config file does not match MapCSS syntax
666 * @throws IOException if any I/O error occurs
667 * @since 7275
668 */
669 public synchronized void addMapCSS(String url) throws ParseException, IOException {
670 CheckParameterUtil.ensureParameterNotNull(url, "url");
671 CachedFile cache = new CachedFile(url);
672 InputStream zip = cache.findZipEntryInputStream("validator.mapcss", "");
673 try (InputStream s = zip != null ? zip : cache.getInputStream()) {
674 List<TagCheck> tagchecks = TagCheck.readMapCSS(new BufferedReader(UTFInputStreamReader.create(s)));
675 checks.remove(url);
676 checks.putAll(url, tagchecks);
677 // Check assertions, useful for development of local files
678 if (Main.pref.getBoolean("validator.check_assert_local_rules", false) && Utils.isLocalUrl(url)) {
679 for (String msg : checkAsserts(tagchecks)) {
680 Main.warn(msg);
681 }
682 }
683 }
684 }
685
686 @Override
687 public synchronized void initialize() throws Exception {
688 checks.clear();
689 for (SourceEntry source : new ValidatorTagCheckerRulesPreference.RulePrefHelper().get()) {
690 if (!source.active) {
691 continue;
692 }
693 String i = source.url;
694 try {
695 if (!i.startsWith("resource:")) {
696 Main.info(tr("Adding {0} to tag checker", i));
697 } else if (Main.isDebugEnabled()) {
698 Main.debug(tr("Adding {0} to tag checker", i));
699 }
700 addMapCSS(i);
701 if (Main.pref.getBoolean("validator.auto_reload_local_rules", true) && source.isLocal()) {
702 try {
703 Main.fileWatcher.registerValidatorRule(source);
704 } catch (IOException e) {
705 Main.error(e);
706 }
707 }
708 } catch (IOException ex) {
709 Main.warn(tr("Failed to add {0} to tag checker", i));
710 Main.warn(ex, false);
711 } catch (Exception ex) {
712 Main.warn(tr("Failed to add {0} to tag checker", i));
713 Main.warn(ex);
714 }
715 }
716 }
717
718 /**
719 * Checks that rule assertions are met for the given set of TagChecks.
720 * @param schecks The TagChecks for which assertions have to be checked
721 * @return A set of error messages, empty if all assertions are met
722 * @since 7356
723 */
724 public Set<String> checkAsserts(final Collection<TagCheck> schecks) {
725 Set<String> assertionErrors = new LinkedHashSet<>();
726 final DataSet ds = new DataSet();
727 for (final TagCheck check : schecks) {
728 if (Main.isDebugEnabled()) {
729 Main.debug("Check: "+check);
730 }
731 for (final Map.Entry<String, Boolean> i : check.assertions.entrySet()) {
732 if (Main.isDebugEnabled()) {
733 Main.debug("- Assertion: "+i);
734 }
735 final OsmPrimitive p = OsmUtils.createPrimitive(i.getKey());
736 // Build minimal ordered list of checks to run to test the assertion
737 List<Set<TagCheck>> checksToRun = new ArrayList<Set<TagCheck>>();
738 Set<TagCheck> checkDependencies = check.getTagCheckDependencies(schecks);
739 if (!checkDependencies.isEmpty()) {
740 checksToRun.add(checkDependencies);
741 }
742 checksToRun.add(Collections.singleton(check));
743 // Add primitive to dataset to avoid DataIntegrityProblemException when evaluating selectors
744 ds.addPrimitive(p);
745 final Collection<TestError> pErrors = getErrorsForPrimitive(p, true, checksToRun);
746 if (Main.isDebugEnabled()) {
747 Main.debug("- Errors: "+pErrors);
748 }
749 final boolean isError = Utils.exists(pErrors, new Predicate<TestError>() {
750 @Override
751 public boolean evaluate(TestError e) {
752 //noinspection EqualsBetweenInconvertibleTypes
753 return e.getTester().equals(check.rule);
754 }
755 });
756 if (isError != i.getValue()) {
757 final String error = MessageFormat.format("Expecting test ''{0}'' (i.e., {1}) to {2} {3} (i.e., {4})",
758 check.getMessage(p), check.rule.selectors, i.getValue() ? "match" : "not match", i.getKey(), p.getKeys());
759 assertionErrors.add(error);
760 }
761 ds.removePrimitive(p);
762 }
763 }
764 return assertionErrors;
765 }
766
767 @Override
768 public synchronized int hashCode() {
769 final int prime = 31;
770 int result = super.hashCode();
771 result = prime * result + ((checks == null) ? 0 : checks.hashCode());
772 return result;
773 }
774
775 @Override
776 public synchronized boolean equals(Object obj) {
777 if (this == obj)
778 return true;
779 if (!super.equals(obj))
780 return false;
781 if (!(obj instanceof MapCSSTagChecker))
782 return false;
783 MapCSSTagChecker other = (MapCSSTagChecker) obj;
784 if (checks == null) {
785 if (other.checks != null)
786 return false;
787 } else if (!checks.equals(other.checks))
788 return false;
789 return true;
790 }
791}
Note: See TracBrowser for help on using the repository browser.