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

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

PMD - VariableNamingConventions

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