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

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

code simplification with some Java 7 new NIO2 Files methods (newBufferedReader, newBufferedWriter, readAllLines)

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