1 package edu.jiangxin.apktoolbox.swing.extend.plugin.runnable;
2
3 import edu.jiangxin.apktoolbox.swing.extend.plugin.ChangeMenuPreparePluginController;
4 import edu.jiangxin.apktoolbox.swing.extend.plugin.IPreparePluginCallback;
5 import org.apache.commons.io.FileUtils;
6 import org.apache.logging.log4j.LogManager;
7 import org.apache.logging.log4j.Logger;
8
9 import javax.swing.*;
10 import java.io.*;
11 import java.net.HttpURLConnection;
12 import java.net.URL;
13 import java.util.List;
14 import java.util.Map;
15
16 public class DownloadRunnable extends AbstractRunnable {
17 private static final Logger LOGGER = LogManager.getLogger(DownloadRunnable.class.getSimpleName());
18 private final URL url;
19 private final File downloadDir;
20
21 public DownloadRunnable(URL url, File downloadDir, IPreparePluginCallback callback) {
22 super("Downloading...", callback);
23 this.url = url;
24 this.downloadDir = downloadDir;
25 }
26
27 @Override
28 public void run() {
29 SwingUtilities.invokeLater(() -> progressBarDialog.setVisible(true));
30 HttpURLConnection conn;
31 try {
32 conn = (HttpURLConnection) url.openConnection();
33 conn.setRequestMethod("GET");
34 conn.setUseCaches(false);
35 conn.setConnectTimeout(5000);
36 conn.connect();
37 } catch (IOException e) {
38 LOGGER.error("download failed: {}", e.getMessage());
39 callback.onDownloadFinished(ChangeMenuPreparePluginController.RESULT_DOWNLOAD_FAILED);
40 return;
41 }
42
43 Map<String, List<String>> map = conn.getHeaderFields();
44 List<String> contentLengthList = map.get("Content-Length");
45 int downloadLength = 1;
46 if (contentLengthList != null && !contentLengthList.isEmpty()) {
47 downloadLength = Integer.parseInt(contentLengthList.get(0));
48 }
49
50 String urlStr = url.toString();
51 String fileName = urlStr.substring(urlStr.lastIndexOf("/") + 1);
52 File downloadFile = new File(downloadDir, fileName);
53
54 try (BufferedInputStream is = new BufferedInputStream(conn.getInputStream());
55 BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(downloadFile))) {
56 byte[] b = new byte[2048];
57 int length;
58 long count = 0;
59 while ((length = is.read(b)) != -1 && !isCancelled) {
60 os.write(b, 0, length);
61 count += length;
62 progress = (int)(count * 100 / downloadLength);
63 }
64 } catch (IOException e) {
65 SwingUtilities.invokeLater(() -> progressBarDialog.dispose());
66 LOGGER.error("download failed: {}", e.getMessage());
67 callback.onDownloadFinished(ChangeMenuPreparePluginController.RESULT_DOWNLOAD_FAILED);
68 return;
69 }
70 if (isCancelled) {
71 LOGGER.info("download cancelled");
72 FileUtils.deleteQuietly(downloadFile);
73 callback.onDownloadFinished(ChangeMenuPreparePluginController.RESULT_DOWNLOAD_CANCELLED);
74 } else {
75 isFinished = true;
76 callback.onDownloadFinished(ChangeMenuPreparePluginController.RESULT_DOWNLOAD_SUCCESS);
77 }
78 }
79 }