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

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

see #9710 - more debug messages

  • 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.net.UnknownHostException;
23import java.util.Collection;
24import java.util.Collections;
25import java.util.HashMap;
26import java.util.Map;
27
28import javax.xml.parsers.ParserConfigurationException;
29import javax.xml.parsers.SAXParserFactory;
30
31import org.openstreetmap.josm.Main;
32import org.openstreetmap.josm.data.osm.Changeset;
33import org.openstreetmap.josm.data.osm.IPrimitive;
34import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
35import org.openstreetmap.josm.gui.layer.ImageryLayer;
36import org.openstreetmap.josm.gui.layer.Layer;
37import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
38import org.openstreetmap.josm.gui.progress.ProgressMonitor;
39import org.openstreetmap.josm.tools.CheckParameterUtil;
40import org.openstreetmap.josm.tools.Utils;
41import org.xml.sax.Attributes;
42import org.xml.sax.InputSource;
43import org.xml.sax.SAXException;
44import org.xml.sax.SAXParseException;
45import org.xml.sax.helpers.DefaultHandler;
46
47/**
48 * Class that encapsulates the communications with the <a href="http://wiki.openstreetmap.org/wiki/API_v0.6">OSM API</a>.<br><br>
49 *
50 * All interaction with the server-side OSM API should go through this class.<br><br>
51 *
52 * It is conceivable to extract this into an interface later and create various
53 * classes implementing the interface, to be able to talk to various kinds of servers.
54 *
55 */
56public class OsmApi extends OsmConnection {
57
58 /**
59 * Maximum number of retries to send a request in case of HTTP 500 errors or timeouts
60 */
61 static public final int DEFAULT_MAX_NUM_RETRIES = 5;
62
63 /**
64 * Maximum number of concurrent download threads, imposed by
65 * <a href="http://wiki.openstreetmap.org/wiki/API_usage_policy#Technical_Usage_Requirements">
66 * OSM API usage policy.</a>
67 * @since 5386
68 */
69 static public final int MAX_DOWNLOAD_THREADS = 2;
70
71 /**
72 * Default URL of the standard OSM API.
73 * @since 5422
74 */
75 static public final String DEFAULT_API_URL = "http://api.openstreetmap.org/api";
76
77 // The collection of instantiated OSM APIs
78 private static Map<String, OsmApi> instances = new HashMap<String, OsmApi>();
79
80 private URL url = null;
81
82 /**
83 * Replies the {@link OsmApi} for a given server URL
84 *
85 * @param serverUrl the server URL
86 * @return the OsmApi
87 * @throws IllegalArgumentException thrown, if serverUrl is null
88 *
89 */
90 static public OsmApi getOsmApi(String serverUrl) {
91 OsmApi api = instances.get(serverUrl);
92 if (api == null) {
93 api = new OsmApi(serverUrl);
94 instances.put(serverUrl,api);
95 }
96 return api;
97 }
98
99 /**
100 * Replies the {@link OsmApi} for the URL given by the preference <code>osm-server.url</code>
101 *
102 * @return the OsmApi
103 */
104 static public OsmApi getOsmApi() {
105 String serverUrl = Main.pref.get("osm-server.url", DEFAULT_API_URL);
106 return getOsmApi(serverUrl);
107 }
108
109 /** the server URL */
110 private String serverUrl;
111
112 /**
113 * Object describing current changeset
114 */
115 private Changeset changeset;
116
117 /**
118 * API version used for server communications
119 */
120 private String version = null;
121
122 /** the api capabilities */
123 private Capabilities capabilities = new Capabilities();
124
125 /**
126 * true if successfully initialized
127 */
128 private boolean initialized = false;
129
130 /**
131 * A parser for the "capabilities" response XML
132 */
133 private class CapabilitiesParser extends DefaultHandler {
134 @Override
135 public void startDocument() throws SAXException {
136 capabilities.clear();
137 }
138
139 @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
140 for (int i=0; i< atts.getLength(); i++) {
141 capabilities.put(qName, atts.getQName(i), atts.getValue(i));
142 }
143 }
144 }
145
146 /**
147 * creates an OSM api for a specific server URL
148 *
149 * @param serverUrl the server URL. Must not be null
150 * @throws IllegalArgumentException thrown, if serverUrl is null
151 */
152 protected OsmApi(String serverUrl) {
153 CheckParameterUtil.ensureParameterNotNull(serverUrl, "serverUrl");
154 this.serverUrl = serverUrl;
155 }
156
157 /**
158 * Replies the OSM protocol version we use to talk to the server.
159 * @return protocol version, or null if not yet negotiated.
160 */
161 public String getVersion() {
162 return version;
163 }
164
165 /**
166 * Replies the host name of the server URL.
167 * @return the host name of the server URL, or null if the server URL is malformed.
168 */
169 public String getHost() {
170 String host = null;
171 try {
172 host = (new URL(serverUrl)).getHost();
173 } catch (MalformedURLException e) {
174 Main.warn(e);
175 }
176 return host;
177 }
178
179 private class CapabilitiesCache extends CacheCustomContent<OsmTransferException> {
180
181 ProgressMonitor monitor;
182 boolean fastFail;
183
184 public CapabilitiesCache(ProgressMonitor monitor, boolean fastFail) {
185 super("capabilities" + getBaseUrl().hashCode(), CacheCustomContent.INTERVAL_WEEKLY);
186 this.monitor = monitor;
187 this.fastFail = fastFail;
188 }
189
190 @Override
191 protected byte[] updateData() throws OsmTransferException {
192 return sendRequest("GET", "capabilities", null, monitor, false, fastFail).getBytes();
193 }
194 }
195
196 /**
197 * Initializes this component by negotiating a protocol version with the server.
198 *
199 * @param monitor the progress monitor
200 * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
201 * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
202 */
203 public void initialize(ProgressMonitor monitor) throws OsmTransferCanceledException, OsmApiInitializationException {
204 initialize(monitor, false);
205 }
206
207 /**
208 * Initializes this component by negotiating a protocol version with the server, with the ability to control the timeout.
209 *
210 * @param monitor the progress monitor
211 * @param fastFail true to request quick initialisation with a small timeout (more likely to throw exception)
212 * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
213 * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
214 */
215 public void initialize(ProgressMonitor monitor, boolean fastFail) throws OsmTransferCanceledException, OsmApiInitializationException {
216 if (initialized)
217 return;
218 cancel = false;
219 try {
220 CapabilitiesCache cache = new CapabilitiesCache(monitor, fastFail);
221 try {
222 initializeCapabilities(cache.updateIfRequiredString());
223 } catch (SAXParseException parseException) {
224 // XML parsing may fail if JOSM previously stored a corrupted capabilities document (see #8278)
225 // In that case, force update and try again
226 initializeCapabilities(cache.updateForceString());
227 }
228 if (capabilities.supportsVersion("0.6")) {
229 version = "0.6";
230 } else {
231 Main.error(tr("This version of JOSM is incompatible with the configured server."));
232 Main.error(tr("It supports protocol version 0.6, while the server says it supports {0} to {1}.",
233 capabilities.get("version", "minimum"), capabilities.get("version", "maximum")));
234 initialized = false; // FIXME gets overridden by next assignment
235 }
236 initialized = true;
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 {
246 capabilities.put("blacklist", "regex", ".*\\.google\\.com/.*");
247 capabilities.put("blacklist", "regex", ".*209\\.85\\.2\\d\\d.*");
248 capabilities.put("blacklist", "regex", ".*209\\.85\\.1[3-9]\\d.*");
249 capabilities.put("blacklist", "regex", ".*209\\.85\\.12[89].*");
250 }
251
252 /* This checks if there are any layers currently displayed that
253 * are now on the blacklist, and removes them. This is a rare
254 * situation - probably only occurs if the user changes the API URL
255 * in the preferences menu. Otherwise they would not have been able
256 * to load the layers in the first place becuase they would have
257 * been disabled! */
258 if (Main.isDisplayingMapView()) {
259 for (Layer l : Main.map.mapView.getLayersOfType(ImageryLayer.class)) {
260 if (((ImageryLayer) l).getInfo().isBlacklisted()) {
261 Main.info(tr("Removed layer {0} because it is not allowed by the configured API.", l.getName()));
262 Main.main.removeLayer(l);
263 }
264 }
265 }
266
267 } catch (OsmTransferCanceledException e) {
268 throw e;
269 } catch (OsmTransferException e) {
270 initialized = false;
271 Main.addNetworkError(url, Utils.getRootCause(e));
272 throw new OsmApiInitializationException(e);
273 } catch (Exception e) {
274 initialized = false;
275 throw new OsmApiInitializationException(e);
276 }
277 }
278
279 private void initializeCapabilities(String xml) throws SAXException, IOException, ParserConfigurationException {
280 InputSource inputSource = new InputSource(new StringReader(xml));
281 SAXParserFactory.newInstance().newSAXParser().parse(inputSource, new CapabilitiesParser());
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 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 return swriter.toString();
301 }
302
303 /**
304 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
305 * @param s the changeset
306 * @return XML string
307 */
308 private String toXml(Changeset s) {
309 StringWriter swriter = new StringWriter();
310 OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version);
311 swriter.getBuffer().setLength(0);
312 osmWriter.header();
313 osmWriter.visit(s);
314 osmWriter.footer();
315 osmWriter.flush();
316 return swriter.toString();
317 }
318
319 /**
320 * Returns the base URL for API requests, including the negotiated version number.
321 * @return base URL string
322 */
323 public String getBaseUrl() {
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; while ((p = rv.indexOf("//", rv.indexOf("://")+2)) > -1) { rv.delete(p, p + 1); }
333 return rv.toString();
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(OsmDataParsingException 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 private 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 private 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 // fix #5369, see http://www.tikalk.com/java/forums/httpurlconnection-disable-keep-alive
612 activeConnection = Utils.openHttpConnection(url, false);
613 activeConnection.setConnectTimeout(fastFail ? 1000 : Main.pref.getInteger("socket.timeout.connect",15)*1000);
614 if (fastFail) {
615 activeConnection.setReadTimeout(1000);
616 }
617 activeConnection.setRequestMethod(requestMethod);
618 if (doAuthenticate) {
619 addAuth(activeConnection);
620 }
621
622 if (requestMethod.equals("PUT") || requestMethod.equals("POST") || requestMethod.equals("DELETE")) {
623 activeConnection.setDoOutput(true);
624 activeConnection.setRequestProperty("Content-type", "text/xml");
625 OutputStream out = activeConnection.getOutputStream();
626
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 BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, Utils.UTF_8));
635 try {
636 bwr.write(requestBody);
637 bwr.flush();
638 } finally {
639 bwr.close();
640 }
641 }
642 Utils.close(out);
643 }
644
645 activeConnection.connect();
646 Main.info(activeConnection.getResponseMessage());
647 int retCode = activeConnection.getResponseCode();
648
649 if (retCode >= 500) {
650 if (retries-- > 0) {
651 sleepAndListen(retries, monitor);
652 Main.info(tr("Starting retry {0} of {1}.", getMaxRetries() - retries,getMaxRetries()));
653 continue;
654 }
655 }
656
657 // populate return fields.
658 responseBody.setLength(0);
659
660 // If the API returned an error code like 403 forbidden, getInputStream
661 // will fail with an IOException.
662 InputStream i = null;
663 try {
664 i = activeConnection.getInputStream();
665 } catch (IOException ioe) {
666 i = activeConnection.getErrorStream();
667 }
668 if (i != null) {
669 // the input stream can be null if both the input and the error stream
670 // are null. Seems to be the case if the OSM server replies a 401
671 // Unauthorized, see #3887.
672 //
673 BufferedReader in = new BufferedReader(new InputStreamReader(i));
674 String s;
675 try {
676 while((s = in.readLine()) != null) {
677 responseBody.append(s);
678 responseBody.append("\n");
679 }
680 } finally {
681 in.close();
682 }
683 }
684 String errorHeader = null;
685 // Look for a detailed error message from the server
686 if (activeConnection.getHeaderField("Error") != null) {
687 errorHeader = activeConnection.getHeaderField("Error");
688 Main.error("Error header: " + errorHeader);
689 } else if (retCode != HttpURLConnection.HTTP_OK && responseBody.length()>0) {
690 Main.error("Error body: " + responseBody);
691 }
692 activeConnection.disconnect();
693
694 if (Main.isDebugEnabled()) {
695 Main.debug("RESPONSE: "+ activeConnection.getHeaderFields());
696 }
697
698 errorHeader = errorHeader == null? null : errorHeader.trim();
699 String errorBody = responseBody.length() == 0? null : responseBody.toString().trim();
700 switch(retCode) {
701 case HttpURLConnection.HTTP_OK:
702 return responseBody.toString();
703 case HttpURLConnection.HTTP_GONE:
704 throw new OsmApiPrimitiveGoneException(errorHeader, errorBody);
705 case HttpURLConnection.HTTP_CONFLICT:
706 if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
707 throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA);
708 else
709 throw new OsmApiException(retCode, errorHeader, errorBody);
710 case HttpURLConnection.HTTP_FORBIDDEN:
711 OsmApiException e = new OsmApiException(retCode, errorHeader, errorBody);
712 e.setAccessedUrl(activeConnection.getURL().toString());
713 throw e;
714 default:
715 throw new OsmApiException(retCode, errorHeader, errorBody);
716 }
717 } catch (UnknownHostException e) {
718 throw new OsmTransferException(e);
719 } catch (SocketTimeoutException e) {
720 if (retries-- > 0) {
721 continue;
722 }
723 throw new OsmTransferException(e);
724 } catch (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(OsmTransferCanceledException e) {
732 throw e;
733 } catch(OsmTransferException e) {
734 throw e;
735 }
736 }
737 }
738
739 /**
740 * Replies the API capabilities
741 *
742 * @return the API capabilities, or null, if the API is not initialized yet
743 */
744 public Capabilities getCapabilities() {
745 return capabilities;
746 }
747
748 /**
749 * Ensures that the current changeset can be used for uploading data
750 *
751 * @throws OsmTransferException thrown if the current changeset can't be used for
752 * uploading data
753 */
754 protected void ensureValidChangeset() throws OsmTransferException {
755 if (changeset == null)
756 throw new OsmTransferException(tr("Current changeset is null. Cannot upload data."));
757 if (changeset.getId() <= 0)
758 throw new OsmTransferException(tr("ID of current changeset > 0 required. Current ID is {0}.", changeset.getId()));
759 }
760
761 /**
762 * Replies the changeset data uploads are currently directed to
763 *
764 * @return the changeset data uploads are currently directed to
765 */
766 public Changeset getChangeset() {
767 return changeset;
768 }
769
770 /**
771 * Sets the changesets to which further data uploads are directed. The changeset
772 * can be null. If it isn't null it must have been created, i.e. id &gt; 0 is required. Furthermore,
773 * it must be open.
774 *
775 * @param changeset the changeset
776 * @throws IllegalArgumentException thrown if changeset.getId() &lt;= 0
777 * @throws IllegalArgumentException thrown if !changeset.isOpen()
778 */
779 public void setChangeset(Changeset changeset) {
780 if (changeset == null) {
781 this.changeset = null;
782 return;
783 }
784 if (changeset.getId() <= 0)
785 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
786 if (!changeset.isOpen())
787 throw new IllegalArgumentException(tr("Open changeset expected. Got closed changeset with id {0}.", changeset.getId()));
788 this.changeset = changeset;
789 }
790}
Note: See TracBrowser for help on using the repository browser.