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

Last change on this file since 12841 was 12841, checked in by bastiK, 5 weeks ago

see #15229 - fix deprecations caused by [12840]

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