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

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

fix #9906 - fix reliance on default encoding

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