Example usage for javafx.beans WeakInvalidationListener WeakInvalidationListener

List of usage examples for javafx.beans WeakInvalidationListener WeakInvalidationListener

Introduction

In this page you can find the example usage for javafx.beans WeakInvalidationListener WeakInvalidationListener.

Prototype

public WeakInvalidationListener(@NamedArg("listener") InvalidationListener listener) 

Source Link

Document

The constructor of WeakInvalidationListener .

Usage

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

@FXML
public void initialize() {

    if (logger.isDebugEnabled()) {
        logger.debug("[INIT] instance={}, configurationDS={}", this.hashCode(), configurationDS.hashCode());
    }/*from  ww  w .  j  a  va 2 s .c  o  m*/

    cbVerbose.getItems().addAll(Boolean.TRUE, Boolean.FALSE);

    pfStorepass.textProperty().bindBidirectional(activeProfile.jarsignerConfigStorepassProperty());
    tfKeystore.textProperty().bindBidirectional(activeProfile.jarsignerConfigKeystoreProperty());
    pfKeypass.textProperty().bindBidirectional(activeProfile.jarsignerConfigKeypassProperty());
    cbVerbose.valueProperty().bindBidirectional(activeProfile.jarsignerConfigVerboseProperty());

    lblConfKeypass.setVisible(false);
    lblConfStorepass.setVisible(false);
    lblKeystoreNotFound.setVisible(false);

    //
    // Enables ChoiceBox controls to use the arrow keys without losing focus
    //
    vbox.addEventFilter(KeyEvent.KEY_PRESSED, (evt) -> {
        if (evt.getCode() == KeyCode.UP || evt.getCode() == KeyCode.DOWN) {
            evt.consume();
        }
    });

    //
    // #7 fire action event when tfs lose focus
    //
    InvalidationListener pfConfStorepassListener = (evt) -> {
        if (!pfConfStorepass.isFocused()) {
            verifyStorepass();
        }
    };

    pfConfStorepass.focusedProperty().addListener(new WeakInvalidationListener(pfConfStorepassListener));

    InvalidationListener pfConfKeypassListener = (evt) -> {
        if (!pfConfKeypass.isFocused()) {
            verifyKeypass();
        }
    };

    pfConfKeypass.focusedProperty().addListener(new WeakInvalidationListener(pfConfKeypassListener));

    tfKeystore.textProperty().addListener(new WeakInvalidationListener(needsSaveListener));
    pfStorepass.textProperty().addListener(new WeakInvalidationListener(needsSaveListener));
    pfKeypass.textProperty().addListener(new WeakInvalidationListener(needsSaveListener));
    cbAlias.valueProperty().addListener(new WeakInvalidationListener(needsSaveListener));
}

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

@FXML
public void initialize() {

    try {/*  ww  w.j a  v a2 s.  c  o  m*/

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

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

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

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

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

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

        });

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

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

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

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

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

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

            if (needsSave.getValue()) {

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

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

        lvProfiles.setCellFactory(TextFieldListCell.forListView());

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

            @Override
            protected Void call() throws Exception {

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

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

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

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

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

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

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

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

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

                    } else {

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

                        return null;
                    }
                } else {

                    PasswordController pc = passwordControllerProvider.get();

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

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

                    Platform.runLater(() -> {

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

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

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

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

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

                        } else {

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

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

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

                            long startTimeMillis = System.currentTimeMillis();

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

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

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

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

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

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

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

                            long endTimeMillis = System.currentTimeMillis();

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

                return null;
            }

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

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

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

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

        new Thread(t).start();

    } catch (Exception exc) {

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

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

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

        Platform.exit();
    }
}