001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions.downloadtasks;
003
004import java.net.URL;
005import java.util.List;
006import java.util.Objects;
007import java.util.concurrent.Future;
008import java.util.stream.Collectors;
009
010import org.openstreetmap.josm.data.Bounds;
011import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
012import org.openstreetmap.josm.gui.progress.ProgressMonitor;
013import org.openstreetmap.josm.io.XmlWriter;
014import org.openstreetmap.josm.tools.ExceptionUtil;
015
016/**
017 * Interface defining a general download task used to download geographic data (OSM data, GPX tracks, etc.) for a given URL or geographic area.
018 */
019public interface DownloadTask {
020
021    /**
022     * Asynchronously launches the download task for a given bounding box.
023     * <p>
024     * Set <code>progressMonitor</code> to null, if the task should create, open, and close a progress monitor.
025     * Set progressMonitor to {@link NullProgressMonitor#INSTANCE} if progress information is to
026     * be discarded.
027     * <p>
028     * You can wait for the asynchronous download task to finish by synchronizing on the returned
029     * {@link Future}, but make sure not to freeze up JOSM. Example:
030     * <pre>
031     *    Future&lt;?&gt; future = task.download(...);
032     *    // DON'T run this on the Swing EDT or JOSM will freeze
033     *    future.get(); // waits for the dowload task to complete
034     * </pre>
035     *
036     * The following example uses a pattern which is better suited if a task is launched from
037     * the Swing EDT:
038     * <pre>
039     *    final Future&lt;?&gt; future = task.download(...);
040     *    Runnable runAfterTask = new Runnable() {
041     *       public void run() {
042     *           // this is not strictly necessary because of the type of executor service
043     *           // Main.worker is initialized with, but it doesn't harm either
044     *           //
045     *           future.get(); // wait for the download task to complete
046     *           doSomethingAfterTheTaskCompleted();
047     *       }
048     *    }
049     *    MainApplication.worker.submit(runAfterTask);
050     * </pre>
051     *
052     * @param settings download settings
053     *
054     * @param downloadArea the area to download
055     * @param progressMonitor the progressMonitor
056     * @return the future representing the asynchronous task
057     * @since 13927
058     */
059    Future<?> download(DownloadParams settings, Bounds downloadArea, ProgressMonitor progressMonitor);
060
061    /**
062     * Asynchronously launches the download task for a given bounding URL.
063     * <p>
064     * Set progressMonitor to null, if the task should create, open, and close a progress monitor.
065     * Set progressMonitor to {@link NullProgressMonitor#INSTANCE} if progress information is to
066     * be discarded.
067
068     * @param settings download settings
069     * @param url the url to download from
070     * @param progressMonitor the progressMonitor
071     * @return the future representing the asynchronous task
072     *
073     * @see #download(DownloadParams, Bounds, ProgressMonitor)
074     * @since 13927
075     */
076    Future<?> loadUrl(DownloadParams settings, String url, ProgressMonitor progressMonitor);
077
078    /**
079     * Returns true if the task is able to open the given URL, false otherwise.
080     * @param url the url to download from
081     * @param isRemotecontrol True if download request comes from remotecontrol.
082     * @return True if the task is able to open the given URL, false otherwise.
083     * Return false, if the request comes from remotecontrol, but the task is not
084     * safe for remotecontrol.
085     * A task is not safe for remotecontrol if it is possible to prepare a file
086     * for download which does something unintended, e.g. gain access to the
087     * local file system.
088     */
089    boolean acceptsUrl(String url, boolean isRemotecontrol);
090
091    /**
092     * Returns a short HTML documentation string, describing acceptable URLs.
093     * @return The HTML documentation
094     * @since 6031
095     */
096    default String acceptsDocumentationSummary() {
097        StringBuilder buff = new StringBuilder(128)
098                .append("<tr><td>")
099                .append(getTitle())
100                .append(":</td><td>");
101        String[] patterns = getPatterns();
102        if (patterns.length > 0) {
103            buff.append("<ul>");
104            for (String pattern: patterns) {
105                buff.append("<li>")
106                        .append(XmlWriter.encode(pattern))
107                        .append("</li>");
108            }
109            buff.append("</ul>");
110        }
111        buff.append("</td></tr>");
112        return buff.toString();
113    }
114
115    /**
116     * Returns human-readable description of the task
117     * @return The task description
118     * @since 6031
119     */
120    String getTitle();
121
122    /**
123     * Returns regular expressions that match the URLs
124     * @return The array of accepted URL patterns
125     * @since 6031
126     */
127    String[] getPatterns();
128
129    /**
130     * Replies the error objects of the task. Empty list, if no error messages are available.
131     * <p>
132     * Error objects are either {@link String}s with error messages or {@link Exception}s.
133     *
134     * @return the list of error objects
135     */
136    List<Object> getErrorObjects();
137
138    /**
139     * Replies the error messages of the task. Empty list, if no error messages are available.
140     *
141     * @return the list of error messages
142     * @since 17330
143     */
144    default List<String> getErrorMessages() {
145        return getErrorObjects().stream().map(o -> {
146            if (o instanceof String) {
147                return (String) o;
148            } else if (o instanceof Exception) {
149                return ExceptionUtil.explainException((Exception) o).replace("<html>", "").replace("</html>", "");
150            } else {
151                return null;
152            }
153        }).filter(Objects::nonNull).collect(Collectors.toList());
154    }
155
156    /**
157     * If this task provides potentially old data, this should return {@code true}. If so, it would be a good decision
158     * to prompt users to verify if they want the data to be downloaded to the current layer.
159     * @return {@code true} if the data could be old.
160     * @since 19550
161     */
162    default boolean providesOldData() {
163        return false;
164    }
165
166    /**
167     * Cancels the asynchronous download task.
168     *
169     */
170    void cancel();
171
172    /**
173     * Replies the HTML-formatted confirmation message to be shown to user when the given URL needs to be confirmed before loading.
174     * @param url The URL to be confirmed
175     * @return The HTML-formatted confirmation message to be shown to user
176     * @since 5691
177     */
178    String getConfirmationMessage(URL url);
179
180    /**
181     * Sets whether the map view will zoom to download area after download
182     * @param zoomAfterDownload if true, the map view will zoom to download area after download
183     * @since 13261
184     */
185    void setZoomAfterDownload(boolean zoomAfterDownload);
186}