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

Last change on this file since 4690 was 4690, checked in by stoecker, 12 years ago

see #7086 - fix passing auth information to wrong server

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