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

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

sonar - Unused private method should be removed
sonar - Unused protected methods should be removed
sonar - Sections of code should not be "commented out"
sonar - Empty statements should be removed
sonar - squid:S1172 - Unused method parameters should be removed
sonar - squid:S1481 - Unused local variables should be removed

  • Property svn:eol-style set to native
File size: 35.4 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.TaggingPreset;
48import org.openstreetmap.josm.gui.tagging.TaggingPresetItem;
49import org.openstreetmap.josm.gui.tagging.TaggingPresetItems.Check;
50import org.openstreetmap.josm.gui.tagging.TaggingPresetItems.CheckGroup;
51import org.openstreetmap.josm.gui.tagging.TaggingPresetItems.KeyedItem;
52import org.openstreetmap.josm.gui.tagging.TaggingPresets;
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<IgnoreKeyPair> ignoreDataKeyPair = 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 ignoreDataKeyPair.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 IgnoreKeyPair tmp = new IgnoreKeyPair();
210 int mid = line.indexOf('=');
211 tmp.key = line.substring(0, mid);
212 tmp.value = line.substring(mid+1);
213 ignoreDataKeyPair.add(tmp);
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 errorSources.append(source).append('\n');
242 }
243 }
244
245 if (errorSources.length() > 0)
246 throw new IOException(tr("Could not access data file(s):\n{0}", errorSources));
247 }
248
249 /**
250 * Reads the presets data.
251 *
252 */
253 public static void initializePresets() {
254
255 if (!Main.pref.getBoolean(PREF_CHECK_VALUES, true))
256 return;
257
258 Collection<TaggingPreset> presets = TaggingPresets.getTaggingPresets();
259 if (!presets.isEmpty()) {
260 presetsValueData = new MultiMap<>();
261 for (String a : OsmPrimitive.getUninterestingKeys()) {
262 presetsValueData.putVoid(a);
263 }
264 // TODO directionKeys are no longer in OsmPrimitive (search pattern is used instead)
265 for (String a : Main.pref.getCollection(ValidatorPreference.PREFIX + ".knownkeys",
266 Arrays.asList(new String[]{"is_in", "int_ref", "fixme", "population"}))) {
267 presetsValueData.putVoid(a);
268 }
269 for (TaggingPreset p : presets) {
270 for (TaggingPresetItem i : p.data) {
271 if (i instanceof KeyedItem) {
272 addPresetValue(p, (KeyedItem) i);
273 } else if (i instanceof CheckGroup) {
274 for (Check c : ((CheckGroup) i).checks) {
275 addPresetValue(p, c);
276 }
277 }
278 }
279 }
280 }
281 }
282
283 private static void addPresetValue(TaggingPreset p, KeyedItem ky) {
284 Collection<String> values = ky.getValues();
285 if (ky.key != null && values != null) {
286 try {
287 presetsValueData.putAll(ky.key, values);
288 harmonizedKeys.put(harmonizeKey(ky.key), ky.key);
289 } catch (NullPointerException e) {
290 Main.error(p+": Unable to initialize "+ky);
291 }
292 }
293 }
294
295 /**
296 * Checks given string (key or value) if it contains characters with code below 0x20 (either newline or some other special characters)
297 * @param s string to check
298 */
299 private boolean containsLow(String s) {
300 if (s == null)
301 return false;
302 for (int i = 0; i < s.length(); i++) {
303 if (s.charAt(i) < 0x20)
304 return true;
305 }
306 return false;
307 }
308
309 /**
310 * Checks the primitive tags
311 * @param p The primitive to check
312 */
313 @Override
314 public void check(OsmPrimitive p) {
315 // Just a collection to know if a primitive has been already marked with error
316 MultiMap<OsmPrimitive, String> withErrors = new MultiMap<>();
317
318 if (checkComplex) {
319 Map<String, String> keys = p.getKeys();
320 for (CheckerData d : checkerData) {
321 if (d.match(p, keys)) {
322 errors.add(new TestError(this, d.getSeverity(), tr("Suspicious tag/value combinations"),
323 d.getDescription(), d.getDescriptionOrig(), d.getCode(), p));
324 withErrors.put(p, "TC");
325 }
326 }
327 }
328
329 for (Entry<String, String> prop : p.getKeys().entrySet()) {
330 String s = marktr("Key ''{0}'' invalid.");
331 String key = prop.getKey();
332 String value = prop.getValue();
333 if (checkValues && (containsLow(value)) && !withErrors.contains(p, "ICV")) {
334 errors.add(new TestError(this, Severity.WARNING, tr("Tag value contains character with code less than 0x20"),
335 tr(s, key), MessageFormat.format(s, key), LOW_CHAR_VALUE, p));
336 withErrors.put(p, "ICV");
337 }
338 if (checkKeys && (containsLow(key)) && !withErrors.contains(p, "ICK")) {
339 errors.add(new TestError(this, Severity.WARNING, tr("Tag key contains character with code less than 0x20"),
340 tr(s, key), MessageFormat.format(s, key), LOW_CHAR_KEY, p));
341 withErrors.put(p, "ICK");
342 }
343 if (checkValues && (value != null && value.length() > 255) && !withErrors.contains(p, "LV")) {
344 errors.add(new TestError(this, Severity.ERROR, tr("Tag value longer than allowed"),
345 tr(s, key), MessageFormat.format(s, key), LONG_VALUE, p));
346 withErrors.put(p, "LV");
347 }
348 if (checkKeys && (key != null && key.length() > 255) && !withErrors.contains(p, "LK")) {
349 errors.add(new TestError(this, Severity.ERROR, tr("Tag key longer than allowed"),
350 tr(s, key), MessageFormat.format(s, key), LONG_KEY, p));
351 withErrors.put(p, "LK");
352 }
353 if (checkValues && (value == null || value.trim().isEmpty()) && !withErrors.contains(p, "EV")) {
354 errors.add(new TestError(this, Severity.WARNING, tr("Tags with empty values"),
355 tr(s, key), MessageFormat.format(s, key), EMPTY_VALUES, p));
356 withErrors.put(p, "EV");
357 }
358 if (checkKeys && key != null && key.indexOf(' ') >= 0 && !withErrors.contains(p, "IPK")) {
359 errors.add(new TestError(this, Severity.WARNING, tr("Invalid white space in property key"),
360 tr(s, key), MessageFormat.format(s, key), INVALID_KEY_SPACE, p));
361 withErrors.put(p, "IPK");
362 }
363 if (checkValues && value != null && (value.startsWith(" ") || value.endsWith(" ")) && !withErrors.contains(p, "SPACE")) {
364 errors.add(new TestError(this, Severity.WARNING, tr("Property values start or end with white space"),
365 tr(s, key), MessageFormat.format(s, key), INVALID_SPACE, p));
366 withErrors.put(p, "SPACE");
367 }
368 if (checkValues && value != null && !value.equals(Entities.unescape(value)) && !withErrors.contains(p, "HTML")) {
369 errors.add(new TestError(this, Severity.OTHER, tr("Property values contain HTML entity"),
370 tr(s, key), MessageFormat.format(s, key), INVALID_HTML, p));
371 withErrors.put(p, "HTML");
372 }
373 if (checkValues && key != null && value != null && !value.isEmpty() && presetsValueData != null) {
374 final Set<String> values = presetsValueData.get(key);
375 final boolean keyInPresets = values != null;
376 final boolean tagInPresets = values != null && (values.isEmpty() || values.contains(prop.getValue()));
377
378 boolean ignore = false;
379 for (String a : ignoreDataStartsWith) {
380 if (key.startsWith(a)) {
381 ignore = true;
382 }
383 }
384 for (String a : ignoreDataEquals) {
385 if (key.equals(a)) {
386 ignore = true;
387 }
388 }
389 for (String a : ignoreDataEndsWith) {
390 if (key.endsWith(a)) {
391 ignore = true;
392 }
393 }
394
395 if (!tagInPresets) {
396 for (IgnoreKeyPair a : ignoreDataKeyPair) {
397 if (key.equals(a.key) && value.equals(a.value)) {
398 ignore = true;
399 }
400 }
401 }
402
403 if (!ignore) {
404 if (!keyInPresets) {
405 String prettifiedKey = harmonizeKey(key);
406 String fixedKey = harmonizedKeys.get(prettifiedKey);
407 if (fixedKey != null && !"".equals(fixedKey)) {
408 // misspelled preset key
409 String i = marktr("Key ''{0}'' looks like ''{1}''.");
410 errors.add(new FixableTestError(this, Severity.WARNING, tr("Misspelled property key"),
411 tr(i, key, fixedKey),
412 MessageFormat.format(i, key, fixedKey), MISSPELLED_KEY, p,
413 new ChangePropertyKeyCommand(p, key, fixedKey)));
414 withErrors.put(p, "WPK");
415 } else {
416 String i = marktr("Key ''{0}'' not in presets.");
417 errors.add(new TestError(this, Severity.OTHER, tr("Presets do not contain property key"),
418 tr(i, key), MessageFormat.format(i, key), INVALID_VALUE, p));
419 withErrors.put(p, "UPK");
420 }
421 } else if (!tagInPresets) {
422 // try to fix common typos and check again if value is still unknown
423 String fixedValue = harmonizeValue(prop.getValue());
424 Map<String, String> possibleValues = getPossibleValues(values);
425 if (possibleValues.containsKey(fixedValue)) {
426 fixedValue = possibleValues.get(fixedValue);
427 // misspelled preset value
428 String i = marktr("Value ''{0}'' for key ''{1}'' looks like ''{2}''.");
429 errors.add(new FixableTestError(this, Severity.WARNING, tr("Misspelled property value"),
430 tr(i, prop.getValue(), key, fixedValue), MessageFormat.format(i, prop.getValue(), fixedValue),
431 MISSPELLED_VALUE, p, new ChangePropertyCommand(p, key, fixedValue)));
432 withErrors.put(p, "WPV");
433 } else {
434 // unknown preset value
435 String i = marktr("Value ''{0}'' for key ''{1}'' not in presets.");
436 errors.add(new TestError(this, Severity.OTHER, tr("Presets do not contain property value"),
437 tr(i, prop.getValue(), key), MessageFormat.format(i, prop.getValue(), key), INVALID_VALUE, p));
438 withErrors.put(p, "UPV");
439 }
440 }
441 }
442 }
443 if (checkFixmes && key != null && value != null && !value.isEmpty()) {
444 if ((value.toLowerCase(Locale.ENGLISH).contains("fixme")
445 || value.contains("check and delete")
446 || key.contains("todo") || key.toLowerCase(Locale.ENGLISH).contains("fixme"))
447 && !withErrors.contains(p, "FIXME")) {
448 errors.add(new TestError(this, Severity.OTHER,
449 tr("FIXMES"), FIXME, p));
450 withErrors.put(p, "FIXME");
451 }
452 }
453 }
454 }
455
456 private Map<String, String> getPossibleValues(Set<String> values) {
457 // generate a map with common typos
458 Map<String, String> map = new HashMap<>();
459 if (values != null) {
460 for (String value : values) {
461 map.put(value, value);
462 if (value.contains("_")) {
463 map.put(value.replace("_", ""), value);
464 }
465 }
466 }
467 return map;
468 }
469
470 private static String harmonizeKey(String key) {
471 key = key.toLowerCase(Locale.ENGLISH).replace('-', '_').replace(':', '_').replace(' ', '_');
472 return Utils.strip(key, "-_;:,");
473 }
474
475 private static String harmonizeValue(String value) {
476 value = value.toLowerCase(Locale.ENGLISH).replace('-', '_').replace(' ', '_');
477 return Utils.strip(value, "-_;:,");
478 }
479
480 @Override
481 public void startTest(ProgressMonitor monitor) {
482 super.startTest(monitor);
483 checkKeys = Main.pref.getBoolean(PREF_CHECK_KEYS, true);
484 if (isBeforeUpload) {
485 checkKeys = checkKeys && Main.pref.getBoolean(PREF_CHECK_KEYS_BEFORE_UPLOAD, true);
486 }
487
488 checkValues = Main.pref.getBoolean(PREF_CHECK_VALUES, true);
489 if (isBeforeUpload) {
490 checkValues = checkValues && Main.pref.getBoolean(PREF_CHECK_VALUES_BEFORE_UPLOAD, true);
491 }
492
493 checkComplex = Main.pref.getBoolean(PREF_CHECK_COMPLEX, true);
494 if (isBeforeUpload) {
495 checkComplex = checkValues && Main.pref.getBoolean(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, true);
496 }
497
498 checkFixmes = Main.pref.getBoolean(PREF_CHECK_FIXMES, true);
499 if (isBeforeUpload) {
500 checkFixmes = checkFixmes && Main.pref.getBoolean(PREF_CHECK_FIXMES_BEFORE_UPLOAD, true);
501 }
502 }
503
504 @Override
505 public void visit(Collection<OsmPrimitive> selection) {
506 if (checkKeys || checkValues || checkComplex || checkFixmes) {
507 super.visit(selection);
508 }
509 }
510
511 @Override
512 public void addGui(JPanel testPanel) {
513 GBC a = GBC.eol();
514 a.anchor = GridBagConstraints.EAST;
515
516 testPanel.add(new JLabel(name+" :"), GBC.eol().insets(3, 0, 0, 0));
517
518 prefCheckKeys = new JCheckBox(tr("Check property keys."), Main.pref.getBoolean(PREF_CHECK_KEYS, true));
519 prefCheckKeys.setToolTipText(tr("Validate that property keys are valid checking against list of words."));
520 testPanel.add(prefCheckKeys, GBC.std().insets(20, 0, 0, 0));
521
522 prefCheckKeysBeforeUpload = new JCheckBox();
523 prefCheckKeysBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_KEYS_BEFORE_UPLOAD, true));
524 testPanel.add(prefCheckKeysBeforeUpload, a);
525
526 prefCheckComplex = new JCheckBox(tr("Use complex property checker."), Main.pref.getBoolean(PREF_CHECK_COMPLEX, true));
527 prefCheckComplex.setToolTipText(tr("Validate property values and tags using complex rules."));
528 testPanel.add(prefCheckComplex, GBC.std().insets(20, 0, 0, 0));
529
530 prefCheckComplexBeforeUpload = new JCheckBox();
531 prefCheckComplexBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, true));
532 testPanel.add(prefCheckComplexBeforeUpload, a);
533
534 final Collection<String> sources = Main.pref.getCollection(PREF_SOURCES, DEFAULT_SOURCES);
535 sourcesList = new EditableList(tr("TagChecker source"));
536 sourcesList.setItems(sources);
537 testPanel.add(new JLabel(tr("Data sources ({0})", "*.cfg")), GBC.eol().insets(23, 0, 0, 0));
538 testPanel.add(sourcesList, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(23, 0, 0, 0));
539
540 ActionListener disableCheckActionListener = new ActionListener() {
541 @Override
542 public void actionPerformed(ActionEvent e) {
543 handlePrefEnable();
544 }
545 };
546 prefCheckKeys.addActionListener(disableCheckActionListener);
547 prefCheckKeysBeforeUpload.addActionListener(disableCheckActionListener);
548 prefCheckComplex.addActionListener(disableCheckActionListener);
549 prefCheckComplexBeforeUpload.addActionListener(disableCheckActionListener);
550
551 handlePrefEnable();
552
553 prefCheckValues = new JCheckBox(tr("Check property values."), Main.pref.getBoolean(PREF_CHECK_VALUES, true));
554 prefCheckValues.setToolTipText(tr("Validate that property values are valid checking against presets."));
555 testPanel.add(prefCheckValues, GBC.std().insets(20, 0, 0, 0));
556
557 prefCheckValuesBeforeUpload = new JCheckBox();
558 prefCheckValuesBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_VALUES_BEFORE_UPLOAD, true));
559 testPanel.add(prefCheckValuesBeforeUpload, a);
560
561 prefCheckFixmes = new JCheckBox(tr("Check for FIXMES."), Main.pref.getBoolean(PREF_CHECK_FIXMES, true));
562 prefCheckFixmes.setToolTipText(tr("Looks for nodes or ways with FIXME in any property value."));
563 testPanel.add(prefCheckFixmes, GBC.std().insets(20, 0, 0, 0));
564
565 prefCheckFixmesBeforeUpload = new JCheckBox();
566 prefCheckFixmesBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_FIXMES_BEFORE_UPLOAD, true));
567 testPanel.add(prefCheckFixmesBeforeUpload, a);
568 }
569
570 public void handlePrefEnable() {
571 boolean selected = prefCheckKeys.isSelected() || prefCheckKeysBeforeUpload.isSelected()
572 || prefCheckComplex.isSelected() || prefCheckComplexBeforeUpload.isSelected();
573 sourcesList.setEnabled(selected);
574 }
575
576 @Override
577 public boolean ok() {
578 enabled = prefCheckKeys.isSelected() || prefCheckValues.isSelected() || prefCheckComplex.isSelected() || prefCheckFixmes.isSelected();
579 testBeforeUpload = prefCheckKeysBeforeUpload.isSelected() || prefCheckValuesBeforeUpload.isSelected()
580 || prefCheckFixmesBeforeUpload.isSelected() || prefCheckComplexBeforeUpload.isSelected();
581
582 Main.pref.put(PREF_CHECK_VALUES, prefCheckValues.isSelected());
583 Main.pref.put(PREF_CHECK_COMPLEX, prefCheckComplex.isSelected());
584 Main.pref.put(PREF_CHECK_KEYS, prefCheckKeys.isSelected());
585 Main.pref.put(PREF_CHECK_FIXMES, prefCheckFixmes.isSelected());
586 Main.pref.put(PREF_CHECK_VALUES_BEFORE_UPLOAD, prefCheckValuesBeforeUpload.isSelected());
587 Main.pref.put(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, prefCheckComplexBeforeUpload.isSelected());
588 Main.pref.put(PREF_CHECK_KEYS_BEFORE_UPLOAD, prefCheckKeysBeforeUpload.isSelected());
589 Main.pref.put(PREF_CHECK_FIXMES_BEFORE_UPLOAD, prefCheckFixmesBeforeUpload.isSelected());
590 return Main.pref.putCollection(PREF_SOURCES, sourcesList.getItems());
591 }
592
593 @Override
594 public Command fixError(TestError testError) {
595 List<Command> commands = new ArrayList<>(50);
596
597 if (testError instanceof FixableTestError) {
598 commands.add(testError.getFix());
599 } else {
600 Collection<? extends OsmPrimitive> primitives = testError.getPrimitives();
601 for (OsmPrimitive p : primitives) {
602 Map<String, String> tags = p.getKeys();
603 if (tags == null || tags.isEmpty()) {
604 continue;
605 }
606
607 for (Entry<String, String> prop: tags.entrySet()) {
608 String key = prop.getKey();
609 String value = prop.getValue();
610 if (value == null || value.trim().isEmpty()) {
611 commands.add(new ChangePropertyCommand(p, key, null));
612 } else if (value.startsWith(" ") || value.endsWith(" ")) {
613 commands.add(new ChangePropertyCommand(p, key, Tag.removeWhiteSpaces(value)));
614 } else if (key.startsWith(" ") || key.endsWith(" ")) {
615 commands.add(new ChangePropertyKeyCommand(p, key, Tag.removeWhiteSpaces(key)));
616 } else {
617 String evalue = Entities.unescape(value);
618 if (!evalue.equals(value)) {
619 commands.add(new ChangePropertyCommand(p, key, evalue));
620 }
621 }
622 }
623 }
624 }
625
626 if (commands.isEmpty())
627 return null;
628 if (commands.size() == 1)
629 return commands.get(0);
630
631 return new SequenceCommand(tr("Fix tags"), commands);
632 }
633
634 @Override
635 public boolean isFixable(TestError testError) {
636 if (testError.getTester() instanceof TagChecker) {
637 int code = testError.getCode();
638 return code == INVALID_KEY || code == EMPTY_VALUES || code == INVALID_SPACE ||
639 code == INVALID_KEY_SPACE || code == INVALID_HTML || code == MISSPELLED_VALUE;
640 }
641
642 return false;
643 }
644
645 protected static class IgnoreKeyPair {
646 public String key;
647 public String value;
648 }
649
650 protected static class CheckerData {
651 private String description;
652 protected List<CheckerElement> data = new ArrayList<>();
653 private OsmPrimitiveType type;
654 private int code;
655 protected Severity severity;
656 protected static final int TAG_CHECK_ERROR = 1250;
657 protected static final int TAG_CHECK_WARN = 1260;
658 protected static final int TAG_CHECK_INFO = 1270;
659
660 protected static class CheckerElement {
661 public Object tag;
662 public Object value;
663 public boolean noMatch;
664 public boolean tagAll;
665 public boolean valueAll;
666 public boolean valueBool;
667
668 private Pattern getPattern(String str) throws PatternSyntaxException {
669 if (str.endsWith("/i"))
670 return Pattern.compile(str.substring(1, str.length()-2), Pattern.CASE_INSENSITIVE);
671 if (str.endsWith("/"))
672 return Pattern.compile(str.substring(1, str.length()-1));
673
674 throw new IllegalStateException();
675 }
676
677 public CheckerElement(String exp) throws PatternSyntaxException {
678 Matcher m = Pattern.compile("(.+)([!=]=)(.+)").matcher(exp);
679 m.matches();
680
681 String n = m.group(1).trim();
682
683 if ("*".equals(n)) {
684 tagAll = true;
685 } else {
686 tag = n.startsWith("/") ? getPattern(n) : n;
687 noMatch = "!=".equals(m.group(2));
688 n = m.group(3).trim();
689 if ("*".equals(n)) {
690 valueAll = true;
691 } else if ("BOOLEAN_TRUE".equals(n)) {
692 valueBool = true;
693 value = OsmUtils.trueval;
694 } else if ("BOOLEAN_FALSE".equals(n)) {
695 valueBool = true;
696 value = OsmUtils.falseval;
697 } else {
698 value = n.startsWith("/") ? getPattern(n) : n;
699 }
700 }
701 }
702
703 public boolean match(Map<String, String> keys) {
704 for (Entry<String, String> prop: keys.entrySet()) {
705 String key = prop.getKey();
706 String val = valueBool ? OsmUtils.getNamedOsmBoolean(prop.getValue()) : prop.getValue();
707 if ((tagAll || (tag instanceof Pattern ? ((Pattern) tag).matcher(key).matches() : key.equals(tag)))
708 && (valueAll || (value instanceof Pattern ? ((Pattern) value).matcher(val).matches() : val.equals(value))))
709 return !noMatch;
710 }
711 return noMatch;
712 }
713 }
714
715 private static final Pattern CLEAN_STR_PATTERN = Pattern.compile(" *# *([^#]+) *$");
716 private static final Pattern SPLIT_TRIMMED_PATTERN = Pattern.compile(" *: *");
717 private static final Pattern SPLIT_ELEMENTS_PATTERN = Pattern.compile(" *&& *");
718
719 public String getData(final String str) {
720 Matcher m = CLEAN_STR_PATTERN.matcher(str);
721 String trimmed = m.replaceFirst("").trim();
722 try {
723 description = m.group(1);
724 if (description != null && description.isEmpty()) {
725 description = null;
726 }
727 } catch (IllegalStateException e) {
728 description = null;
729 }
730 String[] n = SPLIT_TRIMMED_PATTERN.split(trimmed, 3);
731 switch (n[0]) {
732 case "way":
733 type = OsmPrimitiveType.WAY;
734 break;
735 case "node":
736 type = OsmPrimitiveType.NODE;
737 break;
738 case "relation":
739 type = OsmPrimitiveType.RELATION;
740 break;
741 case "*":
742 type = null;
743 break;
744 default:
745 return tr("Could not find element type");
746 }
747 if (n.length != 3)
748 return tr("Incorrect number of parameters");
749
750 switch (n[1]) {
751 case "W":
752 severity = Severity.WARNING;
753 code = TAG_CHECK_WARN;
754 break;
755 case "E":
756 severity = Severity.ERROR;
757 code = TAG_CHECK_ERROR;
758 break;
759 case "I":
760 severity = Severity.OTHER;
761 code = TAG_CHECK_INFO;
762 break;
763 default:
764 return tr("Could not find warning level");
765 }
766 for (String exp: SPLIT_ELEMENTS_PATTERN.split(n[2])) {
767 try {
768 data.add(new CheckerElement(exp));
769 } catch (IllegalStateException e) {
770 return tr("Illegal expression ''{0}''", exp);
771 } catch (PatternSyntaxException e) {
772 return tr("Illegal regular expression ''{0}''", exp);
773 }
774 }
775 return null;
776 }
777
778 public boolean match(OsmPrimitive osm, Map<String, String> keys) {
779 if (type != null && OsmPrimitiveType.from(osm) != type)
780 return false;
781
782 for (CheckerElement ce : data) {
783 if (!ce.match(keys))
784 return false;
785 }
786 return true;
787 }
788
789 public String getDescription() {
790 return tr(description);
791 }
792
793 public String getDescriptionOrig() {
794 return description;
795 }
796
797 public Severity getSeverity() {
798 return severity;
799 }
800
801 public int getCode() {
802 if (type == null)
803 return code;
804
805 return code + type.ordinal() + 1;
806 }
807 }
808}
Note: See TracBrowser for help on using the repository browser.