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

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

fix compilation warnings with JDK8 - equals() and hashcode() must be overriden in pairs

File size: 23.5 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.Reader;
9import java.util.ArrayList;
10import java.util.Arrays;
11import java.util.Collection;
12import java.util.Collections;
13import java.util.HashMap;
14import java.util.Iterator;
15import java.util.LinkedHashMap;
16import java.util.LinkedList;
17import java.util.List;
18import java.util.Map;
19import java.util.regex.Matcher;
20import java.util.regex.Pattern;
21
22import org.openstreetmap.josm.Main;
23import org.openstreetmap.josm.command.ChangePropertyCommand;
24import org.openstreetmap.josm.command.ChangePropertyKeyCommand;
25import org.openstreetmap.josm.command.Command;
26import org.openstreetmap.josm.command.SequenceCommand;
27import org.openstreetmap.josm.data.osm.OsmPrimitive;
28import org.openstreetmap.josm.data.osm.Tag;
29import org.openstreetmap.josm.data.validation.FixableTestError;
30import org.openstreetmap.josm.data.validation.Severity;
31import org.openstreetmap.josm.data.validation.Test;
32import org.openstreetmap.josm.data.validation.TestError;
33import org.openstreetmap.josm.gui.mappaint.Environment;
34import org.openstreetmap.josm.gui.mappaint.MultiCascade;
35import org.openstreetmap.josm.gui.mappaint.mapcss.Condition;
36import org.openstreetmap.josm.gui.mappaint.mapcss.Expression;
37import org.openstreetmap.josm.gui.mappaint.mapcss.Instruction;
38import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule;
39import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule.Declaration;
40import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
41import org.openstreetmap.josm.gui.mappaint.mapcss.Selector;
42import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector;
43import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser;
44import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException;
45import org.openstreetmap.josm.gui.preferences.validator.ValidatorPreference;
46import org.openstreetmap.josm.gui.preferences.validator.ValidatorTagCheckerRulesPreference;
47import org.openstreetmap.josm.io.MirroredInputStream;
48import org.openstreetmap.josm.io.UTFInputStreamReader;
49import org.openstreetmap.josm.tools.CheckParameterUtil;
50import org.openstreetmap.josm.tools.Predicate;
51import org.openstreetmap.josm.tools.Utils;
52
53/**
54 * MapCSS-based tag checker/fixer.
55 * @since 6506
56 */
57public class MapCSSTagChecker extends Test.TagTest {
58
59 public static class GroupedMapCSSRule {
60 final public List<Selector> selectors;
61 final public Declaration declaration;
62
63 public GroupedMapCSSRule(List<Selector> selectors, Declaration declaration) {
64 this.selectors = selectors;
65 this.declaration = declaration;
66 }
67
68 @Override
69 public int hashCode() {
70 final int prime = 31;
71 int result = 1;
72 result = prime * result + ((declaration == null) ? 0 : declaration.hashCode());
73 result = prime * result + ((selectors == null) ? 0 : selectors.hashCode());
74 return result;
75 }
76
77 @Override
78 public boolean equals(Object obj) {
79 if (this == obj)
80 return true;
81 if (obj == null)
82 return false;
83 if (!(obj instanceof GroupedMapCSSRule))
84 return false;
85 GroupedMapCSSRule other = (GroupedMapCSSRule) obj;
86 if (declaration == null) {
87 if (other.declaration != null)
88 return false;
89 } else if (!declaration.equals(other.declaration))
90 return false;
91 if (selectors == null) {
92 if (other.selectors != null)
93 return false;
94 } else if (!selectors.equals(other.selectors))
95 return false;
96 return true;
97 }
98 }
99
100 /**
101 * The preference key for tag checker source entries.
102 * @since 6670
103 */
104 public static final String ENTRIES_PREF_KEY = "validator." + MapCSSTagChecker.class.getName() + ".entries";
105
106 /**
107 * Constructs a new {@code MapCSSTagChecker}.
108 */
109 public MapCSSTagChecker() {
110 super(tr("Tag checker (MapCSS based)"), tr("This test checks for errors in tag keys and values."));
111 }
112
113 final List<TagCheck> checks = new ArrayList<>();
114
115 static class TagCheck implements Predicate<OsmPrimitive> {
116 protected final GroupedMapCSSRule rule;
117 protected final List<PrimitiveToTag> change = new ArrayList<>();
118 protected final Map<String, String> keyChange = new LinkedHashMap<>();
119 protected final List<String> alternatives = new ArrayList<>();
120 protected final Map<Instruction.AssignmentInstruction, Severity> errors = new HashMap<>();
121 protected final Map<String, Boolean> assertions = new HashMap<>();
122
123 TagCheck(GroupedMapCSSRule rule) {
124 this.rule = rule;
125 }
126
127 /**
128 * A function mapping the matched {@link OsmPrimitive} to a {@link Tag}.
129 */
130 abstract static class PrimitiveToTag implements Utils.Function<OsmPrimitive, Tag> {
131
132 private PrimitiveToTag() {
133 // Hide implicit public constructor for utility class
134 }
135
136 /**
137 * Creates a new mapping from an {@code MapCSS} object.
138 * In case of an {@link Expression}, that is evaluated on the matched {@link OsmPrimitive}.
139 * In case of a {@link String}, that is "compiled" to a {@link Tag} instance.
140 */
141 static PrimitiveToTag ofMapCSSObject(final Object obj, final boolean keyOnly) {
142 if (obj instanceof Expression) {
143 return new PrimitiveToTag() {
144 @Override
145 public Tag apply(OsmPrimitive p) {
146 final String s = (String) ((Expression) obj).evaluate(new Environment().withPrimitive(p));
147 return keyOnly? new Tag(s) : Tag.ofString(s);
148 }
149 };
150 } else if (obj instanceof String) {
151 final Tag tag = keyOnly ? new Tag((String) obj) : Tag.ofString((String) obj);
152 return new PrimitiveToTag() {
153 @Override
154 public Tag apply(OsmPrimitive ignore) {
155 return tag;
156 }
157 };
158 } else {
159 return null;
160 }
161 }
162 }
163
164 static TagCheck ofMapCSSRule(final GroupedMapCSSRule rule) {
165 final TagCheck check = new TagCheck(rule);
166 boolean containsSetClassExpression = false;
167 for (Instruction i : rule.declaration.instructions) {
168 if (i instanceof Instruction.AssignmentInstruction) {
169 final Instruction.AssignmentInstruction ai = (Instruction.AssignmentInstruction) i;
170 if (ai.isSetInstruction) {
171 containsSetClassExpression = true;
172 continue;
173 }
174 final String val = ai.val instanceof Expression
175 ? (String) ((Expression) ai.val).evaluate(new Environment())
176 : ai.val instanceof String
177 ? (String) ai.val
178 : null;
179 if (ai.key.startsWith("throw")) {
180 final Severity severity = Severity.valueOf(ai.key.substring("throw".length()).toUpperCase());
181 check.errors.put(ai, severity);
182 } else if ("fixAdd".equals(ai.key)) {
183 final PrimitiveToTag toTag = PrimitiveToTag.ofMapCSSObject(ai.val, false);
184 check.change.add(toTag);
185 } else if ("fixRemove".equals(ai.key)) {
186 CheckParameterUtil.ensureThat(!(ai.val instanceof String) || !val.contains("="), "Unexpected '='. Please only specify the key to remove!");
187 final PrimitiveToTag toTag = PrimitiveToTag.ofMapCSSObject(ai.val, true);
188 check.change.add(toTag);
189 } else if ("fixChangeKey".equals(ai.key) && val != null) {
190 CheckParameterUtil.ensureThat(val.contains("=>"), "Separate old from new key by '=>'!");
191 final String[] x = val.split("=>", 2);
192 check.keyChange.put(Tag.removeWhiteSpaces(x[0]), Tag.removeWhiteSpaces(x[1]));
193 } else if ("suggestAlternative".equals(ai.key) && val != null) {
194 check.alternatives.add(val);
195 } else if ("assertMatch".equals(ai.key) && val != null) {
196 check.assertions.put(val, true);
197 } else if ("assertNoMatch".equals(ai.key) && val != null) {
198 check.assertions.put(val, false);
199 } else {
200 throw new RuntimeException("Cannot add instruction " + ai.key + ": " + ai.val + "!");
201 }
202 }
203 }
204 if (check.errors.isEmpty() && !containsSetClassExpression) {
205 throw new RuntimeException("No throwError/throwWarning/throwOther given! You should specify a validation error message for " + rule.selectors);
206 } else if (check.errors.size() > 1) {
207 throw new RuntimeException("More than one throwError/throwWarning/throwOther given! You should specify a single validation error message for " + rule.selectors);
208 }
209 return check;
210 }
211
212 static List<TagCheck> readMapCSS(Reader css) throws ParseException {
213 CheckParameterUtil.ensureParameterNotNull(css, "css");
214 return readMapCSS(new MapCSSParser(css));
215 }
216
217 static List<TagCheck> readMapCSS(MapCSSParser css) throws ParseException {
218 CheckParameterUtil.ensureParameterNotNull(css, "css");
219 final MapCSSStyleSource source = new MapCSSStyleSource("");
220 css.sheet(source);
221 assert source.getErrors().isEmpty();
222 // Ignore "meta" rule(s) from external rules of JOSM wiki
223 removeMetaRules(source);
224 // group rules with common declaration block
225 Map<Declaration, List<Selector>> g = new LinkedHashMap<>();
226 for (MapCSSRule rule : source.rules) {
227 if (!g.containsKey(rule.declaration)) {
228 List<Selector> sels = new ArrayList<>();
229 sels.add(rule.selector);
230 g.put(rule.declaration, sels);
231 } else {
232 g.get(rule.declaration).add(rule.selector);
233 }
234 }
235 List<TagCheck> result = new ArrayList<>();
236 for (Map.Entry<Declaration, List<Selector>> map : g.entrySet()) {
237 result.add(TagCheck.ofMapCSSRule(
238 new GroupedMapCSSRule(map.getValue(), map.getKey())));
239 }
240 return result;
241 }
242
243 private static void removeMetaRules(MapCSSStyleSource source) {
244 for (Iterator<MapCSSRule> it = source.rules.iterator(); it.hasNext(); ) {
245 MapCSSRule x = it.next();
246 if (x.selector instanceof GeneralSelector) {
247 GeneralSelector gs = (GeneralSelector) x.selector;
248 if ("meta".equals(gs.base) && gs.getConditions().isEmpty()) {
249 it.remove();
250 }
251 }
252 }
253 }
254
255 @Override
256 public boolean evaluate(OsmPrimitive primitive) {
257 // Tests whether the primitive contains a deprecated tag which is represented by this MapCSSTagChecker.
258 return whichSelectorMatchesPrimitive(primitive) != null;
259 }
260
261 Selector whichSelectorMatchesPrimitive(OsmPrimitive primitive) {
262 return whichSelectorMatchesEnvironment(new Environment().withPrimitive(primitive));
263 }
264
265 Selector whichSelectorMatchesEnvironment(Environment env) {
266 for (Selector i : rule.selectors) {
267 env.clearSelectorMatchingInformation();
268 if (i.matches(env)) {
269 return i;
270 }
271 }
272 return null;
273 }
274
275 /**
276 * Determines the {@code index}-th key/value/tag (depending on {@code type}) of the
277 * {@link org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector}.
278 */
279 static String determineArgument(Selector.GeneralSelector matchingSelector, int index, String type) {
280 try {
281 final Condition c = matchingSelector.getConditions().get(index);
282 final Tag tag = c instanceof Condition.KeyCondition
283 ? ((Condition.KeyCondition) c).asTag()
284 : c instanceof Condition.SimpleKeyValueCondition
285 ? ((Condition.SimpleKeyValueCondition) c).asTag()
286 : c instanceof Condition.KeyValueCondition
287 ? ((Condition.KeyValueCondition) c).asTag()
288 : null;
289 if (tag == null) {
290 return null;
291 } else if ("key".equals(type)) {
292 return tag.getKey();
293 } else if ("value".equals(type)) {
294 return tag.getValue();
295 } else if ("tag".equals(type)) {
296 return tag.toString();
297 }
298 } catch (IndexOutOfBoundsException ignore) {
299 Main.debug(ignore.getMessage());
300 }
301 return null;
302 }
303
304 /**
305 * Replaces occurrences of {@code {i.key}}, {@code {i.value}}, {@code {i.tag}} in {@code s} by the corresponding
306 * key/value/tag of the {@code index}-th {@link Condition} of {@code matchingSelector}.
307 */
308 static String insertArguments(Selector matchingSelector, String s) {
309 if (s != null && matchingSelector instanceof Selector.ChildOrParentSelector) {
310 return insertArguments(((Selector.ChildOrParentSelector)matchingSelector).right, s);
311 } else if (s == null || !(matchingSelector instanceof GeneralSelector)) {
312 return s;
313 }
314 final Matcher m = Pattern.compile("\\{(\\d+)\\.(key|value|tag)\\}").matcher(s);
315 final StringBuffer sb = new StringBuffer();
316 while (m.find()) {
317 final String argument = determineArgument((Selector.GeneralSelector) matchingSelector, Integer.parseInt(m.group(1)), m.group(2));
318 try {
319 m.appendReplacement(sb, String.valueOf(argument));
320 } catch (IndexOutOfBoundsException e) {
321 Main.error(tr("Unable to replace argument {0} in {1}: {2}", argument, sb, e.getMessage()));
322 }
323 }
324 m.appendTail(sb);
325 return sb.toString();
326 }
327
328 /**
329 * Constructs a fix in terms of a {@link org.openstreetmap.josm.command.Command} for the {@link OsmPrimitive}
330 * if the error is fixable, or {@code null} otherwise.
331 *
332 * @param p the primitive to construct the fix for
333 * @return the fix or {@code null}
334 */
335 Command fixPrimitive(OsmPrimitive p) {
336 if (change.isEmpty() && keyChange.isEmpty()) {
337 return null;
338 }
339 final Selector matchingSelector = whichSelectorMatchesPrimitive(p);
340 Collection<Command> cmds = new LinkedList<>();
341 for (PrimitiveToTag toTag : change) {
342 final Tag tag = toTag.apply(p);
343 final String key = insertArguments(matchingSelector, tag.getKey());
344 final String value = insertArguments(matchingSelector, tag.getValue());
345 cmds.add(new ChangePropertyCommand(p, key, value));
346 }
347 for (Map.Entry<String, String> i : keyChange.entrySet()) {
348 final String oldKey = insertArguments(matchingSelector, i.getKey());
349 final String newKey = insertArguments(matchingSelector, i.getValue());
350 cmds.add(new ChangePropertyKeyCommand(p, oldKey, newKey));
351 }
352 return new SequenceCommand(tr("Fix of {0}", getDescriptionForMatchingSelector(p, matchingSelector)), cmds);
353 }
354
355 /**
356 * Constructs a (localized) message for this deprecation check.
357 *
358 * @return a message
359 */
360 String getMessage(OsmPrimitive p) {
361 if (errors.isEmpty()) {
362 // Return something to avoid NPEs
363 return rule.declaration.toString();
364 } else {
365 final Object val = errors.keySet().iterator().next().val;
366 return String.valueOf(
367 val instanceof Expression
368 ? ((Expression) val).evaluate(new Environment().withPrimitive(p))
369 : val
370 );
371 }
372 }
373
374 /**
375 * Constructs a (localized) description for this deprecation check.
376 *
377 * @return a description (possibly with alternative suggestions)
378 * @see #getDescriptionForMatchingSelector
379 */
380 String getDescription(OsmPrimitive p) {
381 if (alternatives.isEmpty()) {
382 return getMessage(p);
383 } else {
384 /* I18N: {0} is the test error message and {1} is an alternative */
385 return tr("{0}, use {1} instead", getMessage(p), Utils.join(tr(" or "), alternatives));
386 }
387 }
388
389 /**
390 * Constructs a (localized) description for this deprecation check
391 * where any placeholders are replaced by values of the matched selector.
392 *
393 * @return a description (possibly with alternative suggestions)
394 */
395 String getDescriptionForMatchingSelector(OsmPrimitive p, Selector matchingSelector) {
396 return insertArguments(matchingSelector, getDescription(p));
397 }
398
399 Severity getSeverity() {
400 return errors.isEmpty() ? null : errors.values().iterator().next();
401 }
402
403 @Override
404 public String toString() {
405 return getDescription(null);
406 }
407
408 /**
409 * Constructs a {@link TestError} for the given primitive, or returns null if the primitive does not give rise to an error.
410 *
411 * @param p the primitive to construct the error for
412 * @return an instance of {@link TestError}, or returns null if the primitive does not give rise to an error.
413 */
414 TestError getErrorForPrimitive(OsmPrimitive p) {
415 final Environment env = new Environment().withPrimitive(p);
416 return getErrorForPrimitive(p, whichSelectorMatchesEnvironment(env), env);
417 }
418
419 TestError getErrorForPrimitive(OsmPrimitive p, Selector matchingSelector, Environment env) {
420 if (matchingSelector != null && !errors.isEmpty()) {
421 final Command fix = fixPrimitive(p);
422 final String description = getDescriptionForMatchingSelector(p, matchingSelector);
423 final List<OsmPrimitive> primitives;
424 if (env.child != null) {
425 primitives = Arrays.asList(p, env.child);
426 } else {
427 primitives = Collections.singletonList(p);
428 }
429 if (fix != null) {
430 return new FixableTestError(null, getSeverity(), description, null, matchingSelector.toString(), 3000, primitives, fix);
431 } else {
432 return new TestError(null, getSeverity(), description, null, matchingSelector.toString(), 3000, primitives);
433 }
434 } else {
435 return null;
436 }
437 }
438 }
439
440 static class MapCSSTagCheckerAndRule extends MapCSSTagChecker {
441 public final GroupedMapCSSRule rule;
442
443 MapCSSTagCheckerAndRule(GroupedMapCSSRule rule) {
444 this.rule = rule;
445 }
446
447 @Override
448 public boolean equals(Object obj) {
449 return super.equals(obj)
450 || (obj instanceof TagCheck && rule.equals(((TagCheck) obj).rule))
451 || (obj instanceof GroupedMapCSSRule && rule.equals(obj));
452 }
453
454 @Override
455 public int hashCode() {
456 final int prime = 31;
457 int result = super.hashCode();
458 result = prime * result + ((rule == null) ? 0 : rule.hashCode());
459 return result;
460 }
461 }
462
463 /**
464 * Obtains all {@link TestError}s for the {@link OsmPrimitive} {@code p}.
465 */
466 public Collection<TestError> getErrorsForPrimitive(OsmPrimitive p, boolean includeOtherSeverity) {
467 final ArrayList<TestError> r = new ArrayList<>();
468 final Environment env = new Environment(p, new MultiCascade(), Environment.DEFAULT_LAYER, null);
469 for (TagCheck check : checks) {
470 if (Severity.OTHER.equals(check.getSeverity()) && !includeOtherSeverity) {
471 continue;
472 }
473 final Selector selector = check.whichSelectorMatchesEnvironment(env);
474 if (selector != null) {
475 check.rule.declaration.execute(env);
476 final TestError error = check.getErrorForPrimitive(p, selector, env);
477 if (error != null) {
478 error.setTester(new MapCSSTagCheckerAndRule(check.rule));
479 r.add(error);
480 }
481 }
482 }
483 return r;
484 }
485
486 /**
487 * Visiting call for primitives.
488 *
489 * @param p The primitive to inspect.
490 */
491 @Override
492 public void check(OsmPrimitive p) {
493 errors.addAll(getErrorsForPrimitive(p, ValidatorPreference.PREF_OTHER.get()));
494 }
495
496 /**
497 * Adds a new MapCSS config file from the given {@code Reader}.
498 * @param css The reader
499 * @throws ParseException if the config file does not match MapCSS syntax
500 */
501 public void addMapCSS(Reader css) throws ParseException {
502 checks.addAll(TagCheck.readMapCSS(css));
503 }
504
505 @Override
506 public synchronized void initialize() throws Exception {
507 checks.clear();
508 for (String i : new ValidatorTagCheckerRulesPreference.RulePrefHelper().getActiveUrls()) {
509 try {
510 if (i.startsWith("resource:")) {
511 Main.debug(tr("Adding {0} to tag checker", i));
512 } else {
513 Main.info(tr("Adding {0} to tag checker", i));
514 }
515 try (MirroredInputStream s = new MirroredInputStream(i)) {
516 addMapCSS(new BufferedReader(UTFInputStreamReader.create(s)));
517 }
518 } catch (IOException ex) {
519 Main.warn(tr("Failed to add {0} to tag checker", i));
520 Main.warn(ex, false);
521 } catch (Exception ex) {
522 Main.warn(tr("Failed to add {0} to tag checker", i));
523 Main.warn(ex);
524 }
525 }
526 }
527
528 @Override
529 public int hashCode() {
530 final int prime = 31;
531 int result = super.hashCode();
532 result = prime * result + ((checks == null) ? 0 : checks.hashCode());
533 return result;
534 }
535
536 @Override
537 public boolean equals(Object obj) {
538 if (this == obj)
539 return true;
540 if (!super.equals(obj))
541 return false;
542 if (!(obj instanceof MapCSSTagChecker))
543 return false;
544 MapCSSTagChecker other = (MapCSSTagChecker) obj;
545 if (checks == null) {
546 if (other.checks != null)
547 return false;
548 } else if (!checks.equals(other.checks))
549 return false;
550 return true;
551 }
552}
Note: See TracBrowser for help on using the repository browser.