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

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

code style - Useless parentheses around expressions should be removed to prevent any misunderstanding

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