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

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

Sonar/FindBugs:

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