source: josm/trunk/src/org/openstreetmap/josm/io/OverpassDownloadReader.java@ 12598

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

fix #15147 - do not include OAuth Authorization header towards Overpass API

  • Property svn:eol-style set to native
File size: 11.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.IOException;
7import java.io.InputStream;
8import java.nio.charset.StandardCharsets;
9import java.util.EnumMap;
10import java.util.Map;
11import java.util.NoSuchElementException;
12import java.util.Objects;
13import java.util.concurrent.ConcurrentHashMap;
14import java.util.concurrent.TimeUnit;
15import java.util.regex.Matcher;
16import java.util.regex.Pattern;
17
18import javax.xml.stream.XMLStreamConstants;
19import javax.xml.stream.XMLStreamException;
20
21import org.openstreetmap.josm.Main;
22import org.openstreetmap.josm.data.Bounds;
23import org.openstreetmap.josm.data.DataSource;
24import org.openstreetmap.josm.data.osm.DataSet;
25import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
26import org.openstreetmap.josm.data.osm.PrimitiveId;
27import org.openstreetmap.josm.gui.progress.ProgressMonitor;
28import org.openstreetmap.josm.tools.HttpClient;
29import org.openstreetmap.josm.tools.UncheckedParseException;
30import org.openstreetmap.josm.tools.Utils;
31
32/**
33 * Read content from an Overpass server.
34 *
35 * @since 8744
36 */
37public class OverpassDownloadReader extends BoundingBoxDownloader {
38
39 private static final String DATA_PREFIX = "?data=";
40
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
54 /**
55 * Possible Overpass API output format, with the {@code [out:<directive>]} statement.
56 * @since 11916
57 */
58 public enum OverpassOutpoutFormat {
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
104 static final Map<OverpassOutpoutFormat, Class<? extends AbstractReader>> outputFormatReaders = new ConcurrentHashMap<>();
105
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);
118 setDoAuthenticate(false);
119 this.overpassServer = overpassServer;
120 this.overpassQuery = overpassQuery.trim();
121 }
122
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 */
129 public static final Class<? extends AbstractReader> registerOverpassOutpoutFormatReader(
130 OverpassOutpoutFormat format, Class<? extends AbstractReader> readerClass) {
131 return outputFormatReaders.put(Objects.requireNonNull(format), Objects.requireNonNull(readerClass));
132 }
133
134 static {
135 registerOverpassOutpoutFormatReader(OverpassOutpoutFormat.OSM_XML, OverpassOsmReader.class);
136 }
137
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 {
148 final String query = this.overpassQuery.replace("{{bbox}}", lat1 + "," + lon1 + "," + lat2 + "," + lon2);
149 final String expandedOverpassQuery = expandExtendedQueries(query);
150 return "interpreter" + DATA_PREFIX + Utils.encodeUrl(expandedOverpassQuery);
151 }
152 }
153
154 /**
155 * Evaluates some features of overpass turbo extended query syntax.
156 * See https://wiki.openstreetmap.org/wiki/Overpass_turbo/Extended_Overpass_Turbo_Queries
157 * @param query unexpanded query
158 * @return expanded query
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)));
168 break;
169 default:
170 Main.warn("Unsupported syntax: " + matcher.group(1));
171 }
172 } catch (UncheckedParseException ex) {
173 final String msg = tr("Failed to evaluate {0}", matcher.group());
174 Main.warn(ex, msg);
175 matcher.appendReplacement(sb, "// " + msg + "\n");
176 }
177 }
178 matcher.appendTail(sb);
179 return sb.toString();
180 }
181
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);
186 idOffset.put(OsmPrimitiveType.WAY, 2_400_000_000L);
187 idOffset.put(OsmPrimitiveType.RELATION, 3_600_000_000L);
188 try {
189 final PrimitiveId osmId = NameFinder.queryNominatim(area).stream().filter(
190 x -> !OsmPrimitiveType.NODE.equals(x.getOsmId().getType())).iterator().next().getOsmId();
191 return String.format("area(%d)", osmId.getUniqueId() + idOffset.get(osmId.getType()));
192 } catch (IOException | NoSuchElementException | IndexOutOfBoundsException ex) {
193 throw new UncheckedParseException(ex);
194 }
195 }
196
197 @Override
198 protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason,
199 boolean uncompressAccordingToContentDisposition) throws OsmTransferException {
200 try {
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));
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) {
211 ex.setErrorHeader(errorPlusRest.split("</")[0].replaceAll(".*::request_read_and_idx::", ""));
212 }
213 }
214 throw ex;
215 }
216 }
217
218 @Override
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);
222 final int timeout;
223 if (timeoutMatcher.find()) {
224 timeout = (int) TimeUnit.SECONDS.toMillis(Integer.parseInt(timeoutMatcher.group(1)));
225 } else {
226 timeout = (int) TimeUnit.MINUTES.toMillis(3);
227 }
228 request.setConnectTimeout(timeout);
229 request.setReadTimeout(timeout);
230 }
231
232 @Override
233 protected String getTaskName() {
234 return tr("Contacting Server...");
235 }
236
237 @Override
238 protected DataSet parseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
239 AbstractReader reader = null;
240 Matcher m = OUTPUT_FORMAT_STATEMENT.matcher(overpassQuery);
241 if (m.matches()) {
242 Class<? extends AbstractReader> readerClass = outputFormatReaders.get(OverpassOutpoutFormat.from(m.group(1)));
243 if (readerClass != null) {
244 try {
245 reader = readerClass.getDeclaredConstructor().newInstance();
246 } catch (ReflectiveOperationException | IllegalArgumentException | SecurityException e) {
247 Main.error(e);
248 }
249 }
250 }
251 if (reader == null) {
252 reader = new OverpassOsmReader();
253 }
254 return reader.doParseDataSet(source, progressMonitor);
255 }
256
257 @Override
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)
263 if (ds != null && ds.getDataSources().isEmpty() && overpassQuery.contains("{{bbox}}")) {
264 if (crosses180th) {
265 Bounds bounds = new Bounds(lat1, lon1, lat2, 180.0);
266 DataSource src = new DataSource(bounds, getBaseUrl());
267 ds.addDataSource(src);
268
269 bounds = new Bounds(lat1, -180.0, lat2, lon2);
270 src = new DataSource(bounds, getBaseUrl());
271 ds.addDataSource(src);
272 } else {
273 Bounds bounds = new Bounds(lat1, lon1, lat2, lon2);
274 DataSource src = new DataSource(bounds, getBaseUrl());
275 ds.addDataSource(src);
276 }
277 }
278
279 return ds;
280 }
281}
Note: See TracBrowser for help on using the repository browser.