source: josm/trunk/src/org/openstreetmap/josm/data/validation/tests/TagChecker.java@ 11746

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

PMD - Strict Exceptions

  • Property svn:eol-style set to native
File size: 36.8 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.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.GridBagConstraints;
8import java.awt.event.ActionListener;
9import java.io.BufferedReader;
10import java.io.IOException;
11import java.util.ArrayList;
12import java.util.Arrays;
13import java.util.Collection;
14import java.util.HashMap;
15import java.util.HashSet;
16import java.util.List;
17import java.util.Locale;
18import java.util.Map;
19import java.util.Map.Entry;
20import java.util.Set;
21import java.util.regex.Matcher;
22import java.util.regex.Pattern;
23import java.util.regex.PatternSyntaxException;
24
25import javax.swing.JCheckBox;
26import javax.swing.JLabel;
27import javax.swing.JPanel;
28
29import org.openstreetmap.josm.Main;
30import org.openstreetmap.josm.command.ChangePropertyCommand;
31import org.openstreetmap.josm.command.ChangePropertyKeyCommand;
32import org.openstreetmap.josm.command.Command;
33import org.openstreetmap.josm.command.SequenceCommand;
34import org.openstreetmap.josm.data.osm.OsmPrimitive;
35import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
36import org.openstreetmap.josm.data.osm.OsmUtils;
37import org.openstreetmap.josm.data.osm.Tag;
38import org.openstreetmap.josm.data.validation.Severity;
39import org.openstreetmap.josm.data.validation.Test.TagTest;
40import org.openstreetmap.josm.data.validation.TestError;
41import org.openstreetmap.josm.data.validation.util.Entities;
42import org.openstreetmap.josm.gui.preferences.validator.ValidatorPreference;
43import org.openstreetmap.josm.gui.progress.ProgressMonitor;
44import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;
45import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetItem;
46import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets;
47import org.openstreetmap.josm.gui.tagging.presets.items.Check;
48import org.openstreetmap.josm.gui.tagging.presets.items.CheckGroup;
49import org.openstreetmap.josm.gui.tagging.presets.items.KeyedItem;
50import org.openstreetmap.josm.gui.widgets.EditableList;
51import org.openstreetmap.josm.io.CachedFile;
52import org.openstreetmap.josm.tools.GBC;
53import org.openstreetmap.josm.tools.MultiMap;
54import org.openstreetmap.josm.tools.Utils;
55
56/**
57 * Check for misspelled or wrong tags
58 *
59 * @author frsantos
60 * @since 3669
61 */
62public class TagChecker extends TagTest {
63
64 /** The config file of ignored tags */
65 public static final String IGNORE_FILE = "resource://data/validator/ignoretags.cfg";
66 /** The config file of dictionary words */
67 public static final String SPELL_FILE = "resource://data/validator/words.cfg";
68
69 /** Normalized keys: the key should be substituted by the value if the key was not found in presets */
70 private static final Map<String, String> harmonizedKeys = new HashMap<>();
71 /** The spell check preset values */
72 private static volatile MultiMap<String, String> presetsValueData;
73 /** The TagChecker data */
74 private static final List<CheckerData> checkerData = new ArrayList<>();
75 private static final List<String> ignoreDataStartsWith = new ArrayList<>();
76 private static final List<String> ignoreDataEquals = new ArrayList<>();
77 private static final List<String> ignoreDataEndsWith = new ArrayList<>();
78 private static final List<Tag> ignoreDataTag = new ArrayList<>();
79
80 /** The preferences prefix */
81 protected static final String PREFIX = ValidatorPreference.PREFIX + "." + TagChecker.class.getSimpleName();
82
83 public static final String PREF_CHECK_VALUES = PREFIX + ".checkValues";
84 public static final String PREF_CHECK_KEYS = PREFIX + ".checkKeys";
85 public static final String PREF_CHECK_COMPLEX = PREFIX + ".checkComplex";
86 public static final String PREF_CHECK_FIXMES = PREFIX + ".checkFixmes";
87
88 public static final String PREF_SOURCES = PREFIX + ".source";
89
90 public static final String PREF_CHECK_KEYS_BEFORE_UPLOAD = PREF_CHECK_KEYS + "BeforeUpload";
91 public static final String PREF_CHECK_VALUES_BEFORE_UPLOAD = PREF_CHECK_VALUES + "BeforeUpload";
92 public static final String PREF_CHECK_COMPLEX_BEFORE_UPLOAD = PREF_CHECK_COMPLEX + "BeforeUpload";
93 public static final String PREF_CHECK_FIXMES_BEFORE_UPLOAD = PREF_CHECK_FIXMES + "BeforeUpload";
94
95 protected boolean checkKeys;
96 protected boolean checkValues;
97 protected boolean checkComplex;
98 protected boolean checkFixmes;
99
100 protected JCheckBox prefCheckKeys;
101 protected JCheckBox prefCheckValues;
102 protected JCheckBox prefCheckComplex;
103 protected JCheckBox prefCheckFixmes;
104 protected JCheckBox prefCheckPaint;
105
106 protected JCheckBox prefCheckKeysBeforeUpload;
107 protected JCheckBox prefCheckValuesBeforeUpload;
108 protected JCheckBox prefCheckComplexBeforeUpload;
109 protected JCheckBox prefCheckFixmesBeforeUpload;
110 protected JCheckBox prefCheckPaintBeforeUpload;
111
112 // CHECKSTYLE.OFF: SingleSpaceSeparator
113 protected static final int EMPTY_VALUES = 1200;
114 protected static final int INVALID_KEY = 1201;
115 protected static final int INVALID_VALUE = 1202;
116 protected static final int FIXME = 1203;
117 protected static final int INVALID_SPACE = 1204;
118 protected static final int INVALID_KEY_SPACE = 1205;
119 protected static final int INVALID_HTML = 1206; /* 1207 was PAINT */
120 protected static final int LONG_VALUE = 1208;
121 protected static final int LONG_KEY = 1209;
122 protected static final int LOW_CHAR_VALUE = 1210;
123 protected static final int LOW_CHAR_KEY = 1211;
124 protected static final int MISSPELLED_VALUE = 1212;
125 protected static final int MISSPELLED_KEY = 1213;
126 protected static final int MULTIPLE_SPACES = 1214;
127 // CHECKSTYLE.ON: SingleSpaceSeparator
128 // 1250 and up is used by tagcheck
129
130 protected EditableList sourcesList;
131
132 private static final Set<String> DEFAULT_SOURCES = new HashSet<>(Arrays.asList(/*DATA_FILE, */IGNORE_FILE, SPELL_FILE));
133
134 /**
135 * Constructor
136 */
137 public TagChecker() {
138 super(tr("Tag checker"), tr("This test checks for errors in tag keys and values."));
139 }
140
141 @Override
142 public void initialize() throws IOException {
143 initializeData();
144 initializePresets();
145 }
146
147 /**
148 * Reads the spellcheck file into a HashMap.
149 * The data file is a list of words, beginning with +/-. If it starts with +,
150 * the word is valid, but if it starts with -, the word should be replaced
151 * by the nearest + word before this.
152 *
153 * @throws IOException if any I/O error occurs
154 */
155 private static void initializeData() throws IOException {
156 checkerData.clear();
157 ignoreDataStartsWith.clear();
158 ignoreDataEquals.clear();
159 ignoreDataEndsWith.clear();
160 ignoreDataTag.clear();
161 harmonizedKeys.clear();
162
163 StringBuilder errorSources = new StringBuilder();
164 for (String source : Main.pref.getCollection(PREF_SOURCES, DEFAULT_SOURCES)) {
165 try (
166 CachedFile cf = new CachedFile(source);
167 BufferedReader reader = cf.getContentReader()
168 ) {
169 String okValue = null;
170 boolean tagcheckerfile = false;
171 boolean ignorefile = false;
172 boolean isFirstLine = true;
173 String line;
174 while ((line = reader.readLine()) != null && (tagcheckerfile || !line.isEmpty())) {
175 if (line.startsWith("#")) {
176 if (line.startsWith("# JOSM TagChecker")) {
177 tagcheckerfile = true;
178 if (!DEFAULT_SOURCES.contains(source)) {
179 Main.info(tr("Adding {0} to tag checker", source));
180 }
181 } else
182 if (line.startsWith("# JOSM IgnoreTags")) {
183 ignorefile = true;
184 if (!DEFAULT_SOURCES.contains(source)) {
185 Main.info(tr("Adding {0} to ignore tags", source));
186 }
187 }
188 } else if (ignorefile) {
189 line = line.trim();
190 if (line.length() < 4) {
191 continue;
192 }
193
194 String key = line.substring(0, 2);
195 line = line.substring(2);
196
197 switch (key) {
198 case "S:":
199 ignoreDataStartsWith.add(line);
200 break;
201 case "E:":
202 ignoreDataEquals.add(line);
203 break;
204 case "F:":
205 ignoreDataEndsWith.add(line);
206 break;
207 case "K:":
208 ignoreDataTag.add(Tag.ofString(line));
209 break;
210 default:
211 if (!key.startsWith(";")) {
212 Main.warn("Unsupported TagChecker key: " + key);
213 }
214 }
215 } else if (tagcheckerfile) {
216 if (!line.isEmpty()) {
217 CheckerData d = new CheckerData();
218 String err = d.getData(line);
219
220 if (err == null) {
221 checkerData.add(d);
222 } else {
223 Main.error(tr("Invalid tagchecker line - {0}: {1}", err, line));
224 }
225 }
226 } else if (line.charAt(0) == '+') {
227 okValue = line.substring(1);
228 } else if (line.charAt(0) == '-' && okValue != null) {
229 harmonizedKeys.put(harmonizeKey(line.substring(1)), okValue);
230 } else {
231 Main.error(tr("Invalid spellcheck line: {0}", line));
232 }
233 if (isFirstLine) {
234 isFirstLine = false;
235 if (!(tagcheckerfile || ignorefile) && !DEFAULT_SOURCES.contains(source)) {
236 Main.info(tr("Adding {0} to spellchecker", source));
237 }
238 }
239 }
240 } catch (IOException e) {
241 Main.error(e);
242 errorSources.append(source).append('\n');
243 }
244 }
245
246 if (errorSources.length() > 0)
247 throw new IOException(tr("Could not access data file(s):\n{0}", errorSources));
248 }
249
250 /**
251 * Reads the presets data.
252 *
253 */
254 public static void initializePresets() {
255
256 if (!Main.pref.getBoolean(PREF_CHECK_VALUES, true))
257 return;
258
259 Collection<TaggingPreset> presets = TaggingPresets.getTaggingPresets();
260 if (!presets.isEmpty()) {
261 presetsValueData = new MultiMap<>();
262 for (String a : OsmPrimitive.getUninterestingKeys()) {
263 presetsValueData.putVoid(a);
264 }
265 // TODO directionKeys are no longer in OsmPrimitive (search pattern is used instead)
266 for (String a : Main.pref.getCollection(ValidatorPreference.PREFIX + ".knownkeys",
267 Arrays.asList(new String[]{"is_in", "int_ref", "fixme", "population"}))) {
268 presetsValueData.putVoid(a);
269 }
270 for (TaggingPreset p : presets) {
271 for (TaggingPresetItem i : p.data) {
272 if (i instanceof KeyedItem) {
273 addPresetValue((KeyedItem) i);
274 } else if (i instanceof CheckGroup) {
275 for (Check c : ((CheckGroup) i).checks) {
276 addPresetValue(c);
277 }
278 }
279 }
280 }
281 }
282 }
283
284 private static void addPresetValue(KeyedItem ky) {
285 Collection<String> values = ky.getValues();
286 if (ky.key != null && values != null) {
287 presetsValueData.putAll(ky.key, values);
288 harmonizedKeys.put(harmonizeKey(ky.key), ky.key);
289 }
290 }
291
292 /**
293 * Checks given string (key or value) if it contains characters with code below 0x20 (either newline or some other special characters)
294 * @param s string to check
295 * @return {@code true} if {@code s} contains characters with code below 0x20
296 */
297 private static boolean containsLow(String s) {
298 if (s == null)
299 return false;
300 for (int i = 0; i < s.length(); i++) {
301 if (s.charAt(i) < 0x20)
302 return true;
303 }
304 return false;
305 }
306
307 /**
308 * Determines if the given key is in internal presets.
309 * @param key key
310 * @return {@code true} if the given key is in internal presets
311 * @since 9023
312 */
313 public static boolean isKeyInPresets(String key) {
314 return presetsValueData.get(key) != null;
315 }
316
317 /**
318 * Determines if the given tag is in internal presets.
319 * @param key key
320 * @param value value
321 * @return {@code true} if the given tag is in internal presets
322 * @since 9023
323 */
324 public static boolean isTagInPresets(String key, String value) {
325 final Set<String> values = presetsValueData.get(key);
326 return values != null && (values.isEmpty() || values.contains(value));
327 }
328
329 /**
330 * Returns the list of ignored tags.
331 * @return the list of ignored tags
332 * @since 9023
333 */
334 public static List<Tag> getIgnoredTags() {
335 return new ArrayList<>(ignoreDataTag);
336 }
337
338 /**
339 * Determines if the given tag is ignored for checks "key/tag not in presets".
340 * @param key key
341 * @param value value
342 * @return {@code true} if the given tag is ignored
343 * @since 9023
344 */
345 public static boolean isTagIgnored(String key, String value) {
346 boolean tagInPresets = isTagInPresets(key, value);
347 boolean ignore = false;
348
349 for (String a : ignoreDataStartsWith) {
350 if (key.startsWith(a)) {
351 ignore = true;
352 }
353 }
354 for (String a : ignoreDataEquals) {
355 if (key.equals(a)) {
356 ignore = true;
357 }
358 }
359 for (String a : ignoreDataEndsWith) {
360 if (key.endsWith(a)) {
361 ignore = true;
362 }
363 }
364
365 if (!tagInPresets) {
366 for (Tag a : ignoreDataTag) {
367 if (key.equals(a.getKey()) && value.equals(a.getValue())) {
368 ignore = true;
369 }
370 }
371 }
372 return ignore;
373 }
374
375 /**
376 * Checks the primitive tags
377 * @param p The primitive to check
378 */
379 @Override
380 public void check(OsmPrimitive p) {
381 // Just a collection to know if a primitive has been already marked with error
382 MultiMap<OsmPrimitive, String> withErrors = new MultiMap<>();
383
384 if (checkComplex) {
385 Map<String, String> keys = p.getKeys();
386 for (CheckerData d : checkerData) {
387 if (d.match(p, keys)) {
388 errors.add(TestError.builder(this, d.getSeverity(), d.getCode())
389 .message(tr("Suspicious tag/value combinations"), d.getDescription())
390 .primitives(p)
391 .build());
392 withErrors.put(p, "TC");
393 }
394 }
395 }
396
397 for (Entry<String, String> prop : p.getKeys().entrySet()) {
398 String s = marktr("Key ''{0}'' invalid.");
399 String key = prop.getKey();
400 String value = prop.getValue();
401 if (checkValues && (containsLow(value)) && !withErrors.contains(p, "ICV")) {
402 errors.add(TestError.builder(this, Severity.WARNING, LOW_CHAR_VALUE)
403 .message(tr("Tag value contains character with code less than 0x20"), s, key)
404 .primitives(p)
405 .build());
406 withErrors.put(p, "ICV");
407 }
408 if (checkKeys && (containsLow(key)) && !withErrors.contains(p, "ICK")) {
409 errors.add(TestError.builder(this, Severity.WARNING, LOW_CHAR_KEY)
410 .message(tr("Tag key contains character with code less than 0x20"), s, key)
411 .primitives(p)
412 .build());
413 withErrors.put(p, "ICK");
414 }
415 if (checkValues && (value != null && value.length() > 255) && !withErrors.contains(p, "LV")) {
416 errors.add(TestError.builder(this, Severity.ERROR, LONG_VALUE)
417 .message(tr("Tag value longer than allowed"), s, key)
418 .primitives(p)
419 .build());
420 withErrors.put(p, "LV");
421 }
422 if (checkKeys && (key != null && key.length() > 255) && !withErrors.contains(p, "LK")) {
423 errors.add(TestError.builder(this, Severity.ERROR, LONG_KEY)
424 .message(tr("Tag key longer than allowed"), s, key)
425 .primitives(p)
426 .build());
427 withErrors.put(p, "LK");
428 }
429 if (checkValues && (value == null || value.trim().isEmpty()) && !withErrors.contains(p, "EV")) {
430 errors.add(TestError.builder(this, Severity.WARNING, EMPTY_VALUES)
431 .message(tr("Tags with empty values"), s, key)
432 .primitives(p)
433 .build());
434 withErrors.put(p, "EV");
435 }
436 if (checkKeys && key != null && key.indexOf(' ') >= 0 && !withErrors.contains(p, "IPK")) {
437 errors.add(TestError.builder(this, Severity.WARNING, INVALID_KEY_SPACE)
438 .message(tr("Invalid white space in property key"), s, key)
439 .primitives(p)
440 .build());
441 withErrors.put(p, "IPK");
442 }
443 if (checkValues && value != null && (value.startsWith(" ") || value.endsWith(" ")) && !withErrors.contains(p, "SPACE")) {
444 errors.add(TestError.builder(this, Severity.WARNING, INVALID_SPACE)
445 .message(tr("Property values start or end with white space"), s, key)
446 .primitives(p)
447 .build());
448 withErrors.put(p, "SPACE");
449 }
450 if (checkValues && value != null && value.contains(" ") && !withErrors.contains(p, "SPACE")) {
451 errors.add(TestError.builder(this, Severity.WARNING, MULTIPLE_SPACES)
452 .message(tr("Property values contain multiple white spaces"), s, key)
453 .primitives(p)
454 .build());
455 withErrors.put(p, "SPACE");
456 }
457 if (checkValues && value != null && !value.equals(Entities.unescape(value)) && !withErrors.contains(p, "HTML")) {
458 errors.add(TestError.builder(this, Severity.OTHER, INVALID_HTML)
459 .message(tr("Property values contain HTML entity"), s, key)
460 .primitives(p)
461 .build());
462 withErrors.put(p, "HTML");
463 }
464 if (checkValues && key != null && value != null && !value.isEmpty() && presetsValueData != null && !isTagIgnored(key, value)) {
465 if (!isKeyInPresets(key)) {
466 String prettifiedKey = harmonizeKey(key);
467 String fixedKey = harmonizedKeys.get(prettifiedKey);
468 if (fixedKey != null && !"".equals(fixedKey) && !fixedKey.equals(key)) {
469 // misspelled preset key
470 final TestError.Builder error = TestError.builder(this, Severity.WARNING, MISSPELLED_KEY)
471 .message(tr("Misspelled property key"), marktr("Key ''{0}'' looks like ''{1}''."), key, fixedKey)
472 .primitives(p);
473 if (p.hasKey(fixedKey)) {
474 errors.add(error.build());
475 } else {
476 errors.add(error.fix(() -> new ChangePropertyKeyCommand(p, key, fixedKey)).build());
477 }
478 withErrors.put(p, "WPK");
479 } else {
480 errors.add(TestError.builder(this, Severity.OTHER, INVALID_VALUE)
481 .message(tr("Presets do not contain property key"), marktr("Key ''{0}'' not in presets."), key)
482 .primitives(p)
483 .build());
484 withErrors.put(p, "UPK");
485 }
486 } else if (!isTagInPresets(key, value)) {
487 // try to fix common typos and check again if value is still unknown
488 String fixedValue = harmonizeValue(prop.getValue());
489 Map<String, String> possibleValues = getPossibleValues(presetsValueData.get(key));
490 if (possibleValues.containsKey(fixedValue)) {
491 final String newKey = possibleValues.get(fixedValue);
492 // misspelled preset value
493 errors.add(TestError.builder(this, Severity.WARNING, MISSPELLED_VALUE)
494 .message(tr("Misspelled property value"),
495 marktr("Value ''{0}'' for key ''{1}'' looks like ''{2}''."), prop.getValue(), key, fixedValue)
496 .primitives(p)
497 .fix(() -> new ChangePropertyCommand(p, key, newKey))
498 .build());
499 withErrors.put(p, "WPV");
500 } else {
501 // unknown preset value
502 errors.add(TestError.builder(this, Severity.OTHER, INVALID_VALUE)
503 .message(tr("Presets do not contain property value"),
504 marktr("Value ''{0}'' for key ''{1}'' not in presets."), prop.getValue(), key)
505 .primitives(p)
506 .build());
507 withErrors.put(p, "UPV");
508 }
509 }
510 }
511 if (checkFixmes && key != null && value != null && !value.isEmpty() && isFixme(key, value) && !withErrors.contains(p, "FIXME")) {
512 errors.add(TestError.builder(this, Severity.OTHER, FIXME)
513 .message(tr("FIXMES"))
514 .primitives(p)
515 .build());
516 withErrors.put(p, "FIXME");
517 }
518 }
519 }
520
521 private static boolean isFixme(String key, String value) {
522 return key.toLowerCase(Locale.ENGLISH).contains("fixme") || key.contains("todo")
523 || value.toLowerCase(Locale.ENGLISH).contains("fixme") || value.contains("check and delete");
524 }
525
526 private static Map<String, String> getPossibleValues(Set<String> values) {
527 // generate a map with common typos
528 Map<String, String> map = new HashMap<>();
529 if (values != null) {
530 for (String value : values) {
531 map.put(value, value);
532 if (value.contains("_")) {
533 map.put(value.replace("_", ""), value);
534 }
535 }
536 }
537 return map;
538 }
539
540 private static String harmonizeKey(String key) {
541 return Utils.strip(key.toLowerCase(Locale.ENGLISH).replace('-', '_').replace(':', '_').replace(' ', '_'), "-_;:,");
542 }
543
544 private static String harmonizeValue(String value) {
545 return Utils.strip(value.toLowerCase(Locale.ENGLISH).replace('-', '_').replace(' ', '_'), "-_;:,");
546 }
547
548 @Override
549 public void startTest(ProgressMonitor monitor) {
550 super.startTest(monitor);
551 checkKeys = Main.pref.getBoolean(PREF_CHECK_KEYS, true);
552 if (isBeforeUpload) {
553 checkKeys = checkKeys && Main.pref.getBoolean(PREF_CHECK_KEYS_BEFORE_UPLOAD, true);
554 }
555
556 checkValues = Main.pref.getBoolean(PREF_CHECK_VALUES, true);
557 if (isBeforeUpload) {
558 checkValues = checkValues && Main.pref.getBoolean(PREF_CHECK_VALUES_BEFORE_UPLOAD, true);
559 }
560
561 checkComplex = Main.pref.getBoolean(PREF_CHECK_COMPLEX, true);
562 if (isBeforeUpload) {
563 checkComplex = checkComplex && Main.pref.getBoolean(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, true);
564 }
565
566 checkFixmes = Main.pref.getBoolean(PREF_CHECK_FIXMES, true);
567 if (isBeforeUpload) {
568 checkFixmes = checkFixmes && Main.pref.getBoolean(PREF_CHECK_FIXMES_BEFORE_UPLOAD, true);
569 }
570 }
571
572 @Override
573 public void visit(Collection<OsmPrimitive> selection) {
574 if (checkKeys || checkValues || checkComplex || checkFixmes) {
575 super.visit(selection);
576 }
577 }
578
579 @Override
580 public void addGui(JPanel testPanel) {
581 GBC a = GBC.eol();
582 a.anchor = GridBagConstraints.EAST;
583
584 testPanel.add(new JLabel(name+" :"), GBC.eol().insets(3, 0, 0, 0));
585
586 prefCheckKeys = new JCheckBox(tr("Check property keys."), Main.pref.getBoolean(PREF_CHECK_KEYS, true));
587 prefCheckKeys.setToolTipText(tr("Validate that property keys are valid checking against list of words."));
588 testPanel.add(prefCheckKeys, GBC.std().insets(20, 0, 0, 0));
589
590 prefCheckKeysBeforeUpload = new JCheckBox();
591 prefCheckKeysBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_KEYS_BEFORE_UPLOAD, true));
592 testPanel.add(prefCheckKeysBeforeUpload, a);
593
594 prefCheckComplex = new JCheckBox(tr("Use complex property checker."), Main.pref.getBoolean(PREF_CHECK_COMPLEX, true));
595 prefCheckComplex.setToolTipText(tr("Validate property values and tags using complex rules."));
596 testPanel.add(prefCheckComplex, GBC.std().insets(20, 0, 0, 0));
597
598 prefCheckComplexBeforeUpload = new JCheckBox();
599 prefCheckComplexBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, true));
600 testPanel.add(prefCheckComplexBeforeUpload, a);
601
602 final Collection<String> sources = Main.pref.getCollection(PREF_SOURCES, DEFAULT_SOURCES);
603 sourcesList = new EditableList(tr("TagChecker source"));
604 sourcesList.setItems(sources);
605 testPanel.add(new JLabel(tr("Data sources ({0})", "*.cfg")), GBC.eol().insets(23, 0, 0, 0));
606 testPanel.add(sourcesList, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(23, 0, 0, 0));
607
608 ActionListener disableCheckActionListener = e -> handlePrefEnable();
609 prefCheckKeys.addActionListener(disableCheckActionListener);
610 prefCheckKeysBeforeUpload.addActionListener(disableCheckActionListener);
611 prefCheckComplex.addActionListener(disableCheckActionListener);
612 prefCheckComplexBeforeUpload.addActionListener(disableCheckActionListener);
613
614 handlePrefEnable();
615
616 prefCheckValues = new JCheckBox(tr("Check property values."), Main.pref.getBoolean(PREF_CHECK_VALUES, true));
617 prefCheckValues.setToolTipText(tr("Validate that property values are valid checking against presets."));
618 testPanel.add(prefCheckValues, GBC.std().insets(20, 0, 0, 0));
619
620 prefCheckValuesBeforeUpload = new JCheckBox();
621 prefCheckValuesBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_VALUES_BEFORE_UPLOAD, true));
622 testPanel.add(prefCheckValuesBeforeUpload, a);
623
624 prefCheckFixmes = new JCheckBox(tr("Check for FIXMES."), Main.pref.getBoolean(PREF_CHECK_FIXMES, true));
625 prefCheckFixmes.setToolTipText(tr("Looks for nodes or ways with FIXME in any property value."));
626 testPanel.add(prefCheckFixmes, GBC.std().insets(20, 0, 0, 0));
627
628 prefCheckFixmesBeforeUpload = new JCheckBox();
629 prefCheckFixmesBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_FIXMES_BEFORE_UPLOAD, true));
630 testPanel.add(prefCheckFixmesBeforeUpload, a);
631 }
632
633 public void handlePrefEnable() {
634 boolean selected = prefCheckKeys.isSelected() || prefCheckKeysBeforeUpload.isSelected()
635 || prefCheckComplex.isSelected() || prefCheckComplexBeforeUpload.isSelected();
636 sourcesList.setEnabled(selected);
637 }
638
639 @Override
640 public boolean ok() {
641 enabled = prefCheckKeys.isSelected() || prefCheckValues.isSelected() || prefCheckComplex.isSelected() || prefCheckFixmes.isSelected();
642 testBeforeUpload = prefCheckKeysBeforeUpload.isSelected() || prefCheckValuesBeforeUpload.isSelected()
643 || prefCheckFixmesBeforeUpload.isSelected() || prefCheckComplexBeforeUpload.isSelected();
644
645 Main.pref.put(PREF_CHECK_VALUES, prefCheckValues.isSelected());
646 Main.pref.put(PREF_CHECK_COMPLEX, prefCheckComplex.isSelected());
647 Main.pref.put(PREF_CHECK_KEYS, prefCheckKeys.isSelected());
648 Main.pref.put(PREF_CHECK_FIXMES, prefCheckFixmes.isSelected());
649 Main.pref.put(PREF_CHECK_VALUES_BEFORE_UPLOAD, prefCheckValuesBeforeUpload.isSelected());
650 Main.pref.put(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, prefCheckComplexBeforeUpload.isSelected());
651 Main.pref.put(PREF_CHECK_KEYS_BEFORE_UPLOAD, prefCheckKeysBeforeUpload.isSelected());
652 Main.pref.put(PREF_CHECK_FIXMES_BEFORE_UPLOAD, prefCheckFixmesBeforeUpload.isSelected());
653 return Main.pref.putCollection(PREF_SOURCES, sourcesList.getItems());
654 }
655
656 @Override
657 public Command fixError(TestError testError) {
658 List<Command> commands = new ArrayList<>(50);
659
660 Collection<? extends OsmPrimitive> primitives = testError.getPrimitives();
661 for (OsmPrimitive p : primitives) {
662 Map<String, String> tags = p.getKeys();
663 if (tags.isEmpty()) {
664 continue;
665 }
666
667 for (Entry<String, String> prop: tags.entrySet()) {
668 String key = prop.getKey();
669 String value = prop.getValue();
670 if (value == null || value.trim().isEmpty()) {
671 commands.add(new ChangePropertyCommand(p, key, null));
672 } else if (value.startsWith(" ") || value.endsWith(" ") || value.contains(" ")) {
673 commands.add(new ChangePropertyCommand(p, key, Tag.removeWhiteSpaces(value)));
674 } else if (key.startsWith(" ") || key.endsWith(" ") || key.contains(" ")) {
675 commands.add(new ChangePropertyKeyCommand(p, key, Tag.removeWhiteSpaces(key)));
676 } else {
677 String evalue = Entities.unescape(value);
678 if (!evalue.equals(value)) {
679 commands.add(new ChangePropertyCommand(p, key, evalue));
680 }
681 }
682 }
683 }
684
685 if (commands.isEmpty())
686 return null;
687 if (commands.size() == 1)
688 return commands.get(0);
689
690 return new SequenceCommand(tr("Fix tags"), commands);
691 }
692
693 @Override
694 public boolean isFixable(TestError testError) {
695 if (testError.getTester() instanceof TagChecker) {
696 int code = testError.getCode();
697 return code == INVALID_KEY || code == EMPTY_VALUES || code == INVALID_SPACE ||
698 code == INVALID_KEY_SPACE || code == INVALID_HTML || code == MISSPELLED_VALUE ||
699 code == MULTIPLE_SPACES;
700 }
701
702 return false;
703 }
704
705 protected static class CheckerData {
706 private String description;
707 protected List<CheckerElement> data = new ArrayList<>();
708 private OsmPrimitiveType type;
709 private int code;
710 protected Severity severity;
711 // CHECKSTYLE.OFF: SingleSpaceSeparator
712 protected static final int TAG_CHECK_ERROR = 1250;
713 protected static final int TAG_CHECK_WARN = 1260;
714 protected static final int TAG_CHECK_INFO = 1270;
715 // CHECKSTYLE.ON: SingleSpaceSeparator
716
717 protected static class CheckerElement {
718 public Object tag;
719 public Object value;
720 public boolean noMatch;
721 public boolean tagAll;
722 public boolean valueAll;
723 public boolean valueBool;
724
725 private static Pattern getPattern(String str) {
726 if (str.endsWith("/i"))
727 return Pattern.compile(str.substring(1, str.length()-2), Pattern.CASE_INSENSITIVE);
728 if (str.endsWith("/"))
729 return Pattern.compile(str.substring(1, str.length()-1));
730
731 throw new IllegalStateException();
732 }
733
734 public CheckerElement(String exp) {
735 Matcher m = Pattern.compile("(.+)([!=]=)(.+)").matcher(exp);
736 m.matches();
737
738 String n = m.group(1).trim();
739
740 if ("*".equals(n)) {
741 tagAll = true;
742 } else {
743 tag = n.startsWith("/") ? getPattern(n) : n;
744 noMatch = "!=".equals(m.group(2));
745 n = m.group(3).trim();
746 if ("*".equals(n)) {
747 valueAll = true;
748 } else if ("BOOLEAN_TRUE".equals(n)) {
749 valueBool = true;
750 value = OsmUtils.trueval;
751 } else if ("BOOLEAN_FALSE".equals(n)) {
752 valueBool = true;
753 value = OsmUtils.falseval;
754 } else {
755 value = n.startsWith("/") ? getPattern(n) : n;
756 }
757 }
758 }
759
760 public boolean match(Map<String, String> keys) {
761 for (Entry<String, String> prop: keys.entrySet()) {
762 String key = prop.getKey();
763 String val = valueBool ? OsmUtils.getNamedOsmBoolean(prop.getValue()) : prop.getValue();
764 if ((tagAll || (tag instanceof Pattern ? ((Pattern) tag).matcher(key).matches() : key.equals(tag)))
765 && (valueAll || (value instanceof Pattern ? ((Pattern) value).matcher(val).matches() : val.equals(value))))
766 return !noMatch;
767 }
768 return noMatch;
769 }
770 }
771
772 private static final Pattern CLEAN_STR_PATTERN = Pattern.compile(" *# *([^#]+) *$");
773 private static final Pattern SPLIT_TRIMMED_PATTERN = Pattern.compile(" *: *");
774 private static final Pattern SPLIT_ELEMENTS_PATTERN = Pattern.compile(" *&& *");
775
776 public String getData(final String str) {
777 Matcher m = CLEAN_STR_PATTERN.matcher(str);
778 String trimmed = m.replaceFirst("").trim();
779 try {
780 description = m.group(1);
781 if (description != null && description.isEmpty()) {
782 description = null;
783 }
784 } catch (IllegalStateException e) {
785 Main.error(e);
786 description = null;
787 }
788 String[] n = SPLIT_TRIMMED_PATTERN.split(trimmed, 3);
789 switch (n[0]) {
790 case "way":
791 type = OsmPrimitiveType.WAY;
792 break;
793 case "node":
794 type = OsmPrimitiveType.NODE;
795 break;
796 case "relation":
797 type = OsmPrimitiveType.RELATION;
798 break;
799 case "*":
800 type = null;
801 break;
802 default:
803 return tr("Could not find element type");
804 }
805 if (n.length != 3)
806 return tr("Incorrect number of parameters");
807
808 switch (n[1]) {
809 case "W":
810 severity = Severity.WARNING;
811 code = TAG_CHECK_WARN;
812 break;
813 case "E":
814 severity = Severity.ERROR;
815 code = TAG_CHECK_ERROR;
816 break;
817 case "I":
818 severity = Severity.OTHER;
819 code = TAG_CHECK_INFO;
820 break;
821 default:
822 return tr("Could not find warning level");
823 }
824 for (String exp: SPLIT_ELEMENTS_PATTERN.split(n[2])) {
825 try {
826 data.add(new CheckerElement(exp));
827 } catch (IllegalStateException e) {
828 Main.trace(e);
829 return tr("Illegal expression ''{0}''", exp);
830 } catch (PatternSyntaxException e) {
831 Main.trace(e);
832 return tr("Illegal regular expression ''{0}''", exp);
833 }
834 }
835 return null;
836 }
837
838 public boolean match(OsmPrimitive osm, Map<String, String> keys) {
839 if (type != null && OsmPrimitiveType.from(osm) != type)
840 return false;
841
842 for (CheckerElement ce : data) {
843 if (!ce.match(keys))
844 return false;
845 }
846 return true;
847 }
848
849 public String getDescription() {
850 return description;
851 }
852
853 public Severity getSeverity() {
854 return severity;
855 }
856
857 public int getCode() {
858 if (type == null)
859 return code;
860
861 return code + type.ordinal() + 1;
862 }
863 }
864}
Note: See TracBrowser for help on using the repository browser.