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

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

sonar - squid:S2440 - Classes with only "static" methods should not be instantiated

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