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

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

fix #15435 - do not cache incorrect login credentials when using basic auth

  • Property svn:eol-style set to native
File size: 35.8 KB
RevLine 
[8378]1// License: GPL. For details, see LICENSE file.
[1523]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
[1559]7import java.io.IOException;
[1523]8import java.io.PrintWriter;
9import java.io.StringReader;
[1525]10import java.io.StringWriter;
[12992]11import java.net.Authenticator.RequestorType;
[1523]12import java.net.ConnectException;
13import java.net.HttpURLConnection;
[4690]14import java.net.MalformedURLException;
[1523]15import java.net.SocketTimeoutException;
16import java.net.URL;
[7082]17import java.nio.charset.StandardCharsets;
[1523]18import java.util.Collection;
[1879]19import java.util.Collections;
[1664]20import java.util.HashMap;
[7663]21import java.util.List;
[6317]22import java.util.Map;
[1523]23
[5635]24import javax.xml.parsers.ParserConfigurationException;
[1523]25
26import org.openstreetmap.josm.Main;
[7663]27import org.openstreetmap.josm.data.coor.LatLon;
28import org.openstreetmap.josm.data.notes.Note;
[1523]29import org.openstreetmap.josm.data.osm.Changeset;
[4100]30import org.openstreetmap.josm.data.osm.IPrimitive;
[7656]31import org.openstreetmap.josm.data.osm.OsmPrimitive;
[1670]32import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
[2115]33import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
[1811]34import org.openstreetmap.josm.gui.progress.ProgressMonitor;
[7473]35import org.openstreetmap.josm.io.Capabilities.CapabilitiesParser;
[12992]36import org.openstreetmap.josm.io.auth.CredentialsManager;
[12846]37import org.openstreetmap.josm.spi.preferences.Config;
[2852]38import org.openstreetmap.josm.tools.CheckParameterUtil;
[9172]39import org.openstreetmap.josm.tools.HttpClient;
[12804]40import org.openstreetmap.josm.tools.ListenerList;
[12620]41import org.openstreetmap.josm.tools.Logging;
[5587]42import org.openstreetmap.josm.tools.Utils;
[6906]43import org.openstreetmap.josm.tools.XmlParsingException;
[1523]44import org.xml.sax.InputSource;
45import org.xml.sax.SAXException;
[5635]46import org.xml.sax.SAXParseException;
[1523]47
48/**
[6830]49 * Class that encapsulates the communications with the <a href="http://wiki.openstreetmap.org/wiki/API_v0.6">OSM API</a>.<br><br>
[1523]50 *
[6830]51 * All interaction with the server-side OSM API should go through this class.<br><br>
[1581]52 *
[1523]53 * It is conceivable to extract this into an interface later and create various
54 * classes implementing the interface, to be able to talk to various kinds of servers.
[12805]55 * @since 1523
[1523]56 */
57public class OsmApi extends OsmConnection {
[6070]58
59 /**
60 * Maximum number of retries to send a request in case of HTTP 500 errors or timeouts
[5386]61 */
[6889]62 public static final int DEFAULT_MAX_NUM_RETRIES = 5;
[1523]63
[5386]64 /**
[6070]65 * Maximum number of concurrent download threads, imposed by
[5386]66 * <a href="http://wiki.openstreetmap.org/wiki/API_usage_policy#Technical_Usage_Requirements">
67 * OSM API usage policy.</a>
[5422]68 * @since 5386
[5386]69 */
[6889]70 public static final int MAX_DOWNLOAD_THREADS = 2;
[6070]71
[5422]72 /**
[6070]73 * Default URL of the standard OSM API.
[5422]74 * @since 5422
75 */
[6920]76 public static final String DEFAULT_API_URL = "https://api.openstreetmap.org/api";
[5386]77
78 // The collection of instantiated OSM APIs
[12804]79 private static final Map<String, OsmApi> instances = new HashMap<>();
[1664]80
[12804]81 private static final ListenerList<OsmApiInitializationListener> listeners = ListenerList.create();
82
[8840]83 private URL url;
[6642]84
[1523]85 /**
[12804]86 * OSM API initialization listener.
87 * @since 12804
88 */
89 public interface OsmApiInitializationListener {
90 /**
91 * Called when an OSM API instance has been successfully initialized.
92 * @param instance the initialized OSM API instance
93 */
94 void apiInitialized(OsmApi instance);
95 }
96
97 /**
98 * Adds a new OSM API initialization listener.
99 * @param listener OSM API initialization listener to add
100 * @since 12804
101 */
102 public static void addOsmApiInitializationListener(OsmApiInitializationListener listener) {
103 listeners.addListener(listener);
104 }
105
106 /**
107 * Removes an OSM API initialization listener.
108 * @param listener OSM API initialization listener to remove
109 * @since 12804
110 */
111 public static void removeOsmApiInitializationListener(OsmApiInitializationListener listener) {
112 listeners.removeListener(listener);
113 }
114
115 /**
[5386]116 * Replies the {@link OsmApi} for a given server URL
[1677]117 *
[1664]118 * @param serverUrl the server URL
119 * @return the OsmApi
[8291]120 * @throws IllegalArgumentException if serverUrl is null
[1677]121 *
[1664]122 */
[6889]123 public static OsmApi getOsmApi(String serverUrl) {
[1664]124 OsmApi api = instances.get(serverUrl);
125 if (api == null) {
126 api = new OsmApi(serverUrl);
[10373]127 cacheInstance(api);
[1664]128 }
129 return api;
130 }
[6070]131
[10373]132 protected static void cacheInstance(OsmApi api) {
133 instances.put(api.getServerUrl(), api);
134 }
135
[7434]136 private static String getServerUrlFromPref() {
[12846]137 return Config.getPref().get("osm-server.url", DEFAULT_API_URL);
[7434]138 }
139
[1664]140 /**
[5386]141 * Replies the {@link OsmApi} for the URL given by the preference <code>osm-server.url</code>
[1677]142 *
[1664]143 * @return the OsmApi
144 */
[6889]145 public static OsmApi getOsmApi() {
[7434]146 return getOsmApi(getServerUrlFromPref());
[1664]147 }
148
[7473]149 /** Server URL */
[9078]150 private final String serverUrl;
[1664]151
[7473]152 /** Object describing current changeset */
[1523]153 private Changeset changeset;
154
[7473]155 /** API version used for server communications */
[8840]156 private String version;
[1523]157
[7473]158 /** API capabilities */
[8840]159 private Capabilities capabilities;
[1664]160
[7473]161 /** true if successfully initialized */
[8840]162 private boolean initialized;
[1581]163
[1523]164 /**
[7473]165 * Constructs a new {@code OsmApi} for a specific server URL.
[1677]166 *
[1664]167 * @param serverUrl the server URL. Must not be null
[8291]168 * @throws IllegalArgumentException if serverUrl is null
[1664]169 */
[10378]170 protected OsmApi(String serverUrl) {
[2852]171 CheckParameterUtil.ensureParameterNotNull(serverUrl, "serverUrl");
[1664]172 this.serverUrl = serverUrl;
173 }
174
175 /**
[5386]176 * Replies the OSM protocol version we use to talk to the server.
[1523]177 * @return protocol version, or null if not yet negotiated.
178 */
179 public String getVersion() {
180 return version;
181 }
[1581]182
[5386]183 /**
184 * Replies the host name of the server URL.
185 * @return the host name of the server URL, or null if the server URL is malformed.
186 */
[4690]187 public String getHost() {
188 String host = null;
189 try {
190 host = (new URL(serverUrl)).getHost();
191 } catch (MalformedURLException e) {
[12620]192 Logging.warn(e);
[4690]193 }
194 return host;
195 }
196
[4709]197 private class CapabilitiesCache extends CacheCustomContent<OsmTransferException> {
198
[7434]199 private static final String CAPABILITIES = "capabilities";
200
[9078]201 private final ProgressMonitor monitor;
202 private final boolean fastFail;
[4709]203
[8836]204 CapabilitiesCache(ProgressMonitor monitor, boolean fastFail) {
[7434]205 super(CAPABILITIES + getBaseUrl().hashCode(), CacheCustomContent.INTERVAL_WEEKLY);
[4709]206 this.monitor = monitor;
207 this.fastFail = fastFail;
208 }
[6070]209
[4709]210 @Override
[7434]211 protected void checkOfflineAccess() {
212 OnlineResource.OSM_API.checkOfflineAccess(getBaseUrl(getServerUrlFromPref(), "0.6")+CAPABILITIES, getServerUrlFromPref());
213 }
214
215 @Override
[4709]216 protected byte[] updateData() throws OsmTransferException {
[7434]217 return sendRequest("GET", CAPABILITIES, null, monitor, false, fastFail).getBytes(StandardCharsets.UTF_8);
[4709]218 }
219 }
220
[5386]221 /**
222 * Initializes this component by negotiating a protocol version with the server.
[6070]223 *
[5386]224 * @param monitor the progress monitor
225 * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
226 * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
227 */
228 public void initialize(ProgressMonitor monitor) throws OsmTransferCanceledException, OsmApiInitializationException {
[3993]229 initialize(monitor, false);
230 }
[6070]231
[1523]232 /**
[6070]233 * Initializes this component by negotiating a protocol version with the server, with the ability to control the timeout.
[1670]234 *
[5386]235 * @param monitor the progress monitor
[3993]236 * @param fastFail true to request quick initialisation with a small timeout (more likely to throw exception)
[5386]237 * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
238 * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
[1523]239 */
[5386]240 public void initialize(ProgressMonitor monitor, boolean fastFail) throws OsmTransferCanceledException, OsmApiInitializationException {
[1664]241 if (initialized)
242 return;
[2037]243 cancel = false;
[1523]244 try {
[5635]245 CapabilitiesCache cache = new CapabilitiesCache(monitor, fastFail);
246 try {
247 initializeCapabilities(cache.updateIfRequiredString());
248 } catch (SAXParseException parseException) {
[12620]249 Logging.trace(parseException);
[5635]250 // XML parsing may fail if JOSM previously stored a corrupted capabilities document (see #8278)
251 // In that case, force update and try again
252 initializeCapabilities(cache.updateForceString());
253 }
[7476]254 if (capabilities == null) {
255 if (Main.isOffline(OnlineResource.OSM_API)) {
[12620]256 Logging.warn(tr("{0} not available (offline mode)", tr("OSM API")));
[7476]257 } else {
[12620]258 Logging.error(tr("Unable to initialize OSM API."));
[7476]259 }
260 return;
261 } else if (!capabilities.supportsVersion("0.6")) {
[12620]262 Logging.error(tr("This version of JOSM is incompatible with the configured server."));
263 Logging.error(tr("It supports protocol version 0.6, while the server says it supports {0} to {1}.",
[1664]264 capabilities.get("version", "minimum"), capabilities.get("version", "maximum")));
[7476]265 return;
266 } else {
267 version = "0.6";
268 initialized = true;
[1523]269 }
[3934]270
[12804]271 listeners.fireEvent(l -> l.apiInitialized(this));
[5386]272 } catch (OsmTransferCanceledException e) {
[2641]273 throw e;
[6642]274 } catch (OsmTransferException e) {
275 initialized = false;
276 Main.addNetworkError(url, Utils.getRootCause(e));
277 throw new OsmApiInitializationException(e);
[10212]278 } catch (SAXException | IOException | ParserConfigurationException e) {
[2641]279 initialized = false;
280 throw new OsmApiInitializationException(e);
[1523]281 }
282 }
[6070]283
[7476]284 private synchronized void initializeCapabilities(String xml) throws SAXException, IOException, ParserConfigurationException {
285 if (xml != null) {
286 capabilities = CapabilitiesParser.parse(new InputSource(new StringReader(xml)));
287 }
[5635]288 }
[1581]289
[1523]290 /**
291 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
292 * @param o the OSM primitive
293 * @param addBody true to generate the full XML, false to only generate the encapsulating tag
294 * @return XML string
295 */
[10051]296 protected final String toXml(IPrimitive o, boolean addBody) {
[4645]297 StringWriter swriter = new StringWriter();
[7033]298 try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
299 swriter.getBuffer().setLength(0);
300 osmWriter.setWithBody(addBody);
301 osmWriter.setChangeset(changeset);
302 osmWriter.header();
303 o.accept(osmWriter);
304 osmWriter.footer();
305 osmWriter.flush();
306 } catch (IOException e) {
[12620]307 Logging.warn(e);
[7033]308 }
[3366]309 return swriter.toString();
[1523]310 }
[1581]311
[1523]312 /**
[2115]313 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
[5881]314 * @param s the changeset
[2115]315 * @return XML string
316 */
[10051]317 protected final String toXml(Changeset s) {
[4645]318 StringWriter swriter = new StringWriter();
[7033]319 try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
320 swriter.getBuffer().setLength(0);
321 osmWriter.header();
322 osmWriter.visit(s);
323 osmWriter.footer();
324 osmWriter.flush();
325 } catch (IOException e) {
[12620]326 Logging.warn(e);
[7033]327 }
[2115]328 return swriter.toString();
329 }
330
[7434]331 private static String getBaseUrl(String serverUrl, String version) {
[6822]332 StringBuilder rv = new StringBuilder(serverUrl);
[1523]333 if (version != null) {
[8390]334 rv.append('/').append(version);
[1523]335 }
[8390]336 rv.append('/');
[1581]337 // this works around a ruby (or lighttpd) bug where two consecutive slashes in
[1523]338 // an URL will cause a "404 not found" response.
[7748]339 int p;
340 while ((p = rv.indexOf("//", rv.indexOf("://")+2)) > -1) {
341 rv.delete(p, p + 1);
342 }
[1523]343 return rv.toString();
344 }
345
[1581]346 /**
[7434]347 * Returns the base URL for API requests, including the negotiated version number.
348 * @return base URL string
349 */
350 public String getBaseUrl() {
351 return getBaseUrl(serverUrl, version);
352 }
353
354 /**
[9353]355 * Returns the server URL
356 * @return the server URL
357 * @since 9353
358 */
359 public String getServerUrl() {
360 return serverUrl;
361 }
362
363 /**
[1523]364 * Creates an OSM primitive on the server. The OsmPrimitive object passed in
365 * is modified by giving it the server-assigned id.
[1581]366 *
[1523]367 * @param osm the primitive
[5386]368 * @param monitor the progress monitor
[1523]369 * @throws OsmTransferException if something goes wrong
370 */
[4100]371 public void createPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
[1670]372 String ret = "";
373 try {
[2115]374 ensureValidChangeset();
375 initialize(monitor);
[8510]376 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/create", toXml(osm, true), monitor);
[2070]377 osm.setOsmId(Long.parseLong(ret.trim()), 1);
[2604]378 osm.setChangesetId(getChangeset().getId());
[8510]379 } catch (NumberFormatException e) {
[8394]380 throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret), e);
[1670]381 }
[1523]382 }
[1581]383
[1523]384 /**
[2569]385 * Modifies an OSM primitive on the server.
[1581]386 *
[2569]387 * @param osm the primitive. Must not be null.
388 * @param monitor the progress monitor
[1523]389 * @throws OsmTransferException if something goes wrong
390 */
[4100]391 public void modifyPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
[2115]392 String ret = null;
393 try {
394 ensureValidChangeset();
395 initialize(monitor);
[2569]396 // normal mode (0.6 and up) returns new object version.
[8846]397 ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+'/' + osm.getId(), toXml(osm, true), monitor);
[2569]398 osm.setOsmId(osm.getId(), Integer.parseInt(ret.trim()));
[2604]399 osm.setChangesetId(getChangeset().getId());
[3336]400 osm.setVisible(true);
[8510]401 } catch (NumberFormatException e) {
[7748]402 throw new OsmTransferException(tr("Unexpected format of new version of modified primitive ''{0}''. Got ''{1}''.",
[8394]403 osm.getId(), ret), e);
[1523]404 }
[1581]405 }
406
[1523]407 /**
408 * Deletes an OSM primitive on the server.
409 * @param osm the primitive
[5386]410 * @param monitor the progress monitor
[1523]411 * @throws OsmTransferException if something goes wrong
412 */
[7656]413 public void deletePrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
[2115]414 ensureValidChangeset();
[2035]415 initialize(monitor);
[1879]416 // can't use a the individual DELETE method in the 0.6 API. Java doesn't allow
417 // submitting a DELETE request with content, the 0.6 API requires it, however. Falling back
418 // to diff upload.
419 //
420 uploadDiff(Collections.singleton(osm), monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
[1581]421 }
422
[1523]423 /**
[2115]424 * Creates a new changeset based on the keys in <code>changeset</code>. If this
425 * method succeeds, changeset.getId() replies the id the server assigned to the new
426 * changeset
[2512]427 *
[2115]428 * The changeset must not be null, but its key/value-pairs may be empty.
[2512]429 *
[2115]430 * @param changeset the changeset toe be created. Must not be null.
[2040]431 * @param progressMonitor the progress monitor
[1523]432 * @throws OsmTransferException signifying a non-200 return code, or connection errors
[8291]433 * @throws IllegalArgumentException if changeset is null
[1523]434 */
[2115]435 public void openChangeset(Changeset changeset, ProgressMonitor progressMonitor) throws OsmTransferException {
[2852]436 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
[1811]437 try {
[8345]438 progressMonitor.beginTask(tr("Creating changeset..."));
[2115]439 initialize(progressMonitor);
440 String ret = "";
441 try {
[8510]442 ret = sendRequest("PUT", "changeset/create", toXml(changeset), progressMonitor);
[2604]443 changeset.setId(Integer.parseInt(ret.trim()));
[2115]444 changeset.setOpen(true);
[8510]445 } catch (NumberFormatException e) {
[8394]446 throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret), e);
[2115]447 }
[8510]448 progressMonitor.setCustomText(tr("Successfully opened changeset {0}", changeset.getId()));
[1811]449 } finally {
450 progressMonitor.finishTask();
451 }
[1523]452 }
453
454 /**
[2115]455 * Updates a changeset with the keys in <code>changesetUpdate</code>. The changeset must not
[6830]456 * be null and id &gt; 0 must be true.
[2061]457 *
[2115]458 * @param changeset the changeset to update. Must not be null.
[5266]459 * @param monitor the progress monitor. If null, uses the {@link NullProgressMonitor#INSTANCE}.
[2512]460 *
[2061]461 * @throws OsmTransferException if something goes wrong.
[2115]462 * @throws IllegalArgumentException if changeset is null
[6830]463 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
[2512]464 *
[2061]465 */
[2115]466 public void updateChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
[2852]467 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
[2115]468 if (monitor == null) {
469 monitor = NullProgressMonitor.INSTANCE;
470 }
471 if (changeset.getId() <= 0)
[2181]472 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
[2061]473 try {
[2115]474 monitor.beginTask(tr("Updating changeset..."));
475 initialize(monitor);
476 monitor.setCustomText(tr("Updating changeset {0}...", changeset.getId()));
477 sendRequest(
478 "PUT",
[2135]479 "changeset/" + changeset.getId(),
480 toXml(changeset),
[2115]481 monitor
482 );
[8510]483 } catch (ChangesetClosedException e) {
[2599]484 e.setSource(ChangesetClosedException.Source.UPDATE_CHANGESET);
485 throw e;
[8510]486 } catch (OsmApiException e) {
[7748]487 String errorHeader = e.getErrorHeader();
488 if (e.getResponseCode() == HttpURLConnection.HTTP_CONFLICT && ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
489 throw new ChangesetClosedException(errorHeader, ChangesetClosedException.Source.UPDATE_CHANGESET);
[2480]490 throw e;
[2061]491 } finally {
[2115]492 monitor.finishTask();
[2061]493 }
494 }
495
496 /**
[6830]497 * Closes a changeset on the server. Sets changeset.setOpen(false) if this operation succeeds.
[1581]498 *
[6830]499 * @param changeset the changeset to be closed. Must not be null. changeset.getId() &gt; 0 required.
[5266]500 * @param monitor the progress monitor. If null, uses {@link NullProgressMonitor#INSTANCE}
[2512]501 *
[1523]502 * @throws OsmTransferException if something goes wrong.
[8291]503 * @throws IllegalArgumentException if changeset is null
504 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
[1523]505 */
[2115]506 public void closeChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
[2852]507 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
[2115]508 if (monitor == null) {
509 monitor = NullProgressMonitor.INSTANCE;
[2040]510 }
[2115]511 if (changeset.getId() <= 0)
[2181]512 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
[1811]513 try {
[2115]514 monitor.beginTask(tr("Closing changeset..."));
515 initialize(monitor);
[3566]516 /* send "\r\n" instead of empty string, so we don't send zero payload - works around bugs
517 in proxy software */
518 sendRequest("PUT", "changeset" + "/" + changeset.getId() + "/close", "\r\n", monitor);
[2115]519 changeset.setOpen(false);
[1811]520 } finally {
[2115]521 monitor.finishTask();
[1811]522 }
[1523]523 }
524
525 /**
[1581]526 * Uploads a list of changes in "diff" form to the server.
527 *
[1523]528 * @param list the list of changed OSM Primitives
[2198]529 * @param monitor the progress monitor
[1523]530 * @return list of processed primitives
[1581]531 * @throws OsmTransferException if something is wrong
[1523]532 */
[7748]533 public Collection<OsmPrimitive> uploadDiff(Collection<? extends OsmPrimitive> list, ProgressMonitor monitor)
534 throws OsmTransferException {
[1811]535 try {
[2198]536 monitor.beginTask("", list.size() * 2);
[1811]537 if (changeset == null)
[2181]538 throw new OsmTransferException(tr("No changeset present for diff upload."));
[1581]539
[2198]540 initialize(monitor);
[1581]541
[2604]542 // prepare upload request
543 //
544 OsmChangeBuilder changeBuilder = new OsmChangeBuilder(changeset);
545 monitor.subTask(tr("Preparing upload request..."));
546 changeBuilder.start();
547 changeBuilder.append(list);
548 changeBuilder.finish();
549 String diffUploadRequest = changeBuilder.getDocument();
[1581]550
[2604]551 // Upload to the server
552 //
[2852]553 monitor.indeterminateSubTask(
554 trn("Uploading {0} object...", "Uploading {0} objects...", list.size(), list.size()));
[8510]555 String diffUploadResponse = sendRequest("POST", "changeset/" + changeset.getId() + "/upload", diffUploadRequest, monitor);
[1581]556
[2604]557 // Process the response from the server
558 //
559 DiffResultProcessor reader = new DiffResultProcessor(list);
560 reader.parse(diffUploadResponse, monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
561 return reader.postProcess(
562 getChangeset(),
563 monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)
564 );
[8510]565 } catch (OsmTransferException e) {
[2115]566 throw e;
[8510]567 } catch (XmlParsingException e) {
[2115]568 throw new OsmTransferException(e);
[1690]569 } finally {
[2198]570 monitor.finishTask();
[1523]571 }
572 }
573
[4310]574 private void sleepAndListen(int retry, ProgressMonitor monitor) throws OsmTransferCanceledException {
[12620]575 Logging.info(tr("Waiting 10 seconds ... "));
[8510]576 for (int i = 0; i < 10; i++) {
[2035]577 if (monitor != null) {
[8510]578 monitor.setCustomText(tr("Starting retry {0} of {1} in {2} seconds ...", getMaxRetries() - retry, getMaxRetries(), 10-i));
[2035]579 }
[2641]580 if (cancel)
[8415]581 throw new OsmTransferCanceledException("Operation canceled" + (i > 0 ? " in retry #"+i : ""));
[1523]582 try {
583 Thread.sleep(1000);
[6310]584 } catch (InterruptedException ex) {
[12620]585 Logging.warn("InterruptedException in "+getClass().getSimpleName()+" during sleep");
[11535]586 Thread.currentThread().interrupt();
[6310]587 }
[1523]588 }
[12620]589 Logging.info(tr("OK - trying again."));
[1523]590 }
591
592 /**
[1859]593 * Replies the max. number of retries in case of 5XX errors on the server
[2512]594 *
[1859]595 * @return the max number of retries
596 */
597 protected int getMaxRetries() {
[12846]598 int ret = Config.getPref().getInt("osm-server.max-num-retries", DEFAULT_MAX_NUM_RETRIES);
[8510]599 return Math.max(ret, 0);
[1859]600 }
601
[6349]602 /**
603 * Determines if JOSM is configured to access OSM API via OAuth
604 * @return {@code true} if JOSM is configured to access OSM API via OAuth, {@code false} otherwise
605 * @since 6349
606 */
[9352]607 public static boolean isUsingOAuth() {
608 return "oauth".equals(getAuthMethod());
[2748]609 }
610
[9352]611 /**
612 * Returns the authentication method set in the preferences
613 * @return the authentication method
614 */
615 public static String getAuthMethod() {
[12846]616 return Config.getPref().get("osm-server.auth-method", "oauth");
[9352]617 }
618
[8510]619 protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor)
[7748]620 throws OsmTransferException {
[3993]621 return sendRequest(requestMethod, urlSuffix, requestBody, monitor, true, false);
[2222]622 }
623
[1859]624 /**
[1523]625 * Generic method for sending requests to the OSM API.
626 *
627 * This method will automatically re-try any requests that are answered with a 5xx
628 * error code, or that resulted in a timeout exception from the TCP layer.
[1581]629 *
[1523]630 * @param requestMethod The http method used when talking with the server.
631 * @param urlSuffix The suffix to add at the server url, not including the version number,
632 * but including any object ids (e.g. "/way/1234/history").
633 * @param requestBody the body of the HTTP request, if any.
[2478]634 * @param monitor the progress monitor
635 * @param doAuthenticate set to true, if the request sent to the server shall include authentication
636 * credentials;
[3993]637 * @param fastFail true to request a short timeout
[1581]638 *
[1523]639 * @return the body of the HTTP response, if and only if the response code was "200 OK".
[5386]640 * @throws OsmTransferException if the HTTP return code was not 200 (and retries have
[1581]641 * been exhausted), or rewrapping a Java exception.
[1523]642 */
[8510]643 protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor,
[7748]644 boolean doAuthenticate, boolean fastFail) throws OsmTransferException {
[4854]645 int retries = fastFail ? 0 : getMaxRetries();
[1581]646
[8510]647 while (true) { // the retry loop
[1523]648 try {
[6642]649 url = new URL(new URL(getBaseUrl()), urlSuffix);
[9172]650 final HttpClient client = HttpClient.create(url, requestMethod).keepAlive(false);
[9309]651 activeConnection = client;
[4859]652 if (fastFail) {
[9182]653 client.setConnectTimeout(1000);
[9172]654 client.setReadTimeout(1000);
[9182]655 } else {
656 // use default connect timeout from org.openstreetmap.josm.tools.HttpClient.connectTimeout
657 client.setReadTimeout(0);
[4859]658 }
[2222]659 if (doAuthenticate) {
[9172]660 addAuth(client);
[2222]661 }
[1523]662
[7012]663 if ("PUT".equals(requestMethod) || "POST".equals(requestMethod) || "DELETE".equals(requestMethod)) {
[9182]664 client.setHeader("Content-Type", "text/xml");
[9172]665 // It seems that certain bits of the Ruby API are very unhappy upon
666 // receipt of a PUT/POST message without a Content-length header,
667 // even if the request has no payload.
668 // Since Java will not generate a Content-length header unless
669 // we use the output stream, we create an output stream for PUT/POST
670 // even if there is no payload.
[9182]671 client.setRequestBody((requestBody != null ? requestBody : "").getBytes(StandardCharsets.UTF_8));
[1523]672 }
[1581]673
[9309]674 final HttpClient.Response response = client.connect();
[12620]675 Logging.info(response.getResponseMessage());
[9309]676 int retCode = response.getResponseCode();
[1581]677
[11386]678 if (retCode >= 500 && retries-- > 0) {
679 sleepAndListen(retries, monitor);
[12620]680 Logging.info(tr("Starting retry {0} of {1}.", getMaxRetries() - retries, getMaxRetries()));
[11386]681 continue;
[1523]682 }
683
[9309]684 final String responseBody = response.fetchContent();
[1581]685
[1663]686 String errorHeader = null;
[1523]687 // Look for a detailed error message from the server
[9309]688 if (response.getHeaderField("Error") != null) {
689 errorHeader = response.getHeaderField("Error");
[12620]690 Logging.error("Error header: " + errorHeader);
[8510]691 } else if (retCode != HttpURLConnection.HTTP_OK && responseBody.length() > 0) {
[12620]692 Logging.error("Error body: " + responseBody);
[1523]693 }
694 activeConnection.disconnect();
[1581]695
[8510]696 errorHeader = errorHeader == null ? null : errorHeader.trim();
[9172]697 String errorBody = responseBody.length() == 0 ? null : responseBody.trim();
[2198]698 switch(retCode) {
[2273]699 case HttpURLConnection.HTTP_OK:
[9172]700 return responseBody;
[2273]701 case HttpURLConnection.HTTP_GONE:
702 throw new OsmApiPrimitiveGoneException(errorHeader, errorBody);
[2569]703 case HttpURLConnection.HTTP_CONFLICT:
704 if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
705 throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA);
706 else
707 throw new OsmApiException(retCode, errorHeader, errorBody);
[12992]708 case HttpURLConnection.HTTP_UNAUTHORIZED:
[2748]709 case HttpURLConnection.HTTP_FORBIDDEN:
[12992]710 CredentialsManager.getInstance().purgeCredentialsCache(RequestorType.SERVER);
711 throw new OsmApiException(retCode, errorHeader, errorBody, activeConnection.getURL().toString(),
712 doAuthenticate ? retrieveBasicAuthorizationLogin(client) : null);
[2273]713 default:
714 throw new OsmApiException(retCode, errorHeader, errorBody);
[2198]715 }
[7004]716 } catch (SocketTimeoutException | ConnectException e) {
[1663]717 if (retries-- > 0) {
[1523]718 continue;
[1663]719 }
720 throw new OsmTransferException(e);
[8510]721 } catch (IOException e) {
[2641]722 throw new OsmTransferException(e);
[8510]723 } catch (OsmTransferException e) {
[2115]724 throw e;
[1523]725 }
726 }
727 }
[1670]728
729 /**
[7473]730 * Replies the API capabilities.
[1677]731 *
[5386]732 * @return the API capabilities, or null, if the API is not initialized yet
[1691]733 */
[7476]734 public synchronized Capabilities getCapabilities() {
[1691]735 return capabilities;
736 }
[1868]737
[1894]738 /**
[2115]739 * Ensures that the current changeset can be used for uploading data
[2512]740 *
[8291]741 * @throws OsmTransferException if the current changeset can't be used for uploading data
[1894]742 */
[2115]743 protected void ensureValidChangeset() throws OsmTransferException {
744 if (changeset == null)
[2734]745 throw new OsmTransferException(tr("Current changeset is null. Cannot upload data."));
[2115]746 if (changeset.getId() <= 0)
[2181]747 throw new OsmTransferException(tr("ID of current changeset > 0 required. Current ID is {0}.", changeset.getId()));
[2115]748 }
[6070]749
[2115]750 /**
751 * Replies the changeset data uploads are currently directed to
[2512]752 *
[2115]753 * @return the changeset data uploads are currently directed to
754 */
755 public Changeset getChangeset() {
[1894]756 return changeset;
757 }
[2115]758
759 /**
760 * Sets the changesets to which further data uploads are directed. The changeset
[6830]761 * can be null. If it isn't null it must have been created, i.e. id &gt; 0 is required. Furthermore,
[2115]762 * it must be open.
[2512]763 *
[2115]764 * @param changeset the changeset
[8291]765 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
766 * @throws IllegalArgumentException if !changeset.isOpen()
[2115]767 */
768 public void setChangeset(Changeset changeset) {
769 if (changeset == null) {
770 this.changeset = null;
771 return;
772 }
773 if (changeset.getId() <= 0)
[2181]774 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
[2115]775 if (!changeset.isOpen())
[2181]776 throw new IllegalArgumentException(tr("Open changeset expected. Got closed changeset with id {0}.", changeset.getId()));
[2115]777 this.changeset = changeset;
778 }
[7663]779
[7748]780 private static StringBuilder noteStringBuilder(Note note) {
781 return new StringBuilder().append("notes/").append(note.getId());
782 }
783
[7663]784 /**
[7748]785 * Create a new note on the server.
[7663]786 * @param latlon Location of note
787 * @param text Comment entered by user to open the note
788 * @param monitor Progress monitor
789 * @return Note as it exists on the server after creation (ID assigned)
[8470]790 * @throws OsmTransferException if any error occurs during dialog with OSM API
[7663]791 */
792 public Note createNote(LatLon latlon, String text, ProgressMonitor monitor) throws OsmTransferException {
793 initialize(monitor);
[7748]794 String noteUrl = new StringBuilder()
[7663]795 .append("notes?lat=")
796 .append(latlon.lat())
797 .append("&lon=")
798 .append(latlon.lon())
799 .append("&text=")
[8304]800 .append(Utils.encodeUrl(text)).toString();
[7663]801
[7748]802 String response = sendRequest("POST", noteUrl, null, monitor, true, false);
[7663]803 return parseSingleNote(response);
804 }
805
806 /**
807 * Add a comment to an existing note.
808 * @param note The note to add a comment to
809 * @param comment Text of the comment
810 * @param monitor Progress monitor
811 * @return Note returned by the API after the comment was added
[8470]812 * @throws OsmTransferException if any error occurs during dialog with OSM API
[7663]813 */
814 public Note addCommentToNote(Note note, String comment, ProgressMonitor monitor) throws OsmTransferException {
815 initialize(monitor);
[7748]816 String noteUrl = noteStringBuilder(note)
[7663]817 .append("/comment?text=")
[8304]818 .append(Utils.encodeUrl(comment)).toString();
[7663]819
[7748]820 String response = sendRequest("POST", noteUrl, null, monitor, true, false);
[7663]821 return parseSingleNote(response);
822 }
823
824 /**
[7748]825 * Close a note.
[7663]826 * @param note Note to close. Must currently be open
827 * @param closeMessage Optional message supplied by the user when closing the note
828 * @param monitor Progress monitor
829 * @return Note returned by the API after the close operation
[8470]830 * @throws OsmTransferException if any error occurs during dialog with OSM API
[7663]831 */
832 public Note closeNote(Note note, String closeMessage, ProgressMonitor monitor) throws OsmTransferException {
833 initialize(monitor);
[8304]834 String encodedMessage = Utils.encodeUrl(closeMessage);
[7748]835 StringBuilder urlBuilder = noteStringBuilder(note)
[7663]836 .append("/close");
[11381]837 if (!encodedMessage.trim().isEmpty()) {
[7663]838 urlBuilder.append("?text=");
839 urlBuilder.append(encodedMessage);
840 }
841
842 String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false);
843 return parseSingleNote(response);
844 }
845
846 /**
847 * Reopen a closed note
848 * @param note Note to reopen. Must currently be closed
849 * @param reactivateMessage Optional message supplied by the user when reopening the note
850 * @param monitor Progress monitor
851 * @return Note returned by the API after the reopen operation
[8470]852 * @throws OsmTransferException if any error occurs during dialog with OSM API
[7663]853 */
854 public Note reopenNote(Note note, String reactivateMessage, ProgressMonitor monitor) throws OsmTransferException {
855 initialize(monitor);
[8304]856 String encodedMessage = Utils.encodeUrl(reactivateMessage);
[7748]857 StringBuilder urlBuilder = noteStringBuilder(note)
[7663]858 .append("/reopen");
[11381]859 if (!encodedMessage.trim().isEmpty()) {
[7663]860 urlBuilder.append("?text=");
861 urlBuilder.append(encodedMessage);
862 }
863
864 String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false);
865 return parseSingleNote(response);
866 }
867
[8926]868 /**
869 * Method for parsing API responses for operations on individual notes
870 * @param xml the API response as XML data
871 * @return the resulting Note
872 * @throws OsmTransferException if the API response cannot be parsed
873 */
[10000]874 private static Note parseSingleNote(String xml) throws OsmTransferException {
[7663]875 try {
876 List<Note> newNotes = new NoteReader(xml).parse();
[8510]877 if (newNotes.size() == 1) {
[7663]878 return newNotes.get(0);
879 }
[10000]880 // Shouldn't ever execute. Server will either respond with an error (caught elsewhere) or one note
[7663]881 throw new OsmTransferException(tr("Note upload failed"));
[8510]882 } catch (SAXException | IOException e) {
[12620]883 Logging.error(e);
[7663]884 throw new OsmTransferException(tr("Error parsing note response from server"), e);
885 }
886 }
[1523]887}
Note: See TracBrowser for help on using the repository browser.