Example usage for javafx.application Platform runLater

List of usage examples for javafx.application Platform runLater

Introduction

In this page you can find the example usage for javafx.application Platform runLater.

Prototype

public static void runLater(Runnable runnable) 

Source Link

Document

Run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future.

Usage

From source file:org.mskcc.shenkers.view.IntervalViewNGTest.java

public void testStackedIntervalView() throws InterruptedException {
    StackedIntervalView p = new StackedIntervalView(0, 6);
    p.setData(Arrays.asList(new Pair(0, 1), new Pair(1, 2), new Pair(2, 3), new Pair(3, 4), new Pair(4, 5),
            new Pair(5, 6)
    //, {8, 10}, {1, 2}, {3, 7},
    //            {9, 10}, {1, 2}, {3, 5}, {6, 7}, {8, 10}, {2, 5}, {8, 10}
    ));/*from  w  w w. j a  va2s. c o  m*/

    ScrollPane sp = new ScrollPane(p);
    ScrollBar sb = new ScrollBar();
    sb.maxProperty().bind(sp.vmaxProperty());
    sb.minProperty().bind(sp.vminProperty());
    sb.visibleAmountProperty().bind(sp.heightProperty().divide(p.prefHeightProperty()));
    sb.setOrientation(Orientation.VERTICAL);
    sp.vvalueProperty().bindBidirectional(sb.valueProperty());
    HiddenSidesPane hsp = new HiddenSidesPane();
    hsp.setContent(sp);
    hsp.setRight(sb);
    sp.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    sp.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    p.setOrientation(Orientation.VERTICAL);
    p.prefTileHeightProperty().bind(new SimpleDoubleProperty(40));
    //        p.minHeightProperty().bind(new SimpleDoubleProperty(20).multiply(Bindings.size(p.getChildren())));
    p.prefTileWidthProperty().bind(sp.widthProperty());
    p.prefHeightProperty()
            .bind(new SimpleDoubleProperty(50).multiply(Bindings.size(p.getChildren())).subtract(10));
    p.prefWidthProperty().bind(sp.widthProperty());
    sp.setPadding(Insets.EMPTY);
    p.setVgap(10);

    CountDownLatch l = new CountDownLatch(1);
    Platform.runLater(() -> {

        Stage stage = new Stage();
        stage.setOnHidden(e -> {
            l.countDown();
        });
        Scene scene = new Scene(hsp, 300, 300, Color.GRAY);
        stage.setTitle("StackedPaneTest");
        stage.setScene(scene);
        stage.show();

    });
    l.await();
}

From source file:org.sleuthkit.autopsy.imagegallery.ImageGalleryController.java

private ImageGalleryController() {

    listeningEnabled.addListener((observable, oldValue, newValue) -> {
        //if we just turned on listening and a case is open and that case is not up to date
        if (newValue && !oldValue && Case.existsCurrentCase()
                && ImageGalleryModule.isDrawableDBStale(Case.getCurrentCase())) {
            //populate the db
            queueDBWorkerTask(new CopyAnalyzedFiles());
        }// www .j a v a 2s.c  o m
    });

    groupManager.getAnalyzedGroups().addListener((Observable o) -> {
        if (Case.isCaseOpen()) {
            checkForGroups();
        }
    });

    groupManager.getUnSeenGroups().addListener((Observable observable) -> {
        //if there are unseen groups and none being viewed
        if (groupManager.getUnSeenGroups().isEmpty() == false
                && (getViewState() == null || getViewState().getGroup() == null)) {
            advance(GroupViewState.tile(groupManager.getUnSeenGroups().get(0)));
        }
    });

    viewState().addListener((Observable observable) -> {
        selectionModel.clearSelection();
    });

    regroupDisabled.addListener((Observable observable) -> {
        checkForGroups();
    });

    IngestManager.getInstance().addIngestModuleEventListener((PropertyChangeEvent evt) -> {
        Platform.runLater(this::updateRegroupDisabled);
    });
    IngestManager.getInstance().addIngestJobEventListener((PropertyChangeEvent evt) -> {
        Platform.runLater(this::updateRegroupDisabled);
    });
    //        metaDataCollapsed.bind(Toolbar.getDefault().showMetaDataProperty());
}

From source file:ijfx.ui.plugin.overlay.OverlayPanel.java

@EventHandler
public void handleEvent(OverlaySelectedEvent event) {

    if (event.getOverlay() == null) {
        return;//from w  w w.  ja va2 s  . c o  m
    }

    overlayProperty.setValue(event.getOverlay());
    Platform.runLater(() -> updateChart(event.getOverlay()));
    updateTable();

}

From source file:org.sleuthkit.autopsy.timeline.ui.AbstractTimelineChart.java

/**
 * Constructor/*  ww  w.j  av a  2s  .  com*/
 *
 * @param controller The TimelineController for this view.
 */
protected AbstractTimelineChart(TimeLineController controller) {
    super(controller);
    Platform.runLater(() -> {
        VBox vBox = new VBox(getSpecificLabelPane(), getContextLabelPane());
        vBox.setFillWidth(false);
        HBox hBox = new HBox(getSpacer(), vBox);
        hBox.setFillHeight(false);
        setBottom(hBox);
        DoubleBinding spacerSize = getYAxis().widthProperty().add(getYAxis().tickLengthProperty())
                .add(getAxisMargin());
        getSpacer().minWidthProperty().bind(spacerSize);
        getSpacer().prefWidthProperty().bind(spacerSize);
        getSpacer().maxWidthProperty().bind(spacerSize);
    });

    createSeries();

    selectedNodes.addListener((ListChangeListener.Change<? extends NodeType> change) -> {
        while (change.next()) {
            change.getRemoved().forEach(node -> applySelectionEffect(node, false));
            change.getAddedSubList().forEach(node -> applySelectionEffect(node, true));
        }
    });

    //show tooltip text in status bar
    hoverProperty().addListener(
            hoverProp -> controller.setStatusMessage(isHover() ? getDefaultTooltip().getText() : ""));

}

From source file:account.management.controller.ReportLedgerController.java

@FXML
private void onLedgerIdInsert(KeyEvent event) {
    Platform.runLater(() -> {
        ObservableList<Account> account_list = this.account.getItems();
        Pattern p = Pattern.compile("(?:[A-Za-z 0]+)?([0-9]+).*");
        Matcher m = p.matcher(this.ledger_id.getText());
        if (m.find()) {
            System.out.println("2: " + m.group(1));
            int len = account_list.size();
            for (int i = 0; i < len; i++) {
                if (account_list.get(i).getId() == Integer.parseInt(m.group(1))) {
                    this.account.getSelectionModel().select(i);
                    break;
                }/*from   www. jav  a  2  s .co  m*/
            }
        }

    });

}

From source file:com.core.meka.SOMController.java

private void train() {
    if (neuronas_text.getText().isEmpty()) {
        String result = "Debe ingresar una cantidad de neuronas";
        result += "\nPor ejemplo: cantidad = 4, entonces la red contendra 4 neuronas en total";
        result_text.setText(result);//  w  w w.jav  a  2s .  co m
        return;
    }
    if (epocas_text.getText().isEmpty()) {
        String result = "Debe ingresar una cantidad de epocas";
        result += "\nPor ejemplo: epocas = 5, entonces la red se estabilizara luego de 5 ciclos de entrenamiento";
        result_text.setText(result);
        return;
    }
    if (entradas_text.getText().isEmpty()) {
        String result = "Debe ingresar una cantidad de entradas para el entrenamiento";
        result += "\nPor ejemplo: entradas = 3, entonces [4,2,5] es un patron valido de entrenamiento";
        result_text.setText(result);
        return;
    }
    if (patrones_train_text.getText().isEmpty()) {
        String result = "Debe ingresar algun patron de entrenamiento";
        result += "\nPor ejemplo: patrones = [1,2,4],[6,1,3], entonces la red tendra 2 patrones de entrenamiento validos";
        result_text.setText(result);
        return;
    }
    if (funcion_vecindad_combo.getSelectionModel().getSelectedIndex() < 0) {
        String result = "Debe elegir si desea utilizar una funcion de vecindad";
        result_text.setText(result);
        return;
    }
    //Valores correctos
    Integer dimension = Integer.valueOf(entradas_text.getText());
    boolean formatoPatronesEntrenamiento = SOMManager.validarDimensionArreglo(dimension,
            patrones_train_text.getText());
    if (!formatoPatronesEntrenamiento) {
        String result = "Los patrones ingresados no tienen una dimension correcta";
        result += "\nPor ejemplo: 1.3,2.6 ; 5.6,22,55,66 (2 patrones) es incorrecto Dimension(p1) = 2 y Dimension(p2) = 4";
        result_text.setText(result);
        return;
    }

    if (!pesos_check.isSelected()) {
        boolean formatoPesos = SOMManager.validarDimensionArreglo(dimension, pesos_text.getText());
        if (!formatoPesos) {
            String result = "Los pesos ingresados no tienen una dimension correcta";
            result += "\nPor ejemplo: 1.8,3.6 ; 7.6,12,5,1 (2 patrones) es incorrecto Dimension(p1) = 2 y Dimension(p2) = 4";
            result_text.setText(result);
            return;
        }
    }

    //Correcto, realizar operaciones solicitadas
    Integer epocas = Integer.valueOf(epocas_text.getText());
    Boolean pesosAleatorios = pesos_check.isSelected();
    Boolean utilizarFuncionVecindad = funcion_vecindad_combo.getSelectionModel().getSelectedIndex() == 0;
    Integer clusters = Integer.valueOf(neuronas_text.getText());
    try {
        double[][] patrones = crearArreglo(
                patrones_train_text.getText().replaceAll("\\s+", "").replaceAll("\\n+", "").split(";"),
                result_text);

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                crearCluster(dimension, epocas, pesosAleatorios, utilizarFuncionVecindad, clusters, patrones,
                        (pesosAleatorios ? null
                                : crearArreglo(pesos_text.getText().replaceAll("\\s+", "")
                                        .replaceAll("\\n+", "").split(";"), result_text)));
                test_tab.setDisable(false);
                mostrarNeuronasTest(som, neuronas_test_text);
            }

            private void mostrarNeuronasTest(SOMCluster som, TextArea neuronas_test_text) {
                double[][] W = som.getW();
                String neuronas = Matrix.getMatrix(W);
                neuronas_test_text.setText(neuronas);
            }
        });

    } catch (NumberFormatException e) {
        //                    result_text.setText("Imposible formatear ese numero, verifiquelo\n" + e.getMessage().replaceAll("\\)", ")\n") + 
        //                            "\n\n" + result_text.getText());
    }
}

From source file:org.sleuthkit.autopsy.imagegallery.datamodel.grouping.GroupManager.java

synchronized public void clear() {

    if (groupByTask != null) {
        groupByTask.cancel(true);/*from  www . j  av  a  2s  . c  om*/
    }
    sortBy = GroupSortBy.GROUP_BY_VALUE;
    groupBy = DrawableAttribute.PATH;
    sortOrder = SortOrder.ASCENDING;
    Platform.runLater(() -> {
        unSeenGroups.forEach(controller.getCategoryManager()::unregisterListener);
        unSeenGroups.clear();
        analyzedGroups.forEach(controller.getCategoryManager()::unregisterListener);
        analyzedGroups.clear();

    });
    synchronized (groupMap) {
        groupMap.values().forEach(controller.getCategoryManager()::unregisterListener);
        groupMap.clear();
    }
    db = null;
}

From source file:cz.lbenda.dataman.db.DbStructureFactory.java

public void generateStructure() {
    try (Connection conn = connectionProvider.getConnection()) {
        Map<String, CatalogDesc> catalogs = new HashMap<>();

        DatabaseMetaData dmd = conn.getMetaData();
        SQLDialect dialect = dbConfig.getDialect();
        StatusHelper.getInstance().progressStart(this, TASK_NAME, progressStepCount);
        try (ResultSet tabs = dmd.getTables(null, null, null, null)) {
            tabs.last();//from ww w  .j av a2s  .  c o  m
            StatusHelper.getInstance().progressNextStep(this, STEP_READ_TABLES, tabs.getRow());
        } catch (SQLException e) {
            StatusHelper.getInstance().progressNextStep(this, STEP_READ_TABLES, 200);
        }
        try (ResultSet tabs = dmd.getTables(null, null, null, null)) {
            while (tabs.next()) {
                StatusHelper.getInstance().progress(this);
                String catalogName = tabs.getString(dialect.tableCatalog());
                String schemaName = tabs.getString(dialect.tableSchema());
                String tableName = tabs.getString(dialect.tableName());
                CatalogDesc catalogDesc = catalogs.get(catalogName);
                if (catalogDesc == null) {
                    catalogDesc = new CatalogDesc(catalogName);
                    catalogs.put(catalogDesc.getName(), catalogDesc);
                }
                SchemaDesc schema = catalogDesc.getSchema(schemaName);
                if (schema == null) {
                    schema = new SchemaDesc(catalogDesc, schemaName);
                    catalogDesc.getSchemas().add(schema);
                }
                TableDesc tableDesc = schema.getTable(tableName);
                if (tableDesc == null) {
                    tableDesc = new TableDesc(schema, tabs.getString(dialect.tableType()), tableName);
                    tableDesc.setDbConfig(dbConfig);
                    schema.getTables().add(tableDesc);
                }
                tableDesc.setSavableRegister(connectionProvider.getSavableRegistry());
                tableDesc.setComment(dialect.tableRemarks());
            }
            generateStructureColumns(catalogs, dmd);
            generatePKColumns(catalogs.values(), dmd);
            generateStructureForeignKeys(catalogs, dmd);
            dbConfig.getCatalogs().clear();
            if (Platform.isAccessibilityActive()) {
                Platform.runLater(() -> dbConfig.getCatalogs().addAll(catalogs.values()));
            } else {
                dbConfig.getCatalogs().addAll(catalogs.values());
            }
            StatusHelper.getInstance().progressFinish(this, STEP_FINISH);
        }
    } catch (Exception e) {
        LOG.error("Problem with read database structure", e);
        throw new RuntimeException(e);
    }
}

From source file:bear.fx.DownloadFxApp.java

public void createScene(Stage stage) {
    try {// ww  w.  ja v a2  s . c  o m
        stage.setTitle("Downloading JDK " + version + "...");

        instance.set(this);
        appStartedLatch.countDown();

        final SimpleBrowser browser = SimpleBrowser.newBuilder().useFirebug(false).useJQuery(true)
                .createWebView(!miniMode).build();

        final ProgressBar progressBar = new ProgressBar(0);
        final Label progressLabel = new Label("Retrieving a link...");

        VBox vBox = VBoxBuilder.create().children(progressLabel, progressBar, browser).fillWidth(true).build();

        Scene scene = new Scene(vBox);

        stage.setScene(scene);

        if (miniMode) {
            stage.setWidth(300);
        } else {
            stage.setWidth(1024);
            stage.setHeight(768);
        }

        stage.show();

        VBox.setVgrow(browser, Priority.ALWAYS);

        /**
         *
         location changed to: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html?
         location changed to: http://download.oracle.com/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: https://edelivery.oracle.com/akam/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: https://login.oracle.com/pls/orasso/orasso.wwsso_app_admin.ls_login?Site2pstoreToken=v1.2~CA55CD32~750C6EFBC9B3CB198B2ADFE87BDD4DEB60E0218858C8BFE85DCCC65865D0E810E845839B422974847E1D489D3AF25FDC9574400197F9190C389876C1EC683A6006A06F7F05D41C94455B8354559F5699F5D0EF102F26FE905E77D40487455F7829501E3A783E1354EB0B8F05B828D0FC3BA22C62D3576883850E0B99849309B0C26F286E5650F63E9C6A7C376165C9A3EED86BF2FA0FAEE3D1F7F2957F5FBD5035AF0A3522E534141FE38DFDD55C4F7F517F9E81336C993BB76512C0D30A5B5C5FD82ED1C10E9D27284B6B1633E4B7B9FA5C2E38D9C5E3845C18C009E294E881FD8B654B67050958E57F0DC20885D6FA87A59FAA7564F94F
         location changed to: https://login.oracle.com/mysso/signon.jsp
         location changed to: https://login.oracle.com/oam/server/sso/auth_cred_submit
         location changed to: https://edelivery.oracle.com/osso_login_success?urlc=v1.2%7E30E69346FE17F27D4F83121B0B8EC362E0B315901364AAA7D6F0B7A05CD8AA31802F5A69D70C708F34C64B65D233922B57D3C31839E82CE78E5C8DA55D729DD339893285D21A8E8B1AE8557C9240D6E33C9965956E136F4CB093779F97AF67C3DB8FF19FF2A638296BD0AA81A7801904AC5607F0568B6CEAF7ED9FCE4B7BEA80071617E4B2779F60F0C76A89F7D195965D2F003F9EDD2A1ADFD264C1C4C7F921010B08D3846CEC9524237A9337B6B0BC433BB17993A670B6C913EB4CFDC217A753F9E2943DE0CBDC41D4705AC67C2B96A4892C65F5450B146939B0EBFDF098680BBBE1F13356460C95A23D8D198D1C6762E45E62F120E32C2549E6263071DA84F8321370D2410CCA93E9A071A02ED6EB40BF40EDFC6F65AC7BA73CDB06DF4265455419D9185A6256FFE41A7FF54042374D09F5C720F3104B2EAC924778482D4BE855A45B2636CE91C7D947FF1F764674CE0E42FFCCFE411AABFE07EA0E96838AFEA263D2D5A405BD
         location changed to: https://edelivery.oracle.com/akam/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: http://download.oracle.com/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz?AuthParam=1390405890_f9186a44471784229268632878dd89e4
                
         */

        browser.getEngine().locationProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observableValue, String oldLoc,
                    final String uri) {
                logger.info("change: {}", uri);

                if (uri.contains("signon.jsp")) {
                    browser.getEngine().executeScript(
                            "" + "alert(document);\n" + "alert(document.getElementById('sso_username'));\n");

                    new Thread("signon.jsp waiter") {
                        @Override
                        public void run() {
                            setStatus("waiting for the login form...");

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                throw Exceptions.runtime(e);
                            }

                            browser.waitFor("$('#sso_username').length > 0", 10000);

                            System.out.println("I see it all, I see it now!");

                            Platform.runLater(new Runnable() {
                                @Override
                                public void run() {
                                    browser.getEngine().executeScript(""
                                            + "alert(document.getElementById('sso_username'));\n"
                                            + "alert($('#sso_username').val('" + oracleUser + "'));\n"
                                            + "alert($('#ssopassword').val('" + oraclePassword + "'));\n"
                                            + downloadJDKJs() + "\n" + "clickIt($('.sf-btnarea a'))");
                                }
                            });
                        }
                    }.start();
                }

                if (uri.contains("download.oracle") && uri.contains("?")) {
                    //will be here after
                    // clicking accept license and link -> * not logged in * -> here -> download -> redirect to login
                    // download -> fill form -> * logged in * -> here -> download
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                DefaultHttpClient httpClient = new DefaultHttpClient();

                                HttpGet httppost = new HttpGet(uri);

                                HttpResponse response = httpClient.execute(httppost);

                                int code = response.getStatusLine().getStatusCode();

                                if (code != 200) {
                                    System.out.println(IOUtils.toString(response.getEntity().getContent()));
                                    throw new RuntimeException("failed to download: " + uri);
                                }

                                final File file = new File(tempDestDir,
                                        StringUtils.substringBefore(FilenameUtils.getName(uri), "?"));
                                HttpEntity entity = response.getEntity();

                                final long length = entity.getContentLength();

                                final CountingOutputStream os = new CountingOutputStream(
                                        new FileOutputStream(file));

                                System.out.printf("Downloading %s to %s...%n", uri, file);

                                Thread progressThread = new Thread(new Runnable() {
                                    double lastProgress;

                                    @Override
                                    public void run() {
                                        while (!Thread.currentThread().isInterrupted()) {
                                            long copied = os.getCount();

                                            double progress = copied * 100D / length;

                                            if (progress != lastProgress) {
                                                final String s = String.format("%s: %s/%s %s%%", file.getName(),
                                                        FileUtils.humanReadableByteCount(copied, false, false),
                                                        FileUtils.humanReadableByteCount(length, false, true),
                                                        LangUtils.toConciseString(progress, 1));

                                                setStatus(s);

                                                System.out.print("\r" + s);
                                            }

                                            lastProgress = progress;
                                            progressBar.setProgress(copied * 1D / length);

                                            //                                                progressProp.set(progress);

                                            try {
                                                Thread.sleep(500);
                                            } catch (InterruptedException e) {
                                                break;
                                            }
                                        }
                                    }
                                }, "progressThread");

                                progressThread.start();

                                ByteStreams.copy(entity.getContent(), os);

                                progressThread.interrupt();

                                System.out.println("Download complete.");

                                downloadResult.set(new DownloadResult(file, "", true));
                                downloadLatch.countDown();
                            } catch (Exception e) {
                                LoggerFactory.getLogger("log").warn("", e);
                                downloadResult.set(new DownloadResult(null, e.getMessage(), false));
                                throw Exceptions.runtime(e);
                            }
                        }
                    }, "fx-downloader");

                    thread.start();
                }
            }

            public void setStatus(final String s) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        progressLabel.setText(s);
                    }
                });
            }
        });

        // links from http://www.oracle.com/technetwork/java/archive-139210.html

        Map<Integer, String> archiveLinksMap = new HashMap<Integer, String>();

        archiveLinksMap.put(5,
                "http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase5-419410.html");
        archiveLinksMap.put(6,
                "http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase6-419409.html");
        archiveLinksMap.put(7,
                "http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html");

        Map<Integer, String> latestLinksMap = new HashMap<Integer, String>();

        latestLinksMap.put(7,
                "http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html");

        String archiveUrl = null;
        String latestUrl = null;

        char ch = version.charAt(0);

        switch (ch) {
        case '7':
        case '6':
        case '5':
            latestUrl = latestLinksMap.get(ch - '0');
            archiveUrl = archiveLinksMap.get(ch - '0');
            break;
        default:
            archiveUrl = null;
        }

        if (latestUrl != null) {
            final String finalArchiveUrl = archiveUrl;
            tryFind(browser, latestUrl, new WhenDone() {
                @Override
                public void whenDone(boolean found) {
                    tryArchiveLink(found, finalArchiveUrl, browser);
                }
            });
        } else {
            tryArchiveLink(false, archiveUrl, browser);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fx.DownloadFxApp.java

public void createScene(Stage stage) {
    try {//from  ww w . j  av a 2 s .  c  o  m
        stage.setTitle("Downloading JDK " + version + "...");

        instance.set(this);
        appStartedLatch.countDown();

        final SimpleBrowser browser = SimpleBrowser.newBuilder().useFirebug(false).useJQuery(true)
                .createWebView(!miniMode).build();

        final ProgressBar progressBar = new ProgressBar(0);
        final Label progressLabel = new Label("Retrieving a link...");

        VBox vBox = VBoxBuilder.create().children(progressLabel, progressBar, browser).fillWidth(true).build();

        Scene scene = new Scene(vBox);

        stage.setScene(scene);

        if (miniMode) {
            stage.setWidth(300);
        } else {
            stage.setWidth(1024);
            stage.setHeight(768);
        }

        stage.show();

        VBox.setVgrow(browser, Priority.ALWAYS);

        /**
         The sequence of calls
         location changed to: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html?
         location changed to: http://download.oracle.com/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: https://edelivery.oracle.com/akam/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: https://login.oracle.com/pls/orasso/orasso.wwsso_app_admin.ls_login?Site2pstoreToken=v1.2~CA55CD32~750C6EFBC9B3CB198B2ADFE87BDD4DEB60E0218858C8BFE85DCCC65865D0E810E845839B422974847E1D489D3AF25FDC9574400197F9190C389876C1EC683A6006A06F7F05D41C94455B8354559F5699F5D0EF102F26FE905E77D40487455F7829501E3A783E1354EB0B8F05B828D0FC3BA22C62D3576883850E0B99849309B0C26F286E5650F63E9C6A7C376165C9A3EED86BF2FA0FAEE3D1F7F2957F5FBD5035AF0A3522E534141FE38DFDD55C4F7F517F9E81336C993BB76512C0D30A5B5C5FD82ED1C10E9D27284B6B1633E4B7B9FA5C2E38D9C5E3845C18C009E294E881FD8B654B67050958E57F0DC20885D6FA87A59FAA7564F94F
         location changed to: https://login.oracle.com/mysso/signon.jsp
         location changed to: https://login.oracle.com/oam/server/sso/auth_cred_submit
         location changed to: https://edelivery.oracle.com/osso_login_success?urlc=v1.2%7E30E69346FE17F27D4F83121B0B8EC362E0B315901364AAA7D6F0B7A05CD8AA31802F5A69D70C708F34C64B65D233922B57D3C31839E82CE78E5C8DA55D729DD339893285D21A8E8B1AE8557C9240D6E33C9965956E136F4CB093779F97AF67C3DB8FF19FF2A638296BD0AA81A7801904AC5607F0568B6CEAF7ED9FCE4B7BEA80071617E4B2779F60F0C76A89F7D195965D2F003F9EDD2A1ADFD264C1C4C7F921010B08D3846CEC9524237A9337B6B0BC433BB17993A670B6C913EB4CFDC217A753F9E2943DE0CBDC41D4705AC67C2B96A4892C65F5450B146939B0EBFDF098680BBBE1F13356460C95A23D8D198D1C6762E45E62F120E32C2549E6263071DA84F8321370D2410CCA93E9A071A02ED6EB40BF40EDFC6F65AC7BA73CDB06DF4265455419D9185A6256FFE41A7FF54042374D09F5C720F3104B2EAC924778482D4BE855A45B2636CE91C7D947FF1F764674CE0E42FFCCFE411AABFE07EA0E96838AFEA263D2D5A405BD
         location changed to: https://edelivery.oracle.com/akam/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: http://download.oracle.com/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz?AuthParam=1390405890_f9186a44471784229268632878dd89e4
                
         */

        browser.getEngine().locationProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observableValue, String oldLoc,
                    final String uri) {
                logger.info("change: {}", uri);

                if (uri.contains("signon.jsp")) {
                    browser.getEngine().executeScript(
                            "" + "alert(document);\n" + "alert(document.getElementById('sso_username'));\n");

                    new Thread("signon.jsp waiter") {
                        @Override
                        public void run() {
                            setStatus("waiting for the login form...");

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                throw Exceptions.runtime(e);
                            }

                            browser.waitFor("$('#sso_username').length > 0", 10000);

                            System.out.println("I see it all, I see it now!");

                            Platform.runLater(new Runnable() {
                                @Override
                                public void run() {
                                    browser.getEngine().executeScript(""
                                            + "alert(document.getElementById('sso_username'));\n"
                                            + "alert($('#sso_username').val('" + oracleUser + "'));\n"
                                            + "alert($('#ssopassword').val('" + oraclePassword + "'));\n"
                                            + downloadJDKJs() + "\n" + "clickIt($('.sf-btnarea a'))");
                                }
                            });
                        }
                    }.start();
                }

                if (uri.contains("download.oracle") && uri.contains("?")) {
                    // will be here after
                    // clicking accept license and link -> * not logged in * -> here -> download -> redirect to login
                    // download -> fill form -> * logged in * -> here -> download
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                DefaultHttpClient httpClient = new DefaultHttpClient();

                                HttpGet httppost = new HttpGet(uri);

                                HttpResponse response = httpClient.execute(httppost);

                                int code = response.getStatusLine().getStatusCode();

                                if (code != 200) {
                                    System.out.println(IOUtils.toString(response.getEntity().getContent()));
                                    throw new RuntimeException("failed to download: " + uri);
                                }

                                final File file = new File(tempDestDir,
                                        StringUtils.substringBefore(FilenameUtils.getName(uri), "?"));
                                HttpEntity entity = response.getEntity();

                                final long length = entity.getContentLength();

                                final CountingOutputStream os = new CountingOutputStream(
                                        new FileOutputStream(file));

                                System.out.printf("Downloading %s to %s...%n", uri, file);

                                Thread progressThread = new Thread(new Runnable() {
                                    double lastProgress;

                                    @Override
                                    public void run() {
                                        while (!Thread.currentThread().isInterrupted()) {
                                            long copied = os.getCount();

                                            double progress = copied * 100D / length;

                                            if (progress != lastProgress) {
                                                final String s = String.format("%s: %s/%s %s%%", file.getName(),
                                                        FileUtils.humanReadableByteCount(copied, false, false),
                                                        FileUtils.humanReadableByteCount(length, false, true),
                                                        LangUtils.toConciseString(progress, 1));

                                                setStatus(s);

                                                System.out.print("\r" + s);
                                            }

                                            lastProgress = progress;
                                            progressBar.setProgress(copied * 1D / length);

                                            //                                                progressProp.set(progress);

                                            try {
                                                Thread.sleep(500);
                                            } catch (InterruptedException e) {
                                                break;
                                            }
                                        }
                                    }
                                }, "progressThread");

                                progressThread.start();

                                ByteStreams.copy(entity.getContent(), os);

                                progressThread.interrupt();

                                System.out.println("Download complete.");

                                downloadResult.set(new DownloadResult(file, "", true));
                                downloadLatch.countDown();
                            } catch (Exception e) {
                                LoggerFactory.getLogger("log").warn("", e);
                                downloadResult.set(new DownloadResult(null, e.getMessage(), false));
                                throw Exceptions.runtime(e);
                            }
                        }
                    }, "fx-downloader");

                    thread.start();
                }
            }

            public void setStatus(final String s) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        progressLabel.setText(s);
                    }
                });
            }
        });

        // links from http://www.oracle.com/technetwork/java/archive-139210.html

        Map<Integer, String> archiveLinksMap = new HashMap<Integer, String>();

        archiveLinksMap.put(5,
                "http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase5-419410.html");
        archiveLinksMap.put(6,
                "http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase6-419409.html");
        archiveLinksMap.put(7,
                "http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html");

        Map<Integer, String> latestLinksMap = new HashMap<Integer, String>();

        latestLinksMap.put(7,
                "http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html");

        String archiveUrl = null;
        String latestUrl = null;

        char ch = version.charAt(0);

        switch (ch) {
        case '7':
        case '6':
        case '5':
            latestUrl = latestLinksMap.get(ch - '0');
            archiveUrl = archiveLinksMap.get(ch - '0');
            break;
        default:
            archiveUrl = null;
        }

        if (latestUrl != null) {
            final String finalArchiveUrl = archiveUrl;
            tryFind(browser, latestUrl, new WhenDone() {
                @Override
                public void whenDone(boolean found) {
                    tryArchiveLink(found, finalArchiveUrl, browser);
                }
            });
        } else {
            tryArchiveLink(false, archiveUrl, browser);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}