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

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

fix #8799 - Follow conventional visitor design pattern by renaming visit(Visitor) to accept(Visitor)

  • Property svn:eol-style set to native
File size: 31.9 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;
26
27import javax.xml.parsers.ParserConfigurationException;
28import javax.xml.parsers.SAXParserFactory;
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.tools.CheckParameterUtil;
39import org.openstreetmap.josm.tools.Utils;
40import org.xml.sax.Attributes;
41import org.xml.sax.InputSource;
42import org.xml.sax.SAXException;
43import org.xml.sax.SAXParseException;
44import org.xml.sax.helpers.DefaultHandler;
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 static public 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 static public final int MAX_DOWNLOAD_THREADS = 2;
69
70 /**
71 * Default URL of the standard OSM API.
72 * @since 5422
73 */
74 static public final String DEFAULT_API_URL = "http://api.openstreetmap.org/api";
75
76 // The collection of instantiated OSM APIs
77 private static HashMap<String, OsmApi> instances = new HashMap<String, OsmApi>();
78
79 /**
80 * Replies the {@link OsmApi} for a given server URL
81 *
82 * @param serverUrl the server URL
83 * @return the OsmApi
84 * @throws IllegalArgumentException thrown, if serverUrl is null
85 *
86 */
87 static public OsmApi getOsmApi(String serverUrl) {
88 OsmApi api = instances.get(serverUrl);
89 if (api == null) {
90 api = new OsmApi(serverUrl);
91 instances.put(serverUrl,api);
92 }
93 return api;
94 }
95
96 /**
97 * Replies the {@link OsmApi} for the URL given by the preference <code>osm-server.url</code>
98 *
99 * @return the OsmApi
100 * @throws IllegalStateException thrown, if the preference <code>osm-server.url</code> is not set
101 *
102 */
103 static public OsmApi getOsmApi() {
104 String serverUrl = Main.pref.get("osm-server.url", DEFAULT_API_URL);
105 if (serverUrl == null)
106 throw new IllegalStateException(tr("Preference ''{0}'' missing. Cannot initialize OsmApi.", "osm-server.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 }
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 System.err.println(tr("This version of JOSM is incompatible with the configured server."));
232 System.err.println(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 (this.serverUrl.matches(".*openstreetmap.org/api.*") && capabilities.getImageryBlacklist().isEmpty())
242 {
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 becuase 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 System.out.println(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 (Exception e) {
267 initialized = false;
268 throw new OsmApiInitializationException(e);
269 }
270 }
271
272 private void initializeCapabilities(String xml) throws SAXException, IOException, ParserConfigurationException {
273 InputSource inputSource = new InputSource(new StringReader(xml));
274 SAXParserFactory.newInstance().newSAXParser().parse(inputSource, new CapabilitiesParser());
275 }
276
277 /**
278 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
279 * @param o the OSM primitive
280 * @param addBody true to generate the full XML, false to only generate the encapsulating tag
281 * @return XML string
282 */
283 private String toXml(IPrimitive o, boolean addBody) {
284 StringWriter swriter = new StringWriter();
285 OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version);
286 swriter.getBuffer().setLength(0);
287 osmWriter.setWithBody(addBody);
288 osmWriter.setChangeset(changeset);
289 osmWriter.header();
290 o.accept(osmWriter);
291 osmWriter.footer();
292 osmWriter.flush();
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 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 return swriter.toString();
310 }
311
312 /**
313 * Returns the base URL for API requests, including the negotiated version number.
314 * @return base URL string
315 */
316 public String getBaseUrl() {
317 StringBuffer rv = new StringBuffer(serverUrl);
318 if (version != null) {
319 rv.append("/");
320 rv.append(version);
321 }
322 rv.append("/");
323 // this works around a ruby (or lighttpd) bug where two consecutive slashes in
324 // an URL will cause a "404 not found" response.
325 int p; while ((p = rv.indexOf("//", 6)) > -1) { rv.delete(p, p + 1); }
326 return rv.toString();
327 }
328
329 /**
330 * Creates an OSM primitive on the server. The OsmPrimitive object passed in
331 * is modified by giving it the server-assigned id.
332 *
333 * @param osm the primitive
334 * @param monitor the progress monitor
335 * @throws OsmTransferException if something goes wrong
336 */
337 public void createPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
338 String ret = "";
339 try {
340 ensureValidChangeset();
341 initialize(monitor);
342 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/create", toXml(osm, true),monitor);
343 osm.setOsmId(Long.parseLong(ret.trim()), 1);
344 osm.setChangesetId(getChangeset().getId());
345 } catch(NumberFormatException e){
346 throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret));
347 }
348 }
349
350 /**
351 * Modifies an OSM primitive on the server.
352 *
353 * @param osm the primitive. Must not be null.
354 * @param monitor the progress monitor
355 * @throws OsmTransferException if something goes wrong
356 */
357 public void modifyPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
358 String ret = null;
359 try {
360 ensureValidChangeset();
361 initialize(monitor);
362 // normal mode (0.6 and up) returns new object version.
363 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/" + osm.getId(), toXml(osm, true), monitor);
364 osm.setOsmId(osm.getId(), Integer.parseInt(ret.trim()));
365 osm.setChangesetId(getChangeset().getId());
366 osm.setVisible(true);
367 } catch(NumberFormatException e) {
368 throw new OsmTransferException(tr("Unexpected format of new version of modified primitive ''{0}''. Got ''{1}''.", osm.getId(), ret));
369 }
370 }
371
372 /**
373 * Deletes an OSM primitive on the server.
374 * @param osm the primitive
375 * @param monitor the progress monitor
376 * @throws OsmTransferException if something goes wrong
377 */
378 public void deletePrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
379 ensureValidChangeset();
380 initialize(monitor);
381 // can't use a the individual DELETE method in the 0.6 API. Java doesn't allow
382 // submitting a DELETE request with content, the 0.6 API requires it, however. Falling back
383 // to diff upload.
384 //
385 uploadDiff(Collections.singleton(osm), monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
386 }
387
388 /**
389 * Creates a new changeset based on the keys in <code>changeset</code>. If this
390 * method succeeds, changeset.getId() replies the id the server assigned to the new
391 * changeset
392 *
393 * The changeset must not be null, but its key/value-pairs may be empty.
394 *
395 * @param changeset the changeset toe be created. Must not be null.
396 * @param progressMonitor the progress monitor
397 * @throws OsmTransferException signifying a non-200 return code, or connection errors
398 * @throws IllegalArgumentException thrown if changeset is null
399 */
400 public void openChangeset(Changeset changeset, ProgressMonitor progressMonitor) throws OsmTransferException {
401 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
402 try {
403 progressMonitor.beginTask((tr("Creating changeset...")));
404 initialize(progressMonitor);
405 String ret = "";
406 try {
407 ret = sendRequest("PUT", "changeset/create", toXml(changeset),progressMonitor);
408 changeset.setId(Integer.parseInt(ret.trim()));
409 changeset.setOpen(true);
410 } catch(NumberFormatException e){
411 throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret));
412 }
413 progressMonitor.setCustomText((tr("Successfully opened changeset {0}",changeset.getId())));
414 } finally {
415 progressMonitor.finishTask();
416 }
417 }
418
419 /**
420 * Updates a changeset with the keys in <code>changesetUpdate</code>. The changeset must not
421 * be null and id > 0 must be true.
422 *
423 * @param changeset the changeset to update. Must not be null.
424 * @param monitor the progress monitor. If null, uses the {@link NullProgressMonitor#INSTANCE}.
425 *
426 * @throws OsmTransferException if something goes wrong.
427 * @throws IllegalArgumentException if changeset is null
428 * @throws IllegalArgumentException if changeset.getId() <= 0
429 *
430 */
431 public void updateChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
432 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
433 if (monitor == null) {
434 monitor = NullProgressMonitor.INSTANCE;
435 }
436 if (changeset.getId() <= 0)
437 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
438 try {
439 monitor.beginTask(tr("Updating changeset..."));
440 initialize(monitor);
441 monitor.setCustomText(tr("Updating changeset {0}...", changeset.getId()));
442 sendRequest(
443 "PUT",
444 "changeset/" + changeset.getId(),
445 toXml(changeset),
446 monitor
447 );
448 } catch(ChangesetClosedException e) {
449 e.setSource(ChangesetClosedException.Source.UPDATE_CHANGESET);
450 throw e;
451 } catch(OsmApiException e) {
452 if (e.getResponseCode() == HttpURLConnection.HTTP_CONFLICT && ChangesetClosedException.errorHeaderMatchesPattern(e.getErrorHeader()))
453 throw new ChangesetClosedException(e.getErrorHeader(), ChangesetClosedException.Source.UPDATE_CHANGESET);
454 throw e;
455 } finally {
456 monitor.finishTask();
457 }
458 }
459
460 /**
461 * Closes a changeset on the server. Sets changeset.setOpen(false) if this operation
462 * succeeds.
463 *
464 * @param changeset the changeset to be closed. Must not be null. changeset.getId() > 0 required.
465 * @param monitor the progress monitor. If null, uses {@link NullProgressMonitor#INSTANCE}
466 *
467 * @throws OsmTransferException if something goes wrong.
468 * @throws IllegalArgumentException thrown if changeset is null
469 * @throws IllegalArgumentException thrown if changeset.getId() <= 0
470 */
471 public void closeChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
472 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
473 if (monitor == null) {
474 monitor = NullProgressMonitor.INSTANCE;
475 }
476 if (changeset.getId() <= 0)
477 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
478 try {
479 monitor.beginTask(tr("Closing changeset..."));
480 initialize(monitor);
481 /* send "\r\n" instead of empty string, so we don't send zero payload - works around bugs
482 in proxy software */
483 sendRequest("PUT", "changeset" + "/" + changeset.getId() + "/close", "\r\n", monitor);
484 changeset.setOpen(false);
485 } finally {
486 monitor.finishTask();
487 }
488 }
489
490 /**
491 * Uploads a list of changes in "diff" form to the server.
492 *
493 * @param list the list of changed OSM Primitives
494 * @param monitor the progress monitor
495 * @return list of processed primitives
496 * @throws OsmTransferException if something is wrong
497 */
498 public Collection<IPrimitive> uploadDiff(Collection<? extends IPrimitive> list, ProgressMonitor monitor) throws OsmTransferException {
499 try {
500 monitor.beginTask("", list.size() * 2);
501 if (changeset == null)
502 throw new OsmTransferException(tr("No changeset present for diff upload."));
503
504 initialize(monitor);
505
506 // prepare upload request
507 //
508 OsmChangeBuilder changeBuilder = new OsmChangeBuilder(changeset);
509 monitor.subTask(tr("Preparing upload request..."));
510 changeBuilder.start();
511 changeBuilder.append(list);
512 changeBuilder.finish();
513 String diffUploadRequest = changeBuilder.getDocument();
514
515 // Upload to the server
516 //
517 monitor.indeterminateSubTask(
518 trn("Uploading {0} object...", "Uploading {0} objects...", list.size(), list.size()));
519 String diffUploadResponse = sendRequest("POST", "changeset/" + changeset.getId() + "/upload", diffUploadRequest,monitor);
520
521 // Process the response from the server
522 //
523 DiffResultProcessor reader = new DiffResultProcessor(list);
524 reader.parse(diffUploadResponse, monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
525 return reader.postProcess(
526 getChangeset(),
527 monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)
528 );
529 } catch(OsmTransferException e) {
530 throw e;
531 } catch(OsmDataParsingException e) {
532 throw new OsmTransferException(e);
533 } finally {
534 monitor.finishTask();
535 }
536 }
537
538 private void sleepAndListen(int retry, ProgressMonitor monitor) throws OsmTransferCanceledException {
539 System.out.print(tr("Waiting 10 seconds ... "));
540 for(int i=0; i < 10; i++) {
541 if (monitor != null) {
542 monitor.setCustomText(tr("Starting retry {0} of {1} in {2} seconds ...", getMaxRetries() - retry,getMaxRetries(), 10-i));
543 }
544 if (cancel)
545 throw new OsmTransferCanceledException();
546 try {
547 Thread.sleep(1000);
548 } catch (InterruptedException ex) {}
549 }
550 System.out.println(tr("OK - trying again."));
551 }
552
553 /**
554 * Replies the max. number of retries in case of 5XX errors on the server
555 *
556 * @return the max number of retries
557 */
558 protected int getMaxRetries() {
559 int ret = Main.pref.getInteger("osm-server.max-num-retries", DEFAULT_MAX_NUM_RETRIES);
560 return Math.max(ret,0);
561 }
562
563 protected boolean isUsingOAuth() {
564 String authMethod = Main.pref.get("osm-server.auth-method", "basic");
565 return authMethod.equals("oauth");
566 }
567
568 private String sendRequest(String requestMethod, String urlSuffix,String requestBody, ProgressMonitor monitor) throws OsmTransferException {
569 return sendRequest(requestMethod, urlSuffix, requestBody, monitor, true, false);
570 }
571
572 /**
573 * Generic method for sending requests to the OSM API.
574 *
575 * This method will automatically re-try any requests that are answered with a 5xx
576 * error code, or that resulted in a timeout exception from the TCP layer.
577 *
578 * @param requestMethod The http method used when talking with the server.
579 * @param urlSuffix The suffix to add at the server url, not including the version number,
580 * but including any object ids (e.g. "/way/1234/history").
581 * @param requestBody the body of the HTTP request, if any.
582 * @param monitor the progress monitor
583 * @param doAuthenticate set to true, if the request sent to the server shall include authentication
584 * credentials;
585 * @param fastFail true to request a short timeout
586 *
587 * @return the body of the HTTP response, if and only if the response code was "200 OK".
588 * @throws OsmTransferException if the HTTP return code was not 200 (and retries have
589 * been exhausted), or rewrapping a Java exception.
590 */
591 private String sendRequest(String requestMethod, String urlSuffix,String requestBody, ProgressMonitor monitor, boolean doAuthenticate, boolean fastFail) throws OsmTransferException {
592 StringBuffer responseBody = new StringBuffer();
593 int retries = fastFail ? 0 : getMaxRetries();
594
595 while(true) { // the retry loop
596 try {
597 URL url = new URL(new URL(getBaseUrl()), urlSuffix);
598 System.out.print(requestMethod + " " + url + "... ");
599 // fix #5369, see http://www.tikalk.com/java/forums/httpurlconnection-disable-keep-alive
600 activeConnection = Utils.openHttpConnection(url, false);
601 activeConnection.setConnectTimeout(fastFail ? 1000 : Main.pref.getInteger("socket.timeout.connect",15)*1000);
602 if (fastFail) {
603 activeConnection.setReadTimeout(1000);
604 }
605 activeConnection.setRequestMethod(requestMethod);
606 if (doAuthenticate) {
607 addAuth(activeConnection);
608 }
609
610 if (requestMethod.equals("PUT") || requestMethod.equals("POST") || requestMethod.equals("DELETE")) {
611 activeConnection.setDoOutput(true);
612 activeConnection.setRequestProperty("Content-type", "text/xml");
613 OutputStream out = activeConnection.getOutputStream();
614
615 // It seems that certain bits of the Ruby API are very unhappy upon
616 // receipt of a PUT/POST message without a Content-length header,
617 // even if the request has no payload.
618 // Since Java will not generate a Content-length header unless
619 // we use the output stream, we create an output stream for PUT/POST
620 // even if there is no payload.
621 if (requestBody != null) {
622 BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
623 bwr.write(requestBody);
624 bwr.flush();
625 }
626 Utils.close(out);
627 }
628
629 activeConnection.connect();
630 System.out.println(activeConnection.getResponseMessage());
631 int retCode = activeConnection.getResponseCode();
632
633 if (retCode >= 500) {
634 if (retries-- > 0) {
635 sleepAndListen(retries, monitor);
636 System.out.println(tr("Starting retry {0} of {1}.", getMaxRetries() - retries,getMaxRetries()));
637 continue;
638 }
639 }
640
641 // populate return fields.
642 responseBody.setLength(0);
643
644 // If the API returned an error code like 403 forbidden, getInputStream
645 // will fail with an IOException.
646 InputStream i = null;
647 try {
648 i = activeConnection.getInputStream();
649 } catch (IOException ioe) {
650 i = activeConnection.getErrorStream();
651 }
652 if (i != null) {
653 // the input stream can be null if both the input and the error stream
654 // are null. Seems to be the case if the OSM server replies a 401
655 // Unauthorized, see #3887.
656 //
657 BufferedReader in = new BufferedReader(new InputStreamReader(i));
658 String s;
659 while((s = in.readLine()) != null) {
660 responseBody.append(s);
661 responseBody.append("\n");
662 }
663 }
664 String errorHeader = null;
665 // Look for a detailed error message from the server
666 if (activeConnection.getHeaderField("Error") != null) {
667 errorHeader = activeConnection.getHeaderField("Error");
668 System.err.println("Error header: " + errorHeader);
669 } else if (retCode != 200 && responseBody.length()>0) {
670 System.err.println("Error body: " + responseBody);
671 }
672 activeConnection.disconnect();
673
674 errorHeader = errorHeader == null? null : errorHeader.trim();
675 String errorBody = responseBody.length() == 0? null : responseBody.toString().trim();
676 switch(retCode) {
677 case HttpURLConnection.HTTP_OK:
678 return responseBody.toString();
679 case HttpURLConnection.HTTP_GONE:
680 throw new OsmApiPrimitiveGoneException(errorHeader, errorBody);
681 case HttpURLConnection.HTTP_CONFLICT:
682 if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
683 throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA);
684 else
685 throw new OsmApiException(retCode, errorHeader, errorBody);
686 case HttpURLConnection.HTTP_FORBIDDEN:
687 OsmApiException e = new OsmApiException(retCode, errorHeader, errorBody);
688 e.setAccessedUrl(activeConnection.getURL().toString());
689 throw e;
690 default:
691 throw new OsmApiException(retCode, errorHeader, errorBody);
692 }
693 } catch (UnknownHostException e) {
694 throw new OsmTransferException(e);
695 } catch (SocketTimeoutException e) {
696 if (retries-- > 0) {
697 continue;
698 }
699 throw new OsmTransferException(e);
700 } catch (ConnectException e) {
701 if (retries-- > 0) {
702 continue;
703 }
704 throw new OsmTransferException(e);
705 } catch(IOException e){
706 throw new OsmTransferException(e);
707 } catch(OsmTransferCanceledException e){
708 throw e;
709 } catch(OsmTransferException e) {
710 throw e;
711 }
712 }
713 }
714
715 /**
716 * Replies the API capabilities
717 *
718 * @return the API capabilities, or null, if the API is not initialized yet
719 */
720 public Capabilities getCapabilities() {
721 return capabilities;
722 }
723
724 /**
725 * Ensures that the current changeset can be used for uploading data
726 *
727 * @throws OsmTransferException thrown if the current changeset can't be used for
728 * uploading data
729 */
730 protected void ensureValidChangeset() throws OsmTransferException {
731 if (changeset == null)
732 throw new OsmTransferException(tr("Current changeset is null. Cannot upload data."));
733 if (changeset.getId() <= 0)
734 throw new OsmTransferException(tr("ID of current changeset > 0 required. Current ID is {0}.", changeset.getId()));
735 }
736
737 /**
738 * Replies the changeset data uploads are currently directed to
739 *
740 * @return the changeset data uploads are currently directed to
741 */
742 public Changeset getChangeset() {
743 return changeset;
744 }
745
746 /**
747 * Sets the changesets to which further data uploads are directed. The changeset
748 * can be null. If it isn't null it must have been created, i.e. id > 0 is required. Furthermore,
749 * it must be open.
750 *
751 * @param changeset the changeset
752 * @throws IllegalArgumentException thrown if changeset.getId() <= 0
753 * @throws IllegalArgumentException thrown if !changeset.isOpen()
754 */
755 public void setChangeset(Changeset changeset) {
756 if (changeset == null) {
757 this.changeset = null;
758 return;
759 }
760 if (changeset.getId() <= 0)
761 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
762 if (!changeset.isOpen())
763 throw new IllegalArgumentException(tr("Open changeset expected. Got closed changeset with id {0}.", changeset.getId()));
764 this.changeset = changeset;
765 }
766}
Note: See TracBrowser for help on using the repository browser.