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

Last change on this file since 11136 was 11136, checked in by bastiK, 8 years ago

applied #13086 - Detect all self-intersecting ways (patch by Gerd Petermann)

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