Example usage for javafx.concurrent Task setOnSucceeded

List of usage examples for javafx.concurrent Task setOnSucceeded

Introduction

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

Prototype

public final void setOnSucceeded(EventHandler<WorkerStateEvent> value) 

Source Link

Document

The onSucceeded event handler is called whenever the Task state transitions to the SUCCEEDED state.

Usage

From source file:ui.main.MainViewController.java

private void addRosterListener() {
    //when roster changes occur, the changes are tracked in here
    contactsManager.getRoster().addRosterListener(new RosterListener() {
        @Override/*from   ww w . ja  va  2 s .  co  m*/
        public void entriesAdded(Collection<String> clctn) {
            java.util.Iterator<String> i = clctn.iterator();

            Task t = new Task() {
                @Override
                protected Object call() throws Exception {
                    return new Object();
                }
            };

            t.setOnSucceeded(value -> {
                showContacts();
                while (i.hasNext()) {
                    String user = i.next();
                    if (contactsManager.getUserType(user).equals(ItemType.from)) {
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setTitle("Attention!");
                        alert.setHeaderText("Friend Request!");
                        alert.setContentText(
                                "You have a new friend Request from " + user + ". Please check Contacts.");
                        alert.showAndWait();
                    }
                }
            });
            Thread thread1 = new Thread(t);
            thread1.start();
        }

        @Override
        public void entriesUpdated(Collection<String> clctn) {
            Task t = new Task() {
                @Override
                protected Object call() throws Exception {
                    return new Object();
                }
            };

            t.setOnSucceeded(value -> showContacts());
            Thread thread1 = new Thread(t);
            thread1.start();
        }

        @Override
        public void entriesDeleted(Collection<String> clctn) {
            Task t = new Task() {
                @Override
                protected Object call() throws Exception {
                    return new Object();
                }
            };

            t.setOnSucceeded(value -> showContacts());
            Thread thread1 = new Thread(t);
            thread1.start();
        }

        @Override
        public void presenceChanged(Presence prsnc) {
            if (currentChat != null) {
                if (prsnc.getFrom().contains(currentChat.getParticipant())) {
                    Task<String> t = new Task<String>() {
                        @Override
                        protected String call() throws Exception {
                            return prsnc.toString();
                        }
                    };
                    t.setOnSucceeded(value -> chatterPresence.setText(t.getValue()));

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

            }
            Task t = new Task() {
                @Override
                protected Object call() throws Exception {
                    return new Object();
                }
            };

            t.setOnSucceeded(value -> showContacts());
            Thread thread1 = new Thread(t);
            thread1.start();
        }
    });
}

From source file:ui.main.MainViewController.java

private void addCallListener() {
    //system notifies the incomming calls
    List<JingleMediaManager> mediaManagers1 = new ArrayList<JingleMediaManager>();
    mediaManagers1.add(new JmfMediaManager(new BasicTransportManager()));
    final JingleManager jm1 = new JingleManager(connectionManager.getXMPPConnection(), mediaManagers1);

    jm1.addJingleSessionRequestListener(new JingleSessionRequestListener() {
        @Override// w  w w .  j a va2  s  .c  om
        public void sessionRequested(JingleSessionRequest jsr) {
            try {

                System.out.println("Got one");
                JingleSession session = jsr.accept();
                session.startIncoming();

                Task t = new Task() {
                    @Override
                    protected Object call() throws Exception {
                        return new Object();
                    }
                };

                t.setOnSucceeded(value -> {
                    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                    alert.setTitle("Incoming Call");
                    alert.setHeaderText("You have an incomming call from " + session.getInitiator());

                    ButtonType buttonTpeYes = new ButtonType("Answer");
                    ButtonType buttonTypeNo = new ButtonType("Reject");
                    ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);

                    alert.getButtonTypes().setAll(buttonTpeYes, buttonTypeNo, buttonTypeCancel);

                    Optional<ButtonType> result = alert.showAndWait();
                    if (result.get() == buttonTpeYes) {
                        session.startIncoming(); //accept the call and answer the call

                    } else if (result.get() == buttonTypeNo) {
                        try {
                            session.terminate();
                        } catch (XMPPException ex) {
                            Alert alertError = new Alert(Alert.AlertType.ERROR);
                            alertError.setTitle("Error Occured");
                            alertError.setHeaderText("Call failure occured with " + ex.getMessage());
                        }
                    } else {
                        return;
                    }
                });

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

                Task t1 = new Task() {
                    @Override
                    protected Object call() throws Exception {
                        return new Object();
                    }
                };

                t1.setOnSucceeded(value -> {
                    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                    alert.setTitle("Incoming Call");
                    alert.setHeaderText("Your Call  " + session.getInitiator());

                    ButtonType buttonTypeDisconnect = new ButtonType("Disconnect");

                    alert.getButtonTypes().setAll(buttonTypeDisconnect);

                    Optional<ButtonType> result = alert.showAndWait();
                    try {
                        session.terminate();
                    } catch (XMPPException ex) {
                    }
                });

                if (session.isFullyEstablished()) {
                    Thread thread1 = new Thread(t1);
                    thread.start();
                }
            } catch (XMPPException ex) {
                Logger.getLogger(CallViewController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
}

From source file:ui.main.MainViewController.java

private void addContactListener() {
    //this method adds a contacts list listener
    System.gc();/*from   w ww .  j  av a2 s  . c  om*/
    contacts.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
        @Override
        public void changed(ObservableValue observable, Object oldValue, Object newValue) {
            if (newValue == null) {
                return;
            }
            conversations.getSelectionModel().clearSelection();
            chatList.getChildren().clear();
            isSingleChat = true;
            if (((RosterEntry) newValue).getType().equals(ItemType.from)) {
                friendRequest.setVisible(true);
            } else {
                friendRequest.setVisible(false);
            }
            Call.dialUser = ((RosterEntry) newValue).getUser();
            String chatterNameTem = ((RosterEntry) newValue).getUser(); //get reciever
            String chatterNameTem2 = chatterNameTem;

            ResultSet rs = DBSingleChat.readMessages(chatterNameTem); //load old messages

            chatterNameTem = chatterNameTem.substring(0, chatterNameTem.indexOf("@"));
            chatterNameTem = Character.toUpperCase(chatterNameTem.charAt(0)) + chatterNameTem.substring(1);

            chatterName.setText(chatterNameTem); //set chat box to recievers contacts
            currentChat = chatManager.createChat(((RosterEntry) newValue).getUser()); //set the current chat
            chatterPresence.setText(contactsManager.getPresence(((RosterEntry) newValue).getUser()));

            VCard vcard = new VCard(); //vcard to load presence
            try {
                vcard.load(connectionManager.getXMPPConnection(), currentChat.getParticipant());
                if (vcard.getAvatar() != null) {
                    BufferedImage img = ImageIO.read(new ByteArrayInputStream(vcard.getAvatar()));
                    Image image = SwingFXUtils.toFXImage(img, null);
                    chatterAvatar.setImage(image);
                } else {
                    chatterAvatar.setImage(defaultAvatar);
                }
            } catch (XMPPException ex) {
                chatterAvatar.setImage(defaultAvatar);
            } catch (IOException ex) {
                Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NullPointerException ex) {
                chatterAvatar.setImage(defaultAvatar);
            } finally {
                chatterAvatar.setFitHeight(120);
                chatterAvatar.setFitWidth(100);
            }

            //display old messages -> current chat is required to be set as a prerequisit
            loadChat(chatterNameTem2);
            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();

            //show extra options
            showExtraComButtons();
        }
    });

}

From source file:ui.main.MainViewController.java

private void sendMessageSC() {
    if (currentChat == null) {
        return;//from  ww w  . java 2  s .  c  o m
    }
    try {
        ItemType type = contactsManager.getUserType(currentChat.getParticipant());
        if (type.equals(ItemType.none)) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Attention!");
            alert.setHeaderText("The user is not available for you!");
            alert.setContentText(
                    "The user has not accepted the Friend Request." + " The user is not available for you.");
            alert.showAndWait();
            return;
        } else if (type.equals(ItemType.from)) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Attention!");
            alert.setHeaderText("An unaccepted user!");
            alert.setContentText("You have not accepted the Friend Request."
                    + " You can not send any messages until you accept the friend request.");
            alert.showAndWait();
            return;
        } else if (type.equals(ItemType.to)) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Attention!");
            alert.setHeaderText("The user has not accepted!");
            alert.setContentText("The user has not accepted the Friend Request."
                    + " You can not send any messages until the user accepts the friend request.");
            alert.showAndWait();
            return;
        }
        if (message.getText().isEmpty()) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("IMP");
            alert.setHeaderText("Message is empty!");
            alert.setContentText("You can not send empty messages.");
            alert.showAndWait();
            return;
        }
        try {
            currentChat.sendMessage(message.getText()); //sends message
            if (history.isSelected()) {
                DBSingleChat.saveTextMessage(currentChat.getParticipant(), false, message.getText(),
                        new Timestamp(System.currentTimeMillis()));
            }

            paintSendMessage(message.getText().trim(), dtfT.print(DateTime.now())); //paints the sent item
            message.setText(""); //clears the sent text
            Task tt = new Task() {
                @Override
                protected Object call() throws Exception {
                    Thread.sleep(500);
                    return new Object();
                }
            };

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

            Thread thread1 = new Thread(tt);
            thread1.start();
        } catch (XMPPException ex) {
            Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (NullPointerException e) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("IMP");
        alert.setHeaderText("User is unavailable!");
        alert.setContentText("The user is unavailable for you!.");
        alert.showAndWait();
        return;
    }

}

From source file:ui.main.MainViewController.java

private void sendFile() {
    if (!contactsManager.getAvailabilityforSharing(currentChat.getParticipant())) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Attention!");
        alert.setHeaderText("The user is not available!");
        alert.setContentText("The file receiving user should be available online to receive the file.");
        alert.showAndWait();/*www  . j  a  v a2s  . com*/
        return;
    }
    ItemType type = contactsManager.getUserType(currentChat.getParticipant());

    if (type.equals(ItemType.none)) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Attention!");
        alert.setHeaderText("This user is not available for you!");
        alert.setContentText(
                "The user has not accepted the Friend Request." + " The user is not available for you.");
        alert.showAndWait();
        return;
    } else if (type.equals(ItemType.from)) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Attention!");
        alert.setHeaderText("An unaccepted user!");
        alert.setContentText("You have not accepted the Friend Request."
                + " You can not send any messages until you accept the friend request.");
        alert.showAndWait();
        return;
    } else if (type.equals(ItemType.to)) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Attention!");
        alert.setHeaderText("The user has not accepted!");
        alert.setContentText("The user has not accepted the Friend Request."
                + " You can not send any messages until the user accepts the friend request.");
        alert.showAndWait();
        return;
    }
    if (!contactsManager.getAvailabilityforSharing(currentChat.getParticipant())) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Attention!");
        alert.setHeaderText("The user is not available!");
        alert.setContentText("The file receiving user should be available online to receive the file.");
        alert.showAndWait();
        return;
    }
    FileChooser fc = new FileChooser();
    File file = fc.showOpenDialog(presence.getScene().getWindow());
    if (file == null) {
        return;
    }
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                fileManager.sendFile(file, currentChat.getParticipant());
                if (history.isSelected()) {
                    Timestamp time = new Timestamp(System.currentTimeMillis());
                    DBSingleChat.saveFileMessage(currentChat.getParticipant(), false, file.getPath(), time);
                }

                paintSentFile(currentChat, file.getAbsolutePath(), dtfT.print(DateTime.now()));
                Task tt = new Task() {
                    @Override
                    protected Object call() throws Exception {
                        Thread.sleep(500);
                        return new Object();
                    }
                };

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

                Thread thread1 = new Thread(tt);
                thread1.start();
            } catch (FileNotFoundException ex) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("IMP");
                alert.setHeaderText("File is not Found!");
                alert.setContentText("File you selected does not exist.");
                alert.showAndWait();
                return;
            }
        }
    });
    t.start();
}

From source file:ui.main.MainViewController.java

private void sendImage() {
    if (!contactsManager.getAvailabilityforSharing(currentChat.getParticipant())) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Attention!");
        alert.setHeaderText("The user is not available!");
        alert.setContentText("The file receiving user should be available online to receive the file.");
        alert.showAndWait();//from   w  w  w  . j  ava  2  s . c  o  m
        return;
    }
    ItemType type = contactsManager.getUserType(currentChat.getParticipant());
    if (type.equals(ItemType.none)) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Attention!");
        alert.setHeaderText("The is not available for you!");
        alert.setContentText(
                "The user has not accepted the Friend Request." + " The user is not available for you.");
        alert.showAndWait();
        return;
    } else if (type.equals(ItemType.from)) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Attention!");
        alert.setHeaderText("The user has not accepted!");
        alert.setContentText("The user has not accepted the Friend Request."
                + " You can not send any messages until the user accepts the friend request.");
        alert.showAndWait();
        return;
    } else if (type.equals(ItemType.to)) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Attention!");
        alert.setHeaderText("The user has not accepted!");
        alert.setContentText("The user has not accepted the Friend Request."
                + " You can not send any messages until the user accepts the friend request.");
        alert.showAndWait();
        return;
    }
    try {
        FileChooser fc = new FileChooser();
        fc.setTitle("Choose an image to send");
        fc.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("All Images", "*.jpg*", "*.png", "*.bmp"),
                new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                new FileChooser.ExtensionFilter("PNG", "*.png"),
                new FileChooser.ExtensionFilter("BMP", "*.bmp"));

        File file = fc.showOpenDialog(presence.getScene().getWindow());
        if (file == null) {
            return;
        }
        BufferedImage image = ImageIO.read(file);
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    fileManager.sendFile(file, currentChat.getParticipant());
                    if (history.isSelected()) {
                        Timestamp time = new Timestamp(System.currentTimeMillis());
                        DBSingleChat.savePictureMessage(currentChat.getParticipant(), false, file.getPath(),
                                time);
                    }

                    paintSentPhoto(currentChat, file, dtfT.print(DateTime.now()));

                    Task tt = new Task() {
                        @Override
                        protected Object call() throws Exception {
                            Thread.sleep(500);
                            return new Object();
                        }
                    };

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

                    Thread thread1 = new Thread(tt);
                    thread1.start();
                } catch (FileNotFoundException ex) {
                    Alert alert = new Alert(Alert.AlertType.ERROR);
                    alert.setTitle("IMP");
                    alert.setHeaderText("File is not Found!");
                    alert.setContentText("File you selected does not exist.");
                    alert.showAndWait();
                    return;
                }
            }
        });
        t.start();
    } catch (IOException ex) {
        Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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/* ww  w  .  j  a v  a  2 s  .  c om*/
        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: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/*www  . ja  va2  s .  c  om*/
        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:frontend.GUIController.java

public Thread processInput(Runnable rSuccess, Runnable rFail) throws Exception {
    System.out.println("Steping to next step...");
    progressBar.progressProperty().unbind();
    progressMessage.textProperty().unbind();
    next1.setDisable(true);/*from   w  ww. ja  v  a2s. c o m*/
    final ArrayList<String> comboBoxValues = new ArrayList<String>();
    for (ComboBox<String> c : comboBoxes) {
        comboBoxValues.add(c.getValue());
    }
    Task<Boolean> t = new Task<Boolean>() {
        @Override
        protected Boolean call() throws Exception {
            updateMessage("Doing Prediction");
            updateProgress(3, 10);
            int status = at.processAfterLoadFile(comboBoxValues, predModel.getValue(), visualize.isSelected(),
                    predicted.isSelected());
            if (status > 0) {
                System.err.println("ProcessAfterLoadFile Error occured.");
                return false;
            }
            updateMessage("Finished Prediction");
            if (visualize.isSelected()) {
                updateProgress(5, 10);
                at.showVisualization();
                updateMessage("Finished Visualization");
                updateProgress(8, 10);
            }
            updateProgress(10, 10);
            updateMessage("Done");

            //webpage.getChildren().add(new Browser(url));
            //at.addTweets(at.outputDir+"/visualization/Sentiment.tsv", personData);
            return true;
        };

        @Override
        protected void succeeded() {
            super.succeeded();
            updateMessage("Done!");
        }

        @Override
        protected void cancelled() {
            super.cancelled();
            updateMessage("Cancelled!");
        }

        @Override
        protected void failed() {
            super.failed();
            updateMessage("Failed!");
        }

        @Override
        protected void done() {
            super.done();
            updateMessage("Done!");
        }
    };
    progressBar.progressProperty().bind(t.progressProperty());
    progressMessage.textProperty().bind(t.messageProperty());

    t.setOnSucceeded(new EventHandler<WorkerStateEvent>() {

        @Override
        public void handle(WorkerStateEvent event) {
            if (t.getValue()) {
                Platform.runLater(rSuccess);
            } else {
                Platform.runLater(rFail);
            }
        }
    });

    Thread mythread = new Thread(t);
    mythread.start();
    return mythread;
}

From source file:ui.main.MainViewController.java

private synchronized void paintSendMessage(String msg, String time) {
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override/*from w  ww  .j  av  a2s .co  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);
    }
}