source: josm/trunk/src/org/openstreetmap/josm/io/OsmApi.java@ 9352

Last change on this file since 9352 was 9352, checked in by simon04, 9 years ago

fix #7612 - Prefer OAuth, provide authorization at upload

  • Property svn:eol-style set to native
File size: 35.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.io.IOException;
8import java.io.PrintWriter;
9import java.io.StringReader;
10import java.io.StringWriter;
11import java.net.ConnectException;
12import java.net.HttpURLConnection;
13import java.net.MalformedURLException;
14import java.net.SocketTimeoutException;
15import java.net.URL;
16import java.nio.charset.StandardCharsets;
17import java.util.Collection;
18import java.util.Collections;
19import java.util.HashMap;
20import java.util.List;
21import java.util.Map;
22
23import javax.xml.parsers.ParserConfigurationException;
24
25import org.openstreetmap.josm.Main;
26import org.openstreetmap.josm.data.coor.LatLon;
27import org.openstreetmap.josm.data.notes.Note;
28import org.openstreetmap.josm.data.osm.Changeset;
29import org.openstreetmap.josm.data.osm.IPrimitive;
30import org.openstreetmap.josm.data.osm.OsmPrimitive;
31import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
32import org.openstreetmap.josm.gui.layer.ImageryLayer;
33import org.openstreetmap.josm.gui.layer.Layer;
34import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
35import org.openstreetmap.josm.gui.progress.ProgressMonitor;
36import org.openstreetmap.josm.io.Capabilities.CapabilitiesParser;
37import org.openstreetmap.josm.tools.CheckParameterUtil;
38import org.openstreetmap.josm.tools.HttpClient;
39import org.openstreetmap.josm.tools.Utils;
40import org.openstreetmap.josm.tools.XmlParsingException;
41import org.xml.sax.InputSource;
42import org.xml.sax.SAXException;
43import org.xml.sax.SAXParseException;
44
45/**
46 * Class that encapsulates the communications with the <a href="http://wiki.openstreetmap.org/wiki/API_v0.6">OSM API</a>.<br><br>
47 *
48 * All interaction with the server-side OSM API should go through this class.<br><br>
49 *
50 * It is conceivable to extract this into an interface later and create various
51 * classes implementing the interface, to be able to talk to various kinds of servers.
52 *
53 */
54public class OsmApi extends OsmConnection {
55
56 /**
57 * Maximum number of retries to send a request in case of HTTP 500 errors or timeouts
58 */
59 public static final int DEFAULT_MAX_NUM_RETRIES = 5;
60
61 /**
62 * Maximum number of concurrent download threads, imposed by
63 * <a href="http://wiki.openstreetmap.org/wiki/API_usage_policy#Technical_Usage_Requirements">
64 * OSM API usage policy.</a>
65 * @since 5386
66 */
67 public static final int MAX_DOWNLOAD_THREADS = 2;
68
69 /**
70 * Default URL of the standard OSM API.
71 * @since 5422
72 */
73 public static final String DEFAULT_API_URL = "https://api.openstreetmap.org/api";
74
75 // The collection of instantiated OSM APIs
76 private static Map<String, OsmApi> instances = new HashMap<>();
77
78 private URL url;
79
80 /**
81 * Replies the {@link OsmApi} for a given server URL
82 *
83 * @param serverUrl the server URL
84 * @return the OsmApi
85 * @throws IllegalArgumentException if serverUrl is null
86 *
87 */
88 public static OsmApi getOsmApi(String serverUrl) {
89 OsmApi api = instances.get(serverUrl);
90 if (api == null) {
91 api = new OsmApi(serverUrl);
92 instances.put(serverUrl, api);
93 }
94 return api;
95 }
96
97 private static String getServerUrlFromPref() {
98 return Main.pref.get("osm-server.url", DEFAULT_API_URL);
99 }
100
101 /**
102 * Replies the {@link OsmApi} for the URL given by the preference <code>osm-server.url</code>
103 *
104 * @return the OsmApi
105 */
106 public static OsmApi getOsmApi() {
107 return getOsmApi(getServerUrlFromPref());
108 }
109
110 /** Server URL */
111 private final String serverUrl;
112
113 /** Object describing current changeset */
114 private Changeset changeset;
115
116 /** API version used for server communications */
117 private String version;
118
119 /** API capabilities */
120 private Capabilities capabilities;
121
122 /** true if successfully initialized */
123 private boolean initialized;
124
125 /**
126 * Constructs a new {@code OsmApi} for a specific server URL.
127 *
128 * @param serverUrl the server URL. Must not be null
129 * @throws IllegalArgumentException if serverUrl is null
130 */
131 protected OsmApi(String serverUrl) {
132 CheckParameterUtil.ensureParameterNotNull(serverUrl, "serverUrl");
133 this.serverUrl = serverUrl;
134 }
135
136 /**
137 * Replies the OSM protocol version we use to talk to the server.
138 * @return protocol version, or null if not yet negotiated.
139 */
140 public String getVersion() {
141 return version;
142 }
143
144 /**
145 * Replies the host name of the server URL.
146 * @return the host name of the server URL, or null if the server URL is malformed.
147 */
148 public String getHost() {
149 String host = null;
150 try {
151 host = (new URL(serverUrl)).getHost();
152 } catch (MalformedURLException e) {
153 Main.warn(e);
154 }
155 return host;
156 }
157
158 private class CapabilitiesCache extends CacheCustomContent<OsmTransferException> {
159
160 private static final String CAPABILITIES = "capabilities";
161
162 private final ProgressMonitor monitor;
163 private final boolean fastFail;
164
165 CapabilitiesCache(ProgressMonitor monitor, boolean fastFail) {
166 super(CAPABILITIES + getBaseUrl().hashCode(), CacheCustomContent.INTERVAL_WEEKLY);
167 this.monitor = monitor;
168 this.fastFail = fastFail;
169 }
170
171 @Override
172 protected void checkOfflineAccess() {
173 OnlineResource.OSM_API.checkOfflineAccess(getBaseUrl(getServerUrlFromPref(), "0.6")+CAPABILITIES, getServerUrlFromPref());
174 }
175
176 @Override
177 protected byte[] updateData() throws OsmTransferException {
178 return sendRequest("GET", CAPABILITIES, null, monitor, false, fastFail).getBytes(StandardCharsets.UTF_8);
179 }
180 }
181
182 /**
183 * Initializes this component by negotiating a protocol version with the server.
184 *
185 * @param monitor the progress monitor
186 * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
187 * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
188 */
189 public void initialize(ProgressMonitor monitor) throws OsmTransferCanceledException, OsmApiInitializationException {
190 initialize(monitor, false);
191 }
192
193 /**
194 * Initializes this component by negotiating a protocol version with the server, with the ability to control the timeout.
195 *
196 * @param monitor the progress monitor
197 * @param fastFail true to request quick initialisation with a small timeout (more likely to throw exception)
198 * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
199 * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
200 */
201 public void initialize(ProgressMonitor monitor, boolean fastFail) throws OsmTransferCanceledException, OsmApiInitializationException {
202 if (initialized)
203 return;
204 cancel = false;
205 try {
206 CapabilitiesCache cache = new CapabilitiesCache(monitor, fastFail);
207 try {
208 initializeCapabilities(cache.updateIfRequiredString());
209 } catch (SAXParseException parseException) {
210 // XML parsing may fail if JOSM previously stored a corrupted capabilities document (see #8278)
211 // In that case, force update and try again
212 initializeCapabilities(cache.updateForceString());
213 }
214 if (capabilities == null) {
215 if (Main.isOffline(OnlineResource.OSM_API)) {
216 Main.warn(tr("{0} not available (offline mode)", tr("OSM API")));
217 } else {
218 Main.error(tr("Unable to initialize OSM API."));
219 }
220 return;
221 } else if (!capabilities.supportsVersion("0.6")) {
222 Main.error(tr("This version of JOSM is incompatible with the configured server."));
223 Main.error(tr("It supports protocol version 0.6, while the server says it supports {0} to {1}.",
224 capabilities.get("version", "minimum"), capabilities.get("version", "maximum")));
225 return;
226 } else {
227 version = "0.6";
228 initialized = true;
229 }
230
231 /* This is an interim solution for openstreetmap.org not currently
232 * transmitting their imagery blacklist in the capabilities call.
233 * remove this as soon as openstreetmap.org adds blacklists.
234 * If you want to update this list, please ask for update of
235 * http://trac.openstreetmap.org/ticket/5024
236 * This list should not be maintained by each OSM editor (see #9210) */
237 if (this.serverUrl.matches(".*openstreetmap.org/api.*") && capabilities.getImageryBlacklist().isEmpty()) {
238 capabilities.put("blacklist", "regex", ".*\\.google\\.com/.*");
239 capabilities.put("blacklist", "regex", ".*209\\.85\\.2\\d\\d.*");
240 capabilities.put("blacklist", "regex", ".*209\\.85\\.1[3-9]\\d.*");
241 capabilities.put("blacklist", "regex", ".*209\\.85\\.12[89].*");
242 }
243
244 /* This checks if there are any layers currently displayed that
245 * are now on the blacklist, and removes them. This is a rare
246 * situation - probably only occurs if the user changes the API URL
247 * in the preferences menu. Otherwise they would not have been able
248 * to load the layers in the first place because they would have
249 * been disabled! */
250 if (Main.isDisplayingMapView()) {
251 for (Layer l : Main.map.mapView.getLayersOfType(ImageryLayer.class)) {
252 if (((ImageryLayer) l).getInfo().isBlacklisted()) {
253 Main.info(tr("Removed layer {0} because it is not allowed by the configured API.", l.getName()));
254 Main.main.removeLayer(l);
255 }
256 }
257 }
258
259 } catch (OsmTransferCanceledException e) {
260 throw e;
261 } catch (OsmTransferException e) {
262 initialized = false;
263 Main.addNetworkError(url, Utils.getRootCause(e));
264 throw new OsmApiInitializationException(e);
265 } catch (Exception e) {
266 initialized = false;
267 throw new OsmApiInitializationException(e);
268 }
269 }
270
271 private synchronized void initializeCapabilities(String xml) throws SAXException, IOException, ParserConfigurationException {
272 if (xml != null) {
273 capabilities = CapabilitiesParser.parse(new InputSource(new StringReader(xml)));
274 }
275 }
276
277 /**
278 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
279 * @param o the OSM primitive
280 * @param addBody true to generate the full XML, false to only generate the encapsulating tag
281 * @return XML string
282 */
283 private String toXml(IPrimitive o, boolean addBody) {
284 StringWriter swriter = new StringWriter();
285 try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
286 swriter.getBuffer().setLength(0);
287 osmWriter.setWithBody(addBody);
288 osmWriter.setChangeset(changeset);
289 osmWriter.header();
290 o.accept(osmWriter);
291 osmWriter.footer();
292 osmWriter.flush();
293 } catch (IOException e) {
294 Main.warn(e);
295 }
296 return swriter.toString();
297 }
298
299 /**
300 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
301 * @param s the changeset
302 * @return XML string
303 */
304 private String toXml(Changeset s) {
305 StringWriter swriter = new StringWriter();
306 try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
307 swriter.getBuffer().setLength(0);
308 osmWriter.header();
309 osmWriter.visit(s);
310 osmWriter.footer();
311 osmWriter.flush();
312 } catch (IOException e) {
313 Main.warn(e);
314 }
315 return swriter.toString();
316 }
317
318 private static String getBaseUrl(String serverUrl, String version) {
319 StringBuilder rv = new StringBuilder(serverUrl);
320 if (version != null) {
321 rv.append('/').append(version);
322 }
323 rv.append('/');
324 // this works around a ruby (or lighttpd) bug where two consecutive slashes in
325 // an URL will cause a "404 not found" response.
326 int p;
327 while ((p = rv.indexOf("//", rv.indexOf("://")+2)) > -1) {
328 rv.delete(p, p + 1);
329 }
330 return rv.toString();
331 }
332
333 /**
334 * Returns the base URL for API requests, including the negotiated version number.
335 * @return base URL string
336 */
337 public String getBaseUrl() {
338 return getBaseUrl(serverUrl, version);
339 }
340
341 /**
342 * Creates an OSM primitive on the server. The OsmPrimitive object passed in
343 * is modified by giving it the server-assigned id.
344 *
345 * @param osm the primitive
346 * @param monitor the progress monitor
347 * @throws OsmTransferException if something goes wrong
348 */
349 public void createPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
350 String ret = "";
351 try {
352 ensureValidChangeset();
353 initialize(monitor);
354 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/create", toXml(osm, true), monitor);
355 osm.setOsmId(Long.parseLong(ret.trim()), 1);
356 osm.setChangesetId(getChangeset().getId());
357 } catch (NumberFormatException e) {
358 throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret), e);
359 }
360 }
361
362 /**
363 * Modifies an OSM primitive on the server.
364 *
365 * @param osm the primitive. Must not be null.
366 * @param monitor the progress monitor
367 * @throws OsmTransferException if something goes wrong
368 */
369 public void modifyPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
370 String ret = null;
371 try {
372 ensureValidChangeset();
373 initialize(monitor);
374 // normal mode (0.6 and up) returns new object version.
375 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+'/' + osm.getId(), toXml(osm, true), monitor);
376 osm.setOsmId(osm.getId(), Integer.parseInt(ret.trim()));
377 osm.setChangesetId(getChangeset().getId());
378 osm.setVisible(true);
379 } catch (NumberFormatException e) {
380 throw new OsmTransferException(tr("Unexpected format of new version of modified primitive ''{0}''. Got ''{1}''.",
381 osm.getId(), ret), e);
382 }
383 }
384
385 /**
386 * Deletes an OSM primitive on the server.
387 * @param osm the primitive
388 * @param monitor the progress monitor
389 * @throws OsmTransferException if something goes wrong
390 */
391 public void deletePrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
392 ensureValidChangeset();
393 initialize(monitor);
394 // can't use a the individual DELETE method in the 0.6 API. Java doesn't allow
395 // submitting a DELETE request with content, the 0.6 API requires it, however. Falling back
396 // to diff upload.
397 //
398 uploadDiff(Collections.singleton(osm), monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
399 }
400
401 /**
402 * Creates a new changeset based on the keys in <code>changeset</code>. If this
403 * method succeeds, changeset.getId() replies the id the server assigned to the new
404 * changeset
405 *
406 * The changeset must not be null, but its key/value-pairs may be empty.
407 *
408 * @param changeset the changeset toe be created. Must not be null.
409 * @param progressMonitor the progress monitor
410 * @throws OsmTransferException signifying a non-200 return code, or connection errors
411 * @throws IllegalArgumentException if changeset is null
412 */
413 public void openChangeset(Changeset changeset, ProgressMonitor progressMonitor) throws OsmTransferException {
414 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
415 try {
416 progressMonitor.beginTask(tr("Creating changeset..."));
417 initialize(progressMonitor);
418 String ret = "";
419 try {
420 ret = sendRequest("PUT", "changeset/create", toXml(changeset), progressMonitor);
421 changeset.setId(Integer.parseInt(ret.trim()));
422 changeset.setOpen(true);
423 } catch (NumberFormatException e) {
424 throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret), e);
425 }
426 progressMonitor.setCustomText(tr("Successfully opened changeset {0}", changeset.getId()));
427 } finally {
428 progressMonitor.finishTask();
429 }
430 }
431
432 /**
433 * Updates a changeset with the keys in <code>changesetUpdate</code>. The changeset must not
434 * be null and id &gt; 0 must be true.
435 *
436 * @param changeset the changeset to update. Must not be null.
437 * @param monitor the progress monitor. If null, uses the {@link NullProgressMonitor#INSTANCE}.
438 *
439 * @throws OsmTransferException if something goes wrong.
440 * @throws IllegalArgumentException if changeset is null
441 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
442 *
443 */
444 public void updateChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
445 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
446 if (monitor == null) {
447 monitor = NullProgressMonitor.INSTANCE;
448 }
449 if (changeset.getId() <= 0)
450 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
451 try {
452 monitor.beginTask(tr("Updating changeset..."));
453 initialize(monitor);
454 monitor.setCustomText(tr("Updating changeset {0}...", changeset.getId()));
455 sendRequest(
456 "PUT",
457 "changeset/" + changeset.getId(),
458 toXml(changeset),
459 monitor
460 );
461 } catch (ChangesetClosedException e) {
462 e.setSource(ChangesetClosedException.Source.UPDATE_CHANGESET);
463 throw e;
464 } catch (OsmApiException e) {
465 String errorHeader = e.getErrorHeader();
466 if (e.getResponseCode() == HttpURLConnection.HTTP_CONFLICT && ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
467 throw new ChangesetClosedException(errorHeader, ChangesetClosedException.Source.UPDATE_CHANGESET);
468 throw e;
469 } finally {
470 monitor.finishTask();
471 }
472 }
473
474 /**
475 * Closes a changeset on the server. Sets changeset.setOpen(false) if this operation succeeds.
476 *
477 * @param changeset the changeset to be closed. Must not be null. changeset.getId() &gt; 0 required.
478 * @param monitor the progress monitor. If null, uses {@link NullProgressMonitor#INSTANCE}
479 *
480 * @throws OsmTransferException if something goes wrong.
481 * @throws IllegalArgumentException if changeset is null
482 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
483 */
484 public void closeChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
485 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
486 if (monitor == null) {
487 monitor = NullProgressMonitor.INSTANCE;
488 }
489 if (changeset.getId() <= 0)
490 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
491 try {
492 monitor.beginTask(tr("Closing changeset..."));
493 initialize(monitor);
494 /* send "\r\n" instead of empty string, so we don't send zero payload - works around bugs
495 in proxy software */
496 sendRequest("PUT", "changeset" + "/" + changeset.getId() + "/close", "\r\n", monitor);
497 changeset.setOpen(false);
498 } finally {
499 monitor.finishTask();
500 }
501 }
502
503 /**
504 * Uploads a list of changes in "diff" form to the server.
505 *
506 * @param list the list of changed OSM Primitives
507 * @param monitor the progress monitor
508 * @return list of processed primitives
509 * @throws OsmTransferException if something is wrong
510 */
511 public Collection<OsmPrimitive> uploadDiff(Collection<? extends OsmPrimitive> list, ProgressMonitor monitor)
512 throws OsmTransferException {
513 try {
514 monitor.beginTask("", list.size() * 2);
515 if (changeset == null)
516 throw new OsmTransferException(tr("No changeset present for diff upload."));
517
518 initialize(monitor);
519
520 // prepare upload request
521 //
522 OsmChangeBuilder changeBuilder = new OsmChangeBuilder(changeset);
523 monitor.subTask(tr("Preparing upload request..."));
524 changeBuilder.start();
525 changeBuilder.append(list);
526 changeBuilder.finish();
527 String diffUploadRequest = changeBuilder.getDocument();
528
529 // Upload to the server
530 //
531 monitor.indeterminateSubTask(
532 trn("Uploading {0} object...", "Uploading {0} objects...", list.size(), list.size()));
533 String diffUploadResponse = sendRequest("POST", "changeset/" + changeset.getId() + "/upload", diffUploadRequest, monitor);
534
535 // Process the response from the server
536 //
537 DiffResultProcessor reader = new DiffResultProcessor(list);
538 reader.parse(diffUploadResponse, monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
539 return reader.postProcess(
540 getChangeset(),
541 monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)
542 );
543 } catch (OsmTransferException e) {
544 throw e;
545 } catch (XmlParsingException e) {
546 throw new OsmTransferException(e);
547 } finally {
548 monitor.finishTask();
549 }
550 }
551
552 private void sleepAndListen(int retry, ProgressMonitor monitor) throws OsmTransferCanceledException {
553 Main.info(tr("Waiting 10 seconds ... "));
554 for (int i = 0; i < 10; i++) {
555 if (monitor != null) {
556 monitor.setCustomText(tr("Starting retry {0} of {1} in {2} seconds ...", getMaxRetries() - retry, getMaxRetries(), 10-i));
557 }
558 if (cancel)
559 throw new OsmTransferCanceledException("Operation canceled" + (i > 0 ? " in retry #"+i : ""));
560 try {
561 Thread.sleep(1000);
562 } catch (InterruptedException ex) {
563 Main.warn("InterruptedException in "+getClass().getSimpleName()+" during sleep");
564 }
565 }
566 Main.info(tr("OK - trying again."));
567 }
568
569 /**
570 * Replies the max. number of retries in case of 5XX errors on the server
571 *
572 * @return the max number of retries
573 */
574 protected int getMaxRetries() {
575 int ret = Main.pref.getInteger("osm-server.max-num-retries", DEFAULT_MAX_NUM_RETRIES);
576 return Math.max(ret, 0);
577 }
578
579 /**
580 * Determines if JOSM is configured to access OSM API via OAuth
581 * @return {@code true} if JOSM is configured to access OSM API via OAuth, {@code false} otherwise
582 * @since 6349
583 */
584 public static boolean isUsingOAuth() {
585 return "oauth".equals(getAuthMethod());
586 }
587
588 /**
589 * Returns the authentication method set in the preferences
590 * @return the authentication method
591 */
592 public static String getAuthMethod() {
593 return Main.pref.get("osm-server.auth-method", "oauth");
594 }
595
596 protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor)
597 throws OsmTransferException {
598 return sendRequest(requestMethod, urlSuffix, requestBody, monitor, true, false);
599 }
600
601 /**
602 * Generic method for sending requests to the OSM API.
603 *
604 * This method will automatically re-try any requests that are answered with a 5xx
605 * error code, or that resulted in a timeout exception from the TCP layer.
606 *
607 * @param requestMethod The http method used when talking with the server.
608 * @param urlSuffix The suffix to add at the server url, not including the version number,
609 * but including any object ids (e.g. "/way/1234/history").
610 * @param requestBody the body of the HTTP request, if any.
611 * @param monitor the progress monitor
612 * @param doAuthenticate set to true, if the request sent to the server shall include authentication
613 * credentials;
614 * @param fastFail true to request a short timeout
615 *
616 * @return the body of the HTTP response, if and only if the response code was "200 OK".
617 * @throws OsmTransferException if the HTTP return code was not 200 (and retries have
618 * been exhausted), or rewrapping a Java exception.
619 */
620 protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor,
621 boolean doAuthenticate, boolean fastFail) throws OsmTransferException {
622 int retries = fastFail ? 0 : getMaxRetries();
623
624 while (true) { // the retry loop
625 try {
626 url = new URL(new URL(getBaseUrl()), urlSuffix);
627 final HttpClient client = HttpClient.create(url, requestMethod).keepAlive(false);
628 activeConnection = client;
629 if (fastFail) {
630 client.setConnectTimeout(1000);
631 client.setReadTimeout(1000);
632 } else {
633 // use default connect timeout from org.openstreetmap.josm.tools.HttpClient.connectTimeout
634 client.setReadTimeout(0);
635 }
636 if (doAuthenticate) {
637 addAuth(client);
638 }
639
640 if ("PUT".equals(requestMethod) || "POST".equals(requestMethod) || "DELETE".equals(requestMethod)) {
641 client.setHeader("Content-Type", "text/xml");
642 // It seems that certain bits of the Ruby API are very unhappy upon
643 // receipt of a PUT/POST message without a Content-length header,
644 // even if the request has no payload.
645 // Since Java will not generate a Content-length header unless
646 // we use the output stream, we create an output stream for PUT/POST
647 // even if there is no payload.
648 client.setRequestBody((requestBody != null ? requestBody : "").getBytes(StandardCharsets.UTF_8));
649 }
650
651 final HttpClient.Response response = client.connect();
652 Main.info(response.getResponseMessage());
653 int retCode = response.getResponseCode();
654
655 if (retCode >= 500) {
656 if (retries-- > 0) {
657 sleepAndListen(retries, monitor);
658 Main.info(tr("Starting retry {0} of {1}.", getMaxRetries() - retries, getMaxRetries()));
659 continue;
660 }
661 }
662
663 final String responseBody = response.fetchContent();
664
665 String errorHeader = null;
666 // Look for a detailed error message from the server
667 if (response.getHeaderField("Error") != null) {
668 errorHeader = response.getHeaderField("Error");
669 Main.error("Error header: " + errorHeader);
670 } else if (retCode != HttpURLConnection.HTTP_OK && responseBody.length() > 0) {
671 Main.error("Error body: " + responseBody);
672 }
673 activeConnection.disconnect();
674
675 errorHeader = errorHeader == null ? null : errorHeader.trim();
676 String errorBody = responseBody.length() == 0 ? null : responseBody.trim();
677 switch(retCode) {
678 case HttpURLConnection.HTTP_OK:
679 return responseBody;
680 case HttpURLConnection.HTTP_GONE:
681 throw new OsmApiPrimitiveGoneException(errorHeader, errorBody);
682 case HttpURLConnection.HTTP_CONFLICT:
683 if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
684 throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA);
685 else
686 throw new OsmApiException(retCode, errorHeader, errorBody);
687 case HttpURLConnection.HTTP_FORBIDDEN:
688 OsmApiException e = new OsmApiException(retCode, errorHeader, errorBody);
689 e.setAccessedUrl(activeConnection.getURL().toString());
690 throw e;
691 default:
692 throw new OsmApiException(retCode, errorHeader, errorBody);
693 }
694 } catch (SocketTimeoutException | ConnectException e) {
695 if (retries-- > 0) {
696 continue;
697 }
698 throw new OsmTransferException(e);
699 } catch (IOException e) {
700 throw new OsmTransferException(e);
701 } catch (OsmTransferException e) {
702 throw e;
703 }
704 }
705 }
706
707 /**
708 * Replies the API capabilities.
709 *
710 * @return the API capabilities, or null, if the API is not initialized yet
711 */
712 public synchronized Capabilities getCapabilities() {
713 return capabilities;
714 }
715
716 /**
717 * Ensures that the current changeset can be used for uploading data
718 *
719 * @throws OsmTransferException if the current changeset can't be used for uploading data
720 */
721 protected void ensureValidChangeset() throws OsmTransferException {
722 if (changeset == null)
723 throw new OsmTransferException(tr("Current changeset is null. Cannot upload data."));
724 if (changeset.getId() <= 0)
725 throw new OsmTransferException(tr("ID of current changeset > 0 required. Current ID is {0}.", changeset.getId()));
726 }
727
728 /**
729 * Replies the changeset data uploads are currently directed to
730 *
731 * @return the changeset data uploads are currently directed to
732 */
733 public Changeset getChangeset() {
734 return changeset;
735 }
736
737 /**
738 * Sets the changesets to which further data uploads are directed. The changeset
739 * can be null. If it isn't null it must have been created, i.e. id &gt; 0 is required. Furthermore,
740 * it must be open.
741 *
742 * @param changeset the changeset
743 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
744 * @throws IllegalArgumentException if !changeset.isOpen()
745 */
746 public void setChangeset(Changeset changeset) {
747 if (changeset == null) {
748 this.changeset = null;
749 return;
750 }
751 if (changeset.getId() <= 0)
752 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
753 if (!changeset.isOpen())
754 throw new IllegalArgumentException(tr("Open changeset expected. Got closed changeset with id {0}.", changeset.getId()));
755 this.changeset = changeset;
756 }
757
758 private static StringBuilder noteStringBuilder(Note note) {
759 return new StringBuilder().append("notes/").append(note.getId());
760 }
761
762 /**
763 * Create a new note on the server.
764 * @param latlon Location of note
765 * @param text Comment entered by user to open the note
766 * @param monitor Progress monitor
767 * @return Note as it exists on the server after creation (ID assigned)
768 * @throws OsmTransferException if any error occurs during dialog with OSM API
769 */
770 public Note createNote(LatLon latlon, String text, ProgressMonitor monitor) throws OsmTransferException {
771 initialize(monitor);
772 String noteUrl = new StringBuilder()
773 .append("notes?lat=")
774 .append(latlon.lat())
775 .append("&lon=")
776 .append(latlon.lon())
777 .append("&text=")
778 .append(Utils.encodeUrl(text)).toString();
779
780 String response = sendRequest("POST", noteUrl, null, monitor, true, false);
781 return parseSingleNote(response);
782 }
783
784 /**
785 * Add a comment to an existing note.
786 * @param note The note to add a comment to
787 * @param comment Text of the comment
788 * @param monitor Progress monitor
789 * @return Note returned by the API after the comment was added
790 * @throws OsmTransferException if any error occurs during dialog with OSM API
791 */
792 public Note addCommentToNote(Note note, String comment, ProgressMonitor monitor) throws OsmTransferException {
793 initialize(monitor);
794 String noteUrl = noteStringBuilder(note)
795 .append("/comment?text=")
796 .append(Utils.encodeUrl(comment)).toString();
797
798 String response = sendRequest("POST", noteUrl, null, monitor, true, false);
799 return parseSingleNote(response);
800 }
801
802 /**
803 * Close a note.
804 * @param note Note to close. Must currently be open
805 * @param closeMessage Optional message supplied by the user when closing the note
806 * @param monitor Progress monitor
807 * @return Note returned by the API after the close operation
808 * @throws OsmTransferException if any error occurs during dialog with OSM API
809 */
810 public Note closeNote(Note note, String closeMessage, ProgressMonitor monitor) throws OsmTransferException {
811 initialize(monitor);
812 String encodedMessage = Utils.encodeUrl(closeMessage);
813 StringBuilder urlBuilder = noteStringBuilder(note)
814 .append("/close");
815 if (encodedMessage != null && !encodedMessage.trim().isEmpty()) {
816 urlBuilder.append("?text=");
817 urlBuilder.append(encodedMessage);
818 }
819
820 String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false);
821 return parseSingleNote(response);
822 }
823
824 /**
825 * Reopen a closed note
826 * @param note Note to reopen. Must currently be closed
827 * @param reactivateMessage Optional message supplied by the user when reopening the note
828 * @param monitor Progress monitor
829 * @return Note returned by the API after the reopen operation
830 * @throws OsmTransferException if any error occurs during dialog with OSM API
831 */
832 public Note reopenNote(Note note, String reactivateMessage, ProgressMonitor monitor) throws OsmTransferException {
833 initialize(monitor);
834 String encodedMessage = Utils.encodeUrl(reactivateMessage);
835 StringBuilder urlBuilder = noteStringBuilder(note)
836 .append("/reopen");
837 if (encodedMessage != null && !encodedMessage.trim().isEmpty()) {
838 urlBuilder.append("?text=");
839 urlBuilder.append(encodedMessage);
840 }
841
842 String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false);
843 return parseSingleNote(response);
844 }
845
846 /**
847 * Method for parsing API responses for operations on individual notes
848 * @param xml the API response as XML data
849 * @return the resulting Note
850 * @throws OsmTransferException if the API response cannot be parsed
851 */
852 private Note parseSingleNote(String xml) throws OsmTransferException {
853 try {
854 List<Note> newNotes = new NoteReader(xml).parse();
855 if (newNotes.size() == 1) {
856 return newNotes.get(0);
857 }
858 //Shouldn't ever execute. Server will either respond with an error (caught elsewhere) or one note
859 throw new OsmTransferException(tr("Note upload failed"));
860 } catch (SAXException | IOException e) {
861 Main.error(e, true);
862 throw new OsmTransferException(tr("Error parsing note response from server"), e);
863 }
864 }
865}
Note: See TracBrowser for help on using the repository browser.