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

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

global use of String.isEmpty()

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