001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.io; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.io.IOException; 007import java.io.InputStream; 008import java.nio.charset.StandardCharsets; 009import java.time.Duration; 010import java.time.LocalDateTime; 011import java.time.Period; 012import java.time.ZoneId; 013import java.time.ZoneOffset; 014import java.time.format.DateTimeParseException; 015import java.util.Arrays; 016import java.util.Collection; 017import java.util.Collections; 018import java.util.EnumMap; 019import java.util.List; 020import java.util.Locale; 021import java.util.Map; 022import java.util.NoSuchElementException; 023import java.util.Objects; 024import java.util.Set; 025import java.util.concurrent.ConcurrentHashMap; 026import java.util.concurrent.TimeUnit; 027import java.util.regex.Matcher; 028import java.util.regex.Pattern; 029 030import javax.xml.stream.XMLStreamConstants; 031import javax.xml.stream.XMLStreamException; 032 033import org.openstreetmap.josm.data.Bounds; 034import org.openstreetmap.josm.data.DataSource; 035import org.openstreetmap.josm.data.coor.LatLon; 036import org.openstreetmap.josm.data.osm.BBox; 037import org.openstreetmap.josm.data.osm.DataSet; 038import org.openstreetmap.josm.data.osm.DataSetMerger; 039import org.openstreetmap.josm.data.osm.OsmPrimitiveType; 040import org.openstreetmap.josm.data.osm.PrimitiveId; 041import org.openstreetmap.josm.data.preferences.BooleanProperty; 042import org.openstreetmap.josm.data.preferences.ListProperty; 043import org.openstreetmap.josm.data.preferences.StringProperty; 044import org.openstreetmap.josm.gui.download.OverpassDownloadSource; 045import org.openstreetmap.josm.gui.progress.ProgressMonitor; 046import org.openstreetmap.josm.io.NameFinder.SearchResult; 047import org.openstreetmap.josm.tools.HttpClient; 048import org.openstreetmap.josm.tools.Logging; 049import org.openstreetmap.josm.tools.UncheckedParseException; 050import org.openstreetmap.josm.tools.Utils; 051import org.openstreetmap.josm.tools.date.DateUtils; 052 053/** 054 * Read content from an Overpass server. 055 * 056 * @since 8744 057 */ 058public class OverpassDownloadReader extends BoundingBoxDownloader { 059 060 /** 061 * Property for current Overpass server. 062 * @since 12816 063 */ 064 public static final StringProperty OVERPASS_SERVER = new StringProperty("download.overpass.server", 065 "https://overpass-api.de/api/"); 066 /** 067 * Property for list of known Overpass servers. 068 * @since 12816 069 */ 070 public static final ListProperty OVERPASS_SERVER_HISTORY = new ListProperty("download.overpass.servers", 071 Arrays.asList("https://overpass-api.de/api/", "http://overpass.openstreetmap.ru/cgi/")); 072 /** 073 * Property to determine if Overpass API should be used for multi-fetch download. 074 * @since 12816 075 */ 076 public static final BooleanProperty FOR_MULTI_FETCH = new BooleanProperty("download.overpass.for-multi-fetch", false); 077 078 private static final String DATA_PREFIX = "?data="; 079 080 static final class OverpassOsmReader extends OsmReader { 081 @Override 082 protected void parseUnknown(boolean printWarning) throws XMLStreamException { 083 if ("remark".equals(parser.getLocalName()) && parser.getEventType() == XMLStreamConstants.START_ELEMENT) { 084 final String text = parser.getElementText(); 085 if (text.contains("runtime error")) { 086 throw new XMLStreamException(text); 087 } 088 } 089 super.parseUnknown(printWarning); 090 } 091 } 092 093 static final class OverpassOsmJsonReader extends OsmJsonReader { 094 095 } 096 097 /** 098 * Possible Overpass API output format, with the {@code [out:<directive>]} statement. 099 * @since 11916 100 */ 101 public enum OverpassOutputFormat { 102 /** Default output format: plain OSM XML */ 103 OSM_XML("xml"), 104 /** OSM JSON format (not GeoJson) */ 105 OSM_JSON("json"), 106 /** CSV, see https://wiki.openstreetmap.org/wiki/Overpass_API/Overpass_QL#Output_Format_.28out.29 */ 107 CSV("csv"), 108 /** Custom, see https://overpass-api.de/output_formats.html#custom */ 109 CUSTOM("custom"), 110 /** Popup, see https://overpass-api.de/output_formats.html#popup */ 111 POPUP("popup"), 112 /** PBF, see https://josm.openstreetmap.de/ticket/14653 */ 113 PBF("pbf"); 114 115 private final String directive; 116 117 OverpassOutputFormat(String directive) { 118 this.directive = directive; 119 } 120 121 /** 122 * Returns the directive used in {@code [out:<directive>]} statement. 123 * @return the directive used in {@code [out:<directive>]} statement 124 */ 125 public String getDirective() { 126 return directive; 127 } 128 129 /** 130 * Returns the {@code OverpassOutputFormat} matching the given directive. 131 * @param directive directive used in {@code [out:<directive>]} statement 132 * @return {@code OverpassOutputFormat} matching the given directive 133 * @throws IllegalArgumentException in case of invalid directive 134 */ 135 static OverpassOutputFormat from(String directive) { 136 for (OverpassOutputFormat oof : values()) { 137 if (oof.directive.equals(directive)) { 138 return oof; 139 } 140 } 141 throw new IllegalArgumentException(directive); 142 } 143 } 144 145 static final Pattern OUTPUT_FORMAT_STATEMENT = Pattern.compile(".*\\[out:([a-z]{3,})\\].*", Pattern.DOTALL); 146 147 static final Map<OverpassOutputFormat, Class<? extends AbstractReader>> outputFormatReaders = new ConcurrentHashMap<>(); 148 149 final String overpassServer; 150 final String overpassQuery; 151 152 /** 153 * Constructs a new {@code OverpassDownloadReader}. 154 * 155 * @param downloadArea The area to download 156 * @param overpassServer The Overpass server to use 157 * @param overpassQuery The Overpass query 158 */ 159 public OverpassDownloadReader(Bounds downloadArea, String overpassServer, String overpassQuery) { 160 super(downloadArea); 161 setDoAuthenticate(false); 162 this.overpassServer = overpassServer; 163 this.overpassQuery = overpassQuery.trim(); 164 } 165 166 /** 167 * Registers an OSM reader for the given Overpass output format. 168 * @param format Overpass output format 169 * @param readerClass OSM reader class 170 * @return the previous value associated with {@code format}, or {@code null} if there was no mapping 171 */ 172 public static final Class<? extends AbstractReader> registerOverpassOutputFormatReader( 173 OverpassOutputFormat format, Class<? extends AbstractReader> readerClass) { 174 return outputFormatReaders.put(Objects.requireNonNull(format), Objects.requireNonNull(readerClass)); 175 } 176 177 static { 178 registerOverpassOutputFormatReader(OverpassOutputFormat.OSM_XML, OverpassOsmReader.class); 179 registerOverpassOutputFormatReader(OverpassOutputFormat.OSM_JSON, OverpassOsmJsonReader.class); 180 } 181 182 @Override 183 protected String getBaseUrl() { 184 return overpassServer; 185 } 186 187 @Override 188 protected String getRequestForBbox(double lon1, double lat1, double lon2, double lat2) { 189 if (overpassQuery.isEmpty()) 190 return super.getRequestForBbox(lon1, lat1, lon2, lat2); 191 else { 192 final String query = this.overpassQuery 193 .replace("{{bbox}}", bbox(lon1, lat1, lon2, lat2)) 194 .replace("{{center}}", center(lon1, lat1, lon2, lat2)); 195 final String expandedOverpassQuery = expandExtendedQueries(query); 196 return "interpreter" + DATA_PREFIX + Utils.encodeUrl(expandedOverpassQuery); 197 } 198 } 199 200 /** 201 * Evaluates some features of overpass turbo extended query syntax. 202 * See https://wiki.openstreetmap.org/wiki/Overpass_turbo/Extended_Overpass_Turbo_Queries 203 * @param query unexpanded query 204 * @return expanded query 205 */ 206 static String expandExtendedQueries(String query) { 207 final StringBuffer sb = new StringBuffer(); 208 final Matcher matcher = Pattern.compile("\\{\\{(date|geocodeArea|geocodeBbox|geocodeCoords|geocodeId):([^}]+)\\}\\}").matcher(query); 209 while (matcher.find()) { 210 try { 211 switch (matcher.group(1)) { 212 case "date": 213 matcher.appendReplacement(sb, date(matcher.group(2), LocalDateTime.now(ZoneId.systemDefault()))); 214 break; 215 case "geocodeArea": 216 matcher.appendReplacement(sb, geocodeArea(matcher.group(2))); 217 break; 218 case "geocodeBbox": 219 matcher.appendReplacement(sb, geocodeBbox(matcher.group(2))); 220 break; 221 case "geocodeCoords": 222 matcher.appendReplacement(sb, geocodeCoords(matcher.group(2))); 223 break; 224 case "geocodeId": 225 matcher.appendReplacement(sb, geocodeId(matcher.group(2))); 226 break; 227 default: 228 Logging.warn("Unsupported syntax: " + matcher.group(1)); 229 } 230 } catch (UncheckedParseException | DateTimeParseException | IOException | NoSuchElementException | IndexOutOfBoundsException ex) { 231 final String msg = tr("Failed to evaluate {0}", matcher.group()); 232 Logging.log(Logging.LEVEL_WARN, msg, ex); 233 matcher.appendReplacement(sb, "// " + msg + "\n"); 234 } 235 } 236 matcher.appendTail(sb); 237 return sb.toString(); 238 } 239 240 static String bbox(double lon1, double lat1, double lon2, double lat2) { 241 return lat1 + "," + lon1 + "," + lat2 + "," + lon2; 242 } 243 244 static String center(double lon1, double lat1, double lon2, double lat2) { 245 LatLon c = new BBox(lon1, lat1, lon2, lat2).getCenter(); 246 return c.lat()+ "," + c.lon(); 247 } 248 249 static String date(String dateOrHumanDuration, LocalDateTime from) { 250 try { 251 return DateUtils.parseInstant(dateOrHumanDuration).toString(); 252 } catch (UncheckedParseException e) { 253 Logging.trace(e); 254 } 255 return duration(dateOrHumanDuration, from); 256 } 257 258 static String duration(String humanDuration, LocalDateTime from) { 259 // Convert to ISO 8601. Replace months by X temporarily to avoid conflict with minutes 260 String duration = humanDuration.toLowerCase(Locale.ENGLISH).replace(" ", "") 261 .replaceAll("years?", "Y").replaceAll("months?", "X").replaceAll("weeks?", "W") 262 .replaceAll("days?", "D").replaceAll("hours?", "H").replaceAll("minutes?", "M").replaceAll("seconds?", "S"); 263 Matcher matcher = Pattern.compile( 264 "((?:[0-9]+Y)?(?:[0-9]+X)?(?:[0-9]+W)?)"+ 265 "((?:[0-9]+D)?)" + 266 "((?:[0-9]+H)?(?:[0-9]+M)?(?:[0-9]+(?:[.,][0-9]{0,9})?S)?)?").matcher(duration); 267 boolean javaPer = false; 268 boolean javaDur = false; 269 if (matcher.matches()) { 270 javaPer = !Utils.isEmpty(matcher.group(1)); 271 javaDur = !Utils.isEmpty(matcher.group(3)); 272 duration = 'P' + matcher.group(1).replace('X', 'M') + matcher.group(2); 273 if (javaDur) { 274 duration += 'T' + matcher.group(3); 275 } 276 } 277 278 // Duration is now a full ISO 8601 duration string. Unfortunately Java does not allow to parse it entirely. 279 // We must split the "period" (years, months, weeks, days) from the "duration" (days, hours, minutes, seconds). 280 Period p = null; 281 Duration d = null; 282 int idx = duration.indexOf('T'); 283 if (javaPer) { 284 p = Period.parse(javaDur ? duration.substring(0, idx) : duration); 285 } 286 if (javaDur) { 287 d = Duration.parse(javaPer ? 'P' + duration.substring(idx) : duration); 288 } else if (!javaPer) { 289 d = Duration.parse(duration); 290 } 291 292 // Now that period and duration are known, compute the correct date/time 293 LocalDateTime dt = from; 294 if (p != null) { 295 dt = dt.minus(p); 296 } 297 if (d != null) { 298 dt = dt.minus(d); 299 } 300 301 // Returns the date/time formatted in ISO 8601 302 return dt.toInstant(ZoneOffset.UTC).toString(); 303 } 304 305 private static SearchResult searchName(String area) throws IOException { 306 return searchName(NameFinder.queryNominatim(area)); 307 } 308 309 static SearchResult searchName(List<SearchResult> results) { 310 return results.stream().filter( 311 x -> OsmPrimitiveType.NODE != x.getOsmId().getType()).iterator().next(); 312 } 313 314 static String geocodeArea(String area) throws IOException { 315 // Offsets defined in https://wiki.openstreetmap.org/wiki/Overpass_API/Overpass_QL#By_element_id 316 final EnumMap<OsmPrimitiveType, Long> idOffset = new EnumMap<>(OsmPrimitiveType.class); 317 idOffset.put(OsmPrimitiveType.NODE, 0L); 318 idOffset.put(OsmPrimitiveType.WAY, 2_400_000_000L); 319 idOffset.put(OsmPrimitiveType.RELATION, 3_600_000_000L); 320 final PrimitiveId osmId = searchName(area).getOsmId(); 321 Logging.debug("Area ''{0}'' resolved to {1}", area, osmId); 322 return String.format(Locale.ENGLISH, "area(%d)", osmId.getUniqueId() + idOffset.get(osmId.getType())); 323 } 324 325 static String geocodeBbox(String area) throws IOException { 326 Bounds bounds = searchName(area).getBounds(); 327 return bounds.getMinLat() + "," + bounds.getMinLon() + "," + bounds.getMaxLat() + "," + bounds.getMaxLon(); 328 } 329 330 static String geocodeCoords(String area) throws IOException { 331 SearchResult result = searchName(area); 332 return result.getLat() + "," + result.getLon(); 333 } 334 335 static String geocodeId(String area) throws IOException { 336 PrimitiveId osmId = searchName(area).getOsmId(); 337 return String.format(Locale.ENGLISH, "%s(%d)", osmId.getType().getAPIName(), osmId.getUniqueId()); 338 } 339 340 @Override 341 protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason, 342 boolean uncompressAccordingToContentDisposition) throws OsmTransferException { 343 try { 344 int index = urlStr.indexOf(DATA_PREFIX); 345 // Make an HTTP POST request instead of a simple GET, allows more complex queries 346 return super.getInputStreamRaw(urlStr.substring(0, index), 347 progressMonitor, reason, uncompressAccordingToContentDisposition, 348 "POST", Utils.decodeUrl(urlStr.substring(index + DATA_PREFIX.length())).getBytes(StandardCharsets.UTF_8)); 349 } catch (OsmApiException ex) { 350 final String errorIndicator = "Error</strong>: "; 351 if (ex.getMessage() != null && ex.getMessage().contains(errorIndicator)) { 352 final String errorPlusRest = ex.getMessage().split(errorIndicator, -1)[1]; 353 if (errorPlusRest != null) { 354 ex.setErrorHeader(errorPlusRest.split("</", -1)[0].replaceAll(".*::request_read_and_idx::", "")); 355 } 356 } 357 throw ex; 358 } 359 } 360 361 @Override 362 protected void adaptRequest(HttpClient request) { 363 // see https://wiki.openstreetmap.org/wiki/Overpass_API/Overpass_QL#timeout 364 final Matcher timeoutMatcher = Pattern.compile("\\[timeout:(\\d+)\\]").matcher(overpassQuery); 365 final int timeout; 366 if (timeoutMatcher.find()) { 367 timeout = (int) TimeUnit.SECONDS.toMillis(Integer.parseInt(timeoutMatcher.group(1))); 368 } else { 369 timeout = (int) TimeUnit.MINUTES.toMillis(3); 370 } 371 request.setConnectTimeout(timeout); 372 request.setReadTimeout(timeout); 373 } 374 375 @Override 376 protected String getTaskName() { 377 return tr("Contacting Server..."); 378 } 379 380 @Override 381 protected DataSet parseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException { 382 AbstractReader reader = null; 383 Matcher m = OUTPUT_FORMAT_STATEMENT.matcher(overpassQuery); 384 if (m.matches()) { 385 Class<? extends AbstractReader> readerClass = outputFormatReaders.get(OverpassOutputFormat.from(m.group(1))); 386 if (readerClass != null) { 387 try { 388 reader = readerClass.getDeclaredConstructor().newInstance(); 389 } catch (ReflectiveOperationException | IllegalArgumentException | SecurityException e) { 390 Logging.error(e); 391 } 392 } 393 } 394 if (reader == null) { 395 reader = new OverpassOsmReader(); 396 } 397 return reader.doParseDataSet(source, progressMonitor); 398 } 399 400 @Override 401 public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException { 402 403 DataSet ds = super.parseOsm(progressMonitor); 404 if (!considerAsFullDownload()) { 405 DataSet noBounds = new DataSet(); 406 DataSetMerger dsm = new DataSetMerger(noBounds, ds); 407 dsm.merge(null, false); 408 return dsm.getTargetDataSet(); 409 } else { 410 // add bounds if necessary (note that Overpass API does not return bounds in the response XML) 411 if (ds != null && ds.getDataSources().isEmpty() && overpassQuery.contains("{{bbox}}")) { 412 getBounds().forEach(bounds -> ds.addDataSource(new DataSource(bounds, getBaseUrl()))); 413 } 414 return ds; 415 } 416 } 417 418 /** 419 * Fixes Overpass API query to make sure it will be accepted by JOSM. 420 * @param query Overpass query to check 421 * @return fixed query 422 * @since 13335 423 */ 424 public static String fixQuery(String query) { 425 return query == null ? query : query 426 .replaceAll("out( body| skel| ids)?( id| qt)?;", "out meta$2;") 427 .replaceAll("(?s)\\[out:(csv)[^\\]]*\\]", "[out:xml]"); 428 } 429 430 @Override 431 public boolean considerAsFullDownload() { 432 return overpassQuery.equals(OverpassDownloadSource.FULL_DOWNLOAD_QUERY); 433 } 434 435 @Override 436 protected Collection<Bounds> getBounds() { 437 if (this.overpassQuery.contains("{{bbox}}")) { 438 if (crosses180th) { 439 return Set.of(new Bounds(lat1, lon1, lat2, 180.0), 440 new Bounds(lat1, -180.0, lat2, lon2)); 441 } else { 442 return Collections.singleton(new Bounds(lat1, lon1, lat2, lon2)); 443 } 444 } 445 return Collections.emptySet(); 446 } 447}