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

Last change on this file since 12846 was 12846, checked in by bastiK, 12 months ago

see #15229 - use Config.getPref() wherever possible

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