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

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

sonar - squid:S2142 - "InterruptedException" should not be ignored

  • Property svn:eol-style set to native
File size: 35.2 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 cacheInstance(api);
93 }
94 return api;
95 }
96
97 protected static void cacheInstance(OsmApi api) {
98 instances.put(api.getServerUrl(), api);
99 }
100
101 private static String getServerUrlFromPref() {
102 return Main.pref.get("osm-server.url", DEFAULT_API_URL);
103 }
104
105 /**
106 * Replies the {@link OsmApi} for the URL given by the preference <code>osm-server.url</code>
107 *
108 * @return the OsmApi
109 */
110 public static OsmApi getOsmApi() {
111 return getOsmApi(getServerUrlFromPref());
112 }
113
114 /** Server URL */
115 private final String serverUrl;
116
117 /** Object describing current changeset */
118 private Changeset changeset;
119
120 /** API version used for server communications */
121 private String version;
122
123 /** API capabilities */
124 private Capabilities capabilities;
125
126 /** true if successfully initialized */
127 private boolean initialized;
128
129 /**
130 * Constructs a new {@code OsmApi} for a specific server URL.
131 *
132 * @param serverUrl the server URL. Must not be null
133 * @throws IllegalArgumentException if serverUrl is null
134 */
135 protected OsmApi(String serverUrl) {
136 CheckParameterUtil.ensureParameterNotNull(serverUrl, "serverUrl");
137 this.serverUrl = serverUrl;
138 }
139
140 /**
141 * Replies the OSM protocol version we use to talk to the server.
142 * @return protocol version, or null if not yet negotiated.
143 */
144 public String getVersion() {
145 return version;
146 }
147
148 /**
149 * Replies the host name of the server URL.
150 * @return the host name of the server URL, or null if the server URL is malformed.
151 */
152 public String getHost() {
153 String host = null;
154 try {
155 host = (new URL(serverUrl)).getHost();
156 } catch (MalformedURLException e) {
157 Main.warn(e);
158 }
159 return host;
160 }
161
162 private class CapabilitiesCache extends CacheCustomContent<OsmTransferException> {
163
164 private static final String CAPABILITIES = "capabilities";
165
166 private final ProgressMonitor monitor;
167 private final boolean fastFail;
168
169 CapabilitiesCache(ProgressMonitor monitor, boolean fastFail) {
170 super(CAPABILITIES + getBaseUrl().hashCode(), CacheCustomContent.INTERVAL_WEEKLY);
171 this.monitor = monitor;
172 this.fastFail = fastFail;
173 }
174
175 @Override
176 protected void checkOfflineAccess() {
177 OnlineResource.OSM_API.checkOfflineAccess(getBaseUrl(getServerUrlFromPref(), "0.6")+CAPABILITIES, getServerUrlFromPref());
178 }
179
180 @Override
181 protected byte[] updateData() throws OsmTransferException {
182 return sendRequest("GET", CAPABILITIES, null, monitor, false, fastFail).getBytes(StandardCharsets.UTF_8);
183 }
184 }
185
186 /**
187 * Initializes this component by negotiating a protocol version with the server.
188 *
189 * @param monitor the progress monitor
190 * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
191 * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
192 */
193 public void initialize(ProgressMonitor monitor) throws OsmTransferCanceledException, OsmApiInitializationException {
194 initialize(monitor, false);
195 }
196
197 /**
198 * Initializes this component by negotiating a protocol version with the server, with the ability to control the timeout.
199 *
200 * @param monitor the progress monitor
201 * @param fastFail true to request quick initialisation with a small timeout (more likely to throw exception)
202 * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
203 * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
204 */
205 public void initialize(ProgressMonitor monitor, boolean fastFail) throws OsmTransferCanceledException, OsmApiInitializationException {
206 if (initialized)
207 return;
208 cancel = false;
209 try {
210 CapabilitiesCache cache = new CapabilitiesCache(monitor, fastFail);
211 try {
212 initializeCapabilities(cache.updateIfRequiredString());
213 } catch (SAXParseException parseException) {
214 Main.trace(parseException);
215 // XML parsing may fail if JOSM previously stored a corrupted capabilities document (see #8278)
216 // In that case, force update and try again
217 initializeCapabilities(cache.updateForceString());
218 }
219 if (capabilities == null) {
220 if (Main.isOffline(OnlineResource.OSM_API)) {
221 Main.warn(tr("{0} not available (offline mode)", tr("OSM API")));
222 } else {
223 Main.error(tr("Unable to initialize OSM API."));
224 }
225 return;
226 } else if (!capabilities.supportsVersion("0.6")) {
227 Main.error(tr("This version of JOSM is incompatible with the configured server."));
228 Main.error(tr("It supports protocol version 0.6, while the server says it supports {0} to {1}.",
229 capabilities.get("version", "minimum"), capabilities.get("version", "maximum")));
230 return;
231 } else {
232 version = "0.6";
233 initialized = true;
234 }
235
236 /* This checks if there are any layers currently displayed that
237 * are now on the blacklist, and removes them. This is a rare
238 * situation - probably only occurs if the user changes the API URL
239 * in the preferences menu. Otherwise they would not have been able
240 * to load the layers in the first place because they would have
241 * been disabled! */
242 if (Main.isDisplayingMapView()) {
243 for (Layer l : Main.getLayerManager().getLayersOfType(ImageryLayer.class)) {
244 if (((ImageryLayer) l).getInfo().isBlacklisted()) {
245 Main.info(tr("Removed layer {0} because it is not allowed by the configured API.", l.getName()));
246 Main.getLayerManager().removeLayer(l);
247 }
248 }
249 }
250
251 } catch (OsmTransferCanceledException e) {
252 throw e;
253 } catch (OsmTransferException e) {
254 initialized = false;
255 Main.addNetworkError(url, Utils.getRootCause(e));
256 throw new OsmApiInitializationException(e);
257 } catch (SAXException | IOException | ParserConfigurationException e) {
258 initialized = false;
259 throw new OsmApiInitializationException(e);
260 }
261 }
262
263 private synchronized void initializeCapabilities(String xml) throws SAXException, IOException, ParserConfigurationException {
264 if (xml != null) {
265 capabilities = CapabilitiesParser.parse(new InputSource(new StringReader(xml)));
266 }
267 }
268
269 /**
270 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
271 * @param o the OSM primitive
272 * @param addBody true to generate the full XML, false to only generate the encapsulating tag
273 * @return XML string
274 */
275 protected final String toXml(IPrimitive o, boolean addBody) {
276 StringWriter swriter = new StringWriter();
277 try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
278 swriter.getBuffer().setLength(0);
279 osmWriter.setWithBody(addBody);
280 osmWriter.setChangeset(changeset);
281 osmWriter.header();
282 o.accept(osmWriter);
283 osmWriter.footer();
284 osmWriter.flush();
285 } catch (IOException e) {
286 Main.warn(e);
287 }
288 return swriter.toString();
289 }
290
291 /**
292 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
293 * @param s the changeset
294 * @return XML string
295 */
296 protected final String toXml(Changeset s) {
297 StringWriter swriter = new StringWriter();
298 try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
299 swriter.getBuffer().setLength(0);
300 osmWriter.header();
301 osmWriter.visit(s);
302 osmWriter.footer();
303 osmWriter.flush();
304 } catch (IOException e) {
305 Main.warn(e);
306 }
307 return swriter.toString();
308 }
309
310 private static String getBaseUrl(String serverUrl, String version) {
311 StringBuilder rv = new StringBuilder(serverUrl);
312 if (version != null) {
313 rv.append('/').append(version);
314 }
315 rv.append('/');
316 // this works around a ruby (or lighttpd) bug where two consecutive slashes in
317 // an URL will cause a "404 not found" response.
318 int p;
319 while ((p = rv.indexOf("//", rv.indexOf("://")+2)) > -1) {
320 rv.delete(p, p + 1);
321 }
322 return rv.toString();
323 }
324
325 /**
326 * Returns the base URL for API requests, including the negotiated version number.
327 * @return base URL string
328 */
329 public String getBaseUrl() {
330 return getBaseUrl(serverUrl, version);
331 }
332
333 /**
334 * Returns the server URL
335 * @return the server URL
336 * @since 9353
337 */
338 public String getServerUrl() {
339 return serverUrl;
340 }
341
342 /**
343 * Creates an OSM primitive on the server. The OsmPrimitive object passed in
344 * is modified by giving it the server-assigned id.
345 *
346 * @param osm the primitive
347 * @param monitor the progress monitor
348 * @throws OsmTransferException if something goes wrong
349 */
350 public void createPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
351 String ret = "";
352 try {
353 ensureValidChangeset();
354 initialize(monitor);
355 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/create", toXml(osm, true), monitor);
356 osm.setOsmId(Long.parseLong(ret.trim()), 1);
357 osm.setChangesetId(getChangeset().getId());
358 } catch (NumberFormatException e) {
359 throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret), e);
360 }
361 }
362
363 /**
364 * Modifies an OSM primitive on the server.
365 *
366 * @param osm the primitive. Must not be null.
367 * @param monitor the progress monitor
368 * @throws OsmTransferException if something goes wrong
369 */
370 public void modifyPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
371 String ret = null;
372 try {
373 ensureValidChangeset();
374 initialize(monitor);
375 // normal mode (0.6 and up) returns new object version.
376 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+'/' + osm.getId(), toXml(osm, true), monitor);
377 osm.setOsmId(osm.getId(), Integer.parseInt(ret.trim()));
378 osm.setChangesetId(getChangeset().getId());
379 osm.setVisible(true);
380 } catch (NumberFormatException e) {
381 throw new OsmTransferException(tr("Unexpected format of new version of modified primitive ''{0}''. Got ''{1}''.",
382 osm.getId(), ret), e);
383 }
384 }
385
386 /**
387 * Deletes an OSM primitive on the server.
388 * @param osm the primitive
389 * @param monitor the progress monitor
390 * @throws OsmTransferException if something goes wrong
391 */
392 public void deletePrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
393 ensureValidChangeset();
394 initialize(monitor);
395 // can't use a the individual DELETE method in the 0.6 API. Java doesn't allow
396 // submitting a DELETE request with content, the 0.6 API requires it, however. Falling back
397 // to diff upload.
398 //
399 uploadDiff(Collections.singleton(osm), monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
400 }
401
402 /**
403 * Creates a new changeset based on the keys in <code>changeset</code>. If this
404 * method succeeds, changeset.getId() replies the id the server assigned to the new
405 * changeset
406 *
407 * The changeset must not be null, but its key/value-pairs may be empty.
408 *
409 * @param changeset the changeset toe be created. Must not be null.
410 * @param progressMonitor the progress monitor
411 * @throws OsmTransferException signifying a non-200 return code, or connection errors
412 * @throws IllegalArgumentException if changeset is null
413 */
414 public void openChangeset(Changeset changeset, ProgressMonitor progressMonitor) throws OsmTransferException {
415 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
416 try {
417 progressMonitor.beginTask(tr("Creating changeset..."));
418 initialize(progressMonitor);
419 String ret = "";
420 try {
421 ret = sendRequest("PUT", "changeset/create", toXml(changeset), progressMonitor);
422 changeset.setId(Integer.parseInt(ret.trim()));
423 changeset.setOpen(true);
424 } catch (NumberFormatException e) {
425 throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret), e);
426 }
427 progressMonitor.setCustomText(tr("Successfully opened changeset {0}", changeset.getId()));
428 } finally {
429 progressMonitor.finishTask();
430 }
431 }
432
433 /**
434 * Updates a changeset with the keys in <code>changesetUpdate</code>. The changeset must not
435 * be null and id &gt; 0 must be true.
436 *
437 * @param changeset the changeset to update. Must not be null.
438 * @param monitor the progress monitor. If null, uses the {@link NullProgressMonitor#INSTANCE}.
439 *
440 * @throws OsmTransferException if something goes wrong.
441 * @throws IllegalArgumentException if changeset is null
442 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
443 *
444 */
445 public void updateChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
446 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
447 if (monitor == null) {
448 monitor = NullProgressMonitor.INSTANCE;
449 }
450 if (changeset.getId() <= 0)
451 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
452 try {
453 monitor.beginTask(tr("Updating changeset..."));
454 initialize(monitor);
455 monitor.setCustomText(tr("Updating changeset {0}...", changeset.getId()));
456 sendRequest(
457 "PUT",
458 "changeset/" + changeset.getId(),
459 toXml(changeset),
460 monitor
461 );
462 } catch (ChangesetClosedException e) {
463 e.setSource(ChangesetClosedException.Source.UPDATE_CHANGESET);
464 throw e;
465 } catch (OsmApiException e) {
466 String errorHeader = e.getErrorHeader();
467 if (e.getResponseCode() == HttpURLConnection.HTTP_CONFLICT && ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
468 throw new ChangesetClosedException(errorHeader, ChangesetClosedException.Source.UPDATE_CHANGESET);
469 throw e;
470 } finally {
471 monitor.finishTask();
472 }
473 }
474
475 /**
476 * Closes a changeset on the server. Sets changeset.setOpen(false) if this operation succeeds.
477 *
478 * @param changeset the changeset to be closed. Must not be null. changeset.getId() &gt; 0 required.
479 * @param monitor the progress monitor. If null, uses {@link NullProgressMonitor#INSTANCE}
480 *
481 * @throws OsmTransferException if something goes wrong.
482 * @throws IllegalArgumentException if changeset is null
483 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
484 */
485 public void closeChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
486 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
487 if (monitor == null) {
488 monitor = NullProgressMonitor.INSTANCE;
489 }
490 if (changeset.getId() <= 0)
491 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
492 try {
493 monitor.beginTask(tr("Closing changeset..."));
494 initialize(monitor);
495 /* send "\r\n" instead of empty string, so we don't send zero payload - works around bugs
496 in proxy software */
497 sendRequest("PUT", "changeset" + "/" + changeset.getId() + "/close", "\r\n", monitor);
498 changeset.setOpen(false);
499 } finally {
500 monitor.finishTask();
501 }
502 }
503
504 /**
505 * Uploads a list of changes in "diff" form to the server.
506 *
507 * @param list the list of changed OSM Primitives
508 * @param monitor the progress monitor
509 * @return list of processed primitives
510 * @throws OsmTransferException if something is wrong
511 */
512 public Collection<OsmPrimitive> uploadDiff(Collection<? extends OsmPrimitive> list, ProgressMonitor monitor)
513 throws OsmTransferException {
514 try {
515 monitor.beginTask("", list.size() * 2);
516 if (changeset == null)
517 throw new OsmTransferException(tr("No changeset present for diff upload."));
518
519 initialize(monitor);
520
521 // prepare upload request
522 //
523 OsmChangeBuilder changeBuilder = new OsmChangeBuilder(changeset);
524 monitor.subTask(tr("Preparing upload request..."));
525 changeBuilder.start();
526 changeBuilder.append(list);
527 changeBuilder.finish();
528 String diffUploadRequest = changeBuilder.getDocument();
529
530 // Upload to the server
531 //
532 monitor.indeterminateSubTask(
533 trn("Uploading {0} object...", "Uploading {0} objects...", list.size(), list.size()));
534 String diffUploadResponse = sendRequest("POST", "changeset/" + changeset.getId() + "/upload", diffUploadRequest, monitor);
535
536 // Process the response from the server
537 //
538 DiffResultProcessor reader = new DiffResultProcessor(list);
539 reader.parse(diffUploadResponse, monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
540 return reader.postProcess(
541 getChangeset(),
542 monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)
543 );
544 } catch (OsmTransferException e) {
545 throw e;
546 } catch (XmlParsingException e) {
547 throw new OsmTransferException(e);
548 } finally {
549 monitor.finishTask();
550 }
551 }
552
553 private void sleepAndListen(int retry, ProgressMonitor monitor) throws OsmTransferCanceledException {
554 Main.info(tr("Waiting 10 seconds ... "));
555 for (int i = 0; i < 10; i++) {
556 if (monitor != null) {
557 monitor.setCustomText(tr("Starting retry {0} of {1} in {2} seconds ...", getMaxRetries() - retry, getMaxRetries(), 10-i));
558 }
559 if (cancel)
560 throw new OsmTransferCanceledException("Operation canceled" + (i > 0 ? " in retry #"+i : ""));
561 try {
562 Thread.sleep(1000);
563 } catch (InterruptedException ex) {
564 Main.warn("InterruptedException in "+getClass().getSimpleName()+" during sleep");
565 Thread.currentThread().interrupt();
566 }
567 }
568 Main.info(tr("OK - trying again."));
569 }
570
571 /**
572 * Replies the max. number of retries in case of 5XX errors on the server
573 *
574 * @return the max number of retries
575 */
576 protected int getMaxRetries() {
577 int ret = Main.pref.getInteger("osm-server.max-num-retries", DEFAULT_MAX_NUM_RETRIES);
578 return Math.max(ret, 0);
579 }
580
581 /**
582 * Determines if JOSM is configured to access OSM API via OAuth
583 * @return {@code true} if JOSM is configured to access OSM API via OAuth, {@code false} otherwise
584 * @since 6349
585 */
586 public static boolean isUsingOAuth() {
587 return "oauth".equals(getAuthMethod());
588 }
589
590 /**
591 * Returns the authentication method set in the preferences
592 * @return the authentication method
593 */
594 public static String getAuthMethod() {
595 return Main.pref.get("osm-server.auth-method", "oauth");
596 }
597
598 protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor)
599 throws OsmTransferException {
600 return sendRequest(requestMethod, urlSuffix, requestBody, monitor, true, false);
601 }
602
603 /**
604 * Generic method for sending requests to the OSM API.
605 *
606 * This method will automatically re-try any requests that are answered with a 5xx
607 * error code, or that resulted in a timeout exception from the TCP layer.
608 *
609 * @param requestMethod The http method used when talking with the server.
610 * @param urlSuffix The suffix to add at the server url, not including the version number,
611 * but including any object ids (e.g. "/way/1234/history").
612 * @param requestBody the body of the HTTP request, if any.
613 * @param monitor the progress monitor
614 * @param doAuthenticate set to true, if the request sent to the server shall include authentication
615 * credentials;
616 * @param fastFail true to request a short timeout
617 *
618 * @return the body of the HTTP response, if and only if the response code was "200 OK".
619 * @throws OsmTransferException if the HTTP return code was not 200 (and retries have
620 * been exhausted), or rewrapping a Java exception.
621 */
622 protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor,
623 boolean doAuthenticate, boolean fastFail) throws OsmTransferException {
624 int retries = fastFail ? 0 : getMaxRetries();
625
626 while (true) { // the retry loop
627 try {
628 url = new URL(new URL(getBaseUrl()), urlSuffix);
629 final HttpClient client = HttpClient.create(url, requestMethod).keepAlive(false);
630 activeConnection = client;
631 if (fastFail) {
632 client.setConnectTimeout(1000);
633 client.setReadTimeout(1000);
634 } else {
635 // use default connect timeout from org.openstreetmap.josm.tools.HttpClient.connectTimeout
636 client.setReadTimeout(0);
637 }
638 if (doAuthenticate) {
639 addAuth(client);
640 }
641
642 if ("PUT".equals(requestMethod) || "POST".equals(requestMethod) || "DELETE".equals(requestMethod)) {
643 client.setHeader("Content-Type", "text/xml");
644 // It seems that certain bits of the Ruby API are very unhappy upon
645 // receipt of a PUT/POST message without a Content-length header,
646 // even if the request has no payload.
647 // Since Java will not generate a Content-length header unless
648 // we use the output stream, we create an output stream for PUT/POST
649 // even if there is no payload.
650 client.setRequestBody((requestBody != null ? requestBody : "").getBytes(StandardCharsets.UTF_8));
651 }
652
653 final HttpClient.Response response = client.connect();
654 Main.info(response.getResponseMessage());
655 int retCode = response.getResponseCode();
656
657 if (retCode >= 500 && retries-- > 0) {
658 sleepAndListen(retries, monitor);
659 Main.info(tr("Starting retry {0} of {1}.", getMaxRetries() - retries, getMaxRetries()));
660 continue;
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.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.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 static 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.