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

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

see #15182 - code refactoring to avoid dependence on GUI packages from Preferences

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