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

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

Sonar - fix various issues

  • Property svn:eol-style set to native
File size: 33.2 KB
Line 
1// License: GPL. See LICENSE file for details.
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.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.Map;
20import java.util.Map.Entry;
21import java.util.Set;
22import java.util.regex.Matcher;
23import java.util.regex.Pattern;
24import java.util.regex.PatternSyntaxException;
25
26import javax.swing.JCheckBox;
27import javax.swing.JLabel;
28import javax.swing.JPanel;
29
30import org.openstreetmap.josm.Main;
31import org.openstreetmap.josm.command.ChangePropertyCommand;
32import org.openstreetmap.josm.command.ChangePropertyKeyCommand;
33import org.openstreetmap.josm.command.Command;
34import org.openstreetmap.josm.command.SequenceCommand;
35import org.openstreetmap.josm.data.osm.OsmPrimitive;
36import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
37import org.openstreetmap.josm.data.osm.OsmUtils;
38import org.openstreetmap.josm.data.osm.Tag;
39import org.openstreetmap.josm.data.validation.Severity;
40import org.openstreetmap.josm.data.validation.Test;
41import org.openstreetmap.josm.data.validation.TestError;
42import org.openstreetmap.josm.data.validation.util.Entities;
43import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
44import org.openstreetmap.josm.gui.preferences.validator.ValidatorPreference;
45import org.openstreetmap.josm.gui.progress.ProgressMonitor;
46import org.openstreetmap.josm.gui.tagging.TaggingPreset;
47import org.openstreetmap.josm.gui.tagging.TaggingPresetItem;
48import org.openstreetmap.josm.gui.tagging.TaggingPresetItems.Check;
49import org.openstreetmap.josm.gui.tagging.TaggingPresetItems.CheckGroup;
50import org.openstreetmap.josm.gui.tagging.TaggingPresetItems.KeyedItem;
51import org.openstreetmap.josm.gui.widgets.EditableList;
52import org.openstreetmap.josm.io.MirroredInputStream;
53import org.openstreetmap.josm.io.UTFInputStreamReader;
54import org.openstreetmap.josm.tools.GBC;
55import org.openstreetmap.josm.tools.MultiMap;
56import org.openstreetmap.josm.tools.Utils;
57
58/**
59 * Check for misspelled or wrong tags
60 *
61 * @author frsantos
62 */
63public class TagChecker extends Test.TagTest {
64
65 /** The default data file of tagchecker rules */
66 public static final String DATA_FILE = "resource://data/validator/tagchecker.cfg";
67 /** The config file of ignored tags */
68 public static final String IGNORE_FILE = "resource://data/validator/ignoretags.cfg";
69 /** The config file of dictionary words */
70 public static final String SPELL_FILE = "resource://data/validator/words.cfg";
71
72 /** The spell check key substitutions: the key should be substituted by the value */
73 private static Map<String, String> spellCheckKeyData;
74 /** The spell check preset values */
75 private static MultiMap<String, String> presetsValueData;
76 /** The TagChecker data */
77 private static final List<CheckerData> checkerData = new ArrayList<>();
78 private static final List<String> ignoreDataStartsWith = new ArrayList<>();
79 private static final List<String> ignoreDataEquals = new ArrayList<>();
80 private static final List<String> ignoreDataEndsWith = new ArrayList<>();
81 private static final List<IgnoreKeyPair> ignoreDataKeyPair = new ArrayList<>();
82
83 /** The preferences prefix */
84 protected static final String PREFIX = ValidatorPreference.PREFIX + "." + TagChecker.class.getSimpleName();
85
86 public static final String PREF_CHECK_VALUES = PREFIX + ".checkValues";
87 public static final String PREF_CHECK_KEYS = PREFIX + ".checkKeys";
88 public static final String PREF_CHECK_COMPLEX = PREFIX + ".checkComplex";
89 public static final String PREF_CHECK_FIXMES = PREFIX + ".checkFixmes";
90
91 public static final String PREF_SOURCES = PREFIX + ".source";
92
93 public static final String PREF_CHECK_KEYS_BEFORE_UPLOAD = PREF_CHECK_KEYS + "BeforeUpload";
94 public static final String PREF_CHECK_VALUES_BEFORE_UPLOAD = PREF_CHECK_VALUES + "BeforeUpload";
95 public static final String PREF_CHECK_COMPLEX_BEFORE_UPLOAD = PREF_CHECK_COMPLEX + "BeforeUpload";
96 public static final String PREF_CHECK_FIXMES_BEFORE_UPLOAD = PREF_CHECK_FIXMES + "BeforeUpload";
97
98 protected boolean checkKeys = false;
99 protected boolean checkValues = false;
100 protected boolean checkComplex = false;
101 protected boolean checkFixmes = false;
102
103 protected JCheckBox prefCheckKeys;
104 protected JCheckBox prefCheckValues;
105 protected JCheckBox prefCheckComplex;
106 protected JCheckBox prefCheckFixmes;
107 protected JCheckBox prefCheckPaint;
108
109 protected JCheckBox prefCheckKeysBeforeUpload;
110 protected JCheckBox prefCheckValuesBeforeUpload;
111 protected JCheckBox prefCheckComplexBeforeUpload;
112 protected JCheckBox prefCheckFixmesBeforeUpload;
113 protected JCheckBox prefCheckPaintBeforeUpload;
114
115 protected static final int EMPTY_VALUES = 1200;
116 protected static final int INVALID_KEY = 1201;
117 protected static final int INVALID_VALUE = 1202;
118 protected static final int FIXME = 1203;
119 protected static final int INVALID_SPACE = 1204;
120 protected static final int INVALID_KEY_SPACE = 1205;
121 protected static final int INVALID_HTML = 1206; /* 1207 was PAINT */
122 protected static final int LONG_VALUE = 1208;
123 protected static final int LONG_KEY = 1209;
124 protected static final int LOW_CHAR_VALUE = 1210;
125 protected static final int LOW_CHAR_KEY = 1211;
126 /** 1250 and up is used by tagcheck */
127
128 protected EditableList sourcesList;
129
130 protected static final Entities entities = new Entities();
131
132 static final List<String> DEFAULT_SOURCES = Arrays.asList(DATA_FILE, IGNORE_FILE, SPELL_FILE);
133
134 /**
135 * Constructor
136 */
137 public TagChecker() {
138 super(tr("Tag checker"), tr("This test checks for errors in tag keys and values."));
139 }
140
141 @Override
142 public void initialize() throws IOException {
143 initializeData();
144 initializePresets();
145 }
146
147 /**
148 * Reads the spellcheck file into a HashMap.
149 * The data file is a list of words, beginning with +/-. If it starts with +,
150 * the word is valid, but if it starts with -, the word should be replaced
151 * by the nearest + word before this.
152 *
153 * @throws FileNotFoundException
154 * @throws IOException
155 */
156 private static void initializeData() throws IOException {
157 checkerData.clear();
158 ignoreDataStartsWith.clear();
159 ignoreDataEquals.clear();
160 ignoreDataEndsWith.clear();
161 ignoreDataKeyPair.clear();
162
163 spellCheckKeyData = new HashMap<>();
164
165 String errorSources = "";
166 for (String source : Main.pref.getCollection(PREF_SOURCES, DEFAULT_SOURCES)) {
167 BufferedReader reader = null;
168 try {
169 MirroredInputStream s = new MirroredInputStream(source);
170 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 } finally {
245 Utils.close(reader);
246 }
247 }
248
249 if (errorSources.length() > 0)
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 = TaggingPresetPreference.taggingPresets;
263 if (presets != null) {
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().length() == 0) && !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.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.OTHER, 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 && value != null && value.length() > 0 && 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 String i = marktr("Value ''{0}'' for key ''{1}'' not in presets.");
422 errors.add( new TestError(this, Severity.OTHER, tr("Presets do not contain property value"),
423 tr(i, prop.getValue(), key), MessageFormat.format(i, prop.getValue(), key), INVALID_VALUE, p) );
424 withErrors.put(p, "UPV");
425 }
426 }
427 }
428 if (checkFixmes && value != null && value.length() > 0) {
429 if ((value.toLowerCase().contains("fixme")
430 || value.contains("check and delete")
431 || key.contains("todo") || key.toLowerCase().contains("fixme"))
432 && !withErrors.contains(p, "FIXME")) {
433 errors.add(new TestError(this, Severity.OTHER,
434 tr("FIXMES"), FIXME, p));
435 withErrors.put(p, "FIXME");
436 }
437 }
438 }
439 }
440
441 @Override
442 public void startTest(ProgressMonitor monitor) {
443 super.startTest(monitor);
444 checkKeys = Main.pref.getBoolean(PREF_CHECK_KEYS, true);
445 if (isBeforeUpload) {
446 checkKeys = checkKeys && Main.pref.getBoolean(PREF_CHECK_KEYS_BEFORE_UPLOAD, true);
447 }
448
449 checkValues = Main.pref.getBoolean(PREF_CHECK_VALUES, true);
450 if (isBeforeUpload) {
451 checkValues = checkValues && Main.pref.getBoolean(PREF_CHECK_VALUES_BEFORE_UPLOAD, true);
452 }
453
454 checkComplex = Main.pref.getBoolean(PREF_CHECK_COMPLEX, true);
455 if (isBeforeUpload) {
456 checkComplex = checkValues && Main.pref.getBoolean(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, true);
457 }
458
459 checkFixmes = Main.pref.getBoolean(PREF_CHECK_FIXMES, true);
460 if (isBeforeUpload) {
461 checkFixmes = checkFixmes && Main.pref.getBoolean(PREF_CHECK_FIXMES_BEFORE_UPLOAD, true);
462 }
463 }
464
465 @Override
466 public void visit(Collection<OsmPrimitive> selection) {
467 if (checkKeys || checkValues || checkComplex || checkFixmes) {
468 super.visit(selection);
469 }
470 }
471
472 @Override
473 public void addGui(JPanel testPanel) {
474 GBC a = GBC.eol();
475 a.anchor = GridBagConstraints.EAST;
476
477 testPanel.add(new JLabel(name+" :"), GBC.eol().insets(3,0,0,0));
478
479 prefCheckKeys = new JCheckBox(tr("Check property keys."), Main.pref.getBoolean(PREF_CHECK_KEYS, true));
480 prefCheckKeys.setToolTipText(tr("Validate that property keys are valid checking against list of words."));
481 testPanel.add(prefCheckKeys, GBC.std().insets(20,0,0,0));
482
483 prefCheckKeysBeforeUpload = new JCheckBox();
484 prefCheckKeysBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_KEYS_BEFORE_UPLOAD, true));
485 testPanel.add(prefCheckKeysBeforeUpload, a);
486
487 prefCheckComplex = new JCheckBox(tr("Use complex property checker."), Main.pref.getBoolean(PREF_CHECK_COMPLEX, true));
488 prefCheckComplex.setToolTipText(tr("Validate property values and tags using complex rules."));
489 testPanel.add(prefCheckComplex, GBC.std().insets(20,0,0,0));
490
491 prefCheckComplexBeforeUpload = new JCheckBox();
492 prefCheckComplexBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, true));
493 testPanel.add(prefCheckComplexBeforeUpload, a);
494
495 final Collection<String> sources = Main.pref.getCollection(PREF_SOURCES, Arrays.asList(DATA_FILE, IGNORE_FILE, SPELL_FILE));
496 sourcesList = new EditableList(tr("TagChecker source"));
497 sourcesList.setItems(sources);
498 testPanel.add(new JLabel(tr("Data sources ({0})", "*.cfg")), GBC.eol().insets(23, 0, 0, 0));
499 testPanel.add(sourcesList, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(23, 0, 0, 0));
500
501 ActionListener disableCheckActionListener = new ActionListener() {
502 @Override
503 public void actionPerformed(ActionEvent e) {
504 handlePrefEnable();
505 }
506 };
507 prefCheckKeys.addActionListener(disableCheckActionListener);
508 prefCheckKeysBeforeUpload.addActionListener(disableCheckActionListener);
509 prefCheckComplex.addActionListener(disableCheckActionListener);
510 prefCheckComplexBeforeUpload.addActionListener(disableCheckActionListener);
511
512 handlePrefEnable();
513
514 prefCheckValues = new JCheckBox(tr("Check property values."), Main.pref.getBoolean(PREF_CHECK_VALUES, true));
515 prefCheckValues.setToolTipText(tr("Validate that property values are valid checking against presets."));
516 testPanel.add(prefCheckValues, GBC.std().insets(20,0,0,0));
517
518 prefCheckValuesBeforeUpload = new JCheckBox();
519 prefCheckValuesBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_VALUES_BEFORE_UPLOAD, true));
520 testPanel.add(prefCheckValuesBeforeUpload, a);
521
522 prefCheckFixmes = new JCheckBox(tr("Check for FIXMES."), Main.pref.getBoolean(PREF_CHECK_FIXMES, true));
523 prefCheckFixmes.setToolTipText(tr("Looks for nodes or ways with FIXME in any property value."));
524 testPanel.add(prefCheckFixmes, GBC.std().insets(20,0,0,0));
525
526 prefCheckFixmesBeforeUpload = new JCheckBox();
527 prefCheckFixmesBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_FIXMES_BEFORE_UPLOAD, true));
528 testPanel.add(prefCheckFixmesBeforeUpload, a);
529 }
530
531 public void handlePrefEnable() {
532 boolean selected = prefCheckKeys.isSelected() || prefCheckKeysBeforeUpload.isSelected()
533 || prefCheckComplex.isSelected() || prefCheckComplexBeforeUpload.isSelected();
534 sourcesList.setEnabled(selected);
535 }
536
537 @Override
538 public boolean ok() {
539 enabled = prefCheckKeys.isSelected() || prefCheckValues.isSelected() || prefCheckComplex.isSelected() || prefCheckFixmes.isSelected();
540 testBeforeUpload = prefCheckKeysBeforeUpload.isSelected() || prefCheckValuesBeforeUpload.isSelected()
541 || prefCheckFixmesBeforeUpload.isSelected() || prefCheckComplexBeforeUpload.isSelected();
542
543 Main.pref.put(PREF_CHECK_VALUES, prefCheckValues.isSelected());
544 Main.pref.put(PREF_CHECK_COMPLEX, prefCheckComplex.isSelected());
545 Main.pref.put(PREF_CHECK_KEYS, prefCheckKeys.isSelected());
546 Main.pref.put(PREF_CHECK_FIXMES, prefCheckFixmes.isSelected());
547 Main.pref.put(PREF_CHECK_VALUES_BEFORE_UPLOAD, prefCheckValuesBeforeUpload.isSelected());
548 Main.pref.put(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, prefCheckComplexBeforeUpload.isSelected());
549 Main.pref.put(PREF_CHECK_KEYS_BEFORE_UPLOAD, prefCheckKeysBeforeUpload.isSelected());
550 Main.pref.put(PREF_CHECK_FIXMES_BEFORE_UPLOAD, prefCheckFixmesBeforeUpload.isSelected());
551 return Main.pref.putCollection(PREF_SOURCES, sourcesList.getItems());
552 }
553
554 @Override
555 public Command fixError(TestError testError) {
556 List<Command> commands = new ArrayList<>(50);
557
558 Collection<? extends OsmPrimitive> primitives = testError.getPrimitives();
559 for (OsmPrimitive p : primitives) {
560 Map<String, String> tags = p.getKeys();
561 if (tags == null || tags.isEmpty()) {
562 continue;
563 }
564
565 for (Entry<String, String> prop: tags.entrySet()) {
566 String key = prop.getKey();
567 String value = prop.getValue();
568 if (value == null || value.trim().length() == 0) {
569 commands.add(new ChangePropertyCommand(p, key, null));
570 } else if (value.startsWith(" ") || value.endsWith(" ")) {
571 commands.add(new ChangePropertyCommand(p, key, Tag.removeWhiteSpaces(value)));
572 } else if (key.startsWith(" ") || key.endsWith(" ")) {
573 commands.add(new ChangePropertyKeyCommand(p, key, Tag.removeWhiteSpaces(key)));
574 } else {
575 String evalue = entities.unescape(value);
576 if (!evalue.equals(value)) {
577 commands.add(new ChangePropertyCommand(p, key, evalue));
578 } else {
579 String replacementKey = spellCheckKeyData.get(key);
580 if (replacementKey != null) {
581 commands.add(new ChangePropertyKeyCommand(p, key, replacementKey));
582 }
583 }
584 }
585 }
586 }
587
588 if (commands.isEmpty())
589 return null;
590 if (commands.size() == 1)
591 return commands.get(0);
592
593 return new SequenceCommand(tr("Fix tags"), commands);
594 }
595
596 @Override
597 public boolean isFixable(TestError testError) {
598 if (testError.getTester() instanceof TagChecker) {
599 int code = testError.getCode();
600 return code == INVALID_KEY || code == EMPTY_VALUES || code == INVALID_SPACE || code == INVALID_KEY_SPACE || code == INVALID_HTML;
601 }
602
603 return false;
604 }
605
606 protected static class IgnoreKeyPair {
607 public String key;
608 public String value;
609 }
610
611 protected static class CheckerData {
612 private String description;
613 protected List<CheckerElement> data = new ArrayList<>();
614 private OsmPrimitiveType type;
615 private int code;
616 protected Severity severity;
617 protected static final int TAG_CHECK_ERROR = 1250;
618 protected static final int TAG_CHECK_WARN = 1260;
619 protected static final int TAG_CHECK_INFO = 1270;
620
621 protected static class CheckerElement {
622 public Object tag;
623 public Object value;
624 public boolean noMatch;
625 public boolean tagAll = false;
626 public boolean valueAll = false;
627 public boolean valueBool = false;
628
629 private Pattern getPattern(String str) throws IllegalStateException, PatternSyntaxException {
630 if (str.endsWith("/i"))
631 return Pattern.compile(str.substring(1,str.length()-2), Pattern.CASE_INSENSITIVE);
632 if (str.endsWith("/"))
633 return Pattern.compile(str.substring(1,str.length()-1));
634
635 throw new IllegalStateException();
636 }
637 public CheckerElement(String exp) throws IllegalStateException, PatternSyntaxException {
638 Matcher m = Pattern.compile("(.+)([!=]=)(.+)").matcher(exp);
639 m.matches();
640
641 String n = m.group(1).trim();
642
643 if ("*".equals(n)) {
644 tagAll = true;
645 } else {
646 tag = n.startsWith("/") ? getPattern(n) : n;
647 noMatch = "!=".equals(m.group(2));
648 n = m.group(3).trim();
649 if ("*".equals(n)) {
650 valueAll = true;
651 } else if ("BOOLEAN_TRUE".equals(n)) {
652 valueBool = true;
653 value = OsmUtils.trueval;
654 } else if ("BOOLEAN_FALSE".equals(n)) {
655 valueBool = true;
656 value = OsmUtils.falseval;
657 } else {
658 value = n.startsWith("/") ? getPattern(n) : n;
659 }
660 }
661 }
662
663 public boolean match(OsmPrimitive osm, Map<String, String> keys) {
664 for (Entry<String, String> prop: keys.entrySet()) {
665 String key = prop.getKey();
666 String val = valueBool ? OsmUtils.getNamedOsmBoolean(prop.getValue()) : prop.getValue();
667 if ((tagAll || (tag instanceof Pattern ? ((Pattern) tag).matcher(key).matches() : key.equals(tag)))
668 && (valueAll || (value instanceof Pattern ? ((Pattern) value).matcher(val).matches() : val.equals(value))))
669 return !noMatch;
670 }
671 return noMatch;
672 }
673 }
674
675 private static final Pattern CLEAN_STR_PATTERN = Pattern.compile(" *# *([^#]+) *$");
676 private static final Pattern SPLIT_TRIMMED_PATTERN = Pattern.compile(" *: *");
677 private static final Pattern SPLIT_ELEMENTS_PATTERN = Pattern.compile(" *&& *");
678
679 public String getData(final String str) {
680 Matcher m = CLEAN_STR_PATTERN.matcher(str);
681 String trimmed = m.replaceFirst("").trim();
682 try {
683 description = m.group(1);
684 if (description != null && description.length() == 0) {
685 description = null;
686 }
687 } catch (IllegalStateException e) {
688 description = null;
689 }
690 String[] n = SPLIT_TRIMMED_PATTERN.split(trimmed, 3);
691 switch (n[0]) {
692 case "way":
693 type = OsmPrimitiveType.WAY;
694 break;
695 case "node":
696 type = OsmPrimitiveType.NODE;
697 break;
698 case "relation":
699 type = OsmPrimitiveType.RELATION;
700 break;
701 case "*":
702 type = null;
703 break;
704 default:
705 return tr("Could not find element type");
706 }
707 if (n.length != 3)
708 return tr("Incorrect number of parameters");
709
710 switch (n[1]) {
711 case "W":
712 severity = Severity.WARNING;
713 code = TAG_CHECK_WARN;
714 break;
715 case "E":
716 severity = Severity.ERROR;
717 code = TAG_CHECK_ERROR;
718 break;
719 case "I":
720 severity = Severity.OTHER;
721 code = TAG_CHECK_INFO;
722 break;
723 default:
724 return tr("Could not find warning level");
725 }
726 for (String exp: SPLIT_ELEMENTS_PATTERN.split(n[2])) {
727 try {
728 data.add(new CheckerElement(exp));
729 } catch (IllegalStateException e) {
730 return tr("Illegal expression ''{0}''", exp);
731 } catch (PatternSyntaxException e) {
732 return tr("Illegal regular expression ''{0}''", exp);
733 }
734 }
735 return null;
736 }
737
738 public boolean match(OsmPrimitive osm, Map<String, String> keys) {
739 if (type != null && OsmPrimitiveType.from(osm) != type)
740 return false;
741
742 for (CheckerElement ce : data) {
743 if (!ce.match(osm, keys))
744 return false;
745 }
746 return true;
747 }
748
749 public String getDescription() {
750 return tr(description);
751 }
752
753 public String getDescriptionOrig() {
754 return description;
755 }
756
757 public Severity getSeverity() {
758 return severity;
759 }
760
761 public int getCode() {
762 if (type == null)
763 return code;
764
765 return code + type.ordinal() + 1;
766 }
767 }
768}
Note: See TracBrowser for help on using the repository browser.