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