Example usage for javafx.concurrent Task progressProperty

List of usage examples for javafx.concurrent Task progressProperty

Introduction

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

Prototype

@Override
    public final ReadOnlyDoubleProperty progressProperty() 

Source Link

Usage

From source file:editeurpanovisu.EquiCubeDialogController.java

/**
 *
 *///from  w ww  . ja  v  a  2s . c  o  m
private void validerE2C() {
    if (fileLstFichier == null) {
        Alert alert = new Alert(AlertType.ERROR);
        alert.setTitle(rbLocalisation.getString("transformation.traiteImages"));
        alert.setHeaderText(null);
        alert.setContentText(rbLocalisation.getString("transformation.traiteImagesPasFichiers"));
        alert.showAndWait();
    } else {
        Alert alert = new Alert(AlertType.WARNING);
        alert.setTitle(rbLocalisation.getString("transformation.traiteImages"));
        alert.setHeaderText(null);
        alert.setContentText(rbLocalisation.getString("transformation.traiteImagesMessage"));
        alert.showAndWait();

        lblTermine = new Label();
        lblTermine.setText("Traitement en cours");
        lblTermine.setLayoutX(24);
        lblTermine.setLayoutY(250);
        paneChoixTypeFichier.getChildren().add(lblTermine);
        pbBarreAvancement.setId("bar");
        lblTermine.setId("lblTermine");
        pbBarreAvancement.setVisible(true);
        pbBarreImage.setVisible(true);
        Task taskTraitement;
        taskTraitement = tskTraitement();
        pbBarreAvancement.progressProperty().unbind();
        pbBarreImage.setProgress(0.001);
        pbBarreAvancement.setProgress(0.001);
        pbBarreAvancement.progressProperty().bind(taskTraitement.progressProperty());
        lblTermine.textProperty().unbind();
        lblTermine.textProperty().bind(taskTraitement.messageProperty());
        Thread thrTraitement = new Thread(taskTraitement);
        thrTraitement.setDaemon(true);
        thrTraitement.start();
    }
}

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

private void loadAliases() {

    if (StringUtils.isNotEmpty(tfKeystore.getText()) && StringUtils.isNotEmpty(pfStorepass.getText())) {
        if (logger.isDebugEnabled()) {
            logger.debug("[LOAD ALIASES] there are values for the keytool command");
        }// ww  w  .j  a  v  a  2 s.co  m

        hboxAliasProgress.setVisible(true);
        cbAlias.valueProperty().unbindBidirectional(activeProfile.jarsignerConfigAliasProperty());
        cbAlias.getItems().clear();

        final String ks = tfKeystore.getText();
        final String sp = pfStorepass.getText();

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

                try {

                    updateMessage("Loading...");
                    updateProgress(0.1d, 1.0d);

                    final List<String> aliases = keytoolCommand
                            .findAliases(activeConfiguration.getKeytoolCommand().toString(), ks, sp);

                    updateMessage("Updating...");
                    updateProgress(0.8d, 1.0d);

                    Platform.runLater(() -> {
                        if (CollectionUtils.isNotEmpty(aliases)) {

                            cbAlias.getItems().addAll(aliases);
                            cbAlias.valueProperty()
                                    .bindBidirectional(activeProfile.jarsignerConfigAliasProperty());

                        }

                        cbAlias.setDisable(false); // might be an empty list for empty keystore
                        cbAlias.requestFocus(); // leave the PasswordField
                        hboxAliasProgress.setVisible(false);
                    });

                } catch (CommandExecutionException exc) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("error getting aliases", exc);
                    }
                    Platform.runLater(() -> {
                        cbAlias.setDisable(true);
                        hboxAliasProgress.setVisible(false);
                    });
                } finally {
                    updateMessage("");
                    updateProgress(0.0d, 1.0d);
                }

                return null;
            }
        };

        lblAliasProgress.textProperty().bind(t.messageProperty());
        pbAlias.progressProperty().bind(t.progressProperty());

        new Thread(t).start();

    } else {

        cbAlias.getItems().clear();
        cbAlias.setDisable(true);
    }
}

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  www. j a  v  a  2 s. co  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:com.bekwam.resignator.ResignatorAppMainViewController.java

@FXML
public void sign() {

    if (logger.isDebugEnabled()) {
        logger.debug("[SIGN] activeProfile sourceFile={}, targetFile={}", activeProfile.getSourceFileFileName(),
                activeProfile.getTargetFileFileName());
    }//from www.  ja v  a 2  s .  c  o  m

    boolean isValid = validateSign();

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

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

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

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

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

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

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

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

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

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

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

            @Override
            protected Void call() throws Exception {

                double accruedProgress = 0.0d;

                for (File sf : sourceJars) {

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

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

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

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

                        if (isCancelled()) {
                            return null;
                        }

                    } else {

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

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

                    updateTitle("Signing JAR");

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

                return null;
            }

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

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

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

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

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

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

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

                piSignProgress.setVisible(false);

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

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

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

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

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

                    piSignProgress.setVisible(false);

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

            }
        };

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

        new Thread(task).start();

    } else {

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

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

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

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

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

            @Override
            protected Void call() throws Exception {

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

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

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

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

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

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

                return null;
            }

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

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

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

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

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

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

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

                piSignProgress.setVisible(false);

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

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

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

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

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

                piSignProgress.setVisible(false);

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

            }
        };

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

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

From source file:sh.isaac.api.util.DownloadUnzipTask.java

/**
 * Call.//from   w  w  w .  j  a va  2  s  . c  om
 *
 * @return the file
 * @throws Exception the exception
 * @see javafx.concurrent.Task#call()
 */
@Override
protected File call() throws Exception {
    final File dataFile = download(this.url);
    String calculatedSha1Value = null;
    String expectedSha1Value = null;
    ;

    try {
        LOG.debug("Attempting to get .sha1 file");

        final File sha1File = download(new URL(this.url.toString() + ".sha1"));

        expectedSha1Value = Files.readAllLines(sha1File.toPath()).get(0);

        final Task<String> calculateTask = ChecksumGenerator.calculateChecksum("SHA1", dataFile);

        calculateTask.messageProperty().addListener(
                (ChangeListener<String>) (observable, oldValue, newValue) -> updateMessage(newValue));
        calculateTask.progressProperty().addListener((ChangeListener<Number>) (observable, oldValue,
                newValue) -> updateProgress(calculateTask.getProgress(), calculateTask.getTotalWork()));
        WorkExecutors.get().getExecutor().execute(calculateTask);
        calculatedSha1Value = calculateTask.get();
        sha1File.delete();
    } catch (final Exception e1) {
        LOG.debug("Failed to get .sha1 file", e1);
    }

    if ((calculatedSha1Value != null) && !calculatedSha1Value.equals(expectedSha1Value)) {
        if (this.failOnBadCheksum) {
            throw new RuntimeException("Checksum of downloaded file '" + this.url.toString()
                    + "' does not match the expected value!");
        } else {
            LOG.warn("Checksum of downloaded file '" + this.url.toString()
                    + "' does not match the expected value!");
        }
    }

    if (this.cancel) {
        LOG.debug("Download cancelled");
        throw new Exception("Cancelled!");
    }

    if (this.unzip) {
        updateTitle("Unzipping");

        try {
            final ZipFile zipFile = new ZipFile(dataFile);

            zipFile.setRunInThread(true);
            zipFile.extractAll(this.targetFolder.getAbsolutePath());

            while (zipFile.getProgressMonitor().getState() == ProgressMonitor.STATE_BUSY) {
                if (this.cancel) {
                    zipFile.getProgressMonitor().cancelAllTasks();
                    LOG.debug("Download cancelled");
                    throw new Exception("Cancelled!");
                }

                updateProgress(zipFile.getProgressMonitor().getPercentDone(), 100);
                updateMessage("Unzipping " + dataFile.getName() + " at "
                        + zipFile.getProgressMonitor().getPercentDone() + "%");

                try {
                    // TODO see if there is an API where I don't have to poll for completion
                    Thread.sleep(25);
                } catch (final InterruptedException e) {
                    // noop
                }
            }

            LOG.debug("Unzip complete");
        } catch (final Exception e) {
            LOG.error("error unzipping", e);
            throw new Exception("The downloaded file doesn't appear to be a zip file");
        } finally {
            dataFile.delete();
        }

        return this.targetFolder;
    } else {
        return dataFile;
    }
}

From source file:snpviewer.SnpViewer.java

public void saveRegion(final String chromosome, final double startCoordinate, final double endCoordinate) {
    final Task<RegionSummary> saveSelectionTask = new Task<RegionSummary>() {
        @Override/* ww  w. j av  a 2 s  . c o  m*/
        protected RegionSummary call() throws Exception {
            try {
                updateProgress(-1, -1);
                updateTitle("Finding flanking SNPs");
                updateMessage("Searching for nearest SNP in all files...");

                /* read SnpFiles to find closest SNPs - use binary search
                 * to find nearby SNP and refine to closest
                 */
                List<SnpFile.SnpLine> startAndEndSnps = searchCoordinate(chromosome, (int) startCoordinate,
                        (int) endCoordinate);
                if (startAndEndSnps == null) {
                    System.out.println("Start and End SNPS ARE NULL!");
                    //DISPLAY ERROR HERE?
                    return null;
                }
                RegionSummary region = new RegionSummary(chromosome, startAndEndSnps.get(0).getPosition(),
                        startAndEndSnps.get(1).getPosition(), 0, 0, startAndEndSnps.get(0).getId(),
                        startAndEndSnps.get(1).getId());
                return region;

            } catch (NumberFormatException ex) {
                Dialogs.showErrorDialog(null,
                        "Can't display flanking SNP IDs"
                                + " - missing required componant!\n\nPlease report this error.",
                        "Error!", "SNP Viewer", ex);
            }
            return null;
        }
    };
    setProgressMode(true);
    progressBar.progressProperty().bind(saveSelectionTask.progressProperty());
    progressMessage.textProperty().unbind();
    progressMessage.textProperty().bind(saveSelectionTask.messageProperty());
    progressTitle.textProperty().unbind();
    progressTitle.textProperty().bind(saveSelectionTask.titleProperty());
    saveSelectionTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            setProgressMode(false);
            RegionSummary result = (RegionSummary) e.getSource().getValue();
            savedRegions.add(result);
            RegionSummary sorter = new RegionSummary();
            sorter.mergeRegionsByPosition(savedRegions);
            saveProject();
            clearDragSelectRectangle();
            savedRegionsDisplay.clear();
            savedRegionsReference.clear();
            drawSavedRegions(
                    (String) chromosomeBoxList[chromosomeSelector.getSelectionModel().getSelectedIndex()]);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressTitle.textProperty().unbind();
            progressMessage.textProperty().unbind();
            progressTitle.setText("");
            progressMessage.setText("");
        }

    });
    saveSelectionTask.setOnFailed(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressTitle.textProperty().unbind();
            progressMessage.textProperty().unbind();
            progressTitle.setText("");
            progressMessage.setText("");
            Dialogs.showErrorDialog(null, "Error finding flanking SNPs\n", "Save Region error", "SNP Viewer",
                    saveSelectionTask.getException());

        }

    });
    saveSelectionTask.setOnCancelled(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            progressMessage.setText("Region write cancelled");
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressTitle.textProperty().unbind();
            progressMessage.textProperty().unbind();
            progressTitle.setText("");
            progressMessage.setText("");
            Dialogs.showErrorDialog(null, "User cancelled region save.", "Save Region", "SNP Viewer",
                    saveSelectionTask.getException());
        }

    });
    cancelButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            saveSelectionTask.cancel();

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

From source file:snpviewer.SnpViewer.java

public void displayFlankingSnpIDs(final String chrom, final double start, final double end) {
    final Task<List<String>> displayTask = new Task<List<String>>() {
        @Override//from   w w w  .j a v  a2s .c o m
        protected List<String> call() {
            updateProgress(-1, -1);
            updateTitle("Finding flanking SNPs");
            updateMessage("Searching for nearest SNP in all files...");
            //work out coordinates based on chromosome and pane sizes
            /* read SnpFiles to find closest SNPs - use binary search
            * to find nearby SNP and refine to closest
            */
            List<SnpFile.SnpLine> startAndEndSnps = searchCoordinate(chrom, (int) start, (int) end);
            if (startAndEndSnps == null) {
                //DISPLAY ERROR HERE?
                return null;
            }
            String coordResult = "chr" + chrom + ":" + nf.format(startAndEndSnps.get(0).getPosition()) + "-"
                    + nf.format(startAndEndSnps.get(1).getPosition());
            String idResult = startAndEndSnps.get(0).getId() + ";" + startAndEndSnps.get(1).getId();
            List<String> result = new ArrayList();
            result.add(coordResult);
            result.add(idResult);
            return result;
        }
    };

    setProgressMode(true);
    progressBar.progressProperty().bind(displayTask.progressProperty());
    progressMessage.textProperty().unbind();
    progressMessage.textProperty().bind(displayTask.messageProperty());
    progressTitle.textProperty().unbind();
    progressTitle.textProperty().bind(displayTask.titleProperty());
    displayTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressTitle.textProperty().unbind();
            progressMessage.textProperty().unbind();
            progressTitle.setText("");
            progressMessage.setText("");
        }

    });
    displayTask.setOnFailed(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressTitle.textProperty().unbind();
            progressMessage.textProperty().unbind();
            progressTitle.setText("");
            progressMessage.setText("");
            Dialogs.showErrorDialog(null, "Error displaying flanking SNPs\n", "Display error", "SNP Viewer",
                    displayTask.getException());

        }

    });
    displayTask.setOnCancelled(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            progressMessage.setText("Display flanking SNPs cancelled");
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressTitle.textProperty().unbind();
            progressMessage.textProperty().unbind();
            progressTitle.setText("");
            progressMessage.setText("");
            Dialogs.showErrorDialog(null, "User cancelled display.", "Display error", "SNP Viewer",
                    displayTask.getException());
        }

    });
    cancelButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            displayTask.cancel();

        }
    });
    new Thread(displayTask).start();
    try {
        List<String> result = displayTask.get();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("RegionReporter.fxml"));
        Stage stage = new Stage();
        Pane page = (Pane) loader.load();
        Scene scene = new Scene(page);
        stage.setScene(scene);
        stage.setTitle("SNP Viewer Region Summary");
        stage.getIcons().add(new Image(this.getClass().getResourceAsStream("icon.png")));
        RegionReporterController regionReporter = loader.<RegionReporterController>getController();
        if (result == null) {
            regionReporter.setCoordinates("Error!");
            regionReporter.setIds("Error!");
        } else {
            regionReporter.setCoordinates(result.get(0));
            regionReporter.setIds(result.get(1));
        }
        scene.getStylesheets().add(SnpViewer.class.getResource("SnpViewerStyleSheet.css").toExternalForm());
        stage.setResizable(false);
        stage.initModality(Modality.NONE);

        stage.show();
    } catch (InterruptedException | ExecutionException | IOException ex) {
        Dialogs.showErrorDialog(null,
                "Can't display flanking SNP IDs" + " - exception caught!\n\nPlease report this error.",
                "Error!", "SNP Viewer", ex);
    }

}

From source file:snpviewer.SnpViewer.java

public void writeSavedRegionsToFile() {
    if (savedRegions.size() < 1) {
        Dialogs.showErrorDialog(null, "No Saved Regions exist to write!", "No Saved Regions", "SnpViewer");
        return;/*from  w  w w .  ja  va  2 s. co  m*/
    }
    final int flanks = 10;
    FileChooser fileChooser = new FileChooser();
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Excel (*.xlsx)", "*.xlsx");
    fileChooser.getExtensionFilters().add(extFilter);
    fileChooser.setTitle("Write regions to Excel file (.xlsx)...");
    File rFile = fileChooser.showSaveDialog(mainWindow);
    if (rFile == null) {
        return;
    } else if (!rFile.getName().endsWith(".xlsx")) {
        rFile = new File(rFile.getAbsolutePath() + ".xlsx");
    }
    final File regionFile = rFile;
    final Task<Boolean> writeTask = new Task() {
        @Override
        protected Boolean call() throws Exception {
            try {
                updateProgress(-1, -1);
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(regionFile));
                Workbook wb = new XSSFWorkbook();
                //first create a summary sheet of all regions
                Sheet sheet = wb.createSheet();
                Row row = null;
                int rowNo = 0;
                int sheetNo = 0;
                wb.setSheetName(sheetNo++, "Summary");
                row = sheet.createRow(rowNo++);
                String header[] = { "Coordinates", "rsIDs", "Size (Mb)" };
                for (int col = 0; col < header.length; col++) {
                    Cell cell = row.createCell(col);
                    cell.setCellValue(header[col]);
                }
                for (int i = 0; i < savedRegions.size(); i++) {
                    row = sheet.createRow(rowNo++);
                    int col = 0;
                    Cell cell = row.createCell(col++);
                    cell.setCellValue("chr" + savedRegions.get(i).getCoordinateString());
                    cell = row.createCell(col++);
                    cell.setCellValue(savedRegions.get(i).getIdLine());
                    cell = row.createCell(col++);
                    double mB = (double) savedRegions.get(i).getLength() / 1000000;
                    cell.setCellValue(mB);
                }

                ArrayList<SnpFile> bothFiles = new ArrayList<>();
                bothFiles.addAll(affFiles);
                bothFiles.addAll(unFiles);
                String prevChrom = new String();
                double prog = 0;
                double total = savedRegions.size() * bothFiles.size() * 2;
                updateProgress(prog, total);
                int regCounter = 0;
                for (RegionSummary reg : savedRegions) {
                    updateMessage("Writing region " + ++regCounter + " of " + savedRegions.size());
                    //create a sheet for each chromosome
                    if (!reg.getChromosome().equalsIgnoreCase(prevChrom)) {
                        if (!prevChrom.isEmpty()) {

                            CellRangeAddress[] regions = {
                                    new CellRangeAddress(0, rowNo, 2, 2 + bothFiles.size()) };
                            SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

                            ConditionalFormattingRule rule1 = sheetCF
                                    .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"AA\"");
                            PatternFormatting fill1 = rule1.createPatternFormatting();
                            fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);
                            fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                            ConditionalFormattingRule rule2 = sheetCF
                                    .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"BB\"");
                            PatternFormatting fill2 = rule2.createPatternFormatting();
                            fill2.setFillBackgroundColor(IndexedColors.PALE_BLUE.index);
                            fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                            ConditionalFormattingRule rule3 = sheetCF
                                    .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"AB\"");
                            PatternFormatting fill3 = rule3.createPatternFormatting();
                            fill3.setFillBackgroundColor(IndexedColors.ROSE.index);
                            fill3.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                            sheetCF.addConditionalFormatting(regions, rule3, rule2);
                            sheetCF.addConditionalFormatting(regions, rule1);
                        }
                        rowNo = 0;
                        sheet = wb.createSheet();
                        wb.setSheetName(sheetNo++, reg.getChromosome());
                        prevChrom = reg.getChromosome();

                    } else {//pad regions with an empty line
                        rowNo++;
                    }
                    TreeMap<Integer, HashMap<String, String>> coordMap = new TreeMap();
                    /*coordmap - key is position, key of hashmap 
                     * is input filename and value call
                     */
                    HashMap<Integer, String> coordToId = new HashMap<>();
                    //coordinate to rs ID

                    try {
                        for (SnpFile f : bothFiles) {
                            updateProgress(prog++, total);
                            if (isCancelled()) {
                                return false;
                            }
                            List<SnpFile.SnpLine> lines = f.getSnpsInRegion(reg.getChromosome(),
                                    reg.getStartPos(), reg.getEndPos(), flanks);
                            for (SnpFile.SnpLine snpLine : lines) {
                                if (isCancelled()) {
                                    return false;
                                }
                                Integer coord = snpLine.getPosition();
                                if (!coordMap.containsKey(coord)) {
                                    coordMap.put(coord, new HashMap<String, String>());
                                }
                                String filename = f.inputFile.getName();
                                String rsId = snpLine.getId();
                                String call = snpLine.getCall();
                                coordMap.get(coord).put(filename, call);
                                coordToId.put(coord, rsId);
                            }
                        }
                        row = sheet.createRow(rowNo++);
                        Cell cell = row.createCell(0);
                        cell.setCellValue(reg.getCoordinateString());
                        row = sheet.createRow(rowNo++);
                        cell = row.createCell(0);
                        cell.setCellValue(reg.getIdLine());

                        int col = 0;
                        row = sheet.createRow(rowNo++);
                        cell = row.createCell(col++);
                        cell.setCellValue("Position");
                        cell = row.createCell(col++);
                        cell.setCellValue("rsID");
                        for (SnpFile f : bothFiles) {
                            updateProgress(prog++, total);
                            cell = row.createCell(col++);
                            if (f.getSampleName() != null && !f.getSampleName().isEmpty()) {
                                cell.setCellValue(f.getSampleName());
                            } else {
                                cell.setCellValue(f.inputFile.getName());
                            }
                        }
                        for (Entry current : coordMap.entrySet()) {
                            if (isCancelled()) {
                                return false;
                            }
                            col = 0;
                            Integer coord = (Integer) current.getKey();
                            row = sheet.createRow(rowNo++);
                            cell = row.createCell(col++);
                            cell.setCellValue(coord);
                            cell = row.createCell(col++);
                            cell.setCellValue(coordToId.get(coord));
                            HashMap<String, String> fileToCall = (HashMap<String, String>) current.getValue();
                            for (SnpFile f : bothFiles) {
                                cell = row.createCell(col++);
                                if (fileToCall.containsKey(f.inputFile.getName())) {
                                    cell.setCellValue(fileToCall.get(f.inputFile.getName()));
                                } else {
                                    cell.setCellValue("-");
                                }
                            }
                        }
                    } catch (Exception ex) {
                        return false;
                    }

                }
                CellRangeAddress[] regions = { new CellRangeAddress(0, rowNo, 2, 2 + bothFiles.size()) };
                SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

                ConditionalFormattingRule rule1 = sheetCF
                        .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"AA\"");
                PatternFormatting fill1 = rule1.createPatternFormatting();
                fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);
                fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                ConditionalFormattingRule rule2 = sheetCF
                        .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"BB\"");
                PatternFormatting fill2 = rule2.createPatternFormatting();
                fill2.setFillBackgroundColor(IndexedColors.PALE_BLUE.index);
                fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                ConditionalFormattingRule rule3 = sheetCF
                        .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"AB\"");
                PatternFormatting fill3 = rule3.createPatternFormatting();
                fill3.setFillBackgroundColor(IndexedColors.ROSE.index);
                fill3.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                sheetCF.addConditionalFormatting(regions, rule3, rule2);
                sheetCF.addConditionalFormatting(regions, rule1);
                wb.write(out);
                updateProgress(total, total);
                out.close();
            } catch (IOException | NumberFormatException ex) {
                ex.printStackTrace();
                return false;
            }
            return true;
        }
    };//end of task

    setProgressMode(true);
    progressBar.progressProperty().bind(writeTask.progressProperty());
    progressMessage.textProperty().bind(writeTask.messageProperty());
    writeTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            if (e.getSource().getValue() == true) {
                Dialogs.showInformationDialog(null,
                        "Saved regions written " + "to file " + "(" + regionFile.getName() + ")successfully",
                        "Regions Written", "SNP Viewer");
            } else {
                Dialogs.showErrorDialog(null, "Region write failed.", "Write Failed", "SNP Viewer");
            }
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressMessage.textProperty().unbind();
            progressMessage.setText("");
            progressTitle.setText("");

        }

    });
    writeTask.setOnFailed(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressMessage.textProperty().unbind();
            progressMessage.setText("");
            progressTitle.setText("Region write failed!");
            Dialogs.showErrorDialog(null, "Error writing region to file\n", "Region write error", "SNP Viewer",
                    e.getSource().getException());

        }

    });
    writeTask.setOnCancelled(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            progressMessage.setText("Region write cancelled");
            progressTitle.setText("Cancelled");
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            Dialogs.showErrorDialog(null, "Error writing region to file\n", "Region write error", "SNP Viewer");
        }

    });
    cancelButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            writeTask.cancel();

        }
    });
    progressTitle.setText("Writing regions to .xlsx file");
    new Thread(writeTask).start();
}

From source file:snpviewer.SnpViewer.java

public void writeRegionToFile(final String chromosome, final double start, final double end) {
    /* get coordinates of selection and report back
     * write SNPs in region to file//w w  w.  j ava 2  s .  co  m
     */
    FileChooser fileChooser = new FileChooser();
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Excel  (*.xlsx)", "*.xlsx");
    fileChooser.getExtensionFilters().add(extFilter);
    fileChooser.setTitle("Write region to Excel file (.xlsx)...");
    File rFile = fileChooser.showSaveDialog(mainWindow);
    if (rFile == null) {
        return;
    } else if (!rFile.getName().endsWith(".xlsx")) {
        rFile = new File(rFile.getAbsolutePath() + ".xlsx");
    }
    final File regionFile = rFile;
    final Task<Boolean> writeTask = new Task() {
        @Override
        protected Boolean call() throws Exception {
            try {

                updateProgress(-1, -1);
                ArrayList<SnpFile> bothFiles = new ArrayList<>();
                bothFiles.addAll(affFiles);
                bothFiles.addAll(unFiles);
                TreeMap<Integer, HashMap<String, String>> coordMap = new TreeMap();
                /*coordmap - key is position, key of hashmap 
                 * is input filename and value call
                 */
                HashMap<Integer, String> coordToId = new HashMap<>();
                double progress = 0;
                double total = bothFiles.size() * 5;
                try {
                    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(regionFile));
                    Workbook wb = new XSSFWorkbook();
                    Sheet sheet = wb.createSheet();
                    int rowNo = 0;
                    Row row = sheet.createRow(rowNo++);
                    for (SnpFile f : bothFiles) {
                        if (isCancelled()) {
                            return false;
                        }
                        updateProgress(++progress, total);
                        updateMessage("Reading region in " + f.inputFile.getName());
                        List<SnpFile.SnpLine> lines = f.getSnpsInRegion(chromosome, (int) start, (int) end);
                        for (SnpFile.SnpLine snpLine : lines) {
                            if (isCancelled()) {
                                return false;
                            }
                            Integer coord = snpLine.getPosition();
                            if (!coordMap.containsKey(coord)) {
                                coordMap.put(coord, new HashMap<String, String>());
                            }
                            String filename = f.inputFile.getName();
                            String rsId = snpLine.getId();
                            String call = snpLine.getCall();
                            coordMap.get(coord).put(filename, call);
                            coordToId.put(coord, rsId);
                        }
                    }
                    Cell cell = row.createCell(0);
                    cell.setCellValue(
                            "chr" + chromosome + ":" + coordMap.firstKey() + "-" + coordMap.lastKey());
                    row = sheet.createRow(rowNo++);
                    cell = row.createCell(0);
                    cell.setCellValue(
                            coordToId.get(coordMap.firstKey()) + ";" + coordToId.get(coordMap.lastKey()));
                    row = sheet.createRow(rowNo++);
                    int colNo = 0;
                    cell = row.createCell(colNo++);
                    cell.setCellValue("Position");
                    cell = row.createCell(colNo++);
                    cell.setCellValue("rsID");
                    for (SnpFile f : bothFiles) {
                        cell = row.createCell(colNo++);
                        if (f.getSampleName() != null && f.getSampleName().length() > 0) {
                            cell.setCellValue(f.getSampleName());
                        } else {
                            cell.setCellValue(f.getInputFileName());
                        }
                    }
                    progress = coordMap.size();
                    total = 5 * coordMap.size();
                    updateMessage("Writing region to file...");
                    for (Entry current : coordMap.entrySet()) {
                        if (isCancelled()) {
                            return false;
                        }
                        progress += 4;
                        updateProgress(progress, total);
                        row = sheet.createRow(rowNo++);
                        colNo = 0;
                        Integer coord = (Integer) current.getKey();
                        cell = row.createCell(colNo++);
                        cell.setCellValue(coord);
                        String rsId = coordToId.get(coord);
                        cell = row.createCell(colNo++);
                        cell.setCellValue(rsId);
                        HashMap<String, String> fileToCall = (HashMap<String, String>) current.getValue();
                        for (SnpFile f : bothFiles) {
                            cell = row.createCell(colNo++);
                            if (fileToCall.containsKey(f.inputFile.getName())) {
                                cell.setCellValue(fileToCall.get(f.inputFile.getName()));
                            } else {
                                cell.setCellValue("-");
                            }
                        }
                    }
                    CellRangeAddress[] regions = { new CellRangeAddress(0, rowNo, 2, 2 + bothFiles.size()) };
                    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

                    ConditionalFormattingRule rule1 = sheetCF
                            .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"AA\"");
                    PatternFormatting fill1 = rule1.createPatternFormatting();
                    fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);
                    fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                    ConditionalFormattingRule rule2 = sheetCF
                            .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"BB\"");
                    PatternFormatting fill2 = rule2.createPatternFormatting();
                    fill2.setFillBackgroundColor(IndexedColors.PALE_BLUE.index);
                    fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                    ConditionalFormattingRule rule3 = sheetCF
                            .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"AB\"");
                    PatternFormatting fill3 = rule3.createPatternFormatting();
                    fill3.setFillBackgroundColor(IndexedColors.ROSE.index);
                    fill3.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                    sheetCF.addConditionalFormatting(regions, rule3, rule2);
                    sheetCF.addConditionalFormatting(regions, rule1);
                    wb.write(out);
                    out.close();
                    return true;
                } catch (IOException ex) {
                    return false;
                }
            } catch (Exception ex) {
                return false;
            }
        }
    };//end of task

    setProgressMode(true);
    progressBar.progressProperty().bind(writeTask.progressProperty());
    progressMessage.textProperty().bind(writeTask.messageProperty());
    writeTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            if (e.getSource().getValue() == true) {
                Dialogs.showInformationDialog(null,
                        "Region written to file " + "(" + regionFile.getName() + ") successfully",
                        "Region Written", "SNP Viewer");
            } else {
                Dialogs.showErrorDialog(null, "Region write failed.", "Write Failed", "SNP Viewer");
            }
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressMessage.textProperty().unbind();
            progressMessage.setText("");
            progressTitle.setText("");

        }

    });
    writeTask.setOnFailed(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressMessage.textProperty().unbind();
            progressMessage.setText("");
            progressTitle.setText("Region write failed!");
            Dialogs.showErrorDialog(null, "Error writing region to file\n", "Region write error", "SNP Viewer",
                    e.getSource().getException());

        }

    });
    writeTask.setOnCancelled(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            progressMessage.setText("Region write cancelled");
            progressTitle.setText("Cancelled");
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            Dialogs.showErrorDialog(null, "Error writing region to file\n", "Region write error", "SNP Viewer");
        }

    });
    cancelButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            writeTask.cancel();

        }
    });
    progressTitle.setText("Writing region to .xlsx file");
    new Thread(writeTask).start();
}

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

/**
  * Calculate and display a record/*w  w  w.jav  a  2s  . com*/
  * @param pRecord record to calculate and display
  */
private void internalCalcAndDisplayRecord(final int pRecord) {
    List<CheckResult> single = new LinkedList<CheckResult>();
    single.add(gResults.get(pRecord));
    //this is a hack - create a list with only one entry for processing
    //third param is true to ignore isProcessing checks as the record
    //should be claimed for us by this point
    Task<Integer> task = new ProcessingLoadTask(single, true, true, false);
    progressIndicator.progressProperty().bind(task.progressProperty());
    imageLeftLabel.setText(gResults.get(pRecord).getFileOne().getName());
    imageRightLabel.setText(gResults.get(pRecord).getFileTwo().getName());
    Thread loader = new Thread(task);
    loader.setDaemon(true);
    loader.start();
}