001// License: GPL. See LICENSE file for details. 002package org.openstreetmap.josm.data.validation; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.io.File; 007import java.io.FileNotFoundException; 008import java.io.FileOutputStream; 009import java.io.IOException; 010import java.io.OutputStreamWriter; 011import java.io.PrintWriter; 012import java.nio.charset.StandardCharsets; 013import java.nio.file.Files; 014import java.nio.file.Path; 015import java.nio.file.Paths; 016import java.util.ArrayList; 017import java.util.Arrays; 018import java.util.Collection; 019import java.util.HashMap; 020import java.util.Map; 021import java.util.SortedMap; 022import java.util.TreeMap; 023import java.util.TreeSet; 024 025import javax.swing.JOptionPane; 026 027import org.openstreetmap.josm.Main; 028import org.openstreetmap.josm.actions.ValidateAction; 029import org.openstreetmap.josm.data.validation.tests.Addresses; 030import org.openstreetmap.josm.data.validation.tests.BarriersEntrances; 031import org.openstreetmap.josm.data.validation.tests.Coastlines; 032import org.openstreetmap.josm.data.validation.tests.ConditionalKeys; 033import org.openstreetmap.josm.data.validation.tests.CrossingWays; 034import org.openstreetmap.josm.data.validation.tests.DuplicateNode; 035import org.openstreetmap.josm.data.validation.tests.DuplicateRelation; 036import org.openstreetmap.josm.data.validation.tests.DuplicateWay; 037import org.openstreetmap.josm.data.validation.tests.DuplicatedWayNodes; 038import org.openstreetmap.josm.data.validation.tests.Highways; 039import org.openstreetmap.josm.data.validation.tests.Lanes; 040import org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker; 041import org.openstreetmap.josm.data.validation.tests.MultipolygonTest; 042import org.openstreetmap.josm.data.validation.tests.NameMismatch; 043import org.openstreetmap.josm.data.validation.tests.OpeningHourTest; 044import org.openstreetmap.josm.data.validation.tests.OverlappingWays; 045import org.openstreetmap.josm.data.validation.tests.PowerLines; 046import org.openstreetmap.josm.data.validation.tests.RelationChecker; 047import org.openstreetmap.josm.data.validation.tests.SelfIntersectingWay; 048import org.openstreetmap.josm.data.validation.tests.SimilarNamedWays; 049import org.openstreetmap.josm.data.validation.tests.TagChecker; 050import org.openstreetmap.josm.data.validation.tests.TurnrestrictionTest; 051import org.openstreetmap.josm.data.validation.tests.UnclosedWays; 052import org.openstreetmap.josm.data.validation.tests.UnconnectedWays; 053import org.openstreetmap.josm.data.validation.tests.UntaggedNode; 054import org.openstreetmap.josm.data.validation.tests.UntaggedWay; 055import org.openstreetmap.josm.data.validation.tests.WayConnectedToArea; 056import org.openstreetmap.josm.data.validation.tests.WronglyOrderedWays; 057import org.openstreetmap.josm.gui.MapView.LayerChangeListener; 058import org.openstreetmap.josm.gui.layer.Layer; 059import org.openstreetmap.josm.gui.layer.OsmDataLayer; 060import org.openstreetmap.josm.gui.layer.ValidatorLayer; 061import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference; 062import org.openstreetmap.josm.gui.preferences.validator.ValidatorPreference; 063import org.openstreetmap.josm.tools.Utils; 064 065/** 066 * A OSM data validator. 067 * 068 * @author Francisco R. Santos <frsantos@gmail.com> 069 */ 070public class OsmValidator implements LayerChangeListener { 071 072 public static ValidatorLayer errorLayer = null; 073 074 /** The validate action */ 075 public ValidateAction validateAction = new ValidateAction(); 076 077 /** Grid detail, multiplier of east,north values for valuable cell sizing */ 078 public static double griddetail; 079 080 public static final Collection<String> ignoredErrors = new TreeSet<>(); 081 082 /** 083 * All available tests 084 * TODO: is there any way to find out automatically all available tests? 085 */ 086 @SuppressWarnings("unchecked") 087 private static final Class<Test>[] allAvailableTests = new Class[] { 088 /* FIXME - unique error numbers for tests aren't properly unique - ignoring will not work as expected */ 089 DuplicateNode.class, // ID 1 .. 99 090 OverlappingWays.class, // ID 101 .. 199 091 UntaggedNode.class, // ID 201 .. 299 092 UntaggedWay.class, // ID 301 .. 399 093 SelfIntersectingWay.class, // ID 401 .. 499 094 DuplicatedWayNodes.class, // ID 501 .. 599 095 CrossingWays.Ways.class, // ID 601 .. 699 096 CrossingWays.Boundaries.class, // ID 601 .. 699 097 CrossingWays.Barrier.class, // ID 601 .. 699 098 SimilarNamedWays.class, // ID 701 .. 799 099 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 validator directory. 148 * 149 * @return The validator directory 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&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}