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:genrsa.GenRSAController.java

/**
 * Comprueba la primalidad de P y Q por el metodo de Miller Rabin
 * @param event /*  w  w  w .jav a2 s.  c  o  m*/
 */
public void primalityMiller(ActionEvent event) {
    Task CAstart = new Task() {
        @Override
        protected Object call() throws Exception {

            progress.setVisible(true);

            Platform.runLater(() -> {
                mainWindow.clearPrimality();
                disableOnProgress(true);
            });

            boolean isMiller = true;
            checkPrimes.check(primo_P.getText(), primo_Q.getText(), iteraciones_primalidad.getText(), isMiller);

            Platform.runLater(() -> {
                disableOnProgress(false);
                disableButtons();
            });

            progress.setVisible(false);

            return null;
        }
    };

    new Thread(CAstart).start();

}

From source file:genrsa.GenRSAController.java

/**
 * Comprueba la primalidad de P y Q por el metodo de Fermat
 * @param event //  w  w w  .j av  a  2 s  . co  m
 */
public void primalityFermat(ActionEvent event) {
    Task CAstart = new Task() {
        @Override
        protected Object call() throws Exception {

            progress.setVisible(true);

            Platform.runLater(() -> {
                mainWindow.clearPrimality();
                disableOnProgress(true);
            });

            boolean isMiller = false;
            checkPrimes.check(primo_P.getText(), primo_Q.getText(), iteraciones_primalidad.getText(), isMiller);

            Platform.runLater(() -> {
                disableOnProgress(false);
                disableButtons();
            });

            progress.setVisible(false);

            return null;
        }
    };

    new Thread(CAstart).start();

}

From source file:com.QuarkLabs.BTCeClientJavaFX.MainController.java

/**
 * Gets funds data from server, displays error message at the Log field in case of any Exception
 *//*from w w w  . j  a  v  a2 s .  c o m*/
@FXML
private void updateFunds() {
    Task<JSONObject> task = new Task<JSONObject>() {

        @Override
        protected JSONObject call() throws Exception {
            try {
                return app.getAccountInfo();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return new JSONObject();
        }
    };
    task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent workerStateEvent) {
            JSONObject jsonObject = (JSONObject) workerStateEvent.getSource().getValue();
            //TODO make a check for errors
            if (jsonObject.optInt("success", 0) == 1) {
                parseFundsObject(jsonObject.optJSONObject("return").optJSONObject("funds"));
            } else {
                logField.appendText(ERROR_TITLE + jsonObject.optString("error", SOMETHING_WENT_WRONG) + "\r\n");
            }
        }
    });
    task.setOnFailed(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent workerStateEvent) {
            logField.appendText(workerStateEvent.getSource().getException().getMessage() + "\r\n");
        }
    });
    Thread thread = new Thread(task);
    thread.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();/*w  w w.  j ava  2  s. c  om*/
        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:com.QuarkLabs.BTCeClientJavaFX.MainController.java

/**
 * Reads data from Trading section, sends trade request to server
 * Displays error message at the Log field in case of any Exception
 *
 * @param event Source fired an event (either "Buy" or "Sell" button)
 *//*from ww  w  .  ja va2  s  .  c  o  m*/
@FXML
private void makeTradeRequest(final ActionEvent event) {

    Task<JSONObject> task = new Task<JSONObject>() {
        @Override
        protected JSONObject call() throws Exception {
            String type;
            String idOfSource = ((Button) event.getSource()).getId();
            if (buyButton.getId().equals(idOfSource)) {
                type = "buy";
            } else {
                type = "sell";
            }
            String pair = tradeCurrencyType.getValue().toLowerCase() + "_"
                    + tradePriceCurrencyType.getValue().toLowerCase();

            String rate = tradePriceValue.getText();
            String amount = tradeAmountValue.getText();
            return app.trade(pair, type, rate, amount);
        }
    };
    task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent workerStateEvent) {
            JSONObject jsonObject = (JSONObject) workerStateEvent.getSource().getValue();
            if (jsonObject.optInt("success") == 1) {
                parseFundsObject(jsonObject.optJSONObject("return").optJSONObject("funds"));
                logField.appendText("Order ID = " + jsonObject.optJSONObject("return").optString("order_id")
                        + " was registered successfully" + "\r\n");
            } else {
                logField.appendText(ERROR_TITLE + jsonObject.optString("error", SOMETHING_WENT_WRONG) + "\r\n");
            }

        }
    });

    task.setOnFailed(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent workerStateEvent) {
            logField.appendText(workerStateEvent.getSource().getException().getMessage() + "\r\n");
        }
    });
    Thread thread = new Thread(task);
    thread.start();
}

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

/**
 * Select a service according to service url textfield.
 *
 * @param downloadConf Loaded download config, null if a service is chosen
 *    from an URL or the service List//  w  w  w  .  j a  v a  2  s  .c om
 */
protected void doSelectService(DownloadConfig downloadConf) {
    log.info("Using download config: " + downloadConf);
    dataBean.resetSelectedService();
    serviceSelection.setDisable(true);
    serviceURL.getScene().setCursor(Cursor.WAIT);
    serviceURL.setDisable(true);
    resetGui();
    new Thread(() -> {
        try {
            ServiceModel serviceModel = (ServiceModel) serviceList.getSelectionModel().getSelectedItems()
                    .get(0);
            Service service = null;
            if (serviceModel != null && serviceModel.getUrl().toString().equals(serviceURL.getText())) {
                if (ServiceChecker.isReachable(serviceModel.getItem().getServiceURL())) {
                    service = serviceModel.getItem();
                    service.setPassword(servicePW.getText());
                    service.setUsername(serviceUser.getText());
                }
            } else {
                URL sURL = new URL(serviceURL.getText());
                if (ServiceChecker.isReachable(sURL)) {
                    service = new Service(sURL, "", true, serviceUser.getText(), servicePW.getText());
                }
            }
            if (service == null) {
                setStatusTextUI(I18n.format("status.service-timeout"));
                dataBean.setSelectedService(null);
                serviceSelection.setDisable(false);
                serviceURL.setDisable(false);
                serviceURL.getScene().setCursor(Cursor.DEFAULT);
                return;
            }
            serviceSelection.setDisable(true);
            serviceURL.getScene().setCursor(Cursor.WAIT);
            setStatusTextUI(I18n.format("status.checking-auth"));
            serviceURL.setDisable(true);
            Service finalService = service;
            Task task = new Task() {
                protected Integer call() {
                    try {
                        boolean serviceSelected = selectService(finalService);
                        if (serviceSelected) {
                            chooseSelectedService(downloadConf);
                        }
                        return 0;
                    } finally {
                        serviceSelection.setDisable(false);
                        serviceURL.getScene().setCursor(Cursor.DEFAULT);
                        serviceURL.setDisable(false);
                        validateChainContainerItems();
                    }
                }
            };
            Thread th = new Thread(task);
            th.setDaemon(true);
            th.start();
        } catch (MalformedURLException e) {
            setStatusTextUI(I18n.format("status.no-url"));
            log.error(e.getMessage(), e);
            serviceSelection.setDisable(false);
            serviceURL.getScene().setCursor(Cursor.DEFAULT);
            serviceURL.setDisable(false);
        }
    }).start();
}

From source file:gov.va.isaac.gui.preferences.plugins.ViewCoordinatePreferencesPluginViewController.java

public Region getContent() {
    Task<Void> task = new Task<Void>() {
        @Override//from  ww w .jav  a  2  s .co m
        protected Void call() throws Exception {
            log.debug("initializing content");

            try {
                if (!contentLoaded) {
                    contentLoaded = true;

                    // Populate selectableModules
                    final ConceptVersionBI moduleRootConcept = OTFUtility.getConceptVersion(
                            IsaacMetadataAuxiliaryBinding.MODULE.getPrimodialUuid(), panelViewCoordinate);
                    final Set<ConceptVersionBI> moduleConcepts = new HashSet<>();
                    try {
                        moduleConcepts.addAll(OTFUtility.getAllChildrenOfConcept(moduleRootConcept.getNid(),
                                panelViewCoordinate, false));
                    } catch (Exception e) {
                        log.error("Failed loading module concepts as children of " + moduleRootConcept, e);
                        e.printStackTrace();
                        AppContext.getCommonDialogs()
                                .showErrorDialog("Failed loading module concepts as children of "
                                        + moduleRootConcept + ". See logs.", e);
                    }
                    List<SelectableModule> modules = new ArrayList<>();
                    for (ConceptVersionBI cv : moduleConcepts) {
                        modules.add(new SelectableModule(cv.getNid()));
                    }
                    selectableModules.clear();
                    selectableModules.addAll(modules);

                    allModulesMarker.selected.addListener((observable, oldValue, newValue) -> {
                        if (newValue) {
                            for (SelectableModule module : selectableModules) {
                                module.selectedProperty().set(false);
                            }
                        }
                    });
                    selectableModules.forEach(selectableModule -> selectableModule.selectedProperty()
                            .addListener((observable, wasSelected, isSelected) -> {
                                if (isSelected) {
                                    if (!wasSelected) {
                                        //log.debug("Adding module nid={}, uuid={}, desc={}", selectableModule.getNid(), selectableModule.getUuid(), selectableModule.getDescription());
                                        selectedModules.add(selectableModule.getUuid());
                                        allModulesMarker.selectedProperty().set(false);
                                    }
                                } else {
                                    if (wasSelected) {
                                        //log.debug("Removing module nid={}, uuid={}, desc={}", selectableModule.getNid(), selectableModule.getUuid(), selectableModule.getDescription());
                                        selectedModules.remove(selectableModule.getUuid());

                                        if (selectedModules.size() == 0) {
                                            allModulesMarker.selectedProperty().set(true);
                                        }
                                    }
                                }
                            }));
                    selectableModuleListView.getItems().clear();
                    selectableModuleListView.getItems().add(allModulesMarker);
                    Collections.sort(selectableModules);
                    selectableModuleListView.getItems().addAll(selectableModules);

                    runLaterIfNotFXApplicationThread(
                            () -> pathComboBox.setTooltip(new Tooltip("Default path is \""
                                    + OTFUtility.getDescription(getDefaultPath(), panelViewCoordinate)
                                    + "\"")));

                    pathComboBox.getItems().clear();
                    pathComboBox.getItems().addAll(getPathOptions());
                }

                // Reload persisted values every time

                UserProfile loggedIn = ExtendedAppContext.getCurrentlyLoggedInUserProfile();
                pathComboBox.getSelectionModel().select(loggedIn.getViewCoordinatePath());

                // Reload storedStatedInferredOption
                loadStoredStatedInferredOption();

                // Reload storedStatuses
                loadStoredStatuses();

                // Reload storedModules
                final Set<UUID> storedModuleUuids = getStoredModules();
                if (storedModuleUuids.size() == 0) {
                    allModulesMarker.setSelected(true);
                } else {
                    // Check to make sure that stored UUID refers to an existing, known module
                    for (UUID storedModuleUuid : storedModuleUuids) {
                        boolean foundStoredUuidModuleInSelectableModules = false;
                        for (SelectableModule selectableModule : selectableModules) {
                            if (storedModuleUuid.equals(selectableModule.getUuid())) {
                                foundStoredUuidModuleInSelectableModules = true;
                                break;
                            }
                        }

                        if (!foundStoredUuidModuleInSelectableModules) {
                            log.error(
                                    "Loaded module (uuid={}) from user preferences that does not currently exist",
                                    storedModuleUuid);
                            AppContext.getCommonDialogs().showErrorDialog("Unsupported Module",
                                    "Loaded a module UUID from UserProfile that does not correspond to existing module",
                                    "Concept (UUID=" + storedModuleUuid
                                            + ") not a valid module.  Must be one of "
                                            + Arrays.toString(selectableModules.toArray()));
                        }
                    }
                    for (SelectableModule module : selectableModules) {
                        if (storedModuleUuids.contains(module.getUuid())) {
                            module.setSelected(true);
                        } else {
                            module.setSelected(false);
                        }
                    }
                }

                Long storedTime = getStoredTime();
                if (storedTime.equals(Long.MAX_VALUE)) {
                    dateSelectionMethodComboBox.getSelectionModel().select(DateSelectionMethod.USE_LATEST);
                    currentTimeProperty.set(Long.MAX_VALUE);
                    runLaterIfNotFXApplicationThread(() -> datePicker.setValue(LocalDate.now()));
                } else {
                    dateSelectionMethodComboBox.getSelectionModel().select(DateSelectionMethod.SPECIFY);
                    currentTimeProperty.set(storedTime);
                    setDatePickerFromCurrentTimeProperty();
                }

                return null;
            } catch (Exception e) {
                log.error("initContent() task caught " + e.getClass().getName() + " " + e.getLocalizedMessage(),
                        e);
                e.printStackTrace();
                throw e;
            }
        }

        @Override
        protected void succeeded() {
            log.debug("Content initialization succeeded");

            removeProgressIndicator();
        }

        @Override
        protected void failed() {
            removeProgressIndicator();

            Throwable ex = getException();
            log.error("loadContent() caught " + ex.getClass().getName() + " " + ex.getLocalizedMessage(), ex);
            AppContext.getCommonDialogs().showErrorDialog("Failed loading content. See logs.", ex);
        }
    };

    addProgressIndicator();

    Utility.execute(task);

    return gridPaneInRootStackPane;
}

From source file:ui.main.MainViewController.java

private void addContactListener() {
    //this method adds a contacts list listener
    System.gc();/*  w w w.java  2  s .  c  o m*/
    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:de.bayern.gdi.gui.Controller.java

/**
 * Handle search and filter the service list.
 *
 * @param event the event//  www . jav a 2 s  . com
 */
@FXML
protected void handleSearch(KeyEvent event) {
    if (!catalogReachable) {
        setStatusTextUI(I18n.getMsg("status.catalog-not-available"));
    }
    String currentText = this.searchField.getText();
    this.serviceList.getItems().clear();
    dataBean.resetCatalogLists();
    if (currentText == null || currentText.isEmpty()) {
        this.serviceList.setItems(this.dataBean.getServicesAsList());
    }

    String searchValue = currentText == null ? "" : currentText.toUpperCase();

    ObservableList<ServiceModel> subentries = FXCollections.observableArrayList();
    ObservableList<ServiceModel> all = this.dataBean.getServicesAsList();
    for (ServiceModel entry : all) {
        boolean match = entry.getName().toUpperCase().contains(searchValue);
        if (match) {
            subentries.add(entry);
        }
    }
    if (currentText != null && currentText.length() > 2) {
        Task task = new Task() {
            @Override
            protected Integer call() throws Exception {
                Platform.runLater(() -> {
                    searchButton.setVisible(false);
                    searchButton.setManaged(false);
                    progressSearch.setVisible(true);
                    progressSearch.setManaged(true);
                });
                if (catalogReachable) {
                    List<Service> catalog = dataBean.getCatalogService().getServicesByFilter(currentText);
                    for (Service entry : catalog) {
                        dataBean.addCatalogServiceToList(entry);
                    }
                    Platform.runLater(() -> {
                        for (Service entry : catalog) {
                            subentries.add(new ServiceModel(entry));
                        }
                    });
                }
                Platform.runLater(() -> {
                    progressSearch.setVisible(false);
                    progressSearch.setManaged(false);
                    searchButton.setManaged(true);
                    searchButton.setVisible(true);
                });
                return 0;
            }
        };
        Thread th = new Thread(task);
        if (catalogReachable) {
            setStatusTextUI(I18n.getMsg("status.calling-service"));
        }
        th.setDaemon(true);
        th.start();
    }
    this.serviceList.setItems(subentries);
}

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

/**
 * Pre-cache the next set of images and calculate if necessary
 * @param pRecord/*  w ww. j a v a 2s  . c  o m*/
 */
private void internalPrecachePair(final int pRecord) {
    if (pRecord >= gResults.size()) {
        gLogger.trace("Precache: No next!");
        return;
    }

    if (pRecord < 0) {
        gLogger.trace("Precache: No prev!");
        return;
    }

    gLogger.trace("Precaching record: " + pRecord);

    gArePrecachingNow = true;
    boolean justLoad = false;

    if (!gResults.get(pRecord).processed) {
        if (gResults.get(pRecord).claimForProcessing()) {
            List<CheckResult> single = new LinkedList<CheckResult>();
            single.add(gResults.get(pRecord));
            Task<Integer> task = new ProcessingLoadTask(single, false, true, true);
            Thread loader = new Thread(task);
            loader.setDaemon(true);
            //FIXME: hack here to set precached id
            gPrecached = pRecord;
            loader.start();
            return;
        } else {
            //enter busy-wait loop? - just load images and presume calcs will be done(?)
            justLoad = true;
        }
    }

    if (gResults.get(pRecord).processed | justLoad) {
        Task<Integer> task = new Task<Integer>() {
            @Override
            protected Integer call() throws Exception {
                gLogger.trace("just loading images for precache (no calcs)");
                final Image left = SwingFXUtils.toFXImage(internalLoadImage(gResults.get(pRecord).getFileOne()),
                        null);
                final Image right = SwingFXUtils
                        .toFXImage(internalLoadImage(gResults.get(pRecord).getFileTwo()), null);
                Platform.runLater(new Runnable() {
                    //@Override
                    public void run() {
                        gPrecachedLeft = left;
                        gPrecachedRight = right;
                        gPrecached = pRecord;
                        gArePrecachingNow = false;
                    }
                });
                gLogger.trace("Precaching done for record " + pRecord);
                return null;
            }
        };
        Thread loader = new Thread(task);
        loader.setDaemon(true);
        loader.start();
        return;
    }

    gLogger.trace("Precaching incomplete for record " + pRecord);
    gArePrecachingNow = false;
    gPrecached = -1;
}