[8764] | 1 | // License: GPL. For details, see LICENSE file.
|
---|
[8744] | 2 | package org.openstreetmap.josm.io;
|
---|
| 3 |
|
---|
[8787] | 4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
| 5 |
|
---|
[11003] | 6 | import java.io.IOException;
|
---|
[8782] | 7 | import java.io.InputStream;
|
---|
[12596] | 8 | import java.nio.charset.StandardCharsets;
|
---|
[11003] | 9 | import java.util.EnumMap;
|
---|
[11916] | 10 | import java.util.Map;
|
---|
[11009] | 11 | import java.util.NoSuchElementException;
|
---|
[11916] | 12 | import java.util.Objects;
|
---|
| 13 | import java.util.concurrent.ConcurrentHashMap;
|
---|
[11288] | 14 | import java.util.concurrent.TimeUnit;
|
---|
[9308] | 15 | import java.util.regex.Matcher;
|
---|
| 16 | import java.util.regex.Pattern;
|
---|
[8782] | 17 |
|
---|
[8788] | 18 | import javax.xml.stream.XMLStreamConstants;
|
---|
| 19 | import javax.xml.stream.XMLStreamException;
|
---|
| 20 |
|
---|
[8744] | 21 | import org.openstreetmap.josm.data.Bounds;
|
---|
| 22 | import org.openstreetmap.josm.data.DataSource;
|
---|
| 23 | import org.openstreetmap.josm.data.osm.DataSet;
|
---|
[11003] | 24 | import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
|
---|
| 25 | import org.openstreetmap.josm.data.osm.PrimitiveId;
|
---|
[8744] | 26 | import org.openstreetmap.josm.gui.progress.ProgressMonitor;
|
---|
[9308] | 27 | import org.openstreetmap.josm.tools.HttpClient;
|
---|
[12620] | 28 | import org.openstreetmap.josm.tools.Logging;
|
---|
[11003] | 29 | import org.openstreetmap.josm.tools.UncheckedParseException;
|
---|
[8744] | 30 | import org.openstreetmap.josm.tools.Utils;
|
---|
| 31 |
|
---|
| 32 | /**
|
---|
| 33 | * Read content from an Overpass server.
|
---|
| 34 | *
|
---|
| 35 | * @since 8744
|
---|
| 36 | */
|
---|
| 37 | public class OverpassDownloadReader extends BoundingBoxDownloader {
|
---|
| 38 |
|
---|
[12596] | 39 | private static final String DATA_PREFIX = "?data=";
|
---|
| 40 |
|
---|
[11366] | 41 | static final class OverpassOsmReader extends OsmReader {
|
---|
| 42 | @Override
|
---|
| 43 | protected void parseUnknown(boolean printWarning) throws XMLStreamException {
|
---|
| 44 | if ("remark".equals(parser.getLocalName()) && parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
|
---|
| 45 | final String text = parser.getElementText();
|
---|
| 46 | if (text.contains("runtime error")) {
|
---|
| 47 | throw new XMLStreamException(text);
|
---|
| 48 | }
|
---|
| 49 | }
|
---|
| 50 | super.parseUnknown(printWarning);
|
---|
| 51 | }
|
---|
| 52 | }
|
---|
| 53 |
|
---|
[11916] | 54 | /**
|
---|
| 55 | * Possible Overpass API output format, with the {@code [out:<directive>]} statement.
|
---|
| 56 | * @since 11916
|
---|
| 57 | */
|
---|
[11918] | 58 | public enum OverpassOutpoutFormat {
|
---|
[11916] | 59 | /** Default output format: plain OSM XML */
|
---|
| 60 | OSM_XML("xml"),
|
---|
| 61 | /** OSM JSON format (not GeoJson) */
|
---|
| 62 | OSM_JSON("json"),
|
---|
| 63 | /** CSV, see https://wiki.openstreetmap.org/wiki/Overpass_API/Overpass_QL#Output_Format_.28out.29 */
|
---|
| 64 | CSV("csv"),
|
---|
| 65 | /** Custom, see https://overpass-api.de/output_formats.html#custom */
|
---|
| 66 | CUSTOM("custom"),
|
---|
| 67 | /** Popup, see https://overpass-api.de/output_formats.html#popup */
|
---|
| 68 | POPUP("popup"),
|
---|
| 69 | /** PBF, see https://josm.openstreetmap.de/ticket/14653 */
|
---|
| 70 | PBF("pbf");
|
---|
| 71 |
|
---|
| 72 | private final String directive;
|
---|
| 73 |
|
---|
| 74 | OverpassOutpoutFormat(String directive) {
|
---|
| 75 | this.directive = directive;
|
---|
| 76 | }
|
---|
| 77 |
|
---|
| 78 | /**
|
---|
| 79 | * Returns the directive used in {@code [out:<directive>]} statement.
|
---|
| 80 | * @return the directive used in {@code [out:<directive>]} statement
|
---|
| 81 | */
|
---|
| 82 | public String getDirective() {
|
---|
| 83 | return directive;
|
---|
| 84 | }
|
---|
| 85 |
|
---|
| 86 | /**
|
---|
| 87 | * Returns the {@code OverpassOutpoutFormat} matching the given directive.
|
---|
| 88 | * @param directive directive used in {@code [out:<directive>]} statement
|
---|
| 89 | * @return {@code OverpassOutpoutFormat} matching the given directive
|
---|
| 90 | * @throws IllegalArgumentException in case of invalid directive
|
---|
| 91 | */
|
---|
| 92 | static OverpassOutpoutFormat from(String directive) {
|
---|
| 93 | for (OverpassOutpoutFormat oof : values()) {
|
---|
| 94 | if (oof.directive.equals(directive)) {
|
---|
| 95 | return oof;
|
---|
| 96 | }
|
---|
| 97 | }
|
---|
| 98 | throw new IllegalArgumentException(directive);
|
---|
| 99 | }
|
---|
| 100 | }
|
---|
| 101 |
|
---|
| 102 | static final Pattern OUTPUT_FORMAT_STATEMENT = Pattern.compile(".*\\[out:([a-z]{3,})\\].*", Pattern.DOTALL);
|
---|
| 103 |
|
---|
[12542] | 104 | static final Map<OverpassOutpoutFormat, Class<? extends AbstractReader>> outputFormatReaders = new ConcurrentHashMap<>();
|
---|
[11916] | 105 |
|
---|
[8744] | 106 | final String overpassServer;
|
---|
| 107 | final String overpassQuery;
|
---|
| 108 |
|
---|
| 109 | /**
|
---|
| 110 | * Constructs a new {@code OverpassDownloadReader}.
|
---|
| 111 | *
|
---|
| 112 | * @param downloadArea The area to download
|
---|
| 113 | * @param overpassServer The Overpass server to use
|
---|
| 114 | * @param overpassQuery The Overpass query
|
---|
| 115 | */
|
---|
| 116 | public OverpassDownloadReader(Bounds downloadArea, String overpassServer, String overpassQuery) {
|
---|
| 117 | super(downloadArea);
|
---|
[12598] | 118 | setDoAuthenticate(false);
|
---|
[8744] | 119 | this.overpassServer = overpassServer;
|
---|
| 120 | this.overpassQuery = overpassQuery.trim();
|
---|
| 121 | }
|
---|
| 122 |
|
---|
[11916] | 123 | /**
|
---|
| 124 | * Registers an OSM reader for the given Overpass output format.
|
---|
| 125 | * @param format Overpass output format
|
---|
| 126 | * @param readerClass OSM reader class
|
---|
| 127 | * @return the previous value associated with {@code format}, or {@code null} if there was no mapping
|
---|
| 128 | */
|
---|
[11919] | 129 | public static final Class<? extends AbstractReader> registerOverpassOutpoutFormatReader(
|
---|
| 130 | OverpassOutpoutFormat format, Class<? extends AbstractReader> readerClass) {
|
---|
[12542] | 131 | return outputFormatReaders.put(Objects.requireNonNull(format), Objects.requireNonNull(readerClass));
|
---|
[11916] | 132 | }
|
---|
| 133 |
|
---|
| 134 | static {
|
---|
| 135 | registerOverpassOutpoutFormatReader(OverpassOutpoutFormat.OSM_XML, OverpassOsmReader.class);
|
---|
| 136 | }
|
---|
| 137 |
|
---|
[8744] | 138 | @Override
|
---|
| 139 | protected String getBaseUrl() {
|
---|
| 140 | return overpassServer;
|
---|
| 141 | }
|
---|
| 142 |
|
---|
| 143 | @Override
|
---|
| 144 | protected String getRequestForBbox(double lon1, double lat1, double lon2, double lat2) {
|
---|
| 145 | if (overpassQuery.isEmpty())
|
---|
| 146 | return super.getRequestForBbox(lon1, lat1, lon2, lat2);
|
---|
| 147 | else {
|
---|
[11009] | 148 | final String query = this.overpassQuery.replace("{{bbox}}", lat1 + "," + lon1 + "," + lat2 + "," + lon2);
|
---|
| 149 | final String expandedOverpassQuery = expandExtendedQueries(query);
|
---|
[12596] | 150 | return "interpreter" + DATA_PREFIX + Utils.encodeUrl(expandedOverpassQuery);
|
---|
[8744] | 151 | }
|
---|
| 152 | }
|
---|
| 153 |
|
---|
[11003] | 154 | /**
|
---|
| 155 | * Evaluates some features of overpass turbo extended query syntax.
|
---|
| 156 | * See https://wiki.openstreetmap.org/wiki/Overpass_turbo/Extended_Overpass_Turbo_Queries
|
---|
[11009] | 157 | * @param query unexpanded query
|
---|
| 158 | * @return expanded query
|
---|
[11003] | 159 | */
|
---|
| 160 | static String expandExtendedQueries(String query) {
|
---|
| 161 | final StringBuffer sb = new StringBuffer();
|
---|
| 162 | final Matcher matcher = Pattern.compile("\\{\\{(geocodeArea):([^}]+)\\}\\}").matcher(query);
|
---|
| 163 | while (matcher.find()) {
|
---|
| 164 | try {
|
---|
| 165 | switch (matcher.group(1)) {
|
---|
| 166 | case "geocodeArea":
|
---|
| 167 | matcher.appendReplacement(sb, geocodeArea(matcher.group(2)));
|
---|
[11048] | 168 | break;
|
---|
| 169 | default:
|
---|
[12620] | 170 | Logging.warn("Unsupported syntax: " + matcher.group(1));
|
---|
[11003] | 171 | }
|
---|
[11009] | 172 | } catch (UncheckedParseException ex) {
|
---|
[11003] | 173 | final String msg = tr("Failed to evaluate {0}", matcher.group());
|
---|
[12620] | 174 | Logging.log(Logging.LEVEL_WARN, msg, ex);
|
---|
[11003] | 175 | matcher.appendReplacement(sb, "// " + msg + "\n");
|
---|
[8744] | 176 | }
|
---|
| 177 | }
|
---|
[11003] | 178 | matcher.appendTail(sb);
|
---|
| 179 | return sb.toString();
|
---|
| 180 | }
|
---|
[8744] | 181 |
|
---|
[11003] | 182 | private static String geocodeArea(String area) {
|
---|
| 183 | // Offsets defined in https://wiki.openstreetmap.org/wiki/Overpass_API/Overpass_QL#By_element_id
|
---|
| 184 | final EnumMap<OsmPrimitiveType, Long> idOffset = new EnumMap<>(OsmPrimitiveType.class);
|
---|
| 185 | idOffset.put(OsmPrimitiveType.NODE, 0L);
|
---|
[11009] | 186 | idOffset.put(OsmPrimitiveType.WAY, 2_400_000_000L);
|
---|
| 187 | idOffset.put(OsmPrimitiveType.RELATION, 3_600_000_000L);
|
---|
[11003] | 188 | try {
|
---|
[11560] | 189 | final PrimitiveId osmId = NameFinder.queryNominatim(area).stream().filter(
|
---|
| 190 | x -> !OsmPrimitiveType.NODE.equals(x.getOsmId().getType())).iterator().next().getOsmId();
|
---|
[11003] | 191 | return String.format("area(%d)", osmId.getUniqueId() + idOffset.get(osmId.getType()));
|
---|
[11533] | 192 | } catch (IOException | NoSuchElementException | IndexOutOfBoundsException ex) {
|
---|
[11003] | 193 | throw new UncheckedParseException(ex);
|
---|
[8744] | 194 | }
|
---|
| 195 | }
|
---|
| 196 |
|
---|
| 197 | @Override
|
---|
[8782] | 198 | protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason,
|
---|
| 199 | boolean uncompressAccordingToContentDisposition) throws OsmTransferException {
|
---|
| 200 | try {
|
---|
[12596] | 201 | int index = urlStr.indexOf(DATA_PREFIX);
|
---|
| 202 | // Make an HTTP POST request instead of a simple GET, allows more complex queries
|
---|
| 203 | return super.getInputStreamRaw(urlStr.substring(0, index),
|
---|
| 204 | progressMonitor, reason, uncompressAccordingToContentDisposition,
|
---|
| 205 | "POST", Utils.decodeUrl(urlStr.substring(index + DATA_PREFIX.length())).getBytes(StandardCharsets.UTF_8));
|
---|
[8782] | 206 | } catch (OsmApiException ex) {
|
---|
| 207 | final String errorIndicator = "Error</strong>: ";
|
---|
| 208 | if (ex.getMessage() != null && ex.getMessage().contains(errorIndicator)) {
|
---|
| 209 | final String errorPlusRest = ex.getMessage().split(errorIndicator)[1];
|
---|
| 210 | if (errorPlusRest != null) {
|
---|
[11987] | 211 | ex.setErrorHeader(errorPlusRest.split("</")[0].replaceAll(".*::request_read_and_idx::", ""));
|
---|
[8782] | 212 | }
|
---|
| 213 | }
|
---|
| 214 | throw ex;
|
---|
| 215 | }
|
---|
| 216 | }
|
---|
| 217 |
|
---|
| 218 | @Override
|
---|
[9308] | 219 | protected void adaptRequest(HttpClient request) {
|
---|
| 220 | // see https://wiki.openstreetmap.org/wiki/Overpass_API/Overpass_QL#timeout
|
---|
| 221 | final Matcher timeoutMatcher = Pattern.compile("\\[timeout:(\\d+)\\]").matcher(overpassQuery);
|
---|
[9318] | 222 | final int timeout;
|
---|
[9308] | 223 | if (timeoutMatcher.find()) {
|
---|
[11288] | 224 | timeout = (int) TimeUnit.SECONDS.toMillis(Integer.parseInt(timeoutMatcher.group(1)));
|
---|
[9318] | 225 | } else {
|
---|
[11288] | 226 | timeout = (int) TimeUnit.MINUTES.toMillis(3);
|
---|
[9308] | 227 | }
|
---|
[9318] | 228 | request.setConnectTimeout(timeout);
|
---|
| 229 | request.setReadTimeout(timeout);
|
---|
[9308] | 230 | }
|
---|
| 231 |
|
---|
| 232 | @Override
|
---|
[8787] | 233 | protected String getTaskName() {
|
---|
| 234 | return tr("Contacting Server...");
|
---|
| 235 | }
|
---|
| 236 |
|
---|
| 237 | @Override
|
---|
[8788] | 238 | protected DataSet parseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
|
---|
[11919] | 239 | AbstractReader reader = null;
|
---|
[11916] | 240 | Matcher m = OUTPUT_FORMAT_STATEMENT.matcher(overpassQuery);
|
---|
| 241 | if (m.matches()) {
|
---|
[12542] | 242 | Class<? extends AbstractReader> readerClass = outputFormatReaders.get(OverpassOutpoutFormat.from(m.group(1)));
|
---|
[11916] | 243 | if (readerClass != null) {
|
---|
| 244 | try {
|
---|
[11924] | 245 | reader = readerClass.getDeclaredConstructor().newInstance();
|
---|
[11916] | 246 | } catch (ReflectiveOperationException | IllegalArgumentException | SecurityException e) {
|
---|
[12620] | 247 | Logging.error(e);
|
---|
[11916] | 248 | }
|
---|
| 249 | }
|
---|
| 250 | }
|
---|
| 251 | if (reader == null) {
|
---|
| 252 | reader = new OverpassOsmReader();
|
---|
| 253 | }
|
---|
| 254 | return reader.doParseDataSet(source, progressMonitor);
|
---|
[8788] | 255 | }
|
---|
| 256 |
|
---|
| 257 | @Override
|
---|
[8744] | 258 | public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
|
---|
| 259 |
|
---|
| 260 | DataSet ds = super.parseOsm(progressMonitor);
|
---|
| 261 |
|
---|
| 262 | // add bounds if necessary (note that Overpass API does not return bounds in the response XML)
|
---|
[11627] | 263 | if (ds != null && ds.getDataSources().isEmpty() && overpassQuery.contains("{{bbox}}")) {
|
---|
[8744] | 264 | if (crosses180th) {
|
---|
| 265 | Bounds bounds = new Bounds(lat1, lon1, lat2, 180.0);
|
---|
| 266 | DataSource src = new DataSource(bounds, getBaseUrl());
|
---|
[11627] | 267 | ds.addDataSource(src);
|
---|
[8744] | 268 |
|
---|
| 269 | bounds = new Bounds(lat1, -180.0, lat2, lon2);
|
---|
| 270 | src = new DataSource(bounds, getBaseUrl());
|
---|
[11627] | 271 | ds.addDataSource(src);
|
---|
[8744] | 272 | } else {
|
---|
| 273 | Bounds bounds = new Bounds(lat1, lon1, lat2, lon2);
|
---|
| 274 | DataSource src = new DataSource(bounds, getBaseUrl());
|
---|
[11627] | 275 | ds.addDataSource(src);
|
---|
[8744] | 276 | }
|
---|
| 277 | }
|
---|
| 278 |
|
---|
| 279 | return ds;
|
---|
| 280 | }
|
---|
| 281 | }
|
---|