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