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

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

see #9710 - more debug messages

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