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:ui.main.MainViewController.java

private synchronized void paintWarningInRecieve(Chat chat, String Warning, String time) {
    //this method draws the recievied text message
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override/*from  w  w  w.  j a  va 2s  .  com*/
        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(Warning);
            bbl.setBackground(new Background(new BackgroundFill(Color.RED, 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());
        scrollPane.setVvalue(scrollPane.getHmax());
        scrollPane.setVvalue(scrollPane.getHmax());
    });

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

    }
}

From source file:ui.main.MainViewController.java

private synchronized void paintReceivedPhotoLoad(Chat chat, File recievedFile, String time) {
    //this method paints the recieved picture message
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override//  w w w.  ja v a  2 s  .c o m
        protected HBox call() throws Exception {
            Thread.sleep(100);
            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));

            try {
                Image recievedImage = SwingFXUtils.toFXImage(ImageIO.read(recievedFile), null);
                ImageView receivedImageView = new ImageView(recievedImage);
                receivedImageView.setFitHeight(300);
                receivedImageView.setFitWidth(300);
                receivedImageView.setPreserveRatio(true);

                receivedImageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        if (event.getButton() == MouseButton.PRIMARY) {
                            Desktop dt = Desktop.getDesktop();
                            try {
                                dt.open(recievedFile);
                            } catch (IOException ex) {
                                Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null,
                                        ex);
                            }
                        }
                    }
                });

                receivedImageView.setOnMouseEntered(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.HAND);
                    }
                });

                receivedImageView.setOnMouseExited(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.DEFAULT);
                    }
                });

                vbox.getChildren().addAll(chatterName, receivedImageView, timeL);
            } catch (IOException e) {
                e.printStackTrace();
            }
            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.start();
        try {
            t.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

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

@FXML
public void sign() {

    if (logger.isDebugEnabled()) {
        logger.debug("[SIGN] activeProfile sourceFile={}, targetFile={}", activeProfile.getSourceFileFileName(),
                activeProfile.getTargetFileFileName());
    }//from   w  w w . j av  a2s .  c o m

    boolean isValid = validateSign();

    if (!isValid) {
        if (logger.isDebugEnabled()) {
            logger.debug("[SIGN] form not valid; returning");
        }
        return;
    }

    final Boolean doUnsign = ckReplace.isSelected();
    UnsignCommand unsignCommand = unsignCommandProvider.get();
    SignCommand signCommand = signCommandProvider.get();

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

        if (logger.isDebugEnabled()) {
            logger.debug("[SIGN] signing folder full of jars");
        }

        //
        // Get list of source JARs
        //
        File[] sourceJars = new File(activeProfile.getSourceFileFileName())
                .listFiles((d, n) -> StringUtils.endsWithIgnoreCase(n, ".jar"));

        //
        // Report if no jars to sign and exit
        //
        if (sourceJars == null || sourceJars.length == 0) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION,
                    "There aren't any JARs to sign in '" + activeProfile.getTargetFileFileName() + "'");
            alert.setHeaderText("No JARs to Sign");
            alert.showAndWait();
            return;
        }

        if (logger.isDebugEnabled()) {
            for (File f : sourceJars) {
                logger.debug("[SIGN] source jar={}, filename={}", f.getAbsolutePath(), f.getName());
            }
        }

        //
        // Confirm replace operation
        //
        if (doUnsign && !confirmReplaceExisting()) {
            return;
        }

        //
        // Confirm overwriting of files
        //
        if (!confirmOverwrite(sourceJars)) {
            return;
        }

        //
        // This number is applied to the progress bar to report a particular
        // iterations unit-of-work (2 operations per jar)
        //
        double unitFactor = 1.0d / (sourceJars.length * 2.0d);

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

            @Override
            protected Void call() throws Exception {

                double accruedProgress = 0.0d;

                for (File sf : sourceJars) {

                    File tf = new File(activeProfile.getTargetFileFileName(), sf.getName());

                    if (logger.isDebugEnabled()) {
                        logger.debug("[SIGN] progress={}", accruedProgress);
                    }

                    updateMessage("");
                    Platform.runLater(() -> piSignProgress.setVisible(true));
                    updateProgress(accruedProgress, 1.0d);
                    accruedProgress += unitFactor;

                    if (doUnsign) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("[SIGN] doing bulk unsign operation");
                        }
                        updateTitle("Unsigning JAR");
                        unsignCommand.unsignJAR(Paths.get(sf.getAbsolutePath()),
                                Paths.get(tf.getAbsolutePath()), s -> Platform.runLater(
                                        () -> txtConsole.appendText(s + System.getProperty("line.separator"))));

                        if (isCancelled()) {
                            return null;
                        }

                    } else {

                        if (logger.isDebugEnabled()) {
                            logger.debug("[SIGN] copying bulk for sign operation");
                        }
                        updateTitle("Copying JAR");
                        Platform.runLater(() -> txtConsole
                                .appendText("Copying JAR" + System.getProperty("line.separator")));
                        unsignCommand.copyJAR(sf.getAbsolutePath(), tf.getAbsolutePath());
                    }

                    updateProgress(accruedProgress, 1.0d);
                    accruedProgress += unitFactor;

                    updateTitle("Signing JAR");

                    signCommand.signJAR(Paths.get(tf.getAbsolutePath()),
                            Paths.get(activeProfile.getJarsignerConfigKeystore()),
                            activeProfile.getJarsignerConfigStorepass(),
                            activeProfile.getJarsignerConfigAlias(), activeProfile.getJarsignerConfigKeypass(),
                            s -> Platform.runLater(
                                    () -> txtConsole.appendText(s + System.getProperty("line.separator"))));
                }

                return null;
            }

            @Override
            protected void succeeded() {
                super.succeeded();

                updateProgress(1.0d, 1.0d);
                updateMessage("JARs signed successfully");

                piSignProgress.progressProperty().unbind();
                lblStatus.textProperty().unbind();
            }

            @Override
            protected void failed() {
                super.failed();

                logger.error("error unsigning and signing jar", exceptionProperty().getValue());

                updateProgress(1.0d, 1.0d);
                updateMessage("Error signing JARs");

                piSignProgress.progressProperty().unbind();
                lblStatus.textProperty().unbind();

                piSignProgress.setVisible(false);

                Alert alert = new Alert(Alert.AlertType.ERROR, exceptionProperty().getValue().getMessage());
                alert.showAndWait();
            }

            @Override
            protected void cancelled() {
                super.cancelled();

                if (logger.isWarnEnabled()) {
                    logger.warn("signing jar operation cancelled");
                }

                updateProgress(1.0d, 1.0d);
                updateMessage("JARs signing cancelled");

                Platform.runLater(() -> {
                    piSignProgress.progressProperty().unbind();
                    lblStatus.textProperty().unbind();

                    piSignProgress.setVisible(false);

                    Alert alert = new Alert(Alert.AlertType.INFORMATION, "JARs signing cancelled");
                    alert.showAndWait();
                });

            }
        };

        piSignProgress.progressProperty().bind(task.progressProperty());
        lblStatus.textProperty().bind(task.messageProperty());

        new Thread(task).start();

    } else {

        if (logger.isDebugEnabled()) {
            logger.debug("[SIGN] signing single JAR");
        }

        //
        // #2 confirm an overwrite (if needed); factored 
        //
        if (doUnsign && !confirmReplaceExisting()) {
            return;
        } else {

            //
            // #6 sign-only to a different target filename needs a copy and
            // possible overwrite
            //

            File tf = new File(activeProfile.getTargetFileFileName());
            if (tf.exists()) {
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION,
                        "Overwrite existing file '" + tf.getName() + "'?");
                alert.setHeaderText("Overwrite existing file");
                Optional<ButtonType> response = alert.showAndWait();
                if (!response.isPresent() || response.get() != ButtonType.OK) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("[SIGN] overwrite file cancelled");
                    }
                    return;
                }
            }
        }

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

            @Override
            protected Void call() throws Exception {

                updateMessage("");
                Platform.runLater(() -> piSignProgress.setVisible(true));
                updateProgress(0.1d, 1.0d);

                if (doUnsign) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("[SIGN] doing unsign operation");
                    }
                    updateTitle("Unsigning JAR");
                    unsignCommand.unsignJAR(Paths.get(activeProfile.getSourceFileFileName()),
                            Paths.get(activeProfile.getTargetFileFileName()), s -> Platform.runLater(
                                    () -> txtConsole.appendText(s + System.getProperty("line.separator"))));

                    if (isCancelled()) {
                        return null;
                    }
                } else {

                    //
                    // #6 needs a copy to the target if target file doesn't
                    // exist
                    //
                    if (logger.isDebugEnabled()) {
                        logger.debug("[SIGN] copying for sign operation");
                    }
                    updateTitle("Copying JAR");
                    Platform.runLater(
                            () -> txtConsole.appendText("Copying JAR" + System.getProperty("line.separator")));
                    unsignCommand.copyJAR(activeProfile.getSourceFileFileName(),
                            activeProfile.getTargetFileFileName());
                }

                updateProgress(0.5d, 1.0d);
                updateTitle("Signing JAR");

                signCommand.signJAR(Paths.get(activeProfile.getTargetFileFileName()),
                        Paths.get(activeProfile.getJarsignerConfigKeystore()),
                        activeProfile.getJarsignerConfigStorepass(), activeProfile.getJarsignerConfigAlias(),
                        activeProfile.getJarsignerConfigKeypass(), s -> Platform.runLater(
                                () -> txtConsole.appendText(s + System.getProperty("line.separator"))));

                return null;
            }

            @Override
            protected void succeeded() {
                super.succeeded();

                updateProgress(1.0d, 1.0d);
                updateMessage("JAR signed successfully");

                piSignProgress.progressProperty().unbind();
                lblStatus.textProperty().unbind();
            }

            @Override
            protected void failed() {
                super.failed();

                logger.error("error unsigning and signing jar", exceptionProperty().getValue());

                updateProgress(1.0d, 1.0d);
                updateMessage("Error signing JAR");

                piSignProgress.progressProperty().unbind();
                lblStatus.textProperty().unbind();

                piSignProgress.setVisible(false);

                Alert alert = new Alert(Alert.AlertType.ERROR, exceptionProperty().getValue().getMessage());
                alert.showAndWait();
            }

            @Override
            protected void cancelled() {
                super.cancelled();

                if (logger.isWarnEnabled()) {
                    logger.warn("signing jar operation cancelled");
                }

                updateProgress(1.0d, 1.0d);
                updateMessage("JAR signing cancelled");

                piSignProgress.progressProperty().unbind();
                lblStatus.textProperty().unbind();

                piSignProgress.setVisible(false);

                Alert alert = new Alert(Alert.AlertType.INFORMATION, "JAR signing cancelled");
                alert.showAndWait();

            }
        };

        piSignProgress.progressProperty().bind(task.progressProperty());
        lblStatus.textProperty().bind(task.messageProperty());

        new Thread(task).start();
    }
}

From source file:ui.main.MainViewController.java

private synchronized void paintReceivedPhotoOnTransmit(Chat chat, File recievedFile, String time) {
    //this method paints the recieved picture message
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override// w  w  w .  ja v  a2 s . c  om
        protected HBox call() throws Exception {
            VBox vbox = new VBox(); //to add text
            Thread.sleep(2000);
            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));

            try {
                Image recievedImage = SwingFXUtils.toFXImage(ImageIO.read(recievedFile), null);
                ImageView receivedImageView = new ImageView(recievedImage);
                receivedImageView.setFitHeight(300);
                receivedImageView.setFitWidth(300);
                receivedImageView.setPreserveRatio(true);

                receivedImageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        if (event.getButton() == MouseButton.PRIMARY) {
                            Desktop dt = Desktop.getDesktop();
                            try {
                                dt.open(recievedFile);
                            } catch (IOException ex) {
                                Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null,
                                        ex);
                            }
                        }
                    }
                });

                receivedImageView.setOnMouseEntered(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.HAND);
                    }
                });

                receivedImageView.setOnMouseExited(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.DEFAULT);
                    }
                });

                vbox.getChildren().addAll(chatterName, receivedImageView, timeL);
            } catch (IOException e) {
                e.printStackTrace();
            }
            vbox.setAlignment(Pos.CENTER_RIGHT);
            HBox hbox = new HBox();
            hbox.getChildren().addAll(imageRec, vbox);
            return hbox;
        }
    };

    recievedMessages.setOnSucceeded(event -> {
        chatList.getChildren().add(recievedMessages.getValue());
    });
    //set the received chat message appear on the screen
    if (chat.getParticipant().contains(currentChat.getParticipant())) {
        Thread t = new Thread(recievedMessages);
        t.start();
    }
    Task t = new Task() {
        @Override
        protected Object call() throws Exception {
            Thread.sleep(2500);
            return new Object();
        }
    };

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

    Thread thread1 = new Thread(t);
    thread1.start();
}

From source file:ui.main.MainViewController.java

private synchronized void paintReceivedFile(Chat chat, String path, String time) {
    //this method paints the recieved picture message
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override/*from  ww w  . j  ava  2 s .  co  m*/
        protected HBox call() throws Exception {
            Thread.sleep(100);
            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));

            Hyperlink link = new Hyperlink("File Recieved: " + path);
            link.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<javafx.scene.input.MouseEvent>() {
                @Override
                public void handle(javafx.scene.input.MouseEvent event) {
                    try {
                        if (event.getButton() == MouseButton.PRIMARY) {
                            Runtime.getRuntime().exec("explorer.exe /select," + path);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
            vbox.getChildren().addAll(chatterName, link, 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);
        }
    }
    //set the received chat message appear on the screen
    if (chat.getParticipant().contains(currentChat.getParticipant())) {
        Thread t = new Thread(recievedMessages);
        t.start();
    }
    Task t = new Task() {
        @Override
        protected Object call() throws Exception {
            Thread.sleep(2500);
            return new Object();
        }
    };

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

    Thread thread1 = new Thread(t);
    thread1.start();

}

From source file:ui.main.MainViewController.java

private synchronized void paintSentPhoto(Chat chat, File file, String time) {
    //this method paints the recieved picture message
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override/*from  ww  w. jav  a 2s.com*/
        protected HBox call() throws Exception {
            //                Thread.sleep(100);
            VBox vbox = new VBox(); //to add text

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

            Label chatterName = new Label(name.getText());
            chatterName.setDisable(true);

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

            try {
                Image recievedImage = SwingFXUtils.toFXImage(ImageIO.read(file), null);
                ImageView receivedImageView = new ImageView(recievedImage);
                receivedImageView.setFitHeight(300);
                receivedImageView.setFitWidth(300);
                receivedImageView.setPreserveRatio(true);

                receivedImageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        if (event.getButton() == MouseButton.PRIMARY) {
                            Desktop dt = Desktop.getDesktop();
                            try {
                                dt.open(file);
                            } catch (IOException ex) {
                                Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null,
                                        ex);
                            }
                        }
                    }
                });

                receivedImageView.setOnMouseEntered(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.HAND);
                    }
                });

                receivedImageView.setOnMouseExited(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.DEFAULT);
                    }
                });

                vbox.getChildren().addAll(chatterName, receivedImageView, timeL);
            } catch (IOException e) {
                e.printStackTrace();
            }
            vbox.setAlignment(Pos.CENTER_LEFT);
            HBox hbox = new HBox();
            hbox.setAlignment(Pos.CENTER_RIGHT);
            //bbl.setBubbleSpec(BubbleSpec.FACE_LEFT_CENTER);
            hbox.getChildren().addAll(vbox, imageRec);
            return hbox;
        }
    };

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

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

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

@FXML
public void deleteProfile() {

    final String profileNameToDelete = lvProfiles.getSelectionModel().getSelectedItem();

    if (logger.isDebugEnabled()) {
        logger.debug("[DELETE PROFILE] delete {}", profileNameToDelete);
    }/*w w  w.  j a v  a2  s. c om*/

    Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Delete profile '" + profileNameToDelete + "'?");
    alert.setHeaderText("Delete profile");
    Optional<ButtonType> response = alert.showAndWait();
    if (!response.isPresent() || response.get() != ButtonType.OK) {
        if (logger.isDebugEnabled()) {
            logger.debug("[DELETE PROFILE] delete profile cancelled");
        }
        return;
    }

    final boolean apProfileNameSetFlag = StringUtils.equalsIgnoreCase(activeProfile.getProfileName(),
            profileNameToDelete);

    if (apProfileNameSetFlag) {
        activeProfile.setProfileName("");
    }

    Task<Void> task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {

            //
            // #18 adjust record prior to dao call
            //
            if (activeConfiguration.getRecentProfiles().contains(profileNameToDelete)) {
                activeConfiguration.getRecentProfiles().remove(profileNameToDelete);
            }

            if (StringUtils.equalsIgnoreCase(profileNameToDelete, activeConfiguration.getActiveProfile())) {
                activeConfiguration.setActiveProfile(null);
            }

            configurationDS.deleteProfile(profileNameToDelete);

            return null;
        }

        @Override
        protected void succeeded() {
            super.succeeded();

            Platform.runLater(() -> {

                // #18 recent profiles
                Iterator<MenuItem> iterator = mRecentProfiles.getItems().iterator();
                while (iterator.hasNext()) {
                    MenuItem mi = iterator.next();
                    if (StringUtils.equalsIgnoreCase(mi.getText(), profileNameToDelete)) {
                        iterator.remove();
                    }
                }
                if (CollectionUtils.isEmpty(mRecentProfiles.getItems())) {
                    mRecentProfiles.getItems().add(MI_NO_PROFILES);
                }

                lvProfiles.getItems().remove(profileNameToDelete);

                if (StringUtils.equalsIgnoreCase(profileNameToDelete, activeProfile.getProfileName())) {
                    newProfile();
                }

                needsSave.set(false);
            });
        }

        @Override
        protected void failed() {
            super.failed();
            Alert alert = new Alert(Alert.AlertType.ERROR, getException().getMessage());
            alert.setHeaderText("Error deleting profile");
            alert.showAndWait();
        }

    };

    new Thread(task).start();
}

From source file:ui.main.MainViewController.java

private synchronized void paintSendMessage(String msg, String time) {
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override/*from ww  w.  j av  a  2  s.c  o  m*/
        protected HBox call() throws Exception {
            VBox vbox = new VBox(); //to add text

            ImageView imageRec = new ImageView(myAvatar.getImage());
            imageRec.setFitHeight(60);
            imageRec.setFitWidth(50);

            Label myName = new Label(name.getText());
            myName.setDisable(true);

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

            BubbledLabel bbl = new BubbledLabel();
            bbl.setText(msg);
            bbl.setBackground(new Background(new BackgroundFill(Color.LIGHTBLUE, null, null)));
            HBox hbox = new HBox();
            hbox.setAlignment(Pos.TOP_RIGHT);
            bbl.setBubbleSpec(BubbleSpec.FACE_RIGHT_CENTER);

            vbox.getChildren().addAll(myName, bbl, timeL);

            hbox.getChildren().addAll(vbox, imageRec);
            return hbox;
        }
    };

    recievedMessages.setOnSucceeded(event -> {
        chatList.getChildren().add(recievedMessages.getValue());
    });
    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);
    }
}

From source file:ui.main.MainViewController.java

private synchronized void paintSentFile(Chat chat, String path, String time) {
    //this method paints the recieved picture message
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override/*from  w w  w  . j  a va 2  s.co m*/
        protected HBox call() throws Exception {
            Thread.sleep(100);
            VBox vbox = new VBox(); //to add text

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

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

            Label chatterName = new Label(name.getText());
            chatterName.setDisable(true);

            Hyperlink link = new Hyperlink("File Sent: " + path);
            link.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<javafx.scene.input.MouseEvent>() {
                @Override
                public void handle(javafx.scene.input.MouseEvent event) {
                    try {
                        if (event.getButton() == MouseButton.PRIMARY) {
                            Runtime.getRuntime().exec("explorer.exe /select," + path);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
            vbox.getChildren().addAll(chatterName, link, timeL);
            vbox.setAlignment(Pos.CENTER_LEFT);
            HBox hbox = new HBox();
            hbox.setAlignment(Pos.CENTER_RIGHT);
            //bbl.setBubbleSpec(BubbleSpec.FACE_LEFT_CENTER);
            hbox.getChildren().addAll(vbox, imageRec);
            return hbox;
        }
    };

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

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

    }
}

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

@FXML
public void renameProfile(ListView.EditEvent<String> evt) {
    if (logger.isDebugEnabled()) {
        logger.debug("[RENAME]");
    }//w w w .j  av  a2  s.c om

    final String oldProfileName = lvProfiles.getItems().get(evt.getIndex());
    final boolean apProfileNameSetFlag = StringUtils.equalsIgnoreCase(activeProfile.getProfileName(),
            oldProfileName);

    String suggestedNewProfileName = "";
    if (configurationDS.profileExists(evt.getNewValue())) {

        suggestedNewProfileName = configurationDS.suggestUniqueProfileName(evt.getNewValue());

        if (logger.isDebugEnabled()) {
            logger.debug("[RENAME] configuration exists; suggested name={}", suggestedNewProfileName);
        }

        Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "That profile name already exists."
                + System.getProperty("line.separator") + "Save as " + suggestedNewProfileName + "?");
        alert.setHeaderText("Profile name in use");
        Optional<ButtonType> response = alert.showAndWait();
        if (!response.isPresent() || response.get() != ButtonType.OK) {
            if (logger.isDebugEnabled()) {
                logger.debug("[RENAME] rename cancelled");
            }
            return;
        }
    }

    final String newProfileName = StringUtils.defaultIfBlank(suggestedNewProfileName, evt.getNewValue());

    if (apProfileNameSetFlag) { // needs to be set for save
        activeProfile.setProfileName(newProfileName);
    }

    Task<Void> renameTask = new Task<Void>() {

        @Override
        protected Void call() throws Exception {
            configurationDS.renameProfile(oldProfileName, newProfileName);
            Platform.runLater(() -> {
                lvProfiles.getItems().set(evt.getIndex(), newProfileName);

                Collections.sort(lvProfiles.getItems());
                lvProfiles.getSelectionModel().select(newProfileName);

            });
            return null;
        }

        @Override
        protected void failed() {
            super.failed();
            logger.error("can't rename profile from " + oldProfileName + " to " + newProfileName,
                    getException());
            Alert alert = new Alert(Alert.AlertType.ERROR, getException().getMessage());
            alert.setHeaderText("Can't rename profile '" + oldProfileName + "'");
            alert.showAndWait();

            if (apProfileNameSetFlag) { // revert
                activeProfile.setProfileName(oldProfileName);
            }
        }

        @Override
        protected void cancelled() {
            super.cancelled();
            Alert alert = new Alert(Alert.AlertType.ERROR, "Rename cancelled by user");
            alert.setHeaderText("Cancelled");
            alert.showAndWait();

            if (apProfileNameSetFlag) { // revert
                activeProfile.setProfileName(oldProfileName);
            }
        }
    };

    new Thread(renameTask).start();
}