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

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

When doing a String.toLowerCase()/toUpperCase() call, use a Locale. This avoids problems with certain locales, i.e. Lithuanian or Turkish. See PMD UseLocaleWithCaseConversions rule and String.toLowerCase() javadoc.

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