Example usage for javafx.concurrent Task Task

List of usage examples for javafx.concurrent Task Task

Introduction

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

Prototype

public Task() 

Source Link

Document

Creates a new Task.

Usage

From source file:com.jscriptive.moneyfx.ui.chart.ChartFrame.java

/**
 * This method is invoked when the monthly in/out button has been toggled
 *
 * @param actionEvent/*from w w w.j  a  v  a  2s . c  om*/
 */
public void monthlyInOutToggled(ActionEvent actionEvent) {
    final CategoryAxis xAxis = new CategoryAxis();
    final NumberAxis yAxis = new NumberAxis();
    xAxis.setLabel("Month of Year");
    yAxis.setLabel("In/Out in Euro");

    final BarChart<String, Number> barChart = new BarChart<>(xAxis, yAxis);
    barChart.setTitle("Monthly in/out");

    chartFrame.setCenter(barChart);

    ToggleButton toggle = (ToggleButton) actionEvent.getTarget();
    if (toggle.isSelected()) {
        Account account = accountCombo.getValue();
        String accountLabel = getAccountLabel(account);

        XYChart.Series<String, Number> inSeries = new XYChart.Series<>();
        inSeries.setName("In" + accountLabel);
        barChart.getData().add(inSeries);

        XYChart.Series<String, Number> outSeries = new XYChart.Series<>();
        outSeries.setName("Out" + accountLabel);
        barChart.getData().add(outSeries);

        ValueRange<LocalDate> period = getTransactionOpRange(account, yearCombo.getValue());
        if (period.isEmpty()) {
            return;
        }
        ObservableList<String> monthLabels = FXCollections.observableArrayList();
        for (LocalDate date = period.from().withDayOfMonth(1); !date.isAfter(period.to()); date = date
                .plusMonths(1)) {
            monthLabels.add(getMonthLabel(date.getYear(), date.getMonthValue()));
        }
        xAxis.setCategories(monthLabels);
        Service<Void> service = new Service<Void>() {
            @Override
            protected Task<Void> createTask() {
                return new Task<Void>() {
                    @Override
                    protected Void call() throws Exception {

                        List<TransactionVolume> incomingVolumes = (account == ALL_ACCOUNTS)
                                ? transactionRepository.getMonthlyIncomingVolumes(false)
                                : transactionRepository.getMonthlyIncomingVolumesOfAccount(account, false);
                        if (INTEGER_ZERO.compareTo(yearCombo.getValue()) < 0) {
                            incomingVolumes = incomingVolumes.stream()
                                    .filter(v -> v.getYear().equals(yearCombo.getValue()))
                                    .sorted((v1, v2) -> v1.getDate().compareTo(v2.getDate())).collect(toList());
                        }
                        for (TransactionVolume volume : incomingVolumes) {
                            String monthLabel = getMonthLabel(volume.getYear(), volume.getMonth());
                            XYChart.Data<String, Number> data = new XYChart.Data<>(monthLabel,
                                    volume.getVolume());
                            Platform.runLater(() -> {
                                inSeries.getData().add(data);
                                StackPane barNode = (StackPane) data.getNode();
                                // TODO make that look nicer
                                Label labelNode = new Label(
                                        CurrencyFormat.getInstance().format(volume.getVolume()));
                                labelNode.setPrefWidth(100);
                                labelNode.setAlignment(CENTER_RIGHT);
                                labelNode.setRotate(270);
                                barNode.getChildren().add(labelNode);
                                barNode.addEventHandler(MOUSE_CLICKED,
                                        event -> handleMonthlyInOutChartMouseClickEvent(
                                                (account == ALL_ACCOUNTS) ? null : account,
                                                of(volume.getYear(), volume.getMonth(), 1), event));
                            });
                        }

                        List<TransactionVolume> outgoingVolumes = (account == ALL_ACCOUNTS)
                                ? transactionRepository.getMonthlyOutgoingVolumes(false)
                                : transactionRepository.getMonthlyOutgoingVolumesOfAccount(account, false);
                        if (INTEGER_ZERO.compareTo(yearCombo.getValue()) < 0) {
                            outgoingVolumes = outgoingVolumes.stream()
                                    .filter(v -> v.getYear().equals(yearCombo.getValue()))
                                    .sorted((v1, v2) -> v1.getDate().compareTo(v2.getDate())).collect(toList());
                        }
                        for (TransactionVolume volume : outgoingVolumes) {
                            String monthLabel = getMonthLabel(volume.getYear(), volume.getMonth());
                            XYChart.Data<String, Number> data = new XYChart.Data<>(monthLabel,
                                    volume.getVolume().abs());
                            Platform.runLater(() -> {
                                outSeries.getData().add(data);
                                StackPane node = (StackPane) data.getNode();
                                // TODO make that look nicer
                                Label labelNode = new Label(
                                        CurrencyFormat.getInstance().format(volume.getVolume()));
                                labelNode.setPrefWidth(100);
                                labelNode.setAlignment(CENTER_RIGHT);
                                labelNode.setRotate(270);
                                node.getChildren().add(labelNode);
                                node.addEventHandler(MOUSE_CLICKED,
                                        event -> handleMonthlyInOutChartMouseClickEvent(
                                                (account == ALL_ACCOUNTS ? null : account), volume.getDate(),
                                                event));
                            });
                        }

                        return null;
                    }
                };
            }
        };
        service.start();
    }
}

From source file:com.respam.comniq.Controller.java

public Task createExportWorker() {
    return new Task() {
        @Override/*from   w  w  w . j  a  v  a2  s .c om*/
        protected Object call() throws Exception {
            JSONParser parser = new JSONParser();
            String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator
                    + "output";

            try {
                POIexcelExporter export = new POIexcelExporter();
                Object obj = parser.parse(new FileReader(path + File.separator + "MovieInfo.json"));
                JSONArray parsedArr = (JSONArray) obj;

                // Loop JSON Array
                for (int i = 0; i < parsedArr.size(); i++) {
                    JSONObject parsedObj = (JSONObject) parsedArr.get(i);
                    if (null != parsedObj.get("Title")) {
                        export.excelWriter(parsedObj, i);
                        System.out.println("Done with " + "\"" + parsedObj.get("Title") + "\"");
                    }
                    updateProgress(i, parsedArr.size() - 1);
                }
                //                    export.addImages(parsedArr);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return true;
        }
    };
}

From source file:com.loop81.fxcomparer.FXComparerController.java

/** 
 * Run the compare by embedding the call to {@link Comparer#compare(ComparableArchive, ComparableArchive)} into
 * a {@link Task} since the operation might take some time depending on the client machine and the archives size
 * and we do not like to hang the UI-thread. 
 *///from  www  .  j a v  a2s  .  c om
private void initCompare() {
    new Thread(new Task<ComparisonResult>() {
        @Override
        protected ComparisonResult call() throws Exception {
            return comparer.compare(archive1, archive2);
        }

        @Override
        protected void succeeded() {
            ComparisonResult result = getValue();
            if (result.isSame()) {
                labelCompareResult.setText(MessageBundle.getString("result.same"));
            } else {
                long diff = archive2.getSize() - archive1.getSize();
                labelCompareResult.setText(MessageBundle.getString("result.different",
                        FileUtils.byteCountToDisplaySize(archive1.getSize()),
                        FileUtils.byteCountToDisplaySize(archive2.getSize()),
                        convertdifferenceToReadableString(diff)));
            }

            compareTable.setItems(FXCollections.observableList(result.getEntries()));
        }

        @Override
        protected void failed() {
            new AlertDialog(MessageBundle.getString("exceptions.archive.compare")).show();
            getException().printStackTrace();
        }
    }).start();
}

From source file:org.sleuthkit.autopsy.timeline.ui.detailview.EventNodeBase.java

/**
 * defer tooltip content creation till needed, this had a surprisingly large
 * impact on speed of loading the chart/*  w w  w  . java  2s . c o  m*/
 */
@NbBundle.Messages({ "# {0} - counts", "# {1} - event type", "# {2} - description", "# {3} - start date/time",
        "# {4} - end date/time", "EventNodeBase.tooltip.text={0} {1} events\n{2}\nbetween\t{3}\nand   \t{4}",
        "EventNodeBase.toolTip.loading2=loading tooltip", "# {0} - hash set count string",
        "EventNodeBase.toolTip.hashSetHits=\n\nHash Set Hits\n{0}", "# {0} - tag count string",
        "EventNodeBase.toolTip.tags=\n\nTags\n{0}" })
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
void installTooltip() {
    if (tooltip.getText().equalsIgnoreCase(Bundle.EventBundleNodeBase_toolTip_loading())) {
        final Task<String> tooltTipTask = new Task<String>() {
            {
                updateTitle(Bundle.EventNodeBase_toolTip_loading2());
            }

            @Override
            protected String call() throws Exception {
                HashMap<String, Long> hashSetCounts = new HashMap<>();
                if (tlEvent.getEventIDsWithHashHits().isEmpty() == false) {
                    try {
                        //TODO:push this to DB
                        for (SingleEvent tle : eventsModel.getEventsById(tlEvent.getEventIDsWithHashHits())) {
                            Set<String> hashSetNames = sleuthkitCase.getAbstractFileById(tle.getFileID())
                                    .getHashSetNames();
                            for (String hashSetName : hashSetNames) {
                                hashSetCounts.merge(hashSetName, 1L, Long::sum);
                            }
                        }
                    } catch (TskCoreException ex) {
                        LOGGER.log(Level.SEVERE, "Error getting hashset hit info for event.", ex); //NON-NLS
                    }
                }
                String hashSetCountsString = hashSetCounts.entrySet().stream()
                        .map((Map.Entry<String, Long> t) -> t.getKey() + " : " + t.getValue())
                        .collect(Collectors.joining("\n"));

                Map<String, Long> tagCounts = new HashMap<>();
                if (tlEvent.getEventIDsWithTags().isEmpty() == false) {
                    tagCounts.putAll(eventsModel.getTagCountsByTagName(tlEvent.getEventIDsWithTags()));
                }
                String tagCountsString = tagCounts.entrySet().stream()
                        .map((Map.Entry<String, Long> t) -> t.getKey() + " : " + t.getValue())
                        .collect(Collectors.joining("\n"));

                return Bundle.EventNodeBase_tooltip_text(getEventIDs().size(), getEventType(), getDescription(),
                        TimeLineController.getZonedFormatter().print(getStartMillis()),
                        TimeLineController.getZonedFormatter().print(getEndMillis() + 1000))
                        + (hashSetCountsString.isEmpty() ? ""
                                : Bundle.EventNodeBase_toolTip_hashSetHits(hashSetCountsString))
                        + (tagCountsString.isEmpty() ? "" : Bundle.EventNodeBase_toolTip_tags(tagCountsString));
            }

            @Override
            protected void succeeded() {
                super.succeeded();
                try {
                    tooltip.setText(get());
                    tooltip.setGraphic(null);
                } catch (InterruptedException | ExecutionException ex) {
                    LOGGER.log(Level.SEVERE, "Tooltip generation failed.", ex); //NON-NLS
                }
            }
        };
        new Thread(tooltTipTask).start();
        chartLane.getController().monitorTask(tooltTipTask);
    }
}

From source file:utilitybasedfx.MainGUIController.java

@FXML
private void eventGenerateMutants(ActionEvent event) {
    MutantViewerController c = Prefs.getController("MutantViewer");

    List<File> actualFiles = new ArrayList<>();
    for (File file : listOfSelectedFiles) {
        actualFiles.add(new File(Prefs.getSourcePath(), file.toString()));
    }//from w  w w  .  j a  v a  2  s  .  co  m

    enableWorking(new Task<String>() {
        @Override
        protected String call() throws InterruptedException {
            File root;
            try {
                root = new File(Prefs.getProjectPath()).getCanonicalFile();
            } catch (IOException ioe) {
                updateMessage("Unable to find root directory");
                return "";
            }
            NewMutationSystem nms = new NewMutationSystem(root);

            updateMessage("Generating Mutants!...");
            try {
                List<Mutant> mutants = nms.generateMutants(actualFiles, listOfTraditionalOps, listOfClassOps);
                updateMessage("");

                c.setMutants(mutants);
                Platform.runLater(c::refreshClassesCbos);
                Platform.runLater(() -> {
                    Prefs.getStage().setScene(Prefs.getScene("MutantViewer"));
                });
            } catch (UnableToGenerateException utg) {
                Platform.runLater(() -> {
                    Alert alert = new Alert(AlertType.ERROR);
                    alert.setTitle("There was an error");
                    alert.setHeaderText("There was an issue generating mutants");
                    alert.setContentText(utg.toString());

                    alert.showAndWait();
                });
            } catch (NoClassFilesException ex) {
                Platform.runLater(() -> {
                    Alert alert = new Alert(AlertType.ERROR);
                    alert.setTitle("There was an error");
                    alert.setHeaderText("There was an issue generating mutants");
                    alert.setContentText(
                            "There is no classes in the following folder\n" + Prefs.getClassPath());

                    alert.showAndWait();
                });
            }

            return ""; //[FIXME] find a way to do this inline function without a class as return type
        }
    });
}

From source file:uk.co.everywheremusic.viewcontroller.SetupScene.java

private Task createSetupWorker() {
    return new Task() {
        @Override//from  ww  w . j ava 2  s  .  co  m
        protected Object call() throws Exception {

            updateMessage("0|" + Globals.SETUP_MSG_DB_CREATE);
            LibraryManager.appendLogFile(Globals.SETUP_MSG_DB_CREATE);

            LibraryManager libMan = new LibraryManager(installFolder, musicFolder);

            saveSettings();

            File path = new File(musicFolder);
            Collection<File> files = FileUtils.listFiles(path, Globals.FILE_EXTENSIONS, true);
            Object[] fileArray = files.toArray();

            dbMan = new DBManager(installFolder);
            sdao = dbMan.getSongDAO();
            pdao = dbMan.getPasswordDAO();
            dbMan.wipeDatabase();

            pdao.insertPassword(password);

            files = FileUtils.listFiles(path, Globals.FILE_EXTENSIONS, true);
            fileArray = files.toArray();

            // process files
            for (Integer i = 0; i < fileArray.length; i++) {

                File tempFile = (File) fileArray[i];

                if (!tempFile.isDirectory()) {

                    String[] metaData = libMan.readID3(tempFile);

                    if (metaData != null) {

                        if ((metaData[1] != null && !metaData[1].equals(""))
                                && (metaData[3] != null && !metaData[3].equals(""))) {

                            Float percent = new Float(0);
                            float total = fileArray.length;
                            float number = i + 1;
                            float div = (number / total);
                            percent = div * 100;

                            updateMessage(Math.round(percent) + "|" + Globals.SETUP_MSG_PROCESSING_SONG
                                    + metaData[1] + " - " + metaData[3]);
                            LibraryManager.appendLogFile(
                                    Globals.SETUP_MSG_PROCESSING_SONG + metaData[1] + " - " + metaData[3]);
                            updateProgress(i + 1, fileArray.length);

                        }

                        metaData[0] = libMan.absolutePathtoRelativePath(metaData[0]);

                        SongBean song = new SongBean(0, metaData[1], metaData[2], metaData[3], metaData[4],
                                metaData[5], metaData[6], metaData[7], metaData[8], metaData[9], metaData[10],
                                tempFile.getAbsolutePath(), System.currentTimeMillis());

                        sdao.insertSong(song);

                    }
                }

            }

            updateMessage("100|" + Globals.SETUP_MSG_DONE);
            LibraryManager.appendLogFile(Globals.SETUP_MSG_DONE);

            return true;

        }
    };
}

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

@FXML
public void initialize() {

    try {//www  .j  a  v  a  2  s  .  com

        miHelp.setAccelerator(KeyCombination.keyCombination("F1"));

        cbType.getItems().add(SigningArgumentsType.JAR);
        cbType.getItems().add(SigningArgumentsType.FOLDER);

        cbType.getSelectionModel().select(SigningArgumentsType.JAR);

        cbType.setConverter(new StringConverter<SigningArgumentsType>() {

            @Override
            public String toString(SigningArgumentsType type) {
                return StringUtils.capitalize(StringUtils.lowerCase(String.valueOf(type)));
            }

            @Override
            public SigningArgumentsType fromString(String type) {
                return Enum.valueOf(SigningArgumentsType.class, StringUtils.upperCase(type));
            }

        });

        activeConfiguration.activeProfileProperty().bindBidirectional(activeProfile.profileNameProperty());
        tfSourceFile.textProperty().bindBidirectional(activeProfile.sourceFileFileNameProperty());
        tfTargetFile.textProperty().bindBidirectional(activeProfile.targetFileFileNameProperty());
        ckReplace.selectedProperty().bindBidirectional(activeProfile.replaceSignaturesProperty());
        cbType.valueProperty().bindBidirectional(activeProfile.argsTypeProperty());

        miSave.disableProperty().bind(needsSave.not());

        tfSourceFile.textProperty().addListener(new WeakInvalidationListener(needsSaveListener));
        tfTargetFile.textProperty().addListener(new WeakInvalidationListener(needsSaveListener));
        ckReplace.selectedProperty().addListener(new WeakInvalidationListener(needsSaveListener));
        cbType.valueProperty().addListener(new WeakInvalidationListener(needsSaveListener));

        lblSource.setText(SOURCE_LABEL_JAR);
        lblTarget.setText(TARGET_LABEL_JAR);
        cbType.getSelectionModel().selectedItemProperty().addListener((ov, old_v, new_v) -> {
            if (new_v == SigningArgumentsType.FOLDER) {
                if (!lblSource.getText().equalsIgnoreCase(SOURCE_LABEL_FOLDER)) {
                    lblSource.setText(SOURCE_LABEL_FOLDER);
                }
                if (!lblSource.getText().equalsIgnoreCase(TARGET_LABEL_FOLDER)) {
                    lblTarget.setText(TARGET_LABEL_FOLDER);
                }
            } else {
                if (!lblSource.getText().equalsIgnoreCase(SOURCE_LABEL_JAR)) {
                    lblSource.setText(SOURCE_LABEL_JAR);
                }
                if (!lblSource.getText().equalsIgnoreCase(TARGET_LABEL_JAR)) {
                    lblTarget.setText(TARGET_LABEL_JAR);
                }
            }
        });

        lvProfiles.getSelectionModel().selectedItemProperty().addListener((ov, old_v, new_v) -> {

            if (new_v == null) { // coming from clearSelection or sort
                return;
            }

            if (needsSave.getValue()) {

                Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Discard unsaved profile?");
                alert.setHeaderText("Unsaved profile");
                Optional<ButtonType> response = alert.showAndWait();
                if (!response.isPresent() || response.get() != ButtonType.OK) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("[SELECT] discard canceled");
                    }
                    return;
                }
            }

            if (logger.isDebugEnabled()) {
                logger.debug("[SELECT] nv={}", new_v);
            }
            doLoadProfile(new_v);
        });

        lvProfiles.setCellFactory(TextFieldListCell.forListView());

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

            @Override
            protected Void call() throws Exception {

                updateMessage("Loading configuration");
                configurationDS.loadConfiguration();

                if (!configurationDS.isSecured()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("[CALL] config not secured; getting password");
                    }
                    NewPasswordController npc = newPasswordControllerProvider.get();

                    if (logger.isDebugEnabled()) {
                        logger.debug("[INIT TASK] npc id={}", npc.hashCode());
                    }

                    Platform.runLater(() -> {
                        try {
                            npc.showAndWait();
                        } catch (Exception exc) {
                            logger.error("error showing npc", exc);
                        }
                    });

                    synchronized (npc) {
                        try {
                            npc.wait(MAX_WAIT_TIME); // 10 minutes to enter the password
                        } catch (InterruptedException exc) {
                            logger.error("new password operation interrupted", exc);
                        }
                    }

                    if (logger.isDebugEnabled()) {
                        logger.debug("[INIT TASK] npc={}", npc.getHashedPassword());
                    }

                    if (StringUtils.isNotEmpty(npc.getHashedPassword())) {

                        activeConfiguration.setHashedPassword(npc.getHashedPassword());
                        activeConfiguration.setUnhashedPassword(npc.getUnhashedPassword());
                        activeConfiguration.setLastUpdatedDateTime(LocalDateTime.now());
                        configurationDS.saveConfiguration();

                        configurationDS.loadConfiguration();
                        configurationDS.decrypt(activeConfiguration.getUnhashedPassword());

                    } else {

                        Platform.runLater(() -> {
                            Alert noPassword = new Alert(Alert.AlertType.INFORMATION,
                                    "You'll need to provide a password to save your keystore credentials.");
                            noPassword.showAndWait();
                        });

                        return null;
                    }
                } else {

                    PasswordController pc = passwordControllerProvider.get();

                    Platform.runLater(() -> {
                        try {
                            pc.showAndWait();
                        } catch (Exception exc) {
                            logger.error("error showing pc", exc);
                        }
                    });

                    synchronized (pc) {
                        try {
                            pc.wait(MAX_WAIT_TIME); // 10 minutes to enter the password
                        } catch (InterruptedException exc) {
                            logger.error("password operation interrupted", exc);
                        }
                    }

                    Platform.runLater(() -> {

                        if (pc.getStage().isShowing()) { // ended in timeout timeout
                            pc.getStage().hide();
                        }

                        if (pc.wasCancelled() || pc.wasReset() || !pc.doesPasswordMatch()) {

                            if (logger.isDebugEnabled()) {
                                logger.debug("[INIT TASK] was cancelled or the number of retries was exceeded");
                            }

                            String msg = "";
                            if (pc.wasCancelled()) {
                                msg = "You must provide a password to the datastore. Exitting...";
                            } else if (pc.wasReset()) {
                                msg = "Data file removed. Exitting...";
                            } else {
                                msg = "Exceeded maximum number of retries. Exitting...";
                            }

                            Alert alert = new Alert(Alert.AlertType.WARNING, msg);
                            alert.setOnCloseRequest((evt) -> {
                                Platform.exit();
                                System.exit(1);
                            });
                            alert.showAndWait();

                        } else {

                            //
                            // save password for later decryption ops
                            //

                            activeConfiguration.setUnhashedPassword(pc.getPassword());
                            configurationDS.decrypt(activeConfiguration.getUnhashedPassword());

                            //
                            // init profileBrowser
                            //
                            if (logger.isDebugEnabled()) {
                                logger.debug("[INIT TASK] loading profiles from source");
                            }

                            long startTimeMillis = System.currentTimeMillis();

                            final List<String> profileNames = configurationDS.getProfiles().stream()
                                    .map(Profile::getProfileName).sorted((o1, o2) -> o1.compareToIgnoreCase(o2))
                                    .collect(Collectors.toList());

                            final List<String> recentProfiles = configurationDS.getRecentProfileNames();

                            if (logger.isDebugEnabled()) {
                                logger.debug("[INIT TASK] loading profiles into UI");
                            }

                            lvProfiles.setItems(FXCollections.observableArrayList(profileNames));

                            if (CollectionUtils.isNotEmpty(recentProfiles)) {
                                mRecentProfiles.getItems().clear();
                                mRecentProfiles.getItems().addAll(
                                        FXCollections.observableArrayList(recentProfiles.stream().map((s) -> {
                                            MenuItem mi = new MenuItem(s);
                                            mi.setOnAction(recentProfileLoadHandler);
                                            return mi;
                                        }).collect(Collectors.toList())));
                            }

                            //
                            // #31 preload the last active profile
                            //
                            if (StringUtils.isNotEmpty(activeConfiguration.getActiveProfile())) {

                                if (logger.isDebugEnabled()) {
                                    logger.debug("[INIT TASK] preloading last active profile={}",
                                            activeConfiguration.getActiveProfile());
                                }
                                doLoadProfile(activeConfiguration.getActiveProfile());
                            }

                            long endTimeMillis = System.currentTimeMillis();

                            if (logger.isDebugEnabled()) {
                                logger.debug("[INIT TASK] loading profiles took {} ms",
                                        (endTimeMillis - startTimeMillis));
                            }
                        }
                    });
                }

                return null;
            }

            @Override
            protected void succeeded() {
                super.succeeded();
                updateMessage("");
                lblStatus.textProperty().unbind();
            }

            @Override
            protected void cancelled() {
                super.cancelled();
                logger.error("task cancelled", getException());
                updateMessage("");
                lblStatus.textProperty().unbind();
            }

            @Override
            protected void failed() {
                super.failed();
                logger.error("task failed", getException());
                updateMessage("");
                lblStatus.textProperty().unbind();
            }
        };

        lblStatus.textProperty().bind(t.messageProperty());

        new Thread(t).start();

    } catch (Exception exc) {

        logger.error("can't load configuration", exc);

        String msg = "Verify that the user has access to the directory '" + configFile + "' under "
                + System.getProperty("user.home") + ".";

        Alert alert = new Alert(Alert.AlertType.ERROR, msg);
        alert.setHeaderText("Can't load config file");
        alert.showAndWait();

        Platform.exit();
    }
}

From source file:com.properned.application.SystemController.java

public void openPropertiesFile() {
    logger.info("Open the 'Open file' dialog");
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle(MessageReader.getInstance().getMessage("window.openFile.title"));
    String lastPathUsed = Preferences.getInstance().getLastPathUsed();
    File lastSelectedFile = new File(lastPathUsed);
    if (StringUtils.isNotEmpty(lastPathUsed) && lastSelectedFile != null
            && lastSelectedFile.getParentFile() != null && lastSelectedFile.getParentFile().exists()) {
        fileChooser.setInitialDirectory(lastSelectedFile.getParentFile());
    }/*from w w w . j  ava 2 s .c  o  m*/
    File selectedFile = fileChooser
            .showOpenDialog(Properned.getInstance().getPrimaryStage().getScene().getWindow());
    if (selectedFile != null) {
        logger.info("Selected file : " + selectedFile.getAbsolutePath());
        Task<Void> loadTask = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                loadFileList(selectedFile);
                return null;
            }
        };

        Executors.newSingleThreadExecutor().submit(loadTask);
    }
}

From source file:poe.trade.assist.Main.java

public void manualTaskRun(Search search) {
    String url = search.getUrl();
    if (isNotBlank(url)) {
        Task<Search> task = new Task<Search>() {
            @Override//w  w  w .j a  v  a 2 s. c  o m
            protected Search call() throws Exception {
                String html = AutoSearchService.doDownload(search.getUrl(), search.getSort());
                search.setHtml(html);
                search.parseHtml();
                return search;
            }
        };
        resultPane.progressIndicator.visibleProperty().unbind();
        resultPane.progressIndicator.visibleProperty().bind(task.runningProperty());
        task.setOnSucceeded(e -> {
            resultPane.setSearch(task.getValue());
            //            refreshResultColumn();
        });
        task.setOnFailed(e -> {
            Dialogs.showError(task.getException());
            //            refreshResultColumn();
        });
        new Thread(task).start();
    } else {
        resultPane.setSearch(search);
    }
}

From source file:ui.main.MainViewController.java

private void showAccountInfo() {
    //this method shows the account name and presence
    //create a thread to check the user connected online or not
    Task<Void> presenceWatchTask = new Task<Void>() {
        @Override/*from   w ww.j  av  a 2  s. c o m*/
        public Void call() throws Exception {
            while (true) {
                updateMessage(connectionManager.getMyPresence());
                Thread.sleep(1000);
            }
            //return null;
        }
    };

    presenceWatchTask.messageProperty()
            .addListener((obs, oldMessage, newMessage) -> presence.setText(newMessage));
    new Thread(presenceWatchTask).start();
    name.setText(connectionManager.getMyUsername());
    try {
        if (connectionManager.getMyProfileAvatar() != null) {
            myAvatar.setImage(connectionManager.getMyProfileAvatar());

        } else {
            myAvatar.setImage(defaultAvatar);
        }
    } catch (IOException e) {
        myAvatar.setImage(defaultAvatar);
    } catch (XMPPException e) {
        myAvatar.setImage(defaultAvatar);
    } catch (NullPointerException e) {
        myAvatar.setImage(defaultAvatar);
    } finally {
        myAvatar.setFitHeight(120);
        myAvatar.setFitWidth(100);
    }
}