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

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

see #8570, #7406 - I/O refactorization:

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