source: josm/trunk/src/org/openstreetmap/josm/io/OsmApi.java @ 12992

Last change on this file since 12992 was 12992, checked in by Don-vip, 12 months ago

fix #15435 - do not cache incorrect login credentials when using basic auth

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