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

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

fix findbugs issue RV_RETURN_VALUE_IGNORED_BAD_PRACTICE for java.io.File.mkdirs

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