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

Last change on this file since 7474 was 7473, checked in by Don-vip, 10 years ago

see #10441 - send capabilities request instead of changesets request when testing API url

  • Property svn:eol-style set to native
File size: 32.7 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.Map;
27
28import javax.xml.parsers.ParserConfigurationException;
29
30import org.openstreetmap.josm.Main;
31import org.openstreetmap.josm.data.osm.Changeset;
32import org.openstreetmap.josm.data.osm.IPrimitive;
33import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
34import org.openstreetmap.josm.gui.layer.ImageryLayer;
35import org.openstreetmap.josm.gui.layer.Layer;
36import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
37import org.openstreetmap.josm.gui.progress.ProgressMonitor;
38import org.openstreetmap.josm.io.Capabilities.CapabilitiesParser;
39import org.openstreetmap.josm.tools.CheckParameterUtil;
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 = null;
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 thrown, 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 instances.put(serverUrl,api);
94 }
95 return api;
96 }
97
98 private static String getServerUrlFromPref() {
99 return Main.pref.get("osm-server.url", DEFAULT_API_URL);
100 }
101
102 /**
103 * Replies the {@link OsmApi} for the URL given by the preference <code>osm-server.url</code>
104 *
105 * @return the OsmApi
106 */
107 public static OsmApi getOsmApi() {
108 return getOsmApi(getServerUrlFromPref());
109 }
110
111 /** Server URL */
112 private String serverUrl;
113
114 /** Object describing current changeset */
115 private Changeset changeset;
116
117 /** API version used for server communications */
118 private String version = null;
119
120 /** API capabilities */
121 private Capabilities capabilities = null;
122
123 /** true if successfully initialized */
124 private boolean initialized = false;
125
126 /**
127 * Constructs a new {@code OsmApi} for a specific server URL.
128 *
129 * @param serverUrl the server URL. Must not be null
130 * @throws IllegalArgumentException thrown, if serverUrl is null
131 */
132 protected OsmApi(String serverUrl) {
133 CheckParameterUtil.ensureParameterNotNull(serverUrl, "serverUrl");
134 this.serverUrl = serverUrl;
135 }
136
137 /**
138 * Replies the OSM protocol version we use to talk to the server.
139 * @return protocol version, or null if not yet negotiated.
140 */
141 public String getVersion() {
142 return version;
143 }
144
145 /**
146 * Replies the host name of the server URL.
147 * @return the host name of the server URL, or null if the server URL is malformed.
148 */
149 public String getHost() {
150 String host = null;
151 try {
152 host = (new URL(serverUrl)).getHost();
153 } catch (MalformedURLException e) {
154 Main.warn(e);
155 }
156 return host;
157 }
158
159 private class CapabilitiesCache extends CacheCustomContent<OsmTransferException> {
160
161 private static final String CAPABILITIES = "capabilities";
162
163 ProgressMonitor monitor;
164 boolean fastFail;
165
166 public CapabilitiesCache(ProgressMonitor monitor, boolean fastFail) {
167 super(CAPABILITIES + getBaseUrl().hashCode(), CacheCustomContent.INTERVAL_WEEKLY);
168 this.monitor = monitor;
169 this.fastFail = fastFail;
170 }
171
172 @Override
173 protected void checkOfflineAccess() {
174 OnlineResource.OSM_API.checkOfflineAccess(getBaseUrl(getServerUrlFromPref(), "0.6")+CAPABILITIES, getServerUrlFromPref());
175 }
176
177 @Override
178 protected byte[] updateData() throws OsmTransferException {
179 return sendRequest("GET", CAPABILITIES, null, monitor, false, fastFail).getBytes(StandardCharsets.UTF_8);
180 }
181 }
182
183 /**
184 * Initializes this component by negotiating a protocol version with the server.
185 *
186 * @param monitor the progress monitor
187 * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
188 * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
189 */
190 public void initialize(ProgressMonitor monitor) throws OsmTransferCanceledException, OsmApiInitializationException {
191 initialize(monitor, false);
192 }
193
194 /**
195 * Initializes this component by negotiating a protocol version with the server, with the ability to control the timeout.
196 *
197 * @param monitor the progress monitor
198 * @param fastFail true to request quick initialisation with a small timeout (more likely to throw exception)
199 * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
200 * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
201 */
202 public void initialize(ProgressMonitor monitor, boolean fastFail) throws OsmTransferCanceledException, OsmApiInitializationException {
203 if (initialized)
204 return;
205 if (Main.isOffline(OnlineResource.OSM_API)) {
206 // At this point this is an error because all automatic or UI actions requiring OSM API should have been disabled earlier
207 throw new OfflineAccessException(tr("{0} not available (offline mode)", OnlineResource.OSM_API.getLocName()));
208 }
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.supportsVersion("0.6")) {
220 version = "0.6";
221 } else {
222 Main.error(tr("This version of JOSM is incompatible with the configured server."));
223 Main.error(tr("It supports protocol version 0.6, while the server says it supports {0} to {1}.",
224 capabilities.get("version", "minimum"), capabilities.get("version", "maximum")));
225 initialized = false; // FIXME gets overridden by next assignment
226 }
227 initialized = true;
228
229 /* This is an interim solution for openstreetmap.org not currently
230 * transmitting their imagery blacklist in the capabilities call.
231 * remove this as soon as openstreetmap.org adds blacklists.
232 * If you want to update this list, please ask for update of
233 * http://trac.openstreetmap.org/ticket/5024
234 * This list should not be maintained by each OSM editor (see #9210) */
235 if (this.serverUrl.matches(".*openstreetmap.org/api.*") && capabilities.getImageryBlacklist().isEmpty())
236 {
237 capabilities.put("blacklist", "regex", ".*\\.google\\.com/.*");
238 capabilities.put("blacklist", "regex", ".*209\\.85\\.2\\d\\d.*");
239 capabilities.put("blacklist", "regex", ".*209\\.85\\.1[3-9]\\d.*");
240 capabilities.put("blacklist", "regex", ".*209\\.85\\.12[89].*");
241 }
242
243 /* This checks if there are any layers currently displayed that
244 * are now on the blacklist, and removes them. This is a rare
245 * situation - probably only occurs if the user changes the API URL
246 * in the preferences menu. Otherwise they would not have been able
247 * to load the layers in the first place becuase they would have
248 * been disabled! */
249 if (Main.isDisplayingMapView()) {
250 for (Layer l : Main.map.mapView.getLayersOfType(ImageryLayer.class)) {
251 if (((ImageryLayer) l).getInfo().isBlacklisted()) {
252 Main.info(tr("Removed layer {0} because it is not allowed by the configured API.", l.getName()));
253 Main.main.removeLayer(l);
254 }
255 }
256 }
257
258 } catch (OsmTransferCanceledException e) {
259 throw e;
260 } catch (OsmTransferException e) {
261 initialized = false;
262 Main.addNetworkError(url, Utils.getRootCause(e));
263 throw new OsmApiInitializationException(e);
264 } catch (Exception e) {
265 initialized = false;
266 throw new OsmApiInitializationException(e);
267 }
268 }
269
270 private void initializeCapabilities(String xml) throws SAXException, IOException, ParserConfigurationException {
271 capabilities = CapabilitiesParser.parse(new InputSource(new StringReader(xml)));
272 }
273
274 /**
275 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
276 * @param o the OSM primitive
277 * @param addBody true to generate the full XML, false to only generate the encapsulating tag
278 * @return XML string
279 */
280 private String toXml(IPrimitive o, boolean addBody) {
281 StringWriter swriter = new StringWriter();
282 try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
283 swriter.getBuffer().setLength(0);
284 osmWriter.setWithBody(addBody);
285 osmWriter.setChangeset(changeset);
286 osmWriter.header();
287 o.accept(osmWriter);
288 osmWriter.footer();
289 osmWriter.flush();
290 } catch (IOException e) {
291 Main.warn(e);
292 }
293 return swriter.toString();
294 }
295
296 /**
297 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
298 * @param s the changeset
299 * @return XML string
300 */
301 private String toXml(Changeset s) {
302 StringWriter swriter = new StringWriter();
303 try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
304 swriter.getBuffer().setLength(0);
305 osmWriter.header();
306 osmWriter.visit(s);
307 osmWriter.footer();
308 osmWriter.flush();
309 } catch (IOException e) {
310 Main.warn(e);
311 }
312 return swriter.toString();
313 }
314
315 private static String getBaseUrl(String serverUrl, String version) {
316 StringBuilder rv = new StringBuilder(serverUrl);
317 if (version != null) {
318 rv.append("/");
319 rv.append(version);
320 }
321 rv.append("/");
322 // this works around a ruby (or lighttpd) bug where two consecutive slashes in
323 // an URL will cause a "404 not found" response.
324 int p; while ((p = rv.indexOf("//", rv.indexOf("://")+2)) > -1) { rv.delete(p, p + 1); }
325 return rv.toString();
326 }
327
328 /**
329 * Returns the base URL for API requests, including the negotiated version number.
330 * @return base URL string
331 */
332 public String getBaseUrl() {
333 return getBaseUrl(serverUrl, version);
334 }
335
336 /**
337 * Creates an OSM primitive on the server. The OsmPrimitive object passed in
338 * is modified by giving it the server-assigned id.
339 *
340 * @param osm the primitive
341 * @param monitor the progress monitor
342 * @throws OsmTransferException if something goes wrong
343 */
344 public void createPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
345 String ret = "";
346 try {
347 ensureValidChangeset();
348 initialize(monitor);
349 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/create", toXml(osm, true),monitor);
350 osm.setOsmId(Long.parseLong(ret.trim()), 1);
351 osm.setChangesetId(getChangeset().getId());
352 } catch(NumberFormatException e){
353 throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret));
354 }
355 }
356
357 /**
358 * Modifies an OSM primitive on the server.
359 *
360 * @param osm the primitive. Must not be null.
361 * @param monitor the progress monitor
362 * @throws OsmTransferException if something goes wrong
363 */
364 public void modifyPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
365 String ret = null;
366 try {
367 ensureValidChangeset();
368 initialize(monitor);
369 // normal mode (0.6 and up) returns new object version.
370 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/" + osm.getId(), toXml(osm, true), monitor);
371 osm.setOsmId(osm.getId(), Integer.parseInt(ret.trim()));
372 osm.setChangesetId(getChangeset().getId());
373 osm.setVisible(true);
374 } catch(NumberFormatException e) {
375 throw new OsmTransferException(tr("Unexpected format of new version of modified primitive ''{0}''. Got ''{1}''.", osm.getId(), ret));
376 }
377 }
378
379 /**
380 * Deletes an OSM primitive on the server.
381 * @param osm the primitive
382 * @param monitor the progress monitor
383 * @throws OsmTransferException if something goes wrong
384 */
385 public void deletePrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
386 ensureValidChangeset();
387 initialize(monitor);
388 // can't use a the individual DELETE method in the 0.6 API. Java doesn't allow
389 // submitting a DELETE request with content, the 0.6 API requires it, however. Falling back
390 // to diff upload.
391 //
392 uploadDiff(Collections.singleton(osm), monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
393 }
394
395 /**
396 * Creates a new changeset based on the keys in <code>changeset</code>. If this
397 * method succeeds, changeset.getId() replies the id the server assigned to the new
398 * changeset
399 *
400 * The changeset must not be null, but its key/value-pairs may be empty.
401 *
402 * @param changeset the changeset toe be created. Must not be null.
403 * @param progressMonitor the progress monitor
404 * @throws OsmTransferException signifying a non-200 return code, or connection errors
405 * @throws IllegalArgumentException thrown if changeset is null
406 */
407 public void openChangeset(Changeset changeset, ProgressMonitor progressMonitor) throws OsmTransferException {
408 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
409 try {
410 progressMonitor.beginTask((tr("Creating changeset...")));
411 initialize(progressMonitor);
412 String ret = "";
413 try {
414 ret = sendRequest("PUT", "changeset/create", toXml(changeset),progressMonitor);
415 changeset.setId(Integer.parseInt(ret.trim()));
416 changeset.setOpen(true);
417 } catch(NumberFormatException e){
418 throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret));
419 }
420 progressMonitor.setCustomText((tr("Successfully opened changeset {0}",changeset.getId())));
421 } finally {
422 progressMonitor.finishTask();
423 }
424 }
425
426 /**
427 * Updates a changeset with the keys in <code>changesetUpdate</code>. The changeset must not
428 * be null and id &gt; 0 must be true.
429 *
430 * @param changeset the changeset to update. Must not be null.
431 * @param monitor the progress monitor. If null, uses the {@link NullProgressMonitor#INSTANCE}.
432 *
433 * @throws OsmTransferException if something goes wrong.
434 * @throws IllegalArgumentException if changeset is null
435 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
436 *
437 */
438 public void updateChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
439 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
440 if (monitor == null) {
441 monitor = NullProgressMonitor.INSTANCE;
442 }
443 if (changeset.getId() <= 0)
444 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
445 try {
446 monitor.beginTask(tr("Updating changeset..."));
447 initialize(monitor);
448 monitor.setCustomText(tr("Updating changeset {0}...", changeset.getId()));
449 sendRequest(
450 "PUT",
451 "changeset/" + changeset.getId(),
452 toXml(changeset),
453 monitor
454 );
455 } catch(ChangesetClosedException e) {
456 e.setSource(ChangesetClosedException.Source.UPDATE_CHANGESET);
457 throw e;
458 } catch(OsmApiException e) {
459 if (e.getResponseCode() == HttpURLConnection.HTTP_CONFLICT && ChangesetClosedException.errorHeaderMatchesPattern(e.getErrorHeader()))
460 throw new ChangesetClosedException(e.getErrorHeader(), ChangesetClosedException.Source.UPDATE_CHANGESET);
461 throw e;
462 } finally {
463 monitor.finishTask();
464 }
465 }
466
467 /**
468 * Closes a changeset on the server. Sets changeset.setOpen(false) if this operation succeeds.
469 *
470 * @param changeset the changeset to be closed. Must not be null. changeset.getId() &gt; 0 required.
471 * @param monitor the progress monitor. If null, uses {@link NullProgressMonitor#INSTANCE}
472 *
473 * @throws OsmTransferException if something goes wrong.
474 * @throws IllegalArgumentException thrown if changeset is null
475 * @throws IllegalArgumentException thrown if changeset.getId() &lt;= 0
476 */
477 public void closeChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
478 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
479 if (monitor == null) {
480 monitor = NullProgressMonitor.INSTANCE;
481 }
482 if (changeset.getId() <= 0)
483 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
484 try {
485 monitor.beginTask(tr("Closing changeset..."));
486 initialize(monitor);
487 /* send "\r\n" instead of empty string, so we don't send zero payload - works around bugs
488 in proxy software */
489 sendRequest("PUT", "changeset" + "/" + changeset.getId() + "/close", "\r\n", monitor);
490 changeset.setOpen(false);
491 } finally {
492 monitor.finishTask();
493 }
494 }
495
496 /**
497 * Uploads a list of changes in "diff" form to the server.
498 *
499 * @param list the list of changed OSM Primitives
500 * @param monitor the progress monitor
501 * @return list of processed primitives
502 * @throws OsmTransferException if something is wrong
503 */
504 public Collection<IPrimitive> uploadDiff(Collection<? extends IPrimitive> list, ProgressMonitor monitor) throws OsmTransferException {
505 try {
506 monitor.beginTask("", list.size() * 2);
507 if (changeset == null)
508 throw new OsmTransferException(tr("No changeset present for diff upload."));
509
510 initialize(monitor);
511
512 // prepare upload request
513 //
514 OsmChangeBuilder changeBuilder = new OsmChangeBuilder(changeset);
515 monitor.subTask(tr("Preparing upload request..."));
516 changeBuilder.start();
517 changeBuilder.append(list);
518 changeBuilder.finish();
519 String diffUploadRequest = changeBuilder.getDocument();
520
521 // Upload to the server
522 //
523 monitor.indeterminateSubTask(
524 trn("Uploading {0} object...", "Uploading {0} objects...", list.size(), list.size()));
525 String diffUploadResponse = sendRequest("POST", "changeset/" + changeset.getId() + "/upload", diffUploadRequest,monitor);
526
527 // Process the response from the server
528 //
529 DiffResultProcessor reader = new DiffResultProcessor(list);
530 reader.parse(diffUploadResponse, monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
531 return reader.postProcess(
532 getChangeset(),
533 monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)
534 );
535 } catch(OsmTransferException e) {
536 throw e;
537 } catch(XmlParsingException e) {
538 throw new OsmTransferException(e);
539 } finally {
540 monitor.finishTask();
541 }
542 }
543
544 private void sleepAndListen(int retry, ProgressMonitor monitor) throws OsmTransferCanceledException {
545 Main.info(tr("Waiting 10 seconds ... "));
546 for (int i=0; i < 10; i++) {
547 if (monitor != null) {
548 monitor.setCustomText(tr("Starting retry {0} of {1} in {2} seconds ...", getMaxRetries() - retry,getMaxRetries(), 10-i));
549 }
550 if (cancel)
551 throw new OsmTransferCanceledException();
552 try {
553 Thread.sleep(1000);
554 } catch (InterruptedException ex) {
555 Main.warn("InterruptedException in "+getClass().getSimpleName()+" during sleep");
556 }
557 }
558 Main.info(tr("OK - trying again."));
559 }
560
561 /**
562 * Replies the max. number of retries in case of 5XX errors on the server
563 *
564 * @return the max number of retries
565 */
566 protected int getMaxRetries() {
567 int ret = Main.pref.getInteger("osm-server.max-num-retries", DEFAULT_MAX_NUM_RETRIES);
568 return Math.max(ret,0);
569 }
570
571 /**
572 * Determines if JOSM is configured to access OSM API via OAuth
573 * @return {@code true} if JOSM is configured to access OSM API via OAuth, {@code false} otherwise
574 * @since 6349
575 */
576 public static final boolean isUsingOAuth() {
577 return "oauth".equals(Main.pref.get("osm-server.auth-method", "basic"));
578 }
579
580 protected final String sendRequest(String requestMethod, String urlSuffix,String requestBody, ProgressMonitor monitor) throws OsmTransferException {
581 return sendRequest(requestMethod, urlSuffix, requestBody, monitor, true, false);
582 }
583
584 /**
585 * Generic method for sending requests to the OSM API.
586 *
587 * This method will automatically re-try any requests that are answered with a 5xx
588 * error code, or that resulted in a timeout exception from the TCP layer.
589 *
590 * @param requestMethod The http method used when talking with the server.
591 * @param urlSuffix The suffix to add at the server url, not including the version number,
592 * but including any object ids (e.g. "/way/1234/history").
593 * @param requestBody the body of the HTTP request, if any.
594 * @param monitor the progress monitor
595 * @param doAuthenticate set to true, if the request sent to the server shall include authentication
596 * credentials;
597 * @param fastFail true to request a short timeout
598 *
599 * @return the body of the HTTP response, if and only if the response code was "200 OK".
600 * @throws OsmTransferException if the HTTP return code was not 200 (and retries have
601 * been exhausted), or rewrapping a Java exception.
602 */
603 protected final String sendRequest(String requestMethod, String urlSuffix,String requestBody, ProgressMonitor monitor, boolean doAuthenticate, boolean fastFail) throws OsmTransferException {
604 StringBuilder responseBody = new StringBuilder();
605 int retries = fastFail ? 0 : getMaxRetries();
606
607 while(true) { // the retry loop
608 try {
609 url = new URL(new URL(getBaseUrl()), urlSuffix);
610 Main.info(requestMethod + " " + url + "... ");
611 Main.debug(requestBody);
612 // fix #5369, see http://www.tikalk.com/java/forums/httpurlconnection-disable-keep-alive
613 activeConnection = Utils.openHttpConnection(url, false);
614 activeConnection.setConnectTimeout(fastFail ? 1000 : Main.pref.getInteger("socket.timeout.connect",15)*1000);
615 if (fastFail) {
616 activeConnection.setReadTimeout(1000);
617 }
618 activeConnection.setRequestMethod(requestMethod);
619 if (doAuthenticate) {
620 addAuth(activeConnection);
621 }
622
623 if ("PUT".equals(requestMethod) || "POST".equals(requestMethod) || "DELETE".equals(requestMethod)) {
624 activeConnection.setDoOutput(true);
625 activeConnection.setRequestProperty("Content-type", "text/xml");
626 try (OutputStream out = activeConnection.getOutputStream()) {
627 // It seems that certain bits of the Ruby API are very unhappy upon
628 // receipt of a PUT/POST message without a Content-length header,
629 // even if the request has no payload.
630 // Since Java will not generate a Content-length header unless
631 // we use the output stream, we create an output stream for PUT/POST
632 // even if there is no payload.
633 if (requestBody != null) {
634 try (BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) {
635 bwr.write(requestBody);
636 bwr.flush();
637 }
638 }
639 }
640 }
641
642 activeConnection.connect();
643 Main.info(activeConnection.getResponseMessage());
644 int retCode = activeConnection.getResponseCode();
645
646 if (retCode >= 500) {
647 if (retries-- > 0) {
648 sleepAndListen(retries, monitor);
649 Main.info(tr("Starting retry {0} of {1}.", getMaxRetries() - retries,getMaxRetries()));
650 continue;
651 }
652 }
653
654 // populate return fields.
655 responseBody.setLength(0);
656
657 // If the API returned an error code like 403 forbidden, getInputStream
658 // will fail with an IOException.
659 InputStream i = getConnectionStream();
660 if (i != null) {
661 // the input stream can be null if both the input and the error stream
662 // are null. Seems to be the case if the OSM server replies a 401
663 // Unauthorized, see #3887.
664 //
665 String s;
666 try (BufferedReader in = new BufferedReader(new InputStreamReader(i, StandardCharsets.UTF_8))) {
667 while((s = in.readLine()) != null) {
668 responseBody.append(s);
669 responseBody.append("\n");
670 }
671 }
672 }
673 String errorHeader = null;
674 // Look for a detailed error message from the server
675 if (activeConnection.getHeaderField("Error") != null) {
676 errorHeader = activeConnection.getHeaderField("Error");
677 Main.error("Error header: " + errorHeader);
678 } else if (retCode != HttpURLConnection.HTTP_OK && responseBody.length()>0) {
679 Main.error("Error body: " + responseBody);
680 }
681 activeConnection.disconnect();
682
683 if (Main.isDebugEnabled()) {
684 Main.debug("RESPONSE: "+ activeConnection.getHeaderFields());
685 }
686
687 errorHeader = errorHeader == null? null : errorHeader.trim();
688 String errorBody = responseBody.length() == 0? null : responseBody.toString().trim();
689 switch(retCode) {
690 case HttpURLConnection.HTTP_OK:
691 return responseBody.toString();
692 case HttpURLConnection.HTTP_GONE:
693 throw new OsmApiPrimitiveGoneException(errorHeader, errorBody);
694 case HttpURLConnection.HTTP_CONFLICT:
695 if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
696 throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA);
697 else
698 throw new OsmApiException(retCode, errorHeader, errorBody);
699 case HttpURLConnection.HTTP_FORBIDDEN:
700 OsmApiException e = new OsmApiException(retCode, errorHeader, errorBody);
701 e.setAccessedUrl(activeConnection.getURL().toString());
702 throw e;
703 default:
704 throw new OsmApiException(retCode, errorHeader, errorBody);
705 }
706 } catch (SocketTimeoutException | ConnectException e) {
707 if (retries-- > 0) {
708 continue;
709 }
710 throw new OsmTransferException(e);
711 } catch(IOException e) {
712 throw new OsmTransferException(e);
713 } catch(OsmTransferException e) {
714 throw e;
715 }
716 }
717 }
718
719 private InputStream getConnectionStream() {
720 try {
721 return activeConnection.getInputStream();
722 } catch (IOException ioe) {
723 Main.warn(ioe);
724 return activeConnection.getErrorStream();
725 }
726 }
727
728 /**
729 * Replies the API capabilities.
730 *
731 * @return the API capabilities, or null, if the API is not initialized yet
732 */
733 public Capabilities getCapabilities() {
734 return capabilities;
735 }
736
737 /**
738 * Ensures that the current changeset can be used for uploading data
739 *
740 * @throws OsmTransferException thrown if the current changeset can't be used for
741 * uploading data
742 */
743 protected void ensureValidChangeset() throws OsmTransferException {
744 if (changeset == null)
745 throw new OsmTransferException(tr("Current changeset is null. Cannot upload data."));
746 if (changeset.getId() <= 0)
747 throw new OsmTransferException(tr("ID of current changeset > 0 required. Current ID is {0}.", changeset.getId()));
748 }
749
750 /**
751 * Replies the changeset data uploads are currently directed to
752 *
753 * @return the changeset data uploads are currently directed to
754 */
755 public Changeset getChangeset() {
756 return changeset;
757 }
758
759 /**
760 * Sets the changesets to which further data uploads are directed. The changeset
761 * can be null. If it isn't null it must have been created, i.e. id &gt; 0 is required. Furthermore,
762 * it must be open.
763 *
764 * @param changeset the changeset
765 * @throws IllegalArgumentException thrown if changeset.getId() &lt;= 0
766 * @throws IllegalArgumentException thrown if !changeset.isOpen()
767 */
768 public void setChangeset(Changeset changeset) {
769 if (changeset == null) {
770 this.changeset = null;
771 return;
772 }
773 if (changeset.getId() <= 0)
774 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
775 if (!changeset.isOpen())
776 throw new IllegalArgumentException(tr("Open changeset expected. Got closed changeset with id {0}.", changeset.getId()));
777 this.changeset = changeset;
778 }
779}
Note: See TracBrowser for help on using the repository browser.