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

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

see #15182 - deprecate all Main logging methods and introduce suitable replacements in Logging for most of them

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