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

Last change on this file since 8291 was 8291, checked in by Don-vip, 9 years ago

fix squid:RedundantThrowsDeclarationCheck + consistent Javadoc for exceptions

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