source: josm/trunk/src/org/openstreetmap/josm/data/validation/OsmValidator.java@ 7489

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

fix #10393 - Validation of URLs and e-mails in relevant tags, using modified subset of Apache Commons Validator 1.4

  • Property svn:eol-style set to native
File size: 13.2 KB
Line 
1// License: GPL. See LICENSE file for details.
2package org.openstreetmap.josm.data.validation;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.File;
7import java.io.FileNotFoundException;
8import java.io.FileOutputStream;
9import java.io.IOException;
10import java.io.OutputStreamWriter;
11import java.io.PrintWriter;
12import java.nio.charset.StandardCharsets;
13import java.nio.file.Files;
14import java.nio.file.Path;
15import java.nio.file.Paths;
16import java.util.ArrayList;
17import java.util.Arrays;
18import java.util.Collection;
19import java.util.HashMap;
20import java.util.Map;
21import java.util.SortedMap;
22import java.util.TreeMap;
23import java.util.TreeSet;
24
25import javax.swing.JOptionPane;
26
27import org.openstreetmap.josm.Main;
28import org.openstreetmap.josm.actions.ValidateAction;
29import org.openstreetmap.josm.data.validation.tests.Addresses;
30import org.openstreetmap.josm.data.validation.tests.BarriersEntrances;
31import org.openstreetmap.josm.data.validation.tests.Coastlines;
32import org.openstreetmap.josm.data.validation.tests.ConditionalKeys;
33import org.openstreetmap.josm.data.validation.tests.CrossingWays;
34import org.openstreetmap.josm.data.validation.tests.DuplicateNode;
35import org.openstreetmap.josm.data.validation.tests.DuplicateRelation;
36import org.openstreetmap.josm.data.validation.tests.DuplicateWay;
37import org.openstreetmap.josm.data.validation.tests.DuplicatedWayNodes;
38import org.openstreetmap.josm.data.validation.tests.Highways;
39import org.openstreetmap.josm.data.validation.tests.InternetTags;
40import org.openstreetmap.josm.data.validation.tests.Lanes;
41import org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker;
42import org.openstreetmap.josm.data.validation.tests.MultipolygonTest;
43import org.openstreetmap.josm.data.validation.tests.NameMismatch;
44import org.openstreetmap.josm.data.validation.tests.OpeningHourTest;
45import org.openstreetmap.josm.data.validation.tests.OverlappingWays;
46import org.openstreetmap.josm.data.validation.tests.PowerLines;
47import org.openstreetmap.josm.data.validation.tests.RelationChecker;
48import org.openstreetmap.josm.data.validation.tests.SelfIntersectingWay;
49import org.openstreetmap.josm.data.validation.tests.SimilarNamedWays;
50import org.openstreetmap.josm.data.validation.tests.TagChecker;
51import org.openstreetmap.josm.data.validation.tests.TurnrestrictionTest;
52import org.openstreetmap.josm.data.validation.tests.UnclosedWays;
53import org.openstreetmap.josm.data.validation.tests.UnconnectedWays;
54import org.openstreetmap.josm.data.validation.tests.UntaggedNode;
55import org.openstreetmap.josm.data.validation.tests.UntaggedWay;
56import org.openstreetmap.josm.data.validation.tests.WayConnectedToArea;
57import org.openstreetmap.josm.data.validation.tests.WronglyOrderedWays;
58import org.openstreetmap.josm.gui.MapView.LayerChangeListener;
59import org.openstreetmap.josm.gui.layer.Layer;
60import org.openstreetmap.josm.gui.layer.OsmDataLayer;
61import org.openstreetmap.josm.gui.layer.ValidatorLayer;
62import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
63import org.openstreetmap.josm.gui.preferences.validator.ValidatorPreference;
64import org.openstreetmap.josm.tools.Utils;
65
66/**
67 * A OSM data validator.
68 *
69 * @author Francisco R. Santos <frsantos@gmail.com>
70 */
71public class OsmValidator implements LayerChangeListener {
72
73 public static ValidatorLayer errorLayer = null;
74
75 /** The validate action */
76 public ValidateAction validateAction = new ValidateAction();
77
78 /** Grid detail, multiplier of east,north values for valuable cell sizing */
79 public static double griddetail;
80
81 public static final Collection<String> ignoredErrors = new TreeSet<>();
82
83 /**
84 * All available tests
85 * TODO: is there any way to find out automatically all available tests?
86 */
87 @SuppressWarnings("unchecked")
88 private static final Class<Test>[] allAvailableTests = new Class[] {
89 /* FIXME - unique error numbers for tests aren't properly unique - ignoring will not work as expected */
90 DuplicateNode.class, // ID 1 .. 99
91 OverlappingWays.class, // ID 101 .. 199
92 UntaggedNode.class, // ID 201 .. 299
93 UntaggedWay.class, // ID 301 .. 399
94 SelfIntersectingWay.class, // ID 401 .. 499
95 DuplicatedWayNodes.class, // ID 501 .. 599
96 CrossingWays.Ways.class, // ID 601 .. 699
97 CrossingWays.Boundaries.class, // ID 601 .. 699
98 CrossingWays.Barrier.class, // ID 601 .. 699
99 SimilarNamedWays.class, // ID 701 .. 799
100 Coastlines.class, // ID 901 .. 999
101 WronglyOrderedWays.class, // ID 1001 .. 1099
102 UnclosedWays.class, // ID 1101 .. 1199
103 TagChecker.class, // ID 1201 .. 1299
104 UnconnectedWays.UnconnectedHighways.class, // ID 1301 .. 1399
105 UnconnectedWays.UnconnectedRailways.class, // ID 1301 .. 1399
106 UnconnectedWays.UnconnectedWaterways.class, // ID 1301 .. 1399
107 UnconnectedWays.UnconnectedNaturalOrLanduse.class, // ID 1301 .. 1399
108 UnconnectedWays.UnconnectedPower.class, // ID 1301 .. 1399
109 DuplicateWay.class, // ID 1401 .. 1499
110 NameMismatch.class, // ID 1501 .. 1599
111 MultipolygonTest.class, // ID 1601 .. 1699
112 RelationChecker.class, // ID 1701 .. 1799
113 TurnrestrictionTest.class, // ID 1801 .. 1899
114 DuplicateRelation.class, // ID 1901 .. 1999
115 WayConnectedToArea.class, // ID 2301 .. 2399
116 PowerLines.class, // ID 2501 .. 2599
117 Addresses.class, // ID 2601 .. 2699
118 Highways.class, // ID 2701 .. 2799
119 BarriersEntrances.class, // ID 2801 .. 2899
120 OpeningHourTest.class, // 2901 .. 2999
121 MapCSSTagChecker.class, // 3000 .. 3099
122 Lanes.class, // 3100 .. 3199
123 ConditionalKeys.class, // 3200 .. 3299
124 InternetTags.class, // 3300 .. 3399
125 };
126
127 private static Map<String, Test> allTestsMap;
128 static {
129 allTestsMap = new HashMap<>();
130 for (Class<Test> testClass : allAvailableTests) {
131 try {
132 allTestsMap.put(testClass.getName(), testClass.newInstance());
133 } catch (Exception e) {
134 Main.error(e);
135 }
136 }
137 }
138
139 /**
140 * Constructs a new {@code OsmValidator}.
141 */
142 public OsmValidator() {
143 checkValidatorDir();
144 initializeGridDetail();
145 loadIgnoredErrors(); //FIXME: load only when needed
146 }
147
148 /**
149 * Returns the validator directory.
150 *
151 * @return The validator directory
152 */
153 public static String getValidatorDir() {
154 return Main.pref.getPreferencesDir() + "validator/";
155 }
156
157 /**
158 * Check if plugin directory exists (store ignored errors file)
159 */
160 private void checkValidatorDir() {
161 try {
162 File pathDir = new File(getValidatorDir());
163 if (!pathDir.exists()) {
164 pathDir.mkdirs();
165 }
166 } catch (Exception e){
167 Main.error(e);
168 }
169 }
170
171 private void loadIgnoredErrors() {
172 ignoredErrors.clear();
173 if (Main.pref.getBoolean(ValidatorPreference.PREF_USE_IGNORE, true)) {
174 Path path = Paths.get(getValidatorDir() + "ignorederrors");
175 if (Files.exists(path)) {
176 try {
177 ignoredErrors.addAll(Files.readAllLines(path, StandardCharsets.UTF_8));
178 } catch (final FileNotFoundException e) {
179 Main.debug(Main.getErrorMessage(e));
180 } catch (final IOException e) {
181 Main.error(e);
182 }
183 }
184 }
185 }
186
187 public static void addIgnoredError(String s) {
188 ignoredErrors.add(s);
189 }
190
191 public static boolean hasIgnoredError(String s) {
192 return ignoredErrors.contains(s);
193 }
194
195 public static void saveIgnoredErrors() {
196 try (PrintWriter out = new PrintWriter(new OutputStreamWriter(
197 new FileOutputStream(getValidatorDir() + "ignorederrors"), StandardCharsets.UTF_8), false)) {
198 for (String e : ignoredErrors) {
199 out.println(e);
200 }
201 } catch (IOException e) {
202 Main.error(e);
203 }
204 }
205
206 public static void initializeErrorLayer() {
207 if (!Main.pref.getBoolean(ValidatorPreference.PREF_LAYER, true))
208 return;
209 if (errorLayer == null) {
210 errorLayer = new ValidatorLayer();
211 Main.main.addLayer(errorLayer);
212 }
213 }
214
215 /**
216 * Gets a map from simple names to all tests.
217 * @return A map of all tests, indexed and sorted by the name of their Java class
218 */
219 public static SortedMap<String, Test> getAllTestsMap() {
220 applyPrefs(allTestsMap, false);
221 applyPrefs(allTestsMap, true);
222 return new TreeMap<>(allTestsMap);
223 }
224
225 /**
226 * Returns the instance of the given test class.
227 * @param testClass The class of test to retrieve
228 * @return the instance of the given test class, if any, or {@code null}
229 * @since 6670
230 */
231 @SuppressWarnings("unchecked")
232 public static <T extends Test> T getTest(Class<T> testClass) {
233 if (testClass == null) {
234 return null;
235 }
236 return (T) allTestsMap.get(testClass.getName());
237 }
238
239 private static void applyPrefs(Map<String, Test> tests, boolean beforeUpload) {
240 for(String testName : Main.pref.getCollection(beforeUpload
241 ? ValidatorPreference.PREF_SKIP_TESTS_BEFORE_UPLOAD : ValidatorPreference.PREF_SKIP_TESTS)) {
242 Test test = tests.get(testName);
243 if (test != null) {
244 if (beforeUpload) {
245 test.testBeforeUpload = false;
246 } else {
247 test.enabled = false;
248 }
249 }
250 }
251 }
252
253 public static Collection<Test> getTests() {
254 return getAllTestsMap().values();
255 }
256
257 public static Collection<Test> getEnabledTests(boolean beforeUpload) {
258 Collection<Test> enabledTests = getTests();
259 for (Test t : new ArrayList<>(enabledTests)) {
260 if (beforeUpload ? t.testBeforeUpload : t.enabled) {
261 continue;
262 }
263 enabledTests.remove(t);
264 }
265 return enabledTests;
266 }
267
268 /**
269 * Gets the list of all available test classes
270 *
271 * @return An array of the test classes
272 */
273 public static Class<Test>[] getAllAvailableTests() {
274 return Utils.copyArray(allAvailableTests);
275 }
276
277 /**
278 * Initialize grid details based on current projection system. Values based on
279 * the original value fixed for EPSG:4326 (10000) using heuristics (that is, test&amp;error
280 * until most bugs were discovered while keeping the processing time reasonable)
281 */
282 public final void initializeGridDetail() {
283 String code = Main.getProjection().toCode();
284 if (Arrays.asList(ProjectionPreference.wgs84.allCodes()).contains(code)) {
285 OsmValidator.griddetail = 10000;
286 } else if (Arrays.asList(ProjectionPreference.mercator.allCodes()).contains(code)) {
287 OsmValidator.griddetail = 0.01;
288 } else if (Arrays.asList(ProjectionPreference.lambert.allCodes()).contains(code)) {
289 OsmValidator.griddetail = 0.1;
290 } else {
291 OsmValidator.griddetail = 1.0;
292 }
293 }
294
295 private static boolean testsInitialized = false;
296
297 /**
298 * Initializes all tests if this operations hasn't been performed already.
299 */
300 public static synchronized void initializeTests() {
301 if (!testsInitialized) {
302 Main.debug("Initializing validator tests");
303 final long startTime = System.currentTimeMillis();
304 initializeTests(getTests());
305 testsInitialized = true;
306 if (Main.isDebugEnabled()) {
307 final long elapsedTime = System.currentTimeMillis() - startTime;
308 Main.debug("Initializing validator tests completed in " + Utils.getDurationString(elapsedTime));
309 }
310 }
311 }
312
313 /**
314 * Initializes all tests
315 * @param allTests The tests to initialize
316 */
317 public static void initializeTests(Collection<? extends Test> allTests) {
318 for (Test test : allTests) {
319 try {
320 if (test.enabled) {
321 test.initialize();
322 }
323 } catch (Exception e) {
324 Main.error(e);
325 JOptionPane.showMessageDialog(Main.parent,
326 tr("Error initializing test {0}:\n {1}", test.getClass()
327 .getSimpleName(), e),
328 tr("Error"),
329 JOptionPane.ERROR_MESSAGE);
330 }
331 }
332 }
333
334 /* -------------------------------------------------------------------------- */
335 /* interface LayerChangeListener */
336 /* -------------------------------------------------------------------------- */
337 @Override
338 public void activeLayerChange(Layer oldLayer, Layer newLayer) {
339 }
340
341 @Override
342 public void layerAdded(Layer newLayer) {
343 }
344
345 @Override
346 public void layerRemoved(Layer oldLayer) {
347 if (oldLayer == errorLayer) {
348 errorLayer = null;
349 return;
350 }
351 if (Main.map.mapView.getLayersOfType(OsmDataLayer.class).isEmpty()) {
352 if (errorLayer != null) {
353 Main.main.removeLayer(errorLayer);
354 }
355 }
356 }
357}
Note: See TracBrowser for help on using the repository browser.