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

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

sonar - Methods should not be empty

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