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