Advertisement
heroys6

Updating UI from not FX Thread

Jul 8th, 2016
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.44 KB | None | 0 0
  1. /**
  2.  * in MainLayoutController.java
  3.  * calling download method in Task<> in new Thread
  4.  */
  5.  
  6. final int buffer = 10000; // On my hardware no more makes sense
  7.        
  8. Downloader.setController(this);
  9. Task<Void> downloadTask = new Task<Void>() {
  10.     @Override
  11.     protected Void call() throws Exception {
  12.         Downloader.downloadFile(URL, PATH, buffer);
  13.                
  14.         return null;
  15.     }
  16. };
  17. new Thread(downloadTask).start();
  18.  
  19.  
  20. /**
  21.  * Downloader.java
  22.  */
  23.  
  24. package com.ddownloader.util;
  25.  
  26. import java.io.FileOutputStream;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.io.OutputStream;
  30. import java.math.BigDecimal;
  31. import java.net.HttpURLConnection;
  32. import java.net.URL;
  33.  
  34. import com.ddownloader.view.MainLayoutController;
  35.  
  36. import javafx.application.Platform;
  37.  
  38. public class Downloader {
  39.     private static MainLayoutController mlController;
  40.    
  41.     public static void setController(MainLayoutController c) {
  42.         mlController = c;
  43.     }
  44.    
  45.     public static void downloadFile(String url, String savePath, int buffSize) {
  46.         try {
  47.             /* Get connection */
  48.             URL connection = new URL(url);
  49.             HttpURLConnection urlconn;
  50.             long size;
  51.            
  52.             urlconn = (HttpURLConnection) connection.openConnection();
  53.             urlconn.setRequestMethod("GET");
  54.             size = urlconn.getContentLengthLong();
  55.             urlconn.connect();
  56.            
  57.             /* Set input stream */
  58.             InputStream in = null;
  59.            
  60.             try {
  61.                 in = urlconn.getInputStream();
  62.             }
  63.             catch (IOException e) {
  64.                 Platform.runLater(() -> mlController.throwAlert(e.getMessage()));
  65.                 mlController.doneQuantity++;
  66.                 Platform.runLater(() ->
  67.                 mlController.downloadedLabel.setText(mlController.doneQuantity + "/" + mlController.quantity)
  68.                 );
  69.                 Platform.runLater(() ->
  70.                     mlController.updateDownloadedPB((1.0 / mlController.quantity) * mlController.doneQuantity)
  71.                 );
  72.                 Platform.runLater(() -> mlController.downloadingLabel.setText("Done"));
  73.                 Platform.runLater(() -> mlController.sizeLabel.setText("Size:"));
  74.                 Platform.runLater(() -> mlController.speedLabel.setText("Speed:"));
  75.                 return;
  76.             }
  77.            
  78.             /* Find file full path */
  79.             String[] tempArr = url.split("/");
  80.            
  81.             String fullPath = savePath + tempArr[tempArr.length - 1];
  82.            
  83.             /* Set Labels */
  84.             Platform.runLater(() -> mlController.downloadingLabel.setText(tempArr[tempArr.length - 1]));
  85.             Platform.runLater(() -> mlController.downloadingPB.setProgress(0.0));
  86.            
  87.             Platform.runLater(() ->
  88.                 mlController.downloadedLabel.setText(mlController.doneQuantity + "/" + mlController.quantity)
  89.             );
  90.             if (mlController.doneQuantity == 0) Platform.runLater(() -> mlController.downloadedPB.setProgress(0.0));
  91.            
  92.             Double dTemp = new BigDecimal(size / Math.pow(10, 6))
  93.                     .setScale(3, BigDecimal.ROUND_HALF_UP)
  94.                     .doubleValue();
  95.             Platform.runLater(() -> mlController.sizeLabel.setText("Size: " + dTemp + " Mb"));
  96.            
  97.             /* Set write stream */
  98.             OutputStream writer = new FileOutputStream(fullPath);
  99.             byte buffer[] = new byte[buffSize]; // Max bytes per one reception
  100.            
  101.             /* Download */
  102.             int i = 0;
  103.             long i_sum = 0;
  104.             long delta_t = System.nanoTime();
  105.             double getted_b = 0.0;
  106.            
  107.             while ((i = in.read(buffer)) > 0) {
  108.                 writer.write(buffer, 0, i);
  109.                 getted_b += i;
  110.                 i_sum += i;
  111.                
  112.                 mlController.updateDownloadingPB(size, i_sum); // with method cause lambda needs final values
  113.                
  114.                 if ((System.nanoTime() - delta_t) >= 1E9) { // If the second was over
  115.                     Double speed = new BigDecimal(getted_b / Math.pow(10, 6))
  116.                             .setScale(3, BigDecimal.ROUND_HALF_UP)
  117.                             .doubleValue();
  118.  
  119.                     Platform.runLater(() -> mlController.speedLabel.setText("Speed: " + speed + " Mb/s"));
  120.                    
  121.                     delta_t = System.nanoTime(); // Set to zero
  122.                     getted_b = 0.0;
  123.                 }
  124.                 if (size == i_sum) { // ==> Download is complete
  125.                     mlController.doneQuantity++;
  126.                    
  127.                     Platform.runLater(() ->
  128.                         mlController.downloadedLabel.setText(mlController.doneQuantity + "/" + mlController.quantity)
  129.                     );
  130.                     Platform.runLater(() ->
  131.                         mlController.updateDownloadedPB((1.0 / mlController.quantity) * mlController.doneQuantity)
  132.                     );
  133.                    
  134.                     Platform.runLater(() -> mlController.downloadingLabel.setText("Done"));
  135.                     Platform.runLater(() -> mlController.sizeLabel.setText("Size:"));
  136.                     Platform.runLater(() -> mlController.speedLabel.setText("Speed:"));
  137.                 }
  138.             }
  139.            
  140.             /* Cleaning */
  141.             writer.flush();
  142.             writer.close();
  143.             in.close();
  144.         } catch (IOException e) {
  145.             System.out.println(e);
  146.         }
  147.     }
  148. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement