Example usage for javafx.concurrent Task Task

List of usage examples for javafx.concurrent Task Task

Introduction

In this page you can find the example usage for javafx.concurrent Task Task.

Prototype

public Task() 

Source Link

Document

Creates a new Task.

Usage

From source file:com.virus.removal.javafxapplication.FXMLDocumentController.java

/**
 * @return//from  www .  j  a va 2 s . co m
 */
private Task<Void> createWorker() {
    return new Task<Void>() {

        /* (non-Javadoc)
         * @see javafx.concurrent.Task#call()
         */
        @Override
        protected Void call() throws Exception {

            /* Start the scanning of viruses. */
            //            virusDetectedMap = handler.startScanning(progressBar, 
            //                                           textArea,
            //                                           textForThreatsFound,
            //                                           virusScanning,
            //                                           workerThread);

            javafx.application.Platform.runLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    /* Set the status to Scanning in Dashboard */
                    if (statusValInDash.getStyle() != null) {
                        statusValInDash.setStyle("");
                    }
                    statusValInDash.setText(POTENTIALLY_UNPROTECTED);
                }
            });

            /* Start Scanning */
            int index = 1;
            boolean isNextVirus = false;
            isPageProtected = false;

            final Calendar c = Calendar.getInstance();
            timestamp = simpleDateFormat.format(c.getTime());

            if (isScanCancelled) {
                isScanCancelled = false;
            }

            final Map<String, String> virusDetectedMap = new HashMap<String, String>();
            final List<String> detectedViruses = new ArrayList<String>();

            /* Cancel the Scan */
            q.setOnMouseClicked(new EventHandler<Event>() {

                /**
                 * @param me
                 */
                @Override
                public void handle(Event me) {
                    isScanCancelled = true;
                }
            });

            if (isScanCancelled) {
                handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_STOPPED);
                setVirusScanHistoryIfScanIsStopped(handler);
                return null;
            }

            javafx.application.Platform.runLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {

                    if (textArea != null) {
                        textArea.setFont(Font.font("Verdana", FontWeight.BOLD, 10));
                        if (textArea.getText() != null && !textArea.getText().isEmpty()) {
                            textArea.clear();
                        }
                    }

                    if (StringUtils.equals(drop.getText(), "English")) {
                        virusScanning.setText("Scanning...");
                        timerTextForThreats.setText("Virus Timer: 15 seconds");
                    } else if (StringUtils.equals(drop.getText(), "Spanish")) {
                        virusScanning.setText("Exploracin...");
                        timerTextForThreats.setText("Timer Virus: 15 segundos");
                    } else if (drop.getText().equals("French")) {
                        virusScanning.setText("Balayage...");
                        timerTextForThreats.setText("Virus Timer: 15 secondes");
                    } else if (drop.getText().equals("Portuguese")) {
                        virusScanning.setText("Digitalizao...");
                        timerTextForThreats.setText("Temporizador Vrus: 15 segundos");
                    }

                    progressBar.setTooltip(new Tooltip("Virus scan in progress"));

                    if (textForThreatsFound != null && textForThreatsFound.getText() != null
                            && !textForThreatsFound.getText().isEmpty()) {
                        textForThreatsFound.setText("");
                    }
                    if (textForThreatsRemoved != null && textForThreatsRemoved.getText() != null
                            && !textForThreatsRemoved.getText().isEmpty()) {
                        textForThreatsRemoved.setText("");
                    }

                    if (isScanCancelled) {
                        isScanCancelled = false;
                    }
                }
            });

            System.out.println("Scan in progress..!!");
            System.out.println();

            /* Cancel the Scan */
            q.setOnMouseClicked(new EventHandler<Event>() {

                /**
                 * @param me
                 */
                @Override
                public void handle(Event me) {
                    isScanCancelled = true;
                }
            });

            if (isScanCancelled) {
                handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_STOPPED);
                setVirusScanHistoryIfScanIsStopped(handler);
                return null;
            }

            if (virusRegistry != null) {
                virusSearchList.clear();
                virusSearchList = virusRegistry.getVirusSearchList();
            }
            if (virusCache != null) {
                viruses = virusCache.getAllViruses();
            }
            if (rkm == null) {
                rkm = RegistryKeyManager.getInstance();
            }

            /* Wait for sometime */
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

            javafx.application.Platform.runLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    textArea.appendText("Currently Scanning:");
                    textArea.appendText("\n");
                    textArea.appendText("----------------------");
                    textArea.appendText("\n");

                    /* Cancel the Scan */
                    q.setOnMouseClicked(new EventHandler<Event>() {

                        /**
                         * @param me
                         */
                        @Override
                        public void handle(Event me) {
                            isScanCancelled = true;
                        }
                    });
                }
            });

            if (isScanCancelled) {
                handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_STOPPED);
                setVirusScanHistoryIfScanIsStopped(handler);
                return null;
            }

            for (final String virus : viruses) {

                /* Cancel the Scan */
                q.setOnMouseClicked(new EventHandler<Event>() {

                    /**
                     * @param me
                     */
                    @Override
                    public void handle(Event me) {
                        isScanCancelled = true;
                    }
                });

                if (isScanCancelled) {
                    handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_STOPPED);
                    setVirusScanHistoryIfScanIsStopped(handler);
                    return null;
                }

                if (rkm == null) {
                    System.out.println("Scan is stopped due to: " + REGISTRY_KEY_MANEGER_EMPTY);
                    handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_STOPPED);
                    return null;
                }

                if (isNextVirus) {
                    javafx.application.Platform.runLater(new Runnable() {

                        /* (non-Javadoc)
                         * @see java.lang.Runnable#run()
                         */
                        @Override
                        public void run() {
                            textArea.appendText("\n\n");
                        }
                    });
                }

                javafx.application.Platform.runLater(new Runnable() {

                    /* (non-Javadoc)
                     * @see java.lang.Runnable#run()
                     */
                    @Override
                    public void run() {
                        textArea.appendText(virus);
                        textArea.appendText("\n");
                    }
                });

                for (final String virusSearchUsingReg : virusSearchList) {

                    /* Cancel the Scan */
                    q.setOnMouseClicked(new EventHandler<Event>() {

                        /**
                         * @param me
                         */
                        @Override
                        public void handle(Event me) {
                            isScanCancelled = true;
                        }
                    });

                    if (isScanCancelled) {
                        handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_STOPPED);
                        setVirusScanHistoryIfScanIsStopped(handler);
                        return null;
                    }

                    javafx.application.Platform.runLater(new Runnable() {

                        /* (non-Javadoc)
                         * @see java.lang.Runnable#run()
                         */
                        @Override
                        public void run() {
                            textArea.appendText("\n");
                            textArea.appendText(virusSearchUsingReg);
                        }
                    });

                    try {
                        if (virus != null && !virus.isEmpty() && virusSearchUsingReg != null
                                && !virusSearchUsingReg.isEmpty()) {
                            if (rkm != null) {
                                rkm.query(virusSearchUsingReg, virus);
                                if (rkm.getKey() != null && !rkm.getKey().isEmpty()) {

                                    javafx.application.Platform.runLater(new Runnable() {

                                        /* (non-Javadoc)
                                         * @see java.lang.Runnable#run()
                                         */
                                        @Override
                                        public void run() {
                                            textArea.appendText("\n");
                                        }
                                    });

                                    detectedViruses.add(virusSearchUsingReg + "\\" + virus);
                                    System.out
                                            .println("Found the virus: " + virusSearchUsingReg + "\\" + virus);
                                    virusDetectedMap.put(String.valueOf(index++) + virusSearchUsingReg, virus);
                                }
                            } else {
                                System.out.println("Scan is stopped due to: " + REGISTRY_KEY_MANEGER_EMPTY);
                                handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_STOPPED);
                                return null;
                            }
                        }
                    } catch (final Exception e) {
                        System.out.println("Failed to scan due to: " + e.getMessage());
                        handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_STOPPED);
                        return null;
                    }
                    isNextVirus = true;
                }

            }

            System.out.println("Virus scanning is completed");
            handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_COMPLETED);

            javafx.application.Platform.runLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    virusScanning.setText("");
                    timerTextForThreats.setText("");
                }
            });

            /* Cancel the Scan */
            q.setOnMouseClicked(new EventHandler<Event>() {

                /**
                 * @param me
                 */
                @Override
                public void handle(final Event me) {
                    isScanCancelled = true;
                }
            });

            if (isScanCancelled) {
                handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_STOPPED);
                setVirusScanHistoryIfScanIsStopped(handler);
                return null;
            }

            noOfThreats = virusDetectedMap.size();

            if (handler.getVirusScanStatus() == VirusScanStatus.VIRUS_SCAN_COMPLETED && virusDetectedMap != null
                    && virusDetectedMap.size() > 0) {

                javafx.application.Platform.runLater(new Runnable() {

                    /* (non-Javadoc)
                     * @see java.lang.Runnable#run()
                     */
                    @Override
                    public void run() {
                        if (StringUtils.equals(drop.getText(), "English")) {
                            textForThreatsFound.setText("Found Threats: " + noOfThreats);
                        } else if (StringUtils.equals(drop.getText(), "Spanish")) {
                            textForThreatsFound.setText("Las amenazas que se encuentran: " + noOfThreats);
                        } else if (drop.getText().equals("French")) {
                            textForThreatsFound.setText("Menaces trouvs: " + noOfThreats);
                        } else if (drop.getText().equals("Portuguese")) {
                            textForThreatsFound.setText("Ameaas encontradas: " + noOfThreats);
                        }
                        textArea.appendText("\n\n");
                        textArea.appendText("Found one or more viruses:");
                        textArea.appendText("\n");
                        textArea.appendText("--------------------------------");
                        textArea.appendText("\n");
                        for (final String detectedVirus : detectedViruses) {
                            textArea.appendText(detectedVirus);
                            textArea.appendText("\n");
                        }
                    }
                });

                /* Wait for sometime */
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else {

                javafx.application.Platform.runLater(new Runnable() {

                    /* (non-Javadoc)
                     * @see java.lang.Runnable#run()
                     */
                    @Override
                    public void run() {
                        if (StringUtils.equals(drop.getText(), "English")) {
                            textForThreatsFound.setText("Found Threats: " + noOfThreats);
                        } else if (StringUtils.equals(drop.getText(), "Spanish")) {
                            textForThreatsFound.setText("Las amenazas que se encuentran: " + noOfThreats);
                        } else if (drop.getText().equals("French")) {
                            textForThreatsFound.setText("Menaces trouvs: " + noOfThreats);
                        } else if (drop.getText().equals("Portuguese")) {
                            textForThreatsFound.setText("Ameaas encontradas: " + noOfThreats);
                        }
                        textArea.appendText("\n\n");
                        textArea.appendText("No viruses are found");
                    }
                });

                /* Update the progress */
                updateProgress(1, 1);

                VirusScanHistory virusScanHistory = new VirusScanHistory();
                virusScanHistory.setScanDate(timestamp);
                virusScanHistory.setScanStatus("SUCCESSFUL");
                virusScanHistory.setPcName(System.getenv("COMPUTERNAME"));
                virusScanHistory.setThreatsFound(0);

                virusScanHistoryList.add(virusScanHistory);

                /* Wait for sometime */
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            }

            if (handler.getVirusScanStatus() == VirusScanStatus.VIRUS_SCAN_COMPLETED && noOfThreats > 0) {

                /* Delete the viruses found in scanning. */
                //               final boolean virusesDeleted = handler.deleteViruses(progressBar, 
                //                                                       textArea,
                //                                                       textForThreatsFound,
                //                                                       virusScanning);

                /* Start killing viruses */

                javafx.application.Platform.runLater(new Runnable() {

                    /* (non-Javadoc)
                     * @see java.lang.Runnable#run()
                     */
                    @Override
                    public void run() {
                        textArea.appendText("\n\n");
                        textArea.appendText("Killing:");
                        textArea.appendText("\n");
                        textArea.appendText("--------");
                        textArea.appendText("\n");
                    }
                });

                /* Cancel the Scan */
                q.setOnMouseClicked(new EventHandler<Event>() {

                    /**
                     * @param me
                     */
                    @Override
                    public void handle(Event me) {
                        isScanCancelled = true;
                    }
                });

                if (isScanCancelled) {
                    handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_STOPPED);
                    setVirusScanHistoryIfScanIsStopped(handler);
                    return null;
                }

                System.out.println("\n");

                removedThreats = 0;
                final Map<String, String> tempVirusDetectedMap = new HashMap<String, String>(virusDetectedMap);
                for (final Map.Entry<String, String> virusEntry : tempVirusDetectedMap.entrySet()) {
                    try {
                        if (rkm != null) {
                            rkm.deleteKey(virusEntry.getKey().substring(1), virusEntry.getValue());
                            javafx.application.Platform.runLater(new Runnable() {

                                /* (non-Javadoc)
                                 * @see java.lang.Runnable#run()
                                 */
                                @Override
                                public void run() {
                                    textArea.appendText("Removed the virus: " + virusEntry.getKey().substring(1)
                                            + "\\" + virusEntry.getValue());
                                    virusScanning.setText("");
                                    timerTextForThreats.setText("");
                                }
                            });
                            removedThreats++;
                            System.out.println("Removed the virus: " + virusEntry.getKey().substring(1) + "\\"
                                    + virusEntry.getValue());
                            virusDetectedMap.remove(virusEntry.getKey());
                        } else {
                            System.out.println("Scan is stopped due to: " + REGISTRY_KEY_MANEGER_EMPTY);
                            handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_STOPPED);
                            return null;
                        }
                    } catch (Exception e) {
                        System.out.println(e.getLocalizedMessage());
                    }

                    if (progressCount == tempVirusDetectedMap.size()) {
                        updateProgress(1, 1);
                    }

                    progressCount++;
                }

                if (StringUtils.equals(drop.getText(), "English")) {
                    textForThreatsRemoved.setText("Removed Threats: " + removedThreats);
                } else if (StringUtils.equals(drop.getText(), "Spanish")) {
                    textForThreatsFound.setText("Amenazas eliminados: " + noOfThreats);
                } else if (drop.getText().equals("French")) {
                    textForThreatsFound.setText("Menaces supprimes: " + noOfThreats);
                } else if (drop.getText().equals("Portuguese")) {
                    textForThreatsFound.setText("Ameaas removidos: " + noOfThreats);
                }

                /* Update the progress */
                updateProgress(1, 1);

                /* Wait for sometime */
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

                System.out.println();
                System.out.println("Virus removal is completed");

                if (tempVirusDetectedMap != null) {
                    tempVirusDetectedMap.clear();
                }

                javafx.application.Platform.runLater(new Runnable() {

                    /* (non-Javadoc)
                     * @see java.lang.Runnable#run()
                     */
                    @Override
                    public void run() {
                        if (textForScanInProgress.getText() != null) {
                            textForScanInProgress.clear();
                        }
                        textForScanInProgress.appendText("Virus scanning is completed");
                    }
                });

                if (virusDetectedMap.size() == 0) {

                    /* Display the protected screen. */
                    showTheProtectedPage();
                    isPageProtected = true;

                    javafx.application.Platform.runLater(new Runnable() {

                        /* (non-Javadoc)
                         * @see java.lang.Runnable#run()
                         */
                        @Override
                        public void run() {
                            /* Set the status */
                            statusValInDash.setStyle("-fx-text-fill: green;");

                            if (drop.getText().equals("English")) {
                                statusValInDash.setText("Potentially Protected");
                            } else if (drop.getText().equals("Spanish")
                                    || drop.getText().equals("Portuguese")) {
                                statusValInDash.setText("Potencialmente Protegido");
                            } else if (drop.getText().equals("French")) {
                                statusValInDash.setText("Potentiellement Protg");
                            }

                            VirusScanHistory virusScanHistory = new VirusScanHistory();
                            virusScanHistory.setScanDate(timestamp);
                            virusScanHistory.setScanStatus("SUCCESSFUL");
                            virusScanHistory.setPcName(System.getenv("COMPUTERNAME"));
                            virusScanHistory.setThreatsFound(noOfThreats);

                            virusScanHistoryList.add(virusScanHistory);
                        }
                    });
                } else {
                    c2.setStyle("-fx-background-color:#DF4444");
                    b1.setStyle("-fx-background-color:#373E48");
                    c1.setStyle("-fx-background-color:transparent");
                    b2.setStyle("-fx-background-color:transparent");
                    c3.setStyle("-fx-background-color:transparent");
                    b3.setStyle("-fx-background-color:transparent");
                    c4.setStyle("-fx-background-color:transparent");
                    b4.setStyle("-fx-background-color:transparent");
                    b5.setStyle("-fx-background-color:transparent");
                    b6.setStyle("-fx-background-color:transparent");

                    unprotected.setVisible(true);
                    unprotected.setManaged(true);

                    isProtected.setVisible(false);
                    isProtected.setManaged(false);

                    general.setVisible(false);
                    general.setManaged(false);

                    scann.setVisible(false);
                    scann.setManaged(false);

                    dash.setVisible(false);
                    dash.setManaged(false);

                    his.setVisible(false);
                    his.setManaged(false);

                    about.setVisible(false);
                    about.setManaged(false);

                    update.setVisible(false);
                    update.setManaged(false);

                    javafx.application.Platform.runLater(new Runnable() {

                        /* (non-Javadoc)
                         * @see java.lang.Runnable#run()
                         */
                        @Override
                        public void run() {
                            /* Set the text */
                            statusValInDash.setStyle("-fx-text-fill: red;");

                            if (drop.getText().equals("English")) {
                                statusValInDash.setText(POTENTIALLY_UNPROTECTED);
                            } else if (drop.getText().equals("Spanish")
                                    || drop.getText().equals("Portuguese")) {
                                statusValInDash.setText("Potencialmente Desprotegido");
                            } else if (drop.getText().equals("French")) {
                                statusValInDash.setText("Potentiellement non protg");
                            }

                            VirusScanHistory virusScanHistory = new VirusScanHistory();
                            virusScanHistory.setScanDate(timestamp);
                            virusScanHistory.setScanStatus("FAILED");
                            virusScanHistory.setPcName(System.getenv("COMPUTERNAME"));
                            virusScanHistory.setThreatsFound(noOfThreats);

                            virusScanHistoryList.add(virusScanHistory);
                        }
                    });
                }
                if (virusDetectedMap != null) {
                    virusDetectedMap.clear();
                }
            } else if (handler.getVirusScanStatus() == VirusScanStatus.VIRUS_SCAN_COMPLETED) {

                javafx.application.Platform.runLater(new Runnable() {

                    /* (non-Javadoc)
                     * @see java.lang.Runnable#run()
                     */
                    @Override
                    public void run() {
                        if (textForScanInProgress.getText() != null) {
                            textForScanInProgress.clear();
                        }
                        textForScanInProgress.appendText("Virus scanning is completed");
                        statusValInDash.setStyle("-fx-text-fill: green;");
                        if (drop.getText().equals("English")) {
                            statusValInDash.setText("Potentially Protected");
                        } else if (drop.getText().equals("Spanish") || drop.getText().equals("Portuguese")) {
                            statusValInDash.setText("Potencialmente Protegido");
                        } else if (drop.getText().equals("French")) {
                            statusValInDash.setText("Potentiellement Protg");
                        }
                    }
                });

                showTheProtectedPage();
                isPageProtected = true;

                System.out.println("No viruses are found in scanning");
            }

            handler.setVirusScanStatus(VirusScanStatus.VIRUS_JOB_COMPLETED);

            javafx.application.Platform.runLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {

                    /* Set the values like last-scan, build in Dashboard based on the virus scan results. */
                    if (handler.getVirusScanStatus() == VirusScanStatus.VIRUS_JOB_COMPLETED) {

                        lastScanValInDash.setText(timestamp);
                        if (StringUtils.equals(drop.getText(), "English")) {
                            textForLastScanInHistory.setText("Last Scan: " + timestamp);
                        } else if (StringUtils.equals(drop.getText(), "Spanish")) {
                            textForLastScanInHistory.setText("ltimo escaneo: " + timestamp);
                        } else if (StringUtils.equals(drop.getText(), "French")) {
                            textForLastScanInHistory.setText("Dernier scan: " + timestamp);
                        } else if (StringUtils.equals(drop.getText(), "Portuguese")) {
                            textForLastScanInHistory.setText("ltima anlise: " + timestamp);
                        }

                    } else if (handler.getVirusScanStatus() == VirusScanStatus.VIRUS_SCAN_STOPPED) {

                        statusValInDash.setStyle("-fx-text-fill: red;");

                        if (drop.getText().equals("English")) {
                            statusValInDash.setText(POTENTIALLY_UNPROTECTED);
                        } else if (drop.getText().equals("Spanish") || drop.getText().equals("Portuguese")) {
                            statusValInDash.setText("Potencialmente Desprotegido");
                        } else if (drop.getText().equals("French")) {
                            statusValInDash.setText("Potentiellement non protg");
                        }

                        lastScanValInDash.setText(timestamp);

                    }
                }

            });

            /* Add the scan results to history. */
            processHistoryData();

            return null;
        }
    };
}

From source file:view.FXApplicationController.java

public void classify() {
    final long startTime = System.nanoTime();

    Task<Void> task = new Task<Void>() {
        @Override/* ww w.j a  v a2s .co  m*/
        protected Void call() throws Exception {
            updateProgress(-1, featureModel.getNumberOfEpochs());

            computeFeatures();
            ClassificationController.classify(classifier, featureModel);

            Platform.runLater(new Runnable() {

                @Override
                public void run() {
                    progressBar.setVisible(false);
                    hypnogram.updateAll();
                    updateWindows();
                }
            });

            System.out.println("Elapsed time: " + (System.nanoTime() - startTime) / 1e6);
            return null;
        }
    };

    progressBar.progressProperty().bind(task.progressProperty());

    Thread thread = new Thread(task);
    thread.setDaemon(true);
    thread.start();

}

From source file:ui.main.MainViewController.java

private void addMessageListener() {
    //adds a message listener for the chat application

    //remove the offlinemessagelistener to avoid dual listening
    connectionManager.removeOfflinePacketListener();

    //adds the listener
    chatManager.getChatManager().addChatListener(new ChatManagerListener() {
        @Override//w  w w  .  j a v  a  2  s  .  co  m
        public void chatCreated(Chat chat, boolean bln) {
            chat.addMessageListener(new MessageListener() {
                @Override
                public void processMessage(Chat chat, Message msg) {
                    if (!msg.getBody().equals("")) {
                        Timestamp time = new Timestamp(System.currentTimeMillis());
                        String participant;
                        if (chat.getParticipant().contains("/")) {
                            participant = chat.getParticipant().substring(0,
                                    chat.getParticipant().indexOf("/"));
                        } else {
                            participant = chat.getParticipant();
                        }
                        if (history.isSelected()) {
                            DBSingleChat.saveTextMessage(participant, true, msg.getBody(), time);
                        }
                    }
                    if (currentChat != null) {
                        if (chat.getParticipant().contains(currentChat.getParticipant())) {
                            if (!msg.getBody().equals("")) {
                                DateTime time = DateTime.now();
                                paintReceivedMessage(chat, msg.getBody(), dtfT.print(time));
                                Task t = new Task() {
                                    @Override
                                    protected Object call() throws Exception {
                                        Thread.sleep(500);
                                        return new Object();
                                    }
                                };

                                t.setOnSucceeded(value -> scrollPane.setVvalue(scrollPane.getHmax()));

                                Thread thread1 = new Thread(t);
                                thread1.start();
                            }
                        } else {
                            //shows the file received notification
                            showNotifications(msg.getFrom(), msg.getBody());

                        }
                    } else {
                        //if the current chat is not selected
                        showNotifications(msg.getFrom(), msg.getBody());
                    }
                }
            });

        }
    });
}

From source file:de.bayern.gdi.gui.Controller.java

/**
 * Handle the service selection.//from   w ww. j  a v a2  s  .  c  o  m
 *
 * @param event The mouse click event.
 */
@FXML
protected void handleServiceSelect(MouseEvent event) {
    if (event.getEventType().equals(MouseEvent.MOUSE_CLICKED)) {
        if (event.getClickCount() == 1) {
            clearUserNamePassword();
            ServiceModel serviceModel = (ServiceModel) this.serviceList.getSelectionModel().getSelectedItems()
                    .get(0);
            if (serviceModel != null) {
                serviceSelection.setDisable(true);
                serviceURL.getScene().setCursor(Cursor.WAIT);
                setStatusTextUI(I18n.format("status.checking-auth"));
                Task task = new Task() {
                    protected Integer call() {
                        try {
                            selectService(serviceModel.getItem());
                            return 0;
                        } finally {
                            serviceSelection.setDisable(false);
                            serviceURL.getScene().setCursor(Cursor.DEFAULT);
                        }
                    }
                };
                Thread th = new Thread(task);
                th.setDaemon(true);
                th.start();
            }
        } else if (event.getClickCount() > 1) {
            clearUserNamePassword();
            resetGui();
        }
    }
}

From source file:uk.bl.dpt.qa.gui.DissimilarGUIThread.java

/**
 * Reload a record (no calculations)/*from   w w  w. j  av a  2s.c o  m*/
 * @param pRecord
 */
private void internalReloadRecord(final int pRecord) {
    gLogger.trace("Reloading record: " + pRecord);

    Task<Integer> task = new Task<Integer>() {

        @Override
        protected Integer call() throws Exception {
            int max = 2;
            int count = 0;

            Platform.runLater(new Runnable() {
                //@Override
                public void run() {
                    internalBeforeGUIThread();
                    imageLeft.setImage(null);
                    imageRight.setImage(null);
                    imageLeftLabel.setText(gResults.get(pRecord).getFileOne().getName());
                    imageRightLabel.setText(gResults.get(pRecord).getFileTwo().getName());
                    psnrLabelValue.setText(gResults.get(pRecord).getPsnr() + "");
                    ssimLabelValue.setText(gResults.get(pRecord).getSsimMean() + "");
                    internalSetSSIMVariance(gResults.get(pRecord).getSsimVariance());
                    ssimMinValue.setText(gResults.get(pRecord).getSsimMin() + "");
                    internalUpdateManualCheckLabel(pRecord);
                }
            });

            final BufferedImage one = internalLoadImage(gResults.get(pRecord).getFileOne());
            Platform.runLater(new Runnable() {
                //@Override
                public void run() {
                    imageLeft.setImage(SwingFXUtils.toFXImage(one, null));
                }
            });
            updateProgress(++count, max);
            final BufferedImage two = internalLoadImage(gResults.get(pRecord).getFileTwo());
            Platform.runLater(new Runnable() {
                //@Override
                public void run() {
                    imageRight.setImage(SwingFXUtils.toFXImage(two, null));
                    internalImageZoomToFit();
                }
            });
            updateProgress(++count, max);

            internalAfterGUIThread();

            return null;
        }

    };
    progressIndicator.progressProperty().bind(task.progressProperty());
    Thread loader = new Thread(task);
    loader.setDaemon(true);
    loader.start();

    internalDisableInterface(false);
}

From source file:net.rptools.tokentool.controller.TokenTool_Controller.java

private TreeItem<Path> cacheOverlays(File dir, TreeItem<Path> parent, int THUMB_SIZE) throws IOException {
    log.info("Caching " + dir.getAbsolutePath());

    TreeItem<Path> root = new TreeItem<>(dir.toPath());
    root.setExpanded(false);/*w  ww . j  a v a  2  s . c o  m*/
    File[] files = dir.listFiles();
    final String I18N_CACHE_TEXT = I18N.getString("TokenTool.treeview.caching");

    final Task<Void> task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            for (File file : files) {
                if (loadOverlaysThread.isInterrupted())
                    break;

                if (file.isDirectory()) {
                    cacheOverlays(file, root, THUMB_SIZE);
                } else {
                    Path filePath = file.toPath();
                    TreeItem<Path> imageNode = new TreeItem<>(filePath,
                            ImageUtil.getOverlayThumb(new ImageView(), filePath));
                    root.getChildren().add(imageNode);
                    loadCount.getAndIncrement();
                    overlayTreeProgressBar.progressProperty().set(loadCount.doubleValue() / overlayCount);
                }
            }

            if (parent != null) {
                // When we show the overlay image, the TreeItem value is empty so we need to
                // sort those to the bottom for a cleaner look and keep sub dir's at the top.
                // If a node has no children then it's an overlay, otherwise it's a directory...
                root.getChildren().sort(new Comparator<TreeItem<Path>>() {
                    @Override
                    public int compare(TreeItem<Path> o1, TreeItem<Path> o2) {
                        if (o1.getChildren().size() == 0 && o2.getChildren().size() == 0)
                            return 0;
                        else if (o1.getChildren().size() == 0)
                            return Integer.MAX_VALUE;
                        else if (o2.getChildren().size() == 0)
                            return Integer.MIN_VALUE;
                        else
                            return o1.getValue().compareTo(o2.getValue());
                    }
                });

                parent.getChildren().add(root);

                parent.getChildren().sort(new Comparator<TreeItem<Path>>() {
                    @Override
                    public int compare(TreeItem<Path> o1, TreeItem<Path> o2) {
                        if (o1.getChildren().size() == 0 && o2.getChildren().size() == 0)
                            return 0;
                        else if (o1.getChildren().size() == 0)
                            return Integer.MAX_VALUE;
                        else if (o2.getChildren().size() == 0)
                            return Integer.MIN_VALUE;
                        else
                            return o1.getValue().compareTo(o2.getValue());
                    }
                });
            }

            return null;
        }
    };

    overlayTreeProgressBar.progressProperty().addListener(observable -> {
        Platform.runLater(() -> progressBarLabel
                .setText(I18N_CACHE_TEXT + Math.round(overlayCount - loadCount.doubleValue()) + "..."));
    });

    // Only add this listener to the parent task so it's only called once
    if (parent == null) {
        overlayTreeProgressBar.progressProperty().addListener(observable -> {
            Platform.runLater(() -> {
                if (overlayTreeProgressBar.getProgress() >= 1)
                    treeViewFinish();
            });
        });
    }

    executorService.execute(task);
    return root;
}

From source file:ui.main.MainViewController.java

private synchronized void paintDate(Chat chat, String day) {
    //this method draws the recievied text message
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override/*from   ww w  .  jav  a  2 s. c  o  m*/
        protected HBox call() throws Exception {

            VBox vbox = new VBox(); //to add text

            //chat message
            Label l = new Label(day);
            l.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, null, null)));

            HBox hbox = new HBox();
            hbox.setAlignment(Pos.CENTER);
            hbox.getChildren().addAll(l);
            return hbox;
        }
    };

    recievedMessages.setOnSucceeded(event -> {
        chatList.getChildren().add(recievedMessages.getValue());

    });

    if (chat.getParticipant().contains(currentChat.getParticipant())) {
        Thread t = new Thread(recievedMessages);
        try {
            t.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
        }
        //t.setDaemon(true);
        t.start();
        scrollPane.setVvalue(scrollPane.getHmax());
    }
}

From source file:uk.bl.dpt.qa.gui.DissimilarGUIThread.java

/**
 * overlay heatmap on image//from   ww  w  .  ja v  a2s  .  c  o  m
 */
private void internalOverlayHeatmap() {

    gRightImageSave = imageRight.getImage();

    if (!gHeatmapGenerated) {

        internalBeforeGUIThread();

        //threaded load so GUI doesn't hang
        Task<Integer> task = new Task<Integer>() {

            @Override
            protected Integer call() throws Exception {
                BufferedImage image = SwingFXUtils.fromFXImage(imageRight.getImage(), null);

                if (gHeatmap == null) {
                    //re-generate heatmap (must be on a re-load)
                    try {
                        gHeatmap = Imaging.getBufferedImage(gResults.get(gCurrentRecord).getHeatmapTemp());
                    } catch (IOException | ImageReadException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                for (int y = 0; y < image.getHeight(); y++) {
                    for (int x = 0; x < image.getWidth(); x++) {
                        int rgb = image.getRGB(x, y);

                        Color heatmapColor = new Color(gHeatmap.getRGB((x / DissimilarV2.SSIMWINDOWSIZE),
                                (y / DissimilarV2.SSIMWINDOWSIZE)));
                        int heatmapPixel = heatmapColor.getGreen();//&maxPixelValue;
                        if (heatmapColor.getGreen() != heatmapColor.getBlue()
                                && heatmapColor.getBlue() != heatmapColor.getRed()) {
                            gLogger.error("Heatmap error (should not happen)");
                        }

                        double factor = 1 - (((double) heatmapPixel / 255));

                        Color col = new Color(rgb);
                        int red = (int) (factor * col.getRed());
                        int green = (int) (factor * col.getGreen());
                        int blue = (int) (factor * col.getBlue());

                        if (red < 0)
                            red = 0;
                        if (green < 0)
                            green = 0;
                        if (blue < 0)
                            blue = 0;
                        col = new Color(red, green, blue);

                        image.setRGB(x, y, col.getRGB());
                    }
                }

                gHeatmapImage = SwingFXUtils.toFXImage(image, null);
                gHeatmapGenerated = true;

                Platform.runLater(new Runnable() {
                    //@Override
                    public void run() {
                        imageRight.setImage(gHeatmapImage);
                    }
                });

                internalAfterGUIThread();

                return 1;
            }

        };

        progressIndicator.progressProperty().bind(task.progressProperty());
        Thread loader = new Thread(task);
        loader.setDaemon(true);
        loader.start();

    } else {
        imageRight.setImage(gHeatmapImage);
    }

}

From source file:ui.main.MainViewController.java

private synchronized void paintReceivedMessage(Chat chat, String msg, String time) {
    //this method draws the recievied text message
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override/*from   w  w  w  . ja  v  a 2s  .c om*/
        protected HBox call() throws Exception {

            VBox vbox = new VBox(); //to add text

            ImageView imageRec = new ImageView(chatterAvatar.getImage()); //image
            imageRec.setFitHeight(60);
            imageRec.setFitWidth(50);

            String strChatterName = chat.getParticipant(); //add name of the chatter with light color
            strChatterName = Character.toUpperCase(strChatterName.charAt(0))
                    + strChatterName.substring(1, strChatterName.indexOf("@"));
            Label chatterName = new Label(strChatterName);
            chatterName.setDisable(true);

            Label timeL = new Label(time);
            timeL.setDisable(true);
            timeL.setFont(new Font("Arial", 10));

            //chat message
            BubbledLabel bbl = new BubbledLabel();
            bbl.setText(msg);
            bbl.setBackground(new Background(new BackgroundFill(Color.GAINSBORO, null, null)));

            vbox.getChildren().addAll(chatterName, bbl, timeL);
            vbox.setAlignment(Pos.CENTER_RIGHT);
            HBox hbox = new HBox();
            bbl.setBubbleSpec(BubbleSpec.FACE_LEFT_CENTER);
            hbox.getChildren().addAll(imageRec, vbox);
            return hbox;
        }
    };

    recievedMessages.setOnSucceeded(event -> {
        chatList.getChildren().add(recievedMessages.getValue());

    });

    if (chat.getParticipant().contains(currentChat.getParticipant())) {
        Thread t = new Thread(recievedMessages);
        //t.setDaemon(true);
        t.start();
        try {
            t.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
        }
        scrollPane.setVvalue(scrollPane.getHmax());
    }
}

From source file:com.bekwam.resignator.ResignatorAppMainViewController.java

private boolean validateSign() {

    if (logger.isDebugEnabled()) {
        logger.debug("[VALIDATE]");
    }//from w w  w .ja va 2s.  com

    boolean isValid = true;

    //
    // Validate the Source JAR field
    //

    if (StringUtils.isBlank(activeProfile.getSourceFileFileName())) {

        if (!tfSourceFile.getStyleClass().contains("tf-validation-error")) {
            tfSourceFile.getStyleClass().add("tf-validation-error");
        }
        isValid = false;

    } else {

        if (!new File(activeProfile.getSourceFileFileName()).exists()) {

            if (!tfSourceFile.getStyleClass().contains("tf-validation-error")) {
                tfSourceFile.getStyleClass().add("tf-validation-error");
            }

            Alert alert = new Alert(Alert.AlertType.ERROR,
                    "Specified Source " + activeProfile.getArgsType() + " does not exist");

            alert.showAndWait();

            isValid = false;
        }
    }

    //
    // Validate the TargetJAR field
    //

    if (StringUtils.isBlank(activeProfile.getTargetFileFileName())) {
        if (!tfTargetFile.getStyleClass().contains("tf-validation-error")) {
            tfTargetFile.getStyleClass().add("tf-validation-error");
        }
        isValid = false;
    }

    if (activeProfile.getArgsType() == SigningArgumentsType.FOLDER) {

        if (StringUtils.equalsIgnoreCase(activeProfile.getSourceFileFileName(),
                activeProfile.getTargetFileFileName())) {

            if (!tfTargetFile.getStyleClass().contains("tf-validation-error")) {
                tfTargetFile.getStyleClass().add("tf-validation-error");
            }

            Alert alert = new Alert(Alert.AlertType.ERROR,
                    "Source folder and target folder cannot be the same");
            alert.showAndWait();

            isValid = false;
        }
    }

    //
    // #13 Validate the Jarsigner Config form
    //

    String jarsignerConfigField = "";
    String jarsignerConfigMessage = "";
    if (isValid && StringUtils.isBlank(activeProfile.getJarsignerConfigKeystore())) {
        jarsignerConfigField = "Keystore";
        jarsignerConfigMessage = "A keystore must be specified";
    } else if (isValid && StringUtils.isBlank(activeProfile.getJarsignerConfigStorepass())) {
        jarsignerConfigField = "Storepass";
        jarsignerConfigMessage = "A password for the keystore must be specified";
    } else if (isValid && StringUtils.isBlank(activeProfile.getJarsignerConfigAlias())) {
        jarsignerConfigField = "Alias";
        jarsignerConfigMessage = "An alias for the key must be specified";
    } else if (isValid && StringUtils.isBlank(activeProfile.getJarsignerConfigKeypass())) {
        jarsignerConfigField = "Keypass";
        jarsignerConfigMessage = "A password for the key must be specified";
    }

    if (StringUtils.isNotEmpty(jarsignerConfigMessage)) {

        if (logger.isDebugEnabled()) {
            logger.debug("[VALIDATE] jarsigner config not valid {}", jarsignerConfigMessage);
        }

        Alert alert = new Alert(Alert.AlertType.ERROR, "Set " + jarsignerConfigField + " in Configure");
        alert.setHeaderText(jarsignerConfigMessage);

        FlowPane fp = new FlowPane();
        Label lbl = new Label("Set " + jarsignerConfigField + " in ");
        Hyperlink link = new Hyperlink("Configure");
        fp.getChildren().addAll(lbl, link);

        link.setOnAction((evt) -> {
            alert.close();
            openJarsignerConfig();
        });

        alert.getDialogPane().contentProperty().set(fp);
        alert.showAndWait();

        isValid = false;
    }

    //
    // #38 check keystore prior to running
    //
    KeytoolCommand keytoolCommand = keytoolCommandProvider.get();

    Task<Boolean> keytoolTask = new Task<Boolean>() {
        @Override
        protected Boolean call() throws Exception {

            final List<String> aliases = keytoolCommand.findAliases(
                    activeConfiguration.getKeytoolCommand().toString(),
                    activeProfile.getJarsignerConfigKeystore(), activeProfile.getJarsignerConfigStorepass());
            if (logger.isDebugEnabled()) {
                logger.debug("[KEYTOOL] # aliases=" + CollectionUtils.size(aliases));
            }

            return true;
        }
    };
    new Thread(keytoolTask).start();

    try {
        if (!keytoolTask.get()) {
            if (logger.isDebugEnabled()) {
                logger.debug("[KEYTOOL] keystore or configuration not valid");
            }
            isValid = false;
        }
    } catch (InterruptedException | ExecutionException e) {

        isValid = false;
        logger.error("error accessing keystore", e);
        Alert alert = new Alert(Alert.AlertType.ERROR, e.getMessage() // contains formatted string
        );
        alert.showAndWait();
    }

    return isValid;
}