Example usage for javafx.concurrent WorkerStateEvent getSource

List of usage examples for javafx.concurrent WorkerStateEvent getSource

Introduction

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

Prototype

@Override
public Worker getSource() 

Source Link

Document

The Worker on which the Event initially occurred.

Usage

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

@FXML
void initialize() {
    assert clearLogButton != null : "fx:id=\"clearLogButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert fundsTable != null : "fx:id=\"fundsTable\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert logField != null : "fx:id=\"logField\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert buyButton != null : "fx:id=\"buyButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert sellButton != null : "fx:id=\"sellButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert showActiveOrdersButton != null : "fx:id=\"showActiveOrdersButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTableLastColumn != null : "fx:id=\"tickerTableLastColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTablePairColumn != null : "fx:id=\"tickerTablePairColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTable != null : "fx:id=\"tickersTable\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTableBuyColumn != null : "fx:id=\"tickersTableBuyColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTableFeeColumn != null : "fx:id=\"tickersTableFeeColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTableSellColumn != null : "fx:id=\"tickersTableSellColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tradeAmountValue != null : "fx:id=\"tradeAmountValue\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tradePriceCurrencyType != null : "fx:id=\"tradeCurrencyPriceValue\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tradeCurrencyType != null : "fx:id=\"tradeCurrencyType\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tradePriceValue != null : "fx:id=\"tradePriceValue\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert updateFundsButton != null : "fx:id=\"updateFundsButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert fundsTableCurrencyColumn != null : "fx:id=\"fundsTableCurrencyColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert fundsTableValueColumn != null : "fx:id=\"fundsTableValueColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersTable != null : "fx:id=\"fundsTableValueColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersAmountColumn != null : "fx:id=\"activeOrdersAmountColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersPairColumn != null : "fx:id=\"activeOrdersPairColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersRateColumn != null : "fx:id=\"activeOrdersRateColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersTimeColumn != null : "fx:id=\"activeOrdersTimeColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersTypeColumn != null : "fx:id=\"activeOrdersTypeColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersCancelColumn != null : "fx:id=\"activeOrdersCancelColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";

    //Holder for all main API methods of exchange
    app = new App();

    //Loading configs
    loadExchangeConfig();//  w  w  w  .j  av a 2 s .  c o  m

    //Populate choiceboxes at the trading section
    tradeCurrencyType.setItems(FXCollections.observableArrayList(currencies));
    tradeCurrencyType.setValue(currencies.get(0));
    tradePriceCurrencyType.setItems(FXCollections.observableArrayList(currencies));
    tradePriceCurrencyType.setValue(currencies.get(0));

    //Active Orders table
    activeOrdersAmountColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, Double>("amount"));
    activeOrdersPairColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, String>("pair"));
    activeOrdersRateColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, Double>("rate"));
    activeOrdersTimeColumn.setCellValueFactory(
            new Callback<TableColumn.CellDataFeatures<ActiveOrder, String>, ObservableValue<String>>() {
                @Override
                public ObservableValue<String> call(
                        TableColumn.CellDataFeatures<ActiveOrder, String> activeOrderStringCellDataFeatures) {
                    ActiveOrder activeOrder = activeOrderStringCellDataFeatures.getValue();
                    DateFormat dateFormat = DateFormat.getDateTimeInstance();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(activeOrder.getTimestamp() * 1000);
                    return new SimpleStringProperty(dateFormat.format(calendar.getTime()));
                }
            });
    activeOrdersTypeColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, String>("type"));
    activeOrdersTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

    activeOrdersCancelColumn
            .setCellFactory(new Callback<TableColumn<ActiveOrder, Boolean>, TableCell<ActiveOrder, Boolean>>() {
                @Override
                public TableCell<ActiveOrder, Boolean> call(
                        TableColumn<ActiveOrder, Boolean> activeOrderBooleanTableColumn) {
                    return new ButtonCell<>(activeOrdersTable);
                }
            });
    activeOrdersCancelColumn.setCellValueFactory(
            new Callback<TableColumn.CellDataFeatures<ActiveOrder, Boolean>, ObservableValue<Boolean>>() {
                @Override
                public ObservableValue<Boolean> call(
                        TableColumn.CellDataFeatures<ActiveOrder, Boolean> activeOrderBooleanCellDataFeatures) {
                    return new SimpleBooleanProperty(true);
                }
            });

    //Tickers Table
    MenuItem showOrdersBook = new MenuItem("Show Orders Book");
    MenuItem showPublicTrades = new MenuItem("Show Public Trades");

    ContextMenu contextMenu = new ContextMenu(showOrdersBook, showPublicTrades);

    tickersTable.setItems(tickers);
    tickersTable.setContextMenu(contextMenu);
    tickersTableBuyColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("buy"));
    tickersTableFeeColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("fee"));
    tickersTableSellColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("sell"));
    tickersTableLastColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("last"));
    tickersTablePairColumn.setCellValueFactory(new PropertyValueFactory<Ticker, String>("pair"));
    tickersTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    tickersTable.setRowFactory(new Callback<TableView<Ticker>, TableRow<Ticker>>() {
        @Override
        public TableRow<Ticker> call(TableView<Ticker> tickerTableView) {
            return new TableRow<Ticker>() {
                @Override
                protected void updateItem(Ticker ticker, boolean b) {
                    super.updateItem(ticker, b);
                    if (!b) {
                        if (tickersData.containsKey(ticker.getPair())) {
                            if (ticker.getLast() < tickersData.get(ticker.getPair()).getLast()) {
                                setStyle("-fx-control-inner-background: rgba(186, 0, 0, 0.5);");
                            } else if (ticker.getLast() == tickersData.get(ticker.getPair()).getLast()) {
                                setStyle("-fx-control-inner-background: rgba(215, 193, 44, 0.5);");
                            } else {
                                setStyle("-fx-control-inner-background: rgba(0, 147, 0, 0.5);");
                            }
                        }
                    }
                }
            };
        }
    });

    //Menu item to show Orders Book
    showOrdersBook.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            Ticker selectedTicker = tickersTable.getSelectionModel().getSelectedItem();
            Parent root;
            try {
                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(PATH_TO_ORDERS_BOOK_LAYOUT),
                        resources);
                root = (Parent) fxmlLoader.load();
                OrdersBookController ordersBookController = fxmlLoader.getController();
                ordersBookController.injectPair(selectedTicker.getPair());
                Stage stage = new Stage();
                stage.setTitle("Orders Book for " + selectedTicker.getPair().replace("_", "/").toUpperCase());
                stage.setScene(new Scene(root));
                stage.setResizable(false);
                stage.show();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    //Menu item to show Public Trades
    showPublicTrades.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            Ticker selectedTicker = tickersTable.getSelectionModel().getSelectedItem();
            Parent root;
            try {
                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(PATH_TO_TRADES_LAYOUT),
                        resources);
                root = (Parent) fxmlLoader.load();
                PublicTradesController publicTradesController = fxmlLoader.getController();
                publicTradesController.injectPair(selectedTicker.getPair());
                Stage stage = new Stage();
                stage.setTitle("Public Trades for " + selectedTicker.getPair().replace("_", "/").toUpperCase());
                stage.setScene(new Scene(root));
                stage.setResizable(false);
                stage.show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    //Funds Table
    fundsTableCurrencyColumn.setCellValueFactory(new PropertyValueFactory<Fund, String>("currency"));
    fundsTableValueColumn.setCellValueFactory(new PropertyValueFactory<Fund, Double>("value"));
    fundsTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    fundsTable.setItems(fundsData);

    //Task to load tickers data from server
    final javafx.concurrent.Service loadTickersService = new javafx.concurrent.Service() {
        @Override
        protected Task createTask() {
            Task<JSONObject> loadTickers = new Task<JSONObject>() {
                @Override
                protected JSONObject call() throws Exception {
                    String[] pairsArray = new String[pairs.size()];
                    pairsArray = pairs.toArray(pairsArray);
                    return App.getPairInfo(pairsArray);
                }
            };

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

            loadTickers.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                @Override
                public void handle(WorkerStateEvent workerStateEvent) {
                    JSONObject jsonObject = (JSONObject) workerStateEvent.getSource().getValue();

                    //ugly hack to store old values
                    //dump old values to tickersData
                    //TODO think about better solution
                    if (tickers.size() != 0) {
                        for (Ticker x : tickers) {
                            tickersData.put(x.getPair(), x);
                        }
                    }
                    tickers.clear();
                    for (Iterator iterator = jsonObject.keys(); iterator.hasNext();) {
                        String key = (String) iterator.next();
                        JSONObject data = jsonObject.getJSONObject(key);
                        Ticker ticker = new Ticker();
                        ticker.setPair(key);
                        ticker.setUpdated(data.optLong("updated"));
                        ticker.setAvg(data.optDouble("avg"));
                        ticker.setBuy(data.optDouble("buy"));
                        ticker.setSell(data.optDouble("sell"));
                        ticker.setHigh(data.optDouble("high"));
                        ticker.setLast(data.optDouble("last"));
                        ticker.setLow(data.optDouble("low"));
                        ticker.setVol(data.optDouble("vol"));
                        ticker.setVolCur(data.optDouble("vol_cur"));
                        tickers.add(ticker);
                    }

                }
            });
            return loadTickers;
        }
    };

    //Update tickers every 15 seconds
    //TODO better solution is required
    Timeline timeline = new Timeline(new KeyFrame(Duration.ZERO, new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            loadTickersService.restart();
        }
    }), new KeyFrame(Duration.seconds(15)));
    timeline.setCycleCount(Timeline.INDEFINITE);
    timeline.playFromStart();

}

From source file:caillou.company.clonemanager.gui.handler.AfterPartialHashTaskHandler.java

@Override
public void handle(WorkerStateEvent event) {
    FilterStrategy<String, ApplicationFile> fullHashStrategy = null;
    boolean detectDoublonOperation = false;
    final TaskModel.TASK currentTask = mainModel.getTaskModel().getCurrentTask();
    final LocationsModel locationsModel = mainModel.getLocationsModel();
    switch (currentTask) {
    case DETECT_DOUBLONS:
        if (locationsModel.isDetectsIdentiqueFilesWithinALocation()) {
            fullHashStrategy = new DoublonsFullHashStrategy();
        } else {/* w  w  w.j a v a  2  s  .  c  o  m*/
            fullHashStrategy = new DoublonsPlusGroupFullHashStrategy();
        }
        detectDoublonOperation = true;
        break;
    case DETECT_MISSING:
        fullHashStrategy = new MissingFullHashStrategy();
        break;
    }
    Analyse<String, ApplicationFile> previousAnalyse = (Analyse<String, ApplicationFile>) event.getSource()
            .getValue();
    fullHashTask.setFilterStrategy(fullHashStrategy);
    fullHashTask.setInputData(previousAnalyse);
    fullHashTask.setDoCssStuff(detectDoublonOperation);
    ProgressIndicator fullHashTaskProgress = transitionController.getProgressBarFullHashId();
    fullHashTaskProgress.progressProperty().bind(fullHashTask.progressProperty());
    resultController.valuesProperty().bind(fullHashTask.valueProperty());
    fullHashTask.setOnSucceeded(afterFullHashTaskHandler);
    new Thread(fullHashTask).start();
}

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// w ww.  ja  va2  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 writeRegionToFile(final String chromosome, final double start, final double end) {
    /* get coordinates of selection and report back
     * write SNPs in region to file/*from  w  ww  .j  a  v a 2 s  .c  o  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: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 .j  a v a2  s.  c  o 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 autoFindRegions() {
    if (affObserve.isEmpty()) {
        Dialogs.showErrorDialog(null,//from   ww w.ja  va 2  s .  c o m
                "Find Regions can only be run when there "
                        + "is at least one Affected sample in the project.  Use the "
                        + "'Add Affected' button/menu item to add  Affected samples.",
                "No Affected samples to analyze!", "SnpViewer");
        return;
    }
    Stage stage = new Stage();
    FXMLLoader loader = new FXMLLoader(getClass().getResource("FindRegionsInterface.fxml"));
    try {
        Pane page = (Pane) loader.load();
        FindRegionsInterfaceController findReg = (FindRegionsInterfaceController) loader.getController();
        Scene scene = new Scene(page);
        stage.setScene(scene);
        scene.getStylesheets().add(SnpViewer.class.getResource("SnpViewerStyleSheet.css").toExternalForm());
        setProgressMode(true);
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.getIcons().add(new Image(this.getClass().getResourceAsStream("icon.png")));
        stage.showAndWait();
        if (findReg.getCancelled()) {
            setProgressMode(false);
            return;
        }

        //int w, double r, boolean con, int refWind, double refCut,
        //int minReportSize, int minReportRun, double het, double dischord)
        int window = Integer.parseInt(findReg.getWindow());
        double regionLength = Double.parseDouble(findReg.getRegionLength());
        boolean checkConcordant = findReg.getCheckConcordance();
        int refineWindow = Integer.parseInt(findReg.getRefineSize());
        double refineTolerance = Double.parseDouble(findReg.getRefineTolerance());
        int minReport = Integer.parseInt(findReg.getReportLength());
        int minReportRun = Integer.parseInt(findReg.getReportMinSnps());
        double hetTolerance = Double.parseDouble(findReg.getHetTolerance());
        double dischordTolerance = Double.parseDouble(findReg.getDischordTolerance());
        boolean autosomesOnly = findReg.getAutosomesOnly();
        LinkedHashSet<String> c = new LinkedHashSet();
        for (Object item : chromosomeSelector.getItems()) {
            if (item instanceof String) {
                String chrom = (String) item;
                if (autosomesOnly) {
                    if (chrom.matches("\\d+")) {//only add autosomes
                        c.add(chrom);
                    }
                } else {
                    c.add(chrom);
                }
            }
        }

        final RegionFinder regionFinder = new RegionFinder(c, affFiles, unFiles, window, regionLength,
                checkConcordant, refineWindow, refineTolerance, minReport, minReportRun, hetTolerance,
                dischordTolerance);

        regionFinder.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                progressBar.progressProperty().unbind();
                progressMessage.textProperty().unbind();
                progressMessage.setText("Done");
                progressTitle.textProperty().unbind();
                setProgressMode(false);
                Object result = t.getSource().getValue();
                ArrayList<RegionSummary> foundRegions = new ArrayList<>();
                if (result instanceof ArrayList) {
                    for (Object r : (ArrayList) result) {
                        if (r instanceof RegionSummary) {
                            RegionSummary reg = (RegionSummary) r;
                            foundRegions.add(reg);
                        }
                    }
                    if (foundRegions.size() > 0) {
                        FXMLLoader tableLoader = new FXMLLoader(
                                getClass().getResource("MultiRegionReporter.fxml"));
                        try {
                            Pane tablePane = (Pane) tableLoader.load();
                            MultiRegionReporterController multiReg = (MultiRegionReporterController) tableLoader
                                    .getController();
                            Scene tableScene = new Scene(tablePane);
                            Stage tableStage = new Stage();
                            tableStage.setScene(tableScene);
                            tableScene.getStylesheets().add(
                                    SnpViewer.class.getResource("SnpViewerStyleSheet.css").toExternalForm());
                            multiReg.displayData(foundRegions);
                            tableStage.setTitle("Find Regions Results");
                            tableStage.getIcons()
                                    .add(new Image(this.getClass().getResourceAsStream("icon.png")));
                            tableStage.initModality(Modality.NONE);
                            tableStage.show();
                        } catch (Exception ex) {
                            Dialogs.showErrorDialog(null,
                                    "Error displaying" + " results from Find Regions Method.",
                                    "Find Regions Error!", "SnpViewer", ex);
                        }
                    } else {
                        Dialogs.showInformationDialog(null, "No regions " + "found.", "Find Regions",
                                "SnpViewer");
                    }
                    savedRegions.addAll(foundRegions);
                    RegionSummary sorter = new RegionSummary();
                    sorter.mergeRegionsByPosition(savedRegions);
                }
                saveProject();
                int c = chromosomeSelector.getSelectionModel().getSelectedIndex();
                if (c > -1) {
                    selectionOverlayPane.getChildren().clear();
                    selectionOverlayPane.getChildren().add(dragSelectRectangle);
                    drawSavedRegions((String) chromosomeBoxList[c]);
                }
                progressMessage.setText("");
                progressTitle.setText("");
                progressBar.progressProperty().set(0);
            }
        });
        regionFinder.setOnFailed(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                progressBar.progressProperty().unbind();
                progressMessage.textProperty().unbind();
                progressMessage.setText("Failed!");
                progressTitle.textProperty().unbind();
                Dialogs.showErrorDialog(null, "Find Regions method failed.", "Error!", "SnpViewer",
                        t.getSource().getException());
                setProgressMode(false);
                progressMessage.setText("");
                progressTitle.setText("");
                progressBar.progressProperty().set(0);
            }
        });
        regionFinder.setOnCancelled(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                progressBar.progressProperty().unbind();
                progressMessage.textProperty().unbind();
                progressMessage.setText("Cancelled");
                progressTitle.textProperty().unbind();
                Dialogs.showErrorDialog(null, "Find Regions method Cancelled.", "Cancelled", "SnpViewer");
                setProgressMode(false);
                progressMessage.setText("");
                progressTitle.setText("");
                progressBar.progressProperty().set(0);

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

            }
        });
        progressBar.progressProperty().unbind();
        progressMessage.textProperty().unbind();
        progressTitle.textProperty().unbind();
        progressBar.progressProperty().bind(regionFinder.progressProperty());
        progressMessage.textProperty().bind(regionFinder.messageProperty());
        progressTitle.textProperty().bind(regionFinder.titleProperty());
        regionFinder.start();

    } catch (IOException ex) {
        Dialogs.showErrorDialog(null, "Error starting Find Regions method.", "Error!", "SnpViewer", ex);
        progressBar.progressProperty().unbind();
        progressMessage.textProperty().unbind();
        progressTitle.textProperty().unbind();
        setProgressMode(false);
    }

}

From source file:snpviewer.SnpViewer.java

public void cacheChromsWithIterator(final Iterator chromIter, final SnpFile sfile, final Pane pane,
        final String pngPath, final Iterator sIter, final int currentFile, final int totalFiles,
        final String chrom) {
    final DrawSnpsToPane draw = new DrawSnpsToPane(pane, sfile, chrom, Colors.aa.value, Colors.bb.value,
            Colors.ab.value);/*from   www .  jav  a 2 s. co m*/

    progressBar.progressProperty().unbind();
    //progressBar.progressProperty().bind(draw.progressProperty());
    progressTitle.setText("Processing chr" + chrom);
    progressMessage.setText("File " + sfile.inputFile.getName());
    cancelButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            draw.cancel();

        }
    });

    draw.setOnCancelled(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent t) {
            progressBar.progressProperty().unbind();
            progressBar.setProgress(0);
            progressTitle.setText("Drawing Cancelled");
            progressMessage.textProperty().unbind();
            progressMessage.setText("Drawing Cancelled");
            setProgressMode(false);
            Stage stage = (Stage) chromSplitPane.getScene().getWindow();
            fixStageSize(stage, false);
            // stage.setResizable(true);
        }
    });
    draw.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent t) {
            ArrayList<HashMap<String, Double>> result = (ArrayList<HashMap<String, Double>>) t.getSource()
                    .getValue();
            progressBar.progressProperty().unbind();
            progressBar.setProgress((double) currentFile / ((double) totalFiles * 2));
            progressTitle.setText("");
            progressMessage.textProperty().unbind();
            progressMessage.setText("");
            pane.getChildren().clear();
            /*if (pane.getMinHeight() < 200){
               pane.setMinHeight(200);
            }
            if (pane.getMinWidth() < 800){
               pane.setMinWidth(800);
            }*/
            if (result != null) {
                List<Line> lines = drawLinesToPane(pane, result);
                pane.getChildren().addAll(lines);
                convertSampleViewToImage(sfile, pane, chrom, pngPath);
                lines.clear();
            }
            progressBar.setProgress((double) currentFile / (double) totalFiles);
            if (sIter.hasNext()) {
                cacheChromsWithIterator(chromIter, (SnpFile) sIter.next(), pane, pngPath, sIter,
                        currentFile + 1, totalFiles, chrom);
            } else {
                if (chromIter.hasNext()) {
                    ArrayList<SnpFile> bothFiles = new ArrayList<>(affFiles);
                    bothFiles.addAll(unFiles);
                    Iterator sIterNew = bothFiles.iterator();
                    cacheChromsWithIterator(chromIter, (SnpFile) sIterNew.next(), pane, pngPath, sIterNew,
                            currentFile + 1, totalFiles, (String) chromIter.next());
                } else {
                    progressBar.progressProperty().unbind();
                    progressBar.setProgress(0);
                    setProgressMode(false);
                    redrawCheckBox.setSelected(false);
                    chromosomeSelector.getSelectionModel().selectFirst();
                    refreshView((String) chromosomeSelector.getSelectionModel().getSelectedItem(), false);
                    Stage stage = (Stage) chromSplitPane.getScene().getWindow();
                    fixStageSize(stage, false);
                    stage.setResizable(true);
                }
            }
        }
    });
    draw.setOnFailed(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent t) {
            progressBar.progressProperty().unbind();
            progressBar.setProgress(0);
            progressTitle.setText("ERROR!");
            progressMessage.textProperty().unbind();
            progressMessage.setText("Drawing failed!");
            setProgressMode(false);
            Stage stage = (Stage) chromSplitPane.getScene().getWindow();
            stage.setResizable(true);
            fixStageSize(stage, false);
        }

    });
    draw.start();
}

From source file:snpviewer.SnpViewer.java

public void drawCoordinatesWithIterator(final SnpFile sfile, final Pane pane, final String pngPath,
        final Iterator<SnpFile> sIter, final Iterator<Pane> pIter, final int currentFile, final int totalFiles,
        final String chrom, final Double start, final Double end, final boolean forceRedraw,
        final SplitPane splitPane) {
    Stage stage = (Stage) splitPane.getScene().getWindow();
    fixStageSize(stage, true);/*from w  w w.j a  v  a 2  s.c  om*/

    //stage.setResizable(false);//we have to disable this when using windows due to a bug (in javafx?)
    File pngFile = new File(sfile.getOutputDirectoryName() + "/" + chrom + ".png");
    if (pngPath != null && pngPath.length() > 0) {
        pngFile = new File(sfile.getOutputDirectoryName() + "/" + pngPath + "/" + chrom + ".png");
    }
    if (!forceRedraw && pngFile.exists()) {
        try {
            progressBar.progressProperty().unbind();
            progressBar.setProgress((double) currentFile / (double) totalFiles);
            BufferedImage bufferedImage = ImageIO.read(pngFile);
            Image image = SwingFXUtils.toFXImage(bufferedImage, null);
            ImageView chromImage = new ImageView(image);
            //chromImage.setCache(true);
            pane.getChildren().clear();
            pane.getChildren().add(chromImage);
            //pane.setCache(true);
            chromImage.fitWidthProperty().bind(pane.widthProperty());
            chromImage.fitHeightProperty().bind(pane.heightProperty());
            pane.minHeightProperty().bind(splitPane.heightProperty().divide(totalFiles));
            pane.minWidthProperty().bind(splitPane.widthProperty());

            if (sIter.hasNext()) {
                SnpFile nextFile = sIter.next();
                Pane nextPane = pIter.next();
                drawCoordinatesWithIterator(nextFile, nextPane, pngPath, sIter, pIter, currentFile + 1,
                        totalFiles, chrom, start, end, forceRedraw, splitPane);
            } else {
                progressBar.progressProperty().unbind();
                progressBar.setProgress(0);
                setProgressMode(false);
                fixStageSize(stage, false);//for windows only
                stage.setResizable(true);
            }
        } catch (IOException ex) {
            Dialogs.showErrorDialog(null, "IO error reading cached image", "Error displaying chromosome image",
                    "SnpViewer", ex);
            return;
        }

    } else {

        final DrawSnpsToPane draw = new DrawSnpsToPane(pane, sfile, chrom, Colors.aa.value, Colors.bb.value,
                Colors.ab.value, start, end);

        progressBar.progressProperty().unbind();
        //progressBar.setProgress(0);
        //progressBar.progressProperty().bind(draw.progressProperty());
        progressTitle.setText("Drawing " + currentFile + " of " + totalFiles);
        progressMessage.textProperty().bind(draw.messageProperty());
        cancelButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                draw.cancel();
            }
        });

        draw.setOnCancelled(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {

                progressBar.progressProperty().unbind();
                progressBar.setProgress(0);
                progressTitle.setText("Drawing Cancelled");
                progressMessage.textProperty().unbind();
                progressMessage.setText("Drawing Cancelled");
                setProgressMode(false);
                selectionOverlayPane.getChildren().clear();
                selectionOverlayPane.getChildren().add(dragSelectRectangle);
                Stage stage = (Stage) splitPane.getScene().getWindow();
                stage.setResizable(true);
                fixStageSize(stage, false);//for windows only
            }
        });
        draw.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                ArrayList<HashMap<String, Double>> result = (ArrayList<HashMap<String, Double>>) t.getSource()
                        .getValue();
                progressBar.progressProperty().unbind();
                progressBar.setProgress((double) currentFile / (2 * (double) totalFiles));
                progressTitle.setText("");
                progressMessage.textProperty().unbind();
                progressMessage.setText("");
                /*if (pane.getMinHeight() < 200){
                pane.setMinHeight(200);
                }
                if (pane.getMinWidth() < 800){
                    pane.setMinWidth(800);
                }*/
                if (result != null) {
                    List<Line> lines = drawLinesToPane(pane, result);
                    pane.getChildren().addAll(lines);
                    pane.setVisible(true);
                    convertSampleViewToImage(sfile, pane, chrom, pngPath);
                    /*for (Line l: lines){
                        l.startXProperty().unbind();
                        l.startYProperty().unbind();
                        l.endXProperty().unbind();
                        l.endYProperty().unbind();
                    }*/
                    lines.clear();
                }
                progressBar.setProgress((double) currentFile / (double) totalFiles);
                pane.minWidthProperty().bind(splitPane.widthProperty());
                pane.minHeightProperty().bind(splitPane.heightProperty().divide(totalFiles));
                // pane.setCache(true);
                if (sIter.hasNext()) {
                    SnpFile nextFile = sIter.next();
                    Pane nextPane = pIter.next();
                    drawCoordinatesWithIterator(nextFile, nextPane, pngPath, sIter, pIter, currentFile + 1,
                            totalFiles, chrom, start, end, forceRedraw, splitPane);
                } else {
                    setProgressMode(false);
                    progressBar.progressProperty().unbind();
                    progressBar.setProgress(0);

                    Stage stage = (Stage) splitPane.getScene().getWindow();
                    stage.setResizable(true);
                    fixStageSize(stage, false);//for windows only
                }
            }
        });
        draw.setOnFailed(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                draw.reset();
                progressBar.progressProperty().unbind();
                progressBar.setProgress(0);
                progressTitle.setText("ERROR!");
                progressMessage.textProperty().unbind();
                progressMessage.setText("Drawing failed!");
                setProgressMode(false);
                selectionOverlayPane.getChildren().clear();
                selectionOverlayPane.getChildren().add(dragSelectRectangle);
                //     Stage stage = (Stage) chromSplitPane.getScene().getWindow();
                //     stage.setResizable(true);
            }

        });
        draw.start();
    }
}

From source file:snpviewer.SnpViewer.java

private void addInputFilesWithIterator(final boolean isAffected, final File input, final Iterator it,
        final int fileCounter, final int totalFiles) {
    try {/*from   w  w w.  j  a  va 2 s.co  m*/
        String subDir = input.getName().replaceFirst("[.][^.]+$", "");
        File outputDirectory = new File(snpViewSaveDirectory + "/" + subDir);
        try {
            outputDirectory.mkdir();
        } catch (Exception ex) {
            ex.printStackTrace();
            setProgressMode(false);
            return;
        }
        final SnpFile snpFile = new SnpFile(input, outputDirectory);
        progressBar.progressProperty().unbind();
        progressBar.setProgress(0);
        progressBar.progressProperty().bind(snpFile.progressProperty());
        progressTitle.setText("Processing " + fileCounter + " of " + totalFiles);
        progressMessage.textProperty().bind(snpFile.messageProperty());
        cancelButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                snpFile.cancel();
                progressBar.progressProperty().unbind();
                progressBar.setProgress(0);
                progressTitle.setText("Cancelled");
                progressMessage.textProperty().unbind();
                progressMessage.setText("Cancelled");
                setProgressMode(false);

            }
        });
        snpFile.start();
        snpFile.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                if (snpFile.buildVersion == null) {//need to manually identify snp build for autoSNPa files
                    BuildInferrer buildInferrer = new BuildInferrer();
                    String build = buildInferrer.inferBuild(snpFile);
                    if (build == null) {
                        Dialogs.showErrorDialog(null, "Failed to process file " + input.getName()
                                + ".  Could not determine " + "genome build. Only hg19 and hg18 builds "
                                + "are supported and in the absence of a "
                                + "header containing build information only "
                                + "Affymetrix Genome-Wide Human SNP Array 5.0" + " or 6.0 chips are supported.",
                                "Failure while adding input file.", "SnpViewer");
                        setProgressMode(false);
                        saveProject();
                        return;
                    } else {
                        snpFile.setBuildVersion(build);
                    }
                }
                progressBar.progressProperty().unbind();
                progressBar.setProgress(0);
                progressTitle.setText("");
                progressMessage.textProperty().unbind();
                progressMessage.setText("");
                if (genomeVersion.equals("")) {
                    genomeVersion = snpFile.getBuildVersion();
                    buildLabel.setText(genomeVersion);
                } else {
                    if (!snpFile.getBuildVersion().equalsIgnoreCase(genomeVersion)) {
                        progressTitle.setText("");
                        progressMessage.setText("");
                        Dialogs.showErrorDialog(null,
                                "Genome versions do " + "not match between input files. Error while"
                                        + " adding input file " + input.getName(),
                                "Genome Version Error", "SnpViewer");
                        setProgressMode(false);
                        saveProject();
                        return;
                    }
                }
                if (isAffected) {
                    affObserve.add(snpFile);
                } else {
                    unObserve.add(snpFile);
                }

                if (it.hasNext()) {
                    addInputFilesWithIterator(isAffected, (File) it.next(), it, fileCounter + 1, totalFiles);
                } else {
                    setProgressMode(false);
                    saveProject();
                    refreshView(null, redrawCheckBox.isSelected());
                }
            }
        });
        final String fileNameForFailure = input.getName();
        snpFile.setOnFailed(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                progressBar.progressProperty().unbind();
                progressBar.setProgress(0);
                progressTitle.setText("");
                progressMessage.textProperty().unbind();
                // progressMessage.setText("");
                Dialogs.showErrorDialog(null, "Failed to process file " + fileNameForFailure,
                        "Failure while adding input file.", "SnpViewer", t.getSource().getException());
                setProgressMode(false);
                saveProject();
            }

        });
        snpFile.setOnCancelled(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                progressBar.progressProperty().unbind();
                progressBar.setProgress(0);
                progressTitle.setText("ERROR!");
                progressMessage.textProperty().unbind();
                progressMessage.setText("Processing of " + fileNameForFailure + " failed!");
                setProgressMode(false);
                saveProject();
            }

        });

    } catch (Exception ex) {
        ex.printStackTrace();
        //display error here
    }
}