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

Last change on this file since 18532 was 18532, checked in by taylor.smock, 21 months ago

Fix #22160: Retry on SocketException: Unexpected end of file from server

This allows additional exceptions to force a retry. Specifically, the
following subclasses of SocketException were considered:

  • BindException -- shouldn't be thrown, "Signals that an error occurred

while attempting to bind a socket to a local address and port. Typically,
the port is in use, or the requested local address could not be assigned."
This will be raised if it is ever encountered.

  • ConnectException-- replacing that here, "Signals that an error occurred

while attempting to connect a socket to a remote address and port.
Typically, the connection was refused remotely (e.g., no process is
listening on the remote address/port)."

  • ConnectionResetException -- "Thrown to indicate a connection reset"

This seems to be a Java internal class. It is rethrown.

  • NoRouteToHostException -- "Signals that an error occurred while attempting

to connect a socket to a remote address and port. Typically, the remote
host cannot be reached because of an intervening firewall, or if an
intermediate router is down."

  • PortUnreachableException -- "Signals that an ICMP Port Unreachable message

has been received on a connected datagram."

SocketException is only thrown in one location in the JDK source code, but
just in case someone decided to throw the exception in a library, we
additionally check that the message matches that from the JDK source. This is,
unfortunately, a bit more fragile than it should be.

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