001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.data.validation; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005import static org.openstreetmap.josm.tools.I18n.trn; 006 007import java.io.File; 008import java.io.IOException; 009import java.io.InputStream; 010import java.io.OutputStream; 011import java.nio.charset.StandardCharsets; 012import java.nio.file.Files; 013import java.nio.file.Path; 014import java.nio.file.Paths; 015import java.util.ArrayList; 016import java.util.Arrays; 017import java.util.Collection; 018import java.util.Collections; 019import java.util.HashMap; 020import java.util.List; 021import java.util.Locale; 022import java.util.Map; 023import java.util.Optional; 024import java.util.concurrent.atomic.AtomicReference; 025import java.util.function.Supplier; 026import java.util.logging.Level; 027import java.util.stream.Collectors; 028 029import org.openstreetmap.josm.actions.ExtensionFileFilter; 030import org.openstreetmap.josm.cli.CLIModule; 031import org.openstreetmap.josm.data.Preferences; 032import org.openstreetmap.josm.data.osm.DataSet; 033import org.openstreetmap.josm.data.preferences.JosmBaseDirectories; 034import org.openstreetmap.josm.data.preferences.JosmUrls; 035import org.openstreetmap.josm.data.projection.ProjectionRegistry; 036import org.openstreetmap.josm.data.projection.Projections; 037import org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker; 038import org.openstreetmap.josm.gui.MainApplication; 039import org.openstreetmap.josm.gui.io.CustomConfigurator; 040import org.openstreetmap.josm.gui.io.importexport.FileImporter; 041import org.openstreetmap.josm.gui.layer.OsmDataLayer; 042import org.openstreetmap.josm.gui.mappaint.MapPaintStyles; 043import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource; 044import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException; 045import org.openstreetmap.josm.gui.progress.CLIProgressMonitor; 046import org.openstreetmap.josm.gui.progress.ProgressMonitor; 047import org.openstreetmap.josm.io.Compression; 048import org.openstreetmap.josm.io.GeoJSONMapRouletteWriter; 049import org.openstreetmap.josm.io.IllegalDataException; 050import org.openstreetmap.josm.io.OsmChangeReader; 051import org.openstreetmap.josm.spi.lifecycle.Lifecycle; 052import org.openstreetmap.josm.spi.preferences.Config; 053import org.openstreetmap.josm.spi.preferences.IPreferences; 054import org.openstreetmap.josm.spi.preferences.MemoryPreferences; 055import org.openstreetmap.josm.tools.Http1Client; 056import org.openstreetmap.josm.tools.HttpClient; 057import org.openstreetmap.josm.tools.I18n; 058import org.openstreetmap.josm.tools.JosmRuntimeException; 059import org.openstreetmap.josm.tools.Logging; 060import org.openstreetmap.josm.tools.OptionParser; 061import org.openstreetmap.josm.tools.Stopwatch; 062import org.openstreetmap.josm.tools.Territories; 063import org.openstreetmap.josm.tools.Utils; 064 065import jakarta.json.JsonObject; 066 067/** 068 * Add a validate command to the JOSM command line interface. 069 * @author Taylor Smock 070 * @since 18365 071 */ 072public class ValidatorCLI implements CLIModule { 073 /** 074 * The unique instance. 075 */ 076 public static final ValidatorCLI INSTANCE = new ValidatorCLI(); 077 078 /** The input file(s) */ 079 private final List<String> input = new ArrayList<>(); 080 /** The change files. input file → list of change files */ 081 private final Map<String, List<String>> changeFiles = new HashMap<>(); 082 /** The output file(s). If {@code null}, use input filename as base (replace extension with geojson). input → output */ 083 private final Map<String, String> output = new HashMap<>(); 084 085 private static final Supplier<ProgressMonitor> progressMonitorFactory = CLIProgressMonitor::new; 086 087 /** The log level */ 088 private Level logLevel; 089 090 private enum Option { 091 /** --help Show the help for validate */ 092 HELP(false, 'h'), 093 /** --input=<input-file> Set the current input file */ 094 INPUT(true, 'i', OptionParser.OptionCount.MULTIPLE), 095 /** --output=<output-file> Set the output file for the current input file */ 096 OUTPUT(true, 'o', OptionParser.OptionCount.MULTIPLE), 097 /** --change-file=<change-file> Add a change file */ 098 CHANGE_FILE(true, 'c', OptionParser.OptionCount.MULTIPLE), 099 /** --warn Set logging level to warn */ 100 WARN(false, '*'), 101 /** --debug Set logging level to debug */ 102 DEBUG(false, '*'), 103 /** --trace Set logging level to trace */ 104 TRACE(false, '*'), 105 /** --language=<language> Set the language */ 106 LANGUAGE(true, 'l'), 107 /** --load-preferences=<url-to-xml> Changes preferences according to the XML file */ 108 LOAD_PREFERENCES(true, 'p'), 109 /** --set=<key>=<value> Set preference key to value */ 110 SET(true, 's'); 111 112 private final String name; 113 private final boolean requiresArgument; 114 private final char shortOption; 115 private final OptionParser.OptionCount optionCount; 116 Option(final boolean requiresArgument, final char shortOption) { 117 this(requiresArgument, shortOption, OptionParser.OptionCount.OPTIONAL); 118 } 119 120 Option(final boolean requiresArgument, final char shortOption, final OptionParser.OptionCount optionCount) { 121 this.name = name().toLowerCase(Locale.ROOT).replace('_', '-'); 122 this.requiresArgument = requiresArgument; 123 this.shortOption = shortOption; 124 this.optionCount = optionCount; 125 } 126 127 /** 128 * Replies the option name 129 * @return The option name, in lowercase 130 */ 131 public String getName() { 132 return this.name; 133 } 134 135 /** 136 * Get the number of times this option should be seen 137 * @return The option count 138 */ 139 public OptionParser.OptionCount getOptionCount() { 140 return this.optionCount; 141 } 142 143 /** 144 * Replies the short option (single letter) associated with this option. 145 * @return the short option or '*' if there is no short option 146 */ 147 public char getShortOption() { 148 return this.shortOption; 149 } 150 151 /** 152 * Determines if this option requires an argument. 153 * @return {@code true} if this option requires an argument, {@code false} otherwise 154 */ 155 public boolean requiresArgument() { 156 return this.requiresArgument; 157 } 158 159 } 160 161 @Override 162 public String getActionKeyword() { 163 return "validate"; 164 } 165 166 @Override 167 public void processArguments(final String[] argArray) { 168 try { 169 // for right-left-hand traffic cache file, needed for preferences 170 Config.setBaseDirectoriesProvider(JosmBaseDirectories.getInstance()); 171 // Ensure that preferences are only in memory 172 Config.setPreferencesInstance(new MemoryPreferences()); 173 Logging.setLogLevel(Level.INFO); 174 this.parseArguments(argArray); 175 if (this.input.isEmpty()) { 176 throw new IllegalArgumentException(tr("Missing argument - input data file ({0})", "--input|-i")); 177 } 178 this.initialize(); 179 final ProgressMonitor fileMonitor = progressMonitorFactory.get(); 180 fileMonitor.beginTask(tr("Processing files..."), this.input.size()); 181 for (String inputFile : this.input) { 182 if (inputFile.endsWith(".validator.mapcss")) { 183 processValidatorFile(inputFile); 184 } else if (inputFile.endsWith(".mapcss")) { 185 processMapcssFile(inputFile); 186 } else { 187 this.processFile(inputFile); 188 } 189 fileMonitor.worked(1); 190 } 191 fileMonitor.finishTask(); 192 } catch (Exception e) { 193 Logging.info(e); 194 Lifecycle.exitJosm(true, 1); 195 } 196 Lifecycle.exitJosm(true, 0); 197 } 198 199 /** 200 * Process a standard mapcss file 201 * @param inputFile The mapcss file to validate 202 * @throws ParseException if the file does not match the mapcss syntax 203 */ 204 private static void processMapcssFile(final String inputFile) throws ParseException { 205 final MapCSSStyleSource styleSource = new MapCSSStyleSource(new File(inputFile).toURI().getPath(), inputFile, inputFile); 206 styleSource.loadStyleSource(); 207 if (!styleSource.getErrors().isEmpty()) { 208 throw new ParseException(trn("{0} had {1} error", "{0} had {1} errors", styleSource.getErrors().size(), 209 inputFile, styleSource.getErrors().size())); 210 } else { 211 Logging.info(tr("{0} had no errors", inputFile)); 212 } 213 } 214 215 /** 216 * Process a validator file 217 * @param inputFile The file to check 218 * @throws IOException if there is a problem reading the file 219 * @throws ParseException if the file does not match the validator mapcss syntax 220 */ 221 private static void processValidatorFile(final String inputFile) throws ParseException, IOException { 222 // Check asserts 223 Config.getPref().putBoolean("validator.check_assert_local_rules", true); 224 final MapCSSTagChecker mapCSSTagChecker = new MapCSSTagChecker(); 225 final Collection<String> assertionErrors = new ArrayList<>(); 226 final MapCSSTagChecker.ParseResult result = mapCSSTagChecker.addMapCSS(new File(inputFile).toURI().getPath(), 227 assertionErrors::add); 228 if (!result.parseErrors.isEmpty() || !assertionErrors.isEmpty()) { 229 for (Throwable throwable : result.parseErrors) { 230 Logging.error(throwable); 231 } 232 for (String error : assertionErrors) { 233 Logging.error(error); 234 } 235 throw new ParseException(trn("{0} had {1} error", "{0} had {1} errors", result.parseErrors.size() + assertionErrors.size(), 236 inputFile, result.parseErrors.size() + assertionErrors.size())); 237 } else { 238 Logging.info(tr("{0} had no errors"), inputFile); 239 } 240 } 241 242 /** 243 * Process an OSM file 244 * @param inputFile The input filename 245 * @throws IllegalArgumentException If an argument is not valid 246 * @throws IllegalDataException If there is bad data 247 * @throws IOException If a file could not be read or written 248 */ 249 private void processFile(final String inputFile) throws IllegalDataException, IOException { 250 final File inputFileFile = new File(inputFile); 251 final List<FileImporter> inputFileImporters = ExtensionFileFilter.getImporters().stream() 252 .filter(importer -> importer.acceptFile(inputFileFile)).collect(Collectors.toList()); 253 final Stopwatch stopwatch = Stopwatch.createStarted(); 254 if (inputFileImporters.stream().noneMatch(fileImporter -> 255 fileImporter.importDataHandleExceptions(inputFileFile, progressMonitorFactory.get()))) { 256 throw new IOException(tr("Could not load input file: {0}", inputFile)); 257 } 258 final String outputFile = Optional.ofNullable(this.output.get(inputFile)).orElseGet(() -> getDefaultOutputName(inputFile)); 259 final String task = tr("Validating {0}, saving output to {1}", inputFile, outputFile); 260 OsmDataLayer dataLayer = null; 261 try { 262 Logging.info(task); 263 dataLayer = MainApplication.getLayerManager().getLayersOfType(OsmDataLayer.class) 264 .stream().filter(layer -> inputFileFile.equals(layer.getAssociatedFile())) 265 .findFirst().orElseThrow(() -> new JosmRuntimeException(tr("Could not find a layer for {0}", inputFile))); 266 final DataSet dataSet = dataLayer.getDataSet(); 267 if (this.changeFiles.containsKey(inputFile)) { 268 final ProgressMonitor changeFilesMonitor = progressMonitorFactory.get(); 269 for (String changeFile : this.changeFiles.getOrDefault(inputFile, Collections.emptyList())) { 270 try (InputStream changeStream = Compression.getUncompressedFileInputStream(Paths.get(changeFile))) { 271 dataSet.mergeFrom(OsmChangeReader.parseDataSet(changeStream, changeFilesMonitor)); 272 } 273 } 274 } 275 final Path path = Paths.get(outputFile); 276 if (path.toFile().isFile() && !Files.deleteIfExists(path)) { 277 Logging.error("Could not delete {0}, attempting to append", outputFile); 278 } 279 final GeoJSONMapRouletteWriter geoJSONMapRouletteWriter = new GeoJSONMapRouletteWriter(dataSet); 280 OsmValidator.initializeTests(); 281 282 try (OutputStream fileOutputStream = Files.newOutputStream(path)) { 283 // The first writeErrors catches anything that was written, for whatever reason. This is probably never 284 // going to be called. 285 final ValidationTask validationTask = 286 new ValidationTask(errors -> writeErrors(geoJSONMapRouletteWriter, fileOutputStream, errors), 287 progressMonitorFactory.get(), OsmValidator.getEnabledTests(false), 288 dataSet.allPrimitives(), Collections.emptyList(), false); 289 // This avoids keeping errors in memory 290 validationTask.setTestConsumer((t, test) -> { 291 writeErrors(geoJSONMapRouletteWriter, fileOutputStream, test.getErrors()); 292 t.getErrors().removeIf(test.getErrors()::contains); 293 }); 294 validationTask.run(); 295 } 296 } finally { 297 if (dataLayer != null) { 298 MainApplication.getLayerManager().removeLayer(dataLayer); 299 } 300 Logging.info(stopwatch.toString(task)); 301 } 302 } 303 304 private void writeErrors(GeoJSONMapRouletteWriter geoJSONMapRouletteWriter, OutputStream fileOutputStream, 305 Collection<TestError> errors) { 306 for (TestError error : errors) { 307 Optional<JsonObject> object = geoJSONMapRouletteWriter.write(error); 308 if (object.isPresent()) { 309 try { 310 writeToFile(fileOutputStream, object.get().toString().getBytes(StandardCharsets.UTF_8)); 311 } catch (IOException e) { 312 throw new JosmRuntimeException(e); 313 } 314 } 315 } 316 } 317 318 /** 319 * Get the default output name 320 * @param inputString The input file 321 * @return The default output name for the input file (extension stripped, ".geojson" added) 322 */ 323 private static String getDefaultOutputName(final String inputString) { 324 final String[] parts = getFileParts(inputString); 325 final String extension = parts[1]; 326 if (!Arrays.asList("zip", "bz", "xz", "geojson").contains(extension)) { 327 return parts[0] + ".geojson"; 328 } else if ("geojson".equals(extension)) { 329 // Account for geojson input files 330 return parts[0] + ".validated.geojson"; 331 } 332 return parts[0] + ".geojson"; 333 } 334 335 /** 336 * Split a string into a filename + extension. Example: 337 * "foo.bar.txt" → ["foo.bar", "txt"] 338 * <p> 339 * Please note that future versions of Java may make this method redundant. It is not as of Java 21 (look for 340 * something like {@code Path#getExtension}, see <a href="https://bugs.openjdk.org/browse/JDK-8298318">JDK-8298318</a>. 341 * That may be in Java 22. 342 * @param inputString The string to get the filename and extension from 343 * @return The filename and the (optional) extension 344 */ 345 private static String[] getFileParts(String inputString) { 346 final int split = inputString.lastIndexOf('.'); 347 final int path = inputString.lastIndexOf(File.separatorChar); 348 if (split == -1 || path > split) { 349 return new String[] {inputString, ""}; 350 } else { 351 return new String[]{inputString.substring(0, split), inputString.substring(split + 1)}; 352 } 353 } 354 355 /** 356 * Write to a file. Synchronized to avoid writing to the same file in different threads. 357 * 358 * @param fileOutputStream The file output stream to read 359 * @param bytes The bytes to write (surrounded by RS and LF) 360 * @throws IOException If we couldn't write to file 361 */ 362 private synchronized void writeToFile(final OutputStream fileOutputStream, final byte[] bytes) 363 throws IOException { 364 // Write the ASCII Record Separator character 365 fileOutputStream.write(0x1e); 366 fileOutputStream.write(bytes); 367 // Write the ASCII Line Feed character 368 fileOutputStream.write(0x0a); 369 } 370 371 /** 372 * Initialize everything that might be needed 373 * 374 * Arguments may need to be parsed first. 375 */ 376 void initialize() { 377 Logging.setLogLevel(this.logLevel); 378 HttpClient.setFactory(Http1Client::new); 379 Config.setUrlsProvider(JosmUrls.getInstance()); 380 ProjectionRegistry.setProjection(Projections.getProjectionByCode("epsg:3857".toUpperCase(Locale.ROOT))); 381 382 Territories.initializeInternalData(); // There is no current way to check to see if territories is already initialized 383 OsmValidator.initialize(); 384 MapPaintStyles.readFromPreferences(); 385 } 386 387 /** 388 * Parse command line arguments and do some low-level error checking. 389 * @param argArray the arguments array 390 */ 391 void parseArguments(String[] argArray) { 392 Logging.setLogLevel(Level.INFO); 393 394 OptionParser parser = new OptionParser("JOSM validate"); 395 final AtomicReference<String> currentInput = new AtomicReference<>(null); 396 for (Option o : Option.values()) { 397 if (o.requiresArgument()) { 398 parser.addArgumentParameter(o.getName(), 399 o.getOptionCount(), 400 arg -> handleOption(currentInput.get(), o, arg).ifPresent(currentInput::set)); 401 } else { 402 parser.addFlagParameter(o.getName(), () -> handleOption(o)); 403 } 404 if (o.getShortOption() != '*') { 405 parser.addShortAlias(o.getName(), Character.toString(o.getShortOption())); 406 } 407 } 408 parser.parseOptionsOrExit(Arrays.asList(argArray)); 409 } 410 411 private void handleOption(final Option option) { 412 switch (option) { 413 case HELP: 414 showHelp(); 415 Lifecycle.exitJosm(true, 0); 416 break; 417 case WARN: 418 this.logLevel = Logging.LEVEL_WARN; 419 break; 420 case DEBUG: 421 this.logLevel = Logging.LEVEL_DEBUG; 422 break; 423 case TRACE: 424 this.logLevel = Logging.LEVEL_TRACE; 425 break; 426 default: 427 throw new AssertionError("Unexpected option: " + option); 428 } 429 } 430 431 /** 432 * Handle an option 433 * @param currentInput The current input file, if any. May be {@code null}. 434 * @param option The option to parse 435 * @param argument The argument for the option 436 * @return The new input file, if any. 437 */ 438 private Optional<String> handleOption(final String currentInput, final Option option, final String argument) { 439 switch (option) { 440 case INPUT: 441 this.input.add(argument); 442 return Optional.of(argument); 443 case OUTPUT: 444 this.output.put(currentInput, argument); 445 break; 446 case CHANGE_FILE: 447 this.changeFiles.computeIfAbsent(currentInput, key -> new ArrayList<>()).add(argument); 448 break; 449 case LANGUAGE: 450 I18n.set(argument); 451 break; 452 case LOAD_PREFERENCES: 453 final Preferences tempPreferences = new Preferences(); 454 tempPreferences.enableSaveOnPut(false); 455 CustomConfigurator.XMLCommandProcessor config = new CustomConfigurator.XMLCommandProcessor(tempPreferences); 456 try (InputStream is = Utils.openStream(new File(argument).toURI().toURL())) { 457 config.openAndReadXML(is); 458 } catch (IOException e) { 459 throw new JosmRuntimeException(e); 460 } 461 final IPreferences pref = Config.getPref(); 462 if (pref instanceof MemoryPreferences) { 463 final MemoryPreferences memoryPreferences = (MemoryPreferences) pref; 464 tempPreferences.getAllSettings().forEach(memoryPreferences::putSetting); 465 } else { 466 throw new JosmRuntimeException(tr("Preferences are not the expected type")); 467 } 468 break; 469 case SET: 470 471 default: 472 throw new AssertionError("Unexpected option: " + option); 473 } 474 return Optional.empty(); 475 } 476 477 private static void showHelp() { 478 System.out.println(getHelp()); 479 } 480 481 private static String getHelp() { 482 final String helpPadding = "\t "; 483 // CHECKSTYLE.OFF: SingleSpaceSeparator 484 return tr("JOSM Validation command line interface") + "\n\n" + 485 tr("Usage") + ":\n" + 486 "\tjava -jar josm.jar validate <options>\n\n" + 487 tr("Description") + ":\n" + 488 tr("Validates data and saves the result to a file.") + "\n\n"+ 489 tr("Options") + ":\n" + 490 "\t--help|-h " + tr("Show this help") + "\n" + 491 "\t--input|-i <file> " + tr("Input data file name (.osm, .validator.mapcss, .mapcss).") + '\n' + 492 helpPadding + tr("OSM files can be specified multiple times. Required.") + '\n' + 493 helpPadding + tr(".validator.mapcss and .mapcss files will stop processing on first error.") + '\n' + 494 helpPadding + tr("Non-osm files do not use --output or --change-file") + '\n' + 495 "\t--output|-o <file> " + tr("Output data file name (.geojson, line-by-line delimited for MapRoulette). Optional.") 496 + '\n' + 497 "\t--change-file|-c <file> " + tr("Change file name (.osc). Can be specified multiple times per input.") + '\n' + 498 helpPadding + tr("Changes will be applied in the specified order. Optional."); 499 // CHECKSTYLE.ON: SingleSpaceSeparator 500 } 501}