001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005import static org.openstreetmap.josm.tools.I18n.trn;
006
007import java.io.IOException;
008import java.io.PrintWriter;
009import java.io.StringReader;
010import java.io.StringWriter;
011import java.net.ConnectException;
012import java.net.HttpURLConnection;
013import java.net.MalformedURLException;
014import java.net.SocketTimeoutException;
015import java.net.URL;
016import java.nio.charset.StandardCharsets;
017import java.util.Collection;
018import java.util.Collections;
019import java.util.HashMap;
020import java.util.List;
021import java.util.Map;
022
023import javax.xml.parsers.ParserConfigurationException;
024
025import org.openstreetmap.josm.Main;
026import org.openstreetmap.josm.data.coor.LatLon;
027import org.openstreetmap.josm.data.notes.Note;
028import org.openstreetmap.josm.data.osm.Changeset;
029import org.openstreetmap.josm.data.osm.IPrimitive;
030import org.openstreetmap.josm.data.osm.OsmPrimitive;
031import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
032import org.openstreetmap.josm.gui.layer.ImageryLayer;
033import org.openstreetmap.josm.gui.layer.Layer;
034import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
035import org.openstreetmap.josm.gui.progress.ProgressMonitor;
036import org.openstreetmap.josm.io.Capabilities.CapabilitiesParser;
037import org.openstreetmap.josm.tools.CheckParameterUtil;
038import org.openstreetmap.josm.tools.HttpClient;
039import org.openstreetmap.josm.tools.Utils;
040import org.openstreetmap.josm.tools.XmlParsingException;
041import org.xml.sax.InputSource;
042import org.xml.sax.SAXException;
043import org.xml.sax.SAXParseException;
044
045/**
046 * Class that encapsulates the communications with the <a href="http://wiki.openstreetmap.org/wiki/API_v0.6">OSM API</a>.<br><br>
047 *
048 * All interaction with the server-side OSM API should go through this class.<br><br>
049 *
050 * It is conceivable to extract this into an interface later and create various
051 * classes implementing the interface, to be able to talk to various kinds of servers.
052 *
053 */
054public class OsmApi extends OsmConnection {
055
056    /**
057     * Maximum number of retries to send a request in case of HTTP 500 errors or timeouts
058     */
059    public static final int DEFAULT_MAX_NUM_RETRIES = 5;
060
061    /**
062     * Maximum number of concurrent download threads, imposed by
063     * <a href="http://wiki.openstreetmap.org/wiki/API_usage_policy#Technical_Usage_Requirements">
064     * OSM API usage policy.</a>
065     * @since 5386
066     */
067    public static final int MAX_DOWNLOAD_THREADS = 2;
068
069    /**
070     * Default URL of the standard OSM API.
071     * @since 5422
072     */
073    public static final String DEFAULT_API_URL = "https://api.openstreetmap.org/api";
074
075    // The collection of instantiated OSM APIs
076    private static Map<String, OsmApi> instances = new HashMap<>();
077
078    private URL url;
079
080    /**
081     * Replies the {@link OsmApi} for a given server URL
082     *
083     * @param serverUrl  the server URL
084     * @return the OsmApi
085     * @throws IllegalArgumentException if serverUrl is null
086     *
087     */
088    public static OsmApi getOsmApi(String serverUrl) {
089        OsmApi api = instances.get(serverUrl);
090        if (api == null) {
091            api = new OsmApi(serverUrl);
092            cacheInstance(api);
093        }
094        return api;
095    }
096
097    protected static void cacheInstance(OsmApi api) {
098        instances.put(api.getServerUrl(), api);
099    }
100
101    private static String getServerUrlFromPref() {
102        return Main.pref.get("osm-server.url", DEFAULT_API_URL);
103    }
104
105    /**
106     * Replies the {@link OsmApi} for the URL given by the preference <code>osm-server.url</code>
107     *
108     * @return the OsmApi
109     */
110    public static OsmApi getOsmApi() {
111        return getOsmApi(getServerUrlFromPref());
112    }
113
114    /** Server URL */
115    private final String serverUrl;
116
117    /** Object describing current changeset */
118    private Changeset changeset;
119
120    /** API version used for server communications */
121    private String version;
122
123    /** API capabilities */
124    private Capabilities capabilities;
125
126    /** true if successfully initialized */
127    private boolean initialized;
128
129    /**
130     * Constructs a new {@code OsmApi} for a specific server URL.
131     *
132     * @param serverUrl the server URL. Must not be null
133     * @throws IllegalArgumentException if serverUrl is null
134     */
135    protected OsmApi(String serverUrl) {
136        CheckParameterUtil.ensureParameterNotNull(serverUrl, "serverUrl");
137        this.serverUrl = serverUrl;
138    }
139
140    /**
141     * Replies the OSM protocol version we use to talk to the server.
142     * @return protocol version, or null if not yet negotiated.
143     */
144    public String getVersion() {
145        return version;
146    }
147
148    /**
149     * Replies the host name of the server URL.
150     * @return the host name of the server URL, or null if the server URL is malformed.
151     */
152    public String getHost() {
153        String host = null;
154        try {
155            host = (new URL(serverUrl)).getHost();
156        } catch (MalformedURLException e) {
157            Main.warn(e);
158        }
159        return host;
160    }
161
162    private class CapabilitiesCache extends CacheCustomContent<OsmTransferException> {
163
164        private static final String CAPABILITIES = "capabilities";
165
166        private final ProgressMonitor monitor;
167        private final boolean fastFail;
168
169        CapabilitiesCache(ProgressMonitor monitor, boolean fastFail) {
170            super(CAPABILITIES + getBaseUrl().hashCode(), CacheCustomContent.INTERVAL_WEEKLY);
171            this.monitor = monitor;
172            this.fastFail = fastFail;
173        }
174
175        @Override
176        protected void checkOfflineAccess() {
177            OnlineResource.OSM_API.checkOfflineAccess(getBaseUrl(getServerUrlFromPref(), "0.6")+CAPABILITIES, getServerUrlFromPref());
178        }
179
180        @Override
181        protected byte[] updateData() throws OsmTransferException {
182            return sendRequest("GET", CAPABILITIES, null, monitor, false, fastFail).getBytes(StandardCharsets.UTF_8);
183        }
184    }
185
186    /**
187     * Initializes this component by negotiating a protocol version with the server.
188     *
189     * @param monitor the progress monitor
190     * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
191     * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
192     */
193    public void initialize(ProgressMonitor monitor) throws OsmTransferCanceledException, OsmApiInitializationException {
194        initialize(monitor, false);
195    }
196
197    /**
198     * Initializes this component by negotiating a protocol version with the server, with the ability to control the timeout.
199     *
200     * @param monitor the progress monitor
201     * @param fastFail true to request quick initialisation with a small timeout (more likely to throw exception)
202     * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
203     * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
204     */
205    public void initialize(ProgressMonitor monitor, boolean fastFail) throws OsmTransferCanceledException, OsmApiInitializationException {
206        if (initialized)
207            return;
208        cancel = false;
209        try {
210            CapabilitiesCache cache = new CapabilitiesCache(monitor, fastFail);
211            try {
212                initializeCapabilities(cache.updateIfRequiredString());
213            } catch (SAXParseException parseException) {
214                Main.trace(parseException);
215                // XML parsing may fail if JOSM previously stored a corrupted capabilities document (see #8278)
216                // In that case, force update and try again
217                initializeCapabilities(cache.updateForceString());
218            }
219            if (capabilities == null) {
220                if (Main.isOffline(OnlineResource.OSM_API)) {
221                    Main.warn(tr("{0} not available (offline mode)", tr("OSM API")));
222                } else {
223                    Main.error(tr("Unable to initialize OSM API."));
224                }
225                return;
226            } else if (!capabilities.supportsVersion("0.6")) {
227                Main.error(tr("This version of JOSM is incompatible with the configured server."));
228                Main.error(tr("It supports protocol version 0.6, while the server says it supports {0} to {1}.",
229                        capabilities.get("version", "minimum"), capabilities.get("version", "maximum")));
230                return;
231            } else {
232                version = "0.6";
233                initialized = true;
234            }
235
236            /* This is an interim solution for openstreetmap.org not currently
237             * transmitting their imagery blacklist in the capabilities call.
238             * remove this as soon as openstreetmap.org adds blacklists.
239             * If you want to update this list, please ask for update of
240             * http://trac.openstreetmap.org/ticket/5024
241             * This list should not be maintained by each OSM editor (see #9210) */
242            if (this.serverUrl.matches(".*openstreetmap.org/api.*") && capabilities.getImageryBlacklist().isEmpty()) {
243                capabilities.put("blacklist", "regex", ".*\\.google\\.com/.*");
244                capabilities.put("blacklist", "regex", ".*209\\.85\\.2\\d\\d.*");
245                capabilities.put("blacklist", "regex", ".*209\\.85\\.1[3-9]\\d.*");
246                capabilities.put("blacklist", "regex", ".*209\\.85\\.12[89].*");
247            }
248
249            /* This checks if there are any layers currently displayed that
250             * are now on the blacklist, and removes them. This is a rare
251             * situation - probably only occurs if the user changes the API URL
252             * in the preferences menu. Otherwise they would not have been able
253             * to load the layers in the first place because they would have
254             * been disabled! */
255            if (Main.isDisplayingMapView()) {
256                for (Layer l : Main.getLayerManager().getLayersOfType(ImageryLayer.class)) {
257                    if (((ImageryLayer) l).getInfo().isBlacklisted()) {
258                        Main.info(tr("Removed layer {0} because it is not allowed by the configured API.", l.getName()));
259                        Main.getLayerManager().removeLayer(l);
260                    }
261                }
262            }
263
264        } catch (OsmTransferCanceledException e) {
265            throw e;
266        } catch (OsmTransferException e) {
267            initialized = false;
268            Main.addNetworkError(url, Utils.getRootCause(e));
269            throw new OsmApiInitializationException(e);
270        } catch (SAXException | IOException | ParserConfigurationException e) {
271            initialized = false;
272            throw new OsmApiInitializationException(e);
273        }
274    }
275
276    private synchronized void initializeCapabilities(String xml) throws SAXException, IOException, ParserConfigurationException {
277        if (xml != null) {
278            capabilities = CapabilitiesParser.parse(new InputSource(new StringReader(xml)));
279        }
280    }
281
282    /**
283     * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
284     * @param o the OSM primitive
285     * @param addBody true to generate the full XML, false to only generate the encapsulating tag
286     * @return XML string
287     */
288    protected final String toXml(IPrimitive o, boolean addBody) {
289        StringWriter swriter = new StringWriter();
290        try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
291            swriter.getBuffer().setLength(0);
292            osmWriter.setWithBody(addBody);
293            osmWriter.setChangeset(changeset);
294            osmWriter.header();
295            o.accept(osmWriter);
296            osmWriter.footer();
297            osmWriter.flush();
298        } catch (IOException e) {
299            Main.warn(e);
300        }
301        return swriter.toString();
302    }
303
304    /**
305     * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
306     * @param s the changeset
307     * @return XML string
308     */
309    protected final String toXml(Changeset s) {
310        StringWriter swriter = new StringWriter();
311        try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
312            swriter.getBuffer().setLength(0);
313            osmWriter.header();
314            osmWriter.visit(s);
315            osmWriter.footer();
316            osmWriter.flush();
317        } catch (IOException e) {
318            Main.warn(e);
319        }
320        return swriter.toString();
321    }
322
323    private static String getBaseUrl(String serverUrl, String version) {
324        StringBuilder rv = new StringBuilder(serverUrl);
325        if (version != null) {
326            rv.append('/').append(version);
327        }
328        rv.append('/');
329        // this works around a ruby (or lighttpd) bug where two consecutive slashes in
330        // an URL will cause a "404 not found" response.
331        int p;
332        while ((p = rv.indexOf("//", rv.indexOf("://")+2)) > -1) {
333            rv.delete(p, p + 1);
334        }
335        return rv.toString();
336    }
337
338    /**
339     * Returns the base URL for API requests, including the negotiated version number.
340     * @return base URL string
341     */
342    public String getBaseUrl() {
343        return getBaseUrl(serverUrl, version);
344    }
345
346    /**
347     * Returns the server URL
348     * @return the server URL
349     * @since 9353
350     */
351    public String getServerUrl() {
352        return serverUrl;
353    }
354
355    /**
356     * Creates an OSM primitive on the server. The OsmPrimitive object passed in
357     * is modified by giving it the server-assigned id.
358     *
359     * @param osm the primitive
360     * @param monitor the progress monitor
361     * @throws OsmTransferException if something goes wrong
362     */
363    public void createPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
364        String ret = "";
365        try {
366            ensureValidChangeset();
367            initialize(monitor);
368            ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/create", toXml(osm, true), monitor);
369            osm.setOsmId(Long.parseLong(ret.trim()), 1);
370            osm.setChangesetId(getChangeset().getId());
371        } catch (NumberFormatException e) {
372            throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret), e);
373        }
374    }
375
376    /**
377     * Modifies an OSM primitive on the server.
378     *
379     * @param osm the primitive. Must not be null.
380     * @param monitor the progress monitor
381     * @throws OsmTransferException if something goes wrong
382     */
383    public void modifyPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
384        String ret = null;
385        try {
386            ensureValidChangeset();
387            initialize(monitor);
388            // normal mode (0.6 and up) returns new object version.
389            ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+'/' + osm.getId(), toXml(osm, true), monitor);
390            osm.setOsmId(osm.getId(), Integer.parseInt(ret.trim()));
391            osm.setChangesetId(getChangeset().getId());
392            osm.setVisible(true);
393        } catch (NumberFormatException e) {
394            throw new OsmTransferException(tr("Unexpected format of new version of modified primitive ''{0}''. Got ''{1}''.",
395                    osm.getId(), ret), e);
396        }
397    }
398
399    /**
400     * Deletes an OSM primitive on the server.
401     * @param osm the primitive
402     * @param monitor the progress monitor
403     * @throws OsmTransferException if something goes wrong
404     */
405    public void deletePrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
406        ensureValidChangeset();
407        initialize(monitor);
408        // can't use a the individual DELETE method in the 0.6 API. Java doesn't allow
409        // submitting a DELETE request with content, the 0.6 API requires it, however. Falling back
410        // to diff upload.
411        //
412        uploadDiff(Collections.singleton(osm), monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
413    }
414
415    /**
416     * Creates a new changeset based on the keys in <code>changeset</code>. If this
417     * method succeeds, changeset.getId() replies the id the server assigned to the new
418     * changeset
419     *
420     * The changeset must not be null, but its key/value-pairs may be empty.
421     *
422     * @param changeset the changeset toe be created. Must not be null.
423     * @param progressMonitor the progress monitor
424     * @throws OsmTransferException signifying a non-200 return code, or connection errors
425     * @throws IllegalArgumentException if changeset is null
426     */
427    public void openChangeset(Changeset changeset, ProgressMonitor progressMonitor) throws OsmTransferException {
428        CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
429        try {
430            progressMonitor.beginTask(tr("Creating changeset..."));
431            initialize(progressMonitor);
432            String ret = "";
433            try {
434                ret = sendRequest("PUT", "changeset/create", toXml(changeset), progressMonitor);
435                changeset.setId(Integer.parseInt(ret.trim()));
436                changeset.setOpen(true);
437            } catch (NumberFormatException e) {
438                throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret), e);
439            }
440            progressMonitor.setCustomText(tr("Successfully opened changeset {0}", changeset.getId()));
441        } finally {
442            progressMonitor.finishTask();
443        }
444    }
445
446    /**
447     * Updates a changeset with the keys in  <code>changesetUpdate</code>. The changeset must not
448     * be null and id &gt; 0 must be true.
449     *
450     * @param changeset the changeset to update. Must not be null.
451     * @param monitor the progress monitor. If null, uses the {@link NullProgressMonitor#INSTANCE}.
452     *
453     * @throws OsmTransferException if something goes wrong.
454     * @throws IllegalArgumentException if changeset is null
455     * @throws IllegalArgumentException if changeset.getId() &lt;= 0
456     *
457     */
458    public void updateChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
459        CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
460        if (monitor == null) {
461            monitor = NullProgressMonitor.INSTANCE;
462        }
463        if (changeset.getId() <= 0)
464            throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
465        try {
466            monitor.beginTask(tr("Updating changeset..."));
467            initialize(monitor);
468            monitor.setCustomText(tr("Updating changeset {0}...", changeset.getId()));
469            sendRequest(
470                    "PUT",
471                    "changeset/" + changeset.getId(),
472                    toXml(changeset),
473                    monitor
474            );
475        } catch (ChangesetClosedException e) {
476            e.setSource(ChangesetClosedException.Source.UPDATE_CHANGESET);
477            throw e;
478        } catch (OsmApiException e) {
479            String errorHeader = e.getErrorHeader();
480            if (e.getResponseCode() == HttpURLConnection.HTTP_CONFLICT && ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
481                throw new ChangesetClosedException(errorHeader, ChangesetClosedException.Source.UPDATE_CHANGESET);
482            throw e;
483        } finally {
484            monitor.finishTask();
485        }
486    }
487
488    /**
489     * Closes a changeset on the server. Sets changeset.setOpen(false) if this operation succeeds.
490     *
491     * @param changeset the changeset to be closed. Must not be null. changeset.getId() &gt; 0 required.
492     * @param monitor the progress monitor. If null, uses {@link NullProgressMonitor#INSTANCE}
493     *
494     * @throws OsmTransferException if something goes wrong.
495     * @throws IllegalArgumentException if changeset is null
496     * @throws IllegalArgumentException if changeset.getId() &lt;= 0
497     */
498    public void closeChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
499        CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
500        if (monitor == null) {
501            monitor = NullProgressMonitor.INSTANCE;
502        }
503        if (changeset.getId() <= 0)
504            throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
505        try {
506            monitor.beginTask(tr("Closing changeset..."));
507            initialize(monitor);
508            /* send "\r\n" instead of empty string, so we don't send zero payload - works around bugs
509               in proxy software */
510            sendRequest("PUT", "changeset" + "/" + changeset.getId() + "/close", "\r\n", monitor);
511            changeset.setOpen(false);
512        } finally {
513            monitor.finishTask();
514        }
515    }
516
517    /**
518     * Uploads a list of changes in "diff" form to the server.
519     *
520     * @param list the list of changed OSM Primitives
521     * @param  monitor the progress monitor
522     * @return list of processed primitives
523     * @throws OsmTransferException if something is wrong
524     */
525    public Collection<OsmPrimitive> uploadDiff(Collection<? extends OsmPrimitive> list, ProgressMonitor monitor)
526            throws OsmTransferException {
527        try {
528            monitor.beginTask("", list.size() * 2);
529            if (changeset == null)
530                throw new OsmTransferException(tr("No changeset present for diff upload."));
531
532            initialize(monitor);
533
534            // prepare upload request
535            //
536            OsmChangeBuilder changeBuilder = new OsmChangeBuilder(changeset);
537            monitor.subTask(tr("Preparing upload request..."));
538            changeBuilder.start();
539            changeBuilder.append(list);
540            changeBuilder.finish();
541            String diffUploadRequest = changeBuilder.getDocument();
542
543            // Upload to the server
544            //
545            monitor.indeterminateSubTask(
546                    trn("Uploading {0} object...", "Uploading {0} objects...", list.size(), list.size()));
547            String diffUploadResponse = sendRequest("POST", "changeset/" + changeset.getId() + "/upload", diffUploadRequest, monitor);
548
549            // Process the response from the server
550            //
551            DiffResultProcessor reader = new DiffResultProcessor(list);
552            reader.parse(diffUploadResponse, monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
553            return reader.postProcess(
554                    getChangeset(),
555                    monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)
556            );
557        } catch (OsmTransferException e) {
558            throw e;
559        } catch (XmlParsingException e) {
560            throw new OsmTransferException(e);
561        } finally {
562            monitor.finishTask();
563        }
564    }
565
566    private void sleepAndListen(int retry, ProgressMonitor monitor) throws OsmTransferCanceledException {
567        Main.info(tr("Waiting 10 seconds ... "));
568        for (int i = 0; i < 10; i++) {
569            if (monitor != null) {
570                monitor.setCustomText(tr("Starting retry {0} of {1} in {2} seconds ...", getMaxRetries() - retry, getMaxRetries(), 10-i));
571            }
572            if (cancel)
573                throw new OsmTransferCanceledException("Operation canceled" + (i > 0 ? " in retry #"+i : ""));
574            try {
575                Thread.sleep(1000);
576            } catch (InterruptedException ex) {
577                Main.warn("InterruptedException in "+getClass().getSimpleName()+" during sleep");
578            }
579        }
580        Main.info(tr("OK - trying again."));
581    }
582
583    /**
584     * Replies the max. number of retries in case of 5XX errors on the server
585     *
586     * @return the max number of retries
587     */
588    protected int getMaxRetries() {
589        int ret = Main.pref.getInteger("osm-server.max-num-retries", DEFAULT_MAX_NUM_RETRIES);
590        return Math.max(ret, 0);
591    }
592
593    /**
594     * Determines if JOSM is configured to access OSM API via OAuth
595     * @return {@code true} if JOSM is configured to access OSM API via OAuth, {@code false} otherwise
596     * @since 6349
597     */
598    public static boolean isUsingOAuth() {
599        return "oauth".equals(getAuthMethod());
600    }
601
602    /**
603     * Returns the authentication method set in the preferences
604     * @return the authentication method
605     */
606    public static String getAuthMethod() {
607        return Main.pref.get("osm-server.auth-method", "oauth");
608    }
609
610    protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor)
611            throws OsmTransferException {
612        return sendRequest(requestMethod, urlSuffix, requestBody, monitor, true, false);
613    }
614
615    /**
616     * Generic method for sending requests to the OSM API.
617     *
618     * This method will automatically re-try any requests that are answered with a 5xx
619     * error code, or that resulted in a timeout exception from the TCP layer.
620     *
621     * @param requestMethod The http method used when talking with the server.
622     * @param urlSuffix The suffix to add at the server url, not including the version number,
623     *    but including any object ids (e.g. "/way/1234/history").
624     * @param requestBody the body of the HTTP request, if any.
625     * @param monitor the progress monitor
626     * @param doAuthenticate  set to true, if the request sent to the server shall include authentication
627     * credentials;
628     * @param fastFail true to request a short timeout
629     *
630     * @return the body of the HTTP response, if and only if the response code was "200 OK".
631     * @throws OsmTransferException if the HTTP return code was not 200 (and retries have
632     *    been exhausted), or rewrapping a Java exception.
633     */
634    protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor,
635            boolean doAuthenticate, boolean fastFail) throws OsmTransferException {
636        int retries = fastFail ? 0 : getMaxRetries();
637
638        while (true) { // the retry loop
639            try {
640                url = new URL(new URL(getBaseUrl()), urlSuffix);
641                final HttpClient client = HttpClient.create(url, requestMethod).keepAlive(false);
642                activeConnection = client;
643                if (fastFail) {
644                    client.setConnectTimeout(1000);
645                    client.setReadTimeout(1000);
646                } else {
647                    // use default connect timeout from org.openstreetmap.josm.tools.HttpClient.connectTimeout
648                    client.setReadTimeout(0);
649                }
650                if (doAuthenticate) {
651                    addAuth(client);
652                }
653
654                if ("PUT".equals(requestMethod) || "POST".equals(requestMethod) || "DELETE".equals(requestMethod)) {
655                    client.setHeader("Content-Type", "text/xml");
656                    // It seems that certain bits of the Ruby API are very unhappy upon
657                    // receipt of a PUT/POST message without a Content-length header,
658                    // even if the request has no payload.
659                    // Since Java will not generate a Content-length header unless
660                    // we use the output stream, we create an output stream for PUT/POST
661                    // even if there is no payload.
662                    client.setRequestBody((requestBody != null ? requestBody : "").getBytes(StandardCharsets.UTF_8));
663                }
664
665                final HttpClient.Response response = client.connect();
666                Main.info(response.getResponseMessage());
667                int retCode = response.getResponseCode();
668
669                if (retCode >= 500) {
670                    if (retries-- > 0) {
671                        sleepAndListen(retries, monitor);
672                        Main.info(tr("Starting retry {0} of {1}.", getMaxRetries() - retries, getMaxRetries()));
673                        continue;
674                    }
675                }
676
677                final String responseBody = response.fetchContent();
678
679                String errorHeader = null;
680                // Look for a detailed error message from the server
681                if (response.getHeaderField("Error") != null) {
682                    errorHeader = response.getHeaderField("Error");
683                    Main.error("Error header: " + errorHeader);
684                } else if (retCode != HttpURLConnection.HTTP_OK && responseBody.length() > 0) {
685                    Main.error("Error body: " + responseBody);
686                }
687                activeConnection.disconnect();
688
689                errorHeader = errorHeader == null ? null : errorHeader.trim();
690                String errorBody = responseBody.length() == 0 ? null : responseBody.trim();
691                switch(retCode) {
692                case HttpURLConnection.HTTP_OK:
693                    return responseBody;
694                case HttpURLConnection.HTTP_GONE:
695                    throw new OsmApiPrimitiveGoneException(errorHeader, errorBody);
696                case HttpURLConnection.HTTP_CONFLICT:
697                    if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
698                        throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA);
699                    else
700                        throw new OsmApiException(retCode, errorHeader, errorBody);
701                case HttpURLConnection.HTTP_FORBIDDEN:
702                    OsmApiException e = new OsmApiException(retCode, errorHeader, errorBody);
703                    e.setAccessedUrl(activeConnection.getURL().toString());
704                    throw e;
705                default:
706                    throw new OsmApiException(retCode, errorHeader, errorBody);
707                }
708            } catch (SocketTimeoutException | ConnectException e) {
709                if (retries-- > 0) {
710                    continue;
711                }
712                throw new OsmTransferException(e);
713            } catch (IOException e) {
714                throw new OsmTransferException(e);
715            } catch (OsmTransferException e) {
716                throw e;
717            }
718        }
719    }
720
721    /**
722     * Replies the API capabilities.
723     *
724     * @return the API capabilities, or null, if the API is not initialized yet
725     */
726    public synchronized Capabilities getCapabilities() {
727        return capabilities;
728    }
729
730    /**
731     * Ensures that the current changeset can be used for uploading data
732     *
733     * @throws OsmTransferException if the current changeset can't be used for uploading data
734     */
735    protected void ensureValidChangeset() throws OsmTransferException {
736        if (changeset == null)
737            throw new OsmTransferException(tr("Current changeset is null. Cannot upload data."));
738        if (changeset.getId() <= 0)
739            throw new OsmTransferException(tr("ID of current changeset > 0 required. Current ID is {0}.", changeset.getId()));
740    }
741
742    /**
743     * Replies the changeset data uploads are currently directed to
744     *
745     * @return the changeset data uploads are currently directed to
746     */
747    public Changeset getChangeset() {
748        return changeset;
749    }
750
751    /**
752     * Sets the changesets to which further data uploads are directed. The changeset
753     * can be null. If it isn't null it must have been created, i.e. id &gt; 0 is required. Furthermore,
754     * it must be open.
755     *
756     * @param changeset the changeset
757     * @throws IllegalArgumentException if changeset.getId() &lt;= 0
758     * @throws IllegalArgumentException if !changeset.isOpen()
759     */
760    public void setChangeset(Changeset changeset) {
761        if (changeset == null) {
762            this.changeset = null;
763            return;
764        }
765        if (changeset.getId() <= 0)
766            throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
767        if (!changeset.isOpen())
768            throw new IllegalArgumentException(tr("Open changeset expected. Got closed changeset with id {0}.", changeset.getId()));
769        this.changeset = changeset;
770    }
771
772    private static StringBuilder noteStringBuilder(Note note) {
773        return new StringBuilder().append("notes/").append(note.getId());
774    }
775
776    /**
777     * Create a new note on the server.
778     * @param latlon Location of note
779     * @param text Comment entered by user to open the note
780     * @param monitor Progress monitor
781     * @return Note as it exists on the server after creation (ID assigned)
782     * @throws OsmTransferException if any error occurs during dialog with OSM API
783     */
784    public Note createNote(LatLon latlon, String text, ProgressMonitor monitor) throws OsmTransferException {
785        initialize(monitor);
786        String noteUrl = new StringBuilder()
787            .append("notes?lat=")
788            .append(latlon.lat())
789            .append("&lon=")
790            .append(latlon.lon())
791            .append("&text=")
792            .append(Utils.encodeUrl(text)).toString();
793
794        String response = sendRequest("POST", noteUrl, null, monitor, true, false);
795        return parseSingleNote(response);
796    }
797
798    /**
799     * Add a comment to an existing note.
800     * @param note The note to add a comment to
801     * @param comment Text of the comment
802     * @param monitor Progress monitor
803     * @return Note returned by the API after the comment was added
804     * @throws OsmTransferException if any error occurs during dialog with OSM API
805     */
806    public Note addCommentToNote(Note note, String comment, ProgressMonitor monitor) throws OsmTransferException {
807        initialize(monitor);
808        String noteUrl = noteStringBuilder(note)
809            .append("/comment?text=")
810            .append(Utils.encodeUrl(comment)).toString();
811
812        String response = sendRequest("POST", noteUrl, null, monitor, true, false);
813        return parseSingleNote(response);
814    }
815
816    /**
817     * Close a note.
818     * @param note Note to close. Must currently be open
819     * @param closeMessage Optional message supplied by the user when closing the note
820     * @param monitor Progress monitor
821     * @return Note returned by the API after the close operation
822     * @throws OsmTransferException if any error occurs during dialog with OSM API
823     */
824    public Note closeNote(Note note, String closeMessage, ProgressMonitor monitor) throws OsmTransferException {
825        initialize(monitor);
826        String encodedMessage = Utils.encodeUrl(closeMessage);
827        StringBuilder urlBuilder = noteStringBuilder(note)
828            .append("/close");
829        if (encodedMessage != null && !encodedMessage.trim().isEmpty()) {
830            urlBuilder.append("?text=");
831            urlBuilder.append(encodedMessage);
832        }
833
834        String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false);
835        return parseSingleNote(response);
836    }
837
838    /**
839     * Reopen a closed note
840     * @param note Note to reopen. Must currently be closed
841     * @param reactivateMessage Optional message supplied by the user when reopening the note
842     * @param monitor Progress monitor
843     * @return Note returned by the API after the reopen operation
844     * @throws OsmTransferException if any error occurs during dialog with OSM API
845     */
846    public Note reopenNote(Note note, String reactivateMessage, ProgressMonitor monitor) throws OsmTransferException {
847        initialize(monitor);
848        String encodedMessage = Utils.encodeUrl(reactivateMessage);
849        StringBuilder urlBuilder = noteStringBuilder(note)
850            .append("/reopen");
851        if (encodedMessage != null && !encodedMessage.trim().isEmpty()) {
852            urlBuilder.append("?text=");
853            urlBuilder.append(encodedMessage);
854        }
855
856        String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false);
857        return parseSingleNote(response);
858    }
859
860    /**
861     * Method for parsing API responses for operations on individual notes
862     * @param xml the API response as XML data
863     * @return the resulting Note
864     * @throws OsmTransferException if the API response cannot be parsed
865     */
866    private static Note parseSingleNote(String xml) throws OsmTransferException {
867        try {
868            List<Note> newNotes = new NoteReader(xml).parse();
869            if (newNotes.size() == 1) {
870                return newNotes.get(0);
871            }
872            // Shouldn't ever execute. Server will either respond with an error (caught elsewhere) or one note
873            throw new OsmTransferException(tr("Note upload failed"));
874        } catch (SAXException | IOException e) {
875            Main.error(e, true);
876            throw new OsmTransferException(tr("Error parsing note response from server"), e);
877        }
878    }
879}