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