001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui.io; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.awt.Component; 007import java.io.File; 008import java.io.FileOutputStream; 009import java.io.IOException; 010import java.io.InputStream; 011import java.io.OutputStream; 012import java.net.MalformedURLException; 013import java.net.URL; 014import java.nio.charset.StandardCharsets; 015import java.nio.file.Files; 016import java.nio.file.StandardCopyOption; 017import java.util.Enumeration; 018import java.util.zip.ZipEntry; 019import java.util.zip.ZipFile; 020 021import org.openstreetmap.josm.Main; 022import org.openstreetmap.josm.gui.PleaseWaitDialog; 023import org.openstreetmap.josm.gui.PleaseWaitRunnable; 024import org.openstreetmap.josm.tools.HttpClient; 025import org.openstreetmap.josm.tools.Utils; 026import org.xml.sax.SAXException; 027 028/** 029 * Asynchronous task for downloading and unpacking arbitrary file lists 030 * Shows progress bar when downloading 031 */ 032public class DownloadFileTask extends PleaseWaitRunnable { 033 private final String address; 034 private final File file; 035 private final boolean mkdir; 036 private final boolean unpack; 037 038 /** 039 * Creates the download task 040 * 041 * @param parent the parent component relative to which the {@link PleaseWaitDialog} is displayed 042 * @param address the URL to download 043 * @param file The destination file 044 * @param mkdir {@code true} if the destination directory must be created, {@code false} otherwise 045 * @param unpack {@code true} if zip archives must be unpacked recursively, {@code false} otherwise 046 * @throws IllegalArgumentException if {@code parent} is null 047 */ 048 public DownloadFileTask(Component parent, String address, File file, boolean mkdir, boolean unpack) { 049 super(parent, tr("Downloading file"), false); 050 this.address = address; 051 this.file = file; 052 this.mkdir = mkdir; 053 this.unpack = unpack; 054 } 055 056 private static class DownloadException extends Exception { 057 /** 058 * Constructs a new {@code DownloadException}. 059 * @param message the detail message. The detail message is saved for 060 * later retrieval by the {@link #getMessage()} method. 061 * @param cause the cause (which is saved for later retrieval by the 062 * {@link #getCause()} method). (A <tt>null</tt> value is 063 * permitted, and indicates that the cause is nonexistent or unknown.) 064 */ 065 DownloadException(String message, Throwable cause) { 066 super(message, cause); 067 } 068 } 069 070 private boolean canceled; 071 private HttpClient downloadConnection; 072 073 private synchronized void closeConnectionIfNeeded() { 074 if (downloadConnection != null) { 075 downloadConnection.disconnect(); 076 } 077 downloadConnection = null; 078 } 079 080 @Override 081 protected void cancel() { 082 this.canceled = true; 083 closeConnectionIfNeeded(); 084 } 085 086 @Override 087 protected void finish() {} 088 089 /** 090 * Performs download. 091 * @throws DownloadException if the URL is invalid or if any I/O error occurs. 092 */ 093 public void download() throws DownloadException { 094 try { 095 if (mkdir) { 096 File newDir = file.getParentFile(); 097 if (!newDir.exists()) { 098 newDir.mkdirs(); 099 } 100 } 101 102 URL url = new URL(address); 103 long size; 104 synchronized (this) { 105 downloadConnection = HttpClient.create(url).useCache(false); 106 downloadConnection.connect(); 107 size = downloadConnection.getResponse().getContentLength(); 108 } 109 110 progressMonitor.setTicksCount(100); 111 progressMonitor.subTask(tr("Downloading File {0}: {1} bytes...", file.getName(), size)); 112 113 try ( 114 InputStream in = downloadConnection.getResponse().getContent(); 115 OutputStream out = new FileOutputStream(file) 116 ) { 117 byte[] buffer = new byte[32768]; 118 int count = 0; 119 long p1 = 0, p2 = 0; 120 for (int read = in.read(buffer); read != -1; read = in.read(buffer)) { 121 out.write(buffer, 0, read); 122 count += read; 123 if (canceled) break; 124 p2 = 100 * count / size; 125 if (p2 != p1) { 126 progressMonitor.setTicks((int) p2); 127 p1 = p2; 128 } 129 } 130 } 131 if (!canceled) { 132 Main.info(tr("Download finished")); 133 if (unpack) { 134 Main.info(tr("Unpacking {0} into {1}", file.getAbsolutePath(), file.getParent())); 135 unzipFileRecursively(file, file.getParent()); 136 Utils.deleteFile(file); 137 } 138 } 139 } catch (MalformedURLException e) { 140 String msg = tr("Cannot download file ''{0}''. Its download link ''{1}'' is not a valid URL. Skipping download.", 141 file.getName(), address); 142 Main.warn(msg); 143 throw new DownloadException(msg, e); 144 } catch (IOException e) { 145 if (canceled) 146 return; 147 throw new DownloadException(e.getMessage(), e); 148 } finally { 149 closeConnectionIfNeeded(); 150 } 151 } 152 153 @Override 154 protected void realRun() throws SAXException, IOException { 155 if (canceled) return; 156 try { 157 download(); 158 } catch (DownloadException e) { 159 Main.error(e); 160 } 161 } 162 163 /** 164 * Replies true if the task was canceled by the user 165 * 166 * @return {@code true} if the task was canceled by the user, {@code false} otherwise 167 */ 168 public boolean isCanceled() { 169 return canceled; 170 } 171 172 /** 173 * Recursive unzipping function 174 * TODO: May be placed somewhere else - Tools.Utils? 175 * @param file zip file 176 * @param dir output directory 177 * @throws IOException if any I/O error occurs 178 */ 179 public static void unzipFileRecursively(File file, String dir) throws IOException { 180 try (ZipFile zf = new ZipFile(file, StandardCharsets.UTF_8)) { 181 Enumeration<? extends ZipEntry> es = zf.entries(); 182 while (es.hasMoreElements()) { 183 ZipEntry ze = es.nextElement(); 184 File newFile = new File(dir, ze.getName()); 185 if (ze.isDirectory()) { 186 newFile.mkdirs(); 187 } else try (InputStream is = zf.getInputStream(ze)) { 188 Files.copy(is, newFile.toPath(), StandardCopyOption.REPLACE_EXISTING); 189 } 190 } 191 } 192 } 193}