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

Last change on this file since 9231 was 9182, checked in by simon04, 8 years ago

see #12231 - No read timeout for OsmApi connections

Fixes regression from r9172

  • Property svn:eol-style set to native
File size: 35.6 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 final boolean isUsingOAuth() {
585 return "oauth".equals(Main.pref.get("osm-server.auth-method", "basic"));
586 }
587
588 protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor)
589 throws OsmTransferException {
590 return sendRequest(requestMethod, urlSuffix, requestBody, monitor, true, false);
591 }
592
593 /**
594 * Generic method for sending requests to the OSM API.
595 *
596 * This method will automatically re-try any requests that are answered with a 5xx
597 * error code, or that resulted in a timeout exception from the TCP layer.
598 *
599 * @param requestMethod The http method used when talking with the server.
600 * @param urlSuffix The suffix to add at the server url, not including the version number,
601 * but including any object ids (e.g. "/way/1234/history").
602 * @param requestBody the body of the HTTP request, if any.
603 * @param monitor the progress monitor
604 * @param doAuthenticate set to true, if the request sent to the server shall include authentication
605 * credentials;
606 * @param fastFail true to request a short timeout
607 *
608 * @return the body of the HTTP response, if and only if the response code was "200 OK".
609 * @throws OsmTransferException if the HTTP return code was not 200 (and retries have
610 * been exhausted), or rewrapping a Java exception.
611 */
612 protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor,
613 boolean doAuthenticate, boolean fastFail) throws OsmTransferException {
614 int retries = fastFail ? 0 : getMaxRetries();
615
616 while (true) { // the retry loop
617 try {
618 url = new URL(new URL(getBaseUrl()), urlSuffix);
619 final HttpClient client = HttpClient.create(url, requestMethod).keepAlive(false);
620 if (fastFail) {
621 client.setConnectTimeout(1000);
622 client.setReadTimeout(1000);
623 } else {
624 // use default connect timeout from org.openstreetmap.josm.tools.HttpClient.connectTimeout
625 client.setReadTimeout(0);
626 }
627 if (doAuthenticate) {
628 addAuth(client);
629 }
630
631 if ("PUT".equals(requestMethod) || "POST".equals(requestMethod) || "DELETE".equals(requestMethod)) {
632 client.setHeader("Content-Type", "text/xml");
633 // It seems that certain bits of the Ruby API are very unhappy upon
634 // receipt of a PUT/POST message without a Content-length header,
635 // even if the request has no payload.
636 // Since Java will not generate a Content-length header unless
637 // we use the output stream, we create an output stream for PUT/POST
638 // even if there is no payload.
639 client.setRequestBody((requestBody != null ? requestBody : "").getBytes(StandardCharsets.UTF_8));
640 }
641
642 activeConnection = client.connect();
643 Main.info(activeConnection.getResponseMessage());
644 int retCode = activeConnection.getResponseCode();
645
646 if (retCode >= 500) {
647 if (retries-- > 0) {
648 sleepAndListen(retries, monitor);
649 Main.info(tr("Starting retry {0} of {1}.", getMaxRetries() - retries, getMaxRetries()));
650 continue;
651 }
652 }
653
654 final String responseBody = activeConnection.fetchContent();
655
656 String errorHeader = null;
657 // Look for a detailed error message from the server
658 if (activeConnection.getHeaderField("Error") != null) {
659 errorHeader = activeConnection.getHeaderField("Error");
660 Main.error("Error header: " + errorHeader);
661 } else if (retCode != HttpURLConnection.HTTP_OK && responseBody.length() > 0) {
662 Main.error("Error body: " + responseBody);
663 }
664 activeConnection.disconnect();
665
666 errorHeader = errorHeader == null ? null : errorHeader.trim();
667 String errorBody = responseBody.length() == 0 ? null : responseBody.trim();
668 switch(retCode) {
669 case HttpURLConnection.HTTP_OK:
670 return responseBody;
671 case HttpURLConnection.HTTP_GONE:
672 throw new OsmApiPrimitiveGoneException(errorHeader, errorBody);
673 case HttpURLConnection.HTTP_CONFLICT:
674 if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
675 throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA);
676 else
677 throw new OsmApiException(retCode, errorHeader, errorBody);
678 case HttpURLConnection.HTTP_FORBIDDEN:
679 OsmApiException e = new OsmApiException(retCode, errorHeader, errorBody);
680 e.setAccessedUrl(activeConnection.getURL().toString());
681 throw e;
682 default:
683 throw new OsmApiException(retCode, errorHeader, errorBody);
684 }
685 } catch (SocketTimeoutException | ConnectException e) {
686 if (retries-- > 0) {
687 continue;
688 }
689 throw new OsmTransferException(e);
690 } catch (IOException e) {
691 throw new OsmTransferException(e);
692 } catch (OsmTransferException e) {
693 throw e;
694 }
695 }
696 }
697
698 /**
699 * Replies the API capabilities.
700 *
701 * @return the API capabilities, or null, if the API is not initialized yet
702 */
703 public synchronized Capabilities getCapabilities() {
704 return capabilities;
705 }
706
707 /**
708 * Ensures that the current changeset can be used for uploading data
709 *
710 * @throws OsmTransferException if the current changeset can't be used for uploading data
711 */
712 protected void ensureValidChangeset() throws OsmTransferException {
713 if (changeset == null)
714 throw new OsmTransferException(tr("Current changeset is null. Cannot upload data."));
715 if (changeset.getId() <= 0)
716 throw new OsmTransferException(tr("ID of current changeset > 0 required. Current ID is {0}.", changeset.getId()));
717 }
718
719 /**
720 * Replies the changeset data uploads are currently directed to
721 *
722 * @return the changeset data uploads are currently directed to
723 */
724 public Changeset getChangeset() {
725 return changeset;
726 }
727
728 /**
729 * Sets the changesets to which further data uploads are directed. The changeset
730 * can be null. If it isn't null it must have been created, i.e. id &gt; 0 is required. Furthermore,
731 * it must be open.
732 *
733 * @param changeset the changeset
734 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
735 * @throws IllegalArgumentException if !changeset.isOpen()
736 */
737 public void setChangeset(Changeset changeset) {
738 if (changeset == null) {
739 this.changeset = null;
740 return;
741 }
742 if (changeset.getId() <= 0)
743 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
744 if (!changeset.isOpen())
745 throw new IllegalArgumentException(tr("Open changeset expected. Got closed changeset with id {0}.", changeset.getId()));
746 this.changeset = changeset;
747 }
748
749 private static StringBuilder noteStringBuilder(Note note) {
750 return new StringBuilder().append("notes/").append(note.getId());
751 }
752
753 /**
754 * Create a new note on the server.
755 * @param latlon Location of note
756 * @param text Comment entered by user to open the note
757 * @param monitor Progress monitor
758 * @return Note as it exists on the server after creation (ID assigned)
759 * @throws OsmTransferException if any error occurs during dialog with OSM API
760 */
761 public Note createNote(LatLon latlon, String text, ProgressMonitor monitor) throws OsmTransferException {
762 initialize(monitor);
763 String noteUrl = new StringBuilder()
764 .append("notes?lat=")
765 .append(latlon.lat())
766 .append("&lon=")
767 .append(latlon.lon())
768 .append("&text=")
769 .append(Utils.encodeUrl(text)).toString();
770
771 String response = sendRequest("POST", noteUrl, null, monitor, true, false);
772 return parseSingleNote(response);
773 }
774
775 /**
776 * Add a comment to an existing note.
777 * @param note The note to add a comment to
778 * @param comment Text of the comment
779 * @param monitor Progress monitor
780 * @return Note returned by the API after the comment was added
781 * @throws OsmTransferException if any error occurs during dialog with OSM API
782 */
783 public Note addCommentToNote(Note note, String comment, ProgressMonitor monitor) throws OsmTransferException {
784 initialize(monitor);
785 String noteUrl = noteStringBuilder(note)
786 .append("/comment?text=")
787 .append(Utils.encodeUrl(comment)).toString();
788
789 String response = sendRequest("POST", noteUrl, null, monitor, true, false);
790 return parseSingleNote(response);
791 }
792
793 /**
794 * Close a note.
795 * @param note Note to close. Must currently be open
796 * @param closeMessage Optional message supplied by the user when closing the note
797 * @param monitor Progress monitor
798 * @return Note returned by the API after the close operation
799 * @throws OsmTransferException if any error occurs during dialog with OSM API
800 */
801 public Note closeNote(Note note, String closeMessage, ProgressMonitor monitor) throws OsmTransferException {
802 initialize(monitor);
803 String encodedMessage = Utils.encodeUrl(closeMessage);
804 StringBuilder urlBuilder = noteStringBuilder(note)
805 .append("/close");
806 if (encodedMessage != null && !encodedMessage.trim().isEmpty()) {
807 urlBuilder.append("?text=");
808 urlBuilder.append(encodedMessage);
809 }
810
811 String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false);
812 return parseSingleNote(response);
813 }
814
815 /**
816 * Reopen a closed note
817 * @param note Note to reopen. Must currently be closed
818 * @param reactivateMessage Optional message supplied by the user when reopening the note
819 * @param monitor Progress monitor
820 * @return Note returned by the API after the reopen operation
821 * @throws OsmTransferException if any error occurs during dialog with OSM API
822 */
823 public Note reopenNote(Note note, String reactivateMessage, ProgressMonitor monitor) throws OsmTransferException {
824 initialize(monitor);
825 String encodedMessage = Utils.encodeUrl(reactivateMessage);
826 StringBuilder urlBuilder = noteStringBuilder(note)
827 .append("/reopen");
828 if (encodedMessage != null && !encodedMessage.trim().isEmpty()) {
829 urlBuilder.append("?text=");
830 urlBuilder.append(encodedMessage);
831 }
832
833 String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false);
834 return parseSingleNote(response);
835 }
836
837 /**
838 * Method for parsing API responses for operations on individual notes
839 * @param xml the API response as XML data
840 * @return the resulting Note
841 * @throws OsmTransferException if the API response cannot be parsed
842 */
843 private Note parseSingleNote(String xml) throws OsmTransferException {
844 try {
845 List<Note> newNotes = new NoteReader(xml).parse();
846 if (newNotes.size() == 1) {
847 return newNotes.get(0);
848 }
849 //Shouldn't ever execute. Server will either respond with an error (caught elsewhere) or one note
850 throw new OsmTransferException(tr("Note upload failed"));
851 } catch (SAXException | IOException e) {
852 Main.error(e, true);
853 throw new OsmTransferException(tr("Error parsing note response from server"), e);
854 }
855 }
856}
Note: See TracBrowser for help on using the repository browser.