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

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

fix coverity 1012839 - Copy-paste error

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