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