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