private boolean checkInfo() {
   String temp = new String();
   boolean value = false;
   if (companyIDField.getText() == null || companyIDField.getText().isEmpty()) {
     temp += "Company Name \n";
     value = true;
   }
   if (groupUsernameField.getText() == null || groupUsernameField.getText().isEmpty()) {
     temp += "Username \n";
     value = true;
   }
   if (groupPasswordField.getText() == null || groupPasswordField.getText().isEmpty()) {
     temp += "Password \n";
     value = true;
   }
   if (groupSecurityQuestion.getText() == null || groupSecurityQuestion.getText().isEmpty()) {
     temp += "Security Question \n";
     value = true;
   }
   if (groupSecurityAnswer.getText() == null || groupSecurityAnswer.getText().isEmpty()) {
     temp += "Security Answer \n";
     value = true;
   }
   if (value) {
     errorStr = temp;
     return true;
   }
   return false;
 }
  private void doRegister() {

    if (usernameField.getText().isEmpty()) {
      showConsoleText("username missing");
      return;
    }

    if (passwordField.getText().isEmpty()) {
      showConsoleText("password missing");
      return;
    }

    if (emailField.getText().isEmpty()) {
      showConsoleText("email missing");
      return;
    }

    if (userService.findByName(usernameField.getText()) != null) {
      showConsoleText("username taken");
      return;
    }

    userService.addUser(
        new User(usernameField.getText(), passwordField.getText(), emailField.getText()));

    if (userService.findByName(usernameField.getText()) == null) {
      showConsoleText("registration failed");
      return;
    }

    showLogin();
    showConsoleText("registration successful");
  }
  /**
   * Creates a new account (User)
   *
   * @param event
   * @throws IOException
   * @throws ClassNotFoundException
   * @throws SQLException
   */
  @FXML
  public void createAccount(ActionEvent event)
      throws IOException, ClassNotFoundException, SQLException {

    roles.setTextFill(Color.RED);
    wrongPass.setTextFill(Color.RED);
    duplicateID.setTextFill(Color.RED);

    if (super.loadShell() != null) {
      Shell loadShell = loadShell();
      shl.setEmployees(loadShell.getEmployees());
      shl.setManagers(loadShell.getManagers());
      shl.setTabs(loadShell.getTabs());
      shl.setUsers(loadShell.getUsers());
    }

    loadLog();

    if (!user.getText().equals("")
        && !password.getText().equals("")
        && !passconf.getText().equals("")
        && !name.getText().equals("")
        && !post.getText().equals("")) {

      if (shl.findUser(user.getText()) != null) {
        user.getStyleClass().add("error");
        duplicateID.setVisible(true);

        System.out.printf(
            "[SHELL] User %s exists as %s %s\n ",
            user.getText(), shl.findUser(user.getText()), shl.findUser(user.getText()));
      } else if (password.getText().equals(passconf.getText())) {
        shl.createUser(user.getText(), password.getText(), post.getText(), name.getText());

        System.out.printf("Created User %s\n", user.getText());

        user.getStyleClass().remove("error");
        password.getStyleClass().remove("error");
        passconf.getStyleClass().remove("error");
        roles.setVisible(false);
        duplicateID.setVisible(false);
        wrongPass.setVisible(false);

        super.saveShell();
        super.saveLog("USER " + user.getText() + " - " + name.getText() + " HAS BEEN CREATED");

        goToScreen1(event);

      } else {
        System.out.println("[SHELL] User creation failed - Passwords don't match");

        password.getStyleClass().add("error");
        passconf.getStyleClass().add("error");
        wrongPass.setVisible(true);
      }

    } else System.out.println("[SHELL] User creation failed - Missing fields");
  }
  private static void setButtonsActions() {
    sign_in_button.setOnAction(
        event -> {
          try {
            if ((username.getText().length() > 3) && (password.getText().length() > 3)) {
              UserData.saveData();
              UserCommands.authorization();
              synchronized (ThreadStorage.getInterfaceLauncher()) {
                ThreadStorage.getInterfaceLauncher().wait();
              }
              if (UserData.authorized) {
                loginForm.close();
                MainProgram.getMainProgram().launchForm();
              }
            } else {
              error_message_field.setText("Too short username or password");
            }
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        });

    register_button.setOnAction(
        event -> {
          try {
            if ((username.getText().length() > 3) && (password.getText().length() > 3)) {
              UserData.saveData();
              UserCommands.user_exists();
              synchronized (ThreadStorage.getInterfaceLauncher()) {
                ThreadStorage.getInterfaceLauncher().wait();
              }
              if (!user_exists) {
                CategoryForm.launchForm();
                UserCommands.register();
                synchronized (ThreadStorage.getInterfaceLauncher()) {
                  ThreadStorage.getInterfaceLauncher().wait();
                }
                if (UserData.authorized) {
                  LoginForm.closeForm();
                  MainProgram.getMainProgram().launchForm();
                }
              } else {
                error_message_field.setText("Username is already existed");
              }
            } else {
              error_message_field.setText("Too short username or password");
            }
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        });
  }
  public void Login() throws IOException {

    // TODO set username og password til en string istedet for at hent dem på den måde

    // if username field is empty = error message
    if (usernameText.getText().equals("")) {

      passwordErrorLbl.setVisible(false);
      usernameErrorLbl.setVisible(true);

      loginErrorLbl.setVisible(false);
    }
    // if passwordfield is empty = error message
    if (passwordText.getText().equals("")) {

      usernameErrorLbl.setVisible(false);
      passwordErrorLbl.setVisible(true);

      loginErrorLbl.setVisible(false);
    }

    if (passwordText.getText().equals("") && usernameText.getText().equals("")) {

      usernameErrorLbl.setVisible(true);
      passwordErrorLbl.setVisible(true);

      loginErrorLbl.setVisible(false);
    }

    if (logic.userAuth(usernameText.getText(), passwordText.getText())) {

      usernameErrorLbl.setVisible(false);
      passwordErrorLbl.setVisible(false);
      loginErrorLbl.setVisible(false);

      usernameText.clear();
      passwordText.clear();

      // TODO get menu to display currentuser

      myController.setScreen(Main.screenMenuID);

    } else {

      usernameErrorLbl.setVisible(false);
      passwordErrorLbl.setVisible(false);

      loginErrorLbl.setVisible(true);
    }
  }
  /**
   * @param title Title, message
   * @param correct_password Password to check
   */
  public PasswordDialog(final String title, final String correct_password) {
    this.correct_password = correct_password;
    final DialogPane pane = getDialogPane();

    pass_entry.setPromptText(Messages.Password_Prompt);
    pass_entry.setMaxWidth(Double.MAX_VALUE);

    getDialogPane().setContent(pass_entry);

    setTitle(Messages.Password);
    setHeaderText(title);
    pane.getStyleClass().add("text-input-dialog");
    pane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

    // Check password in dialog?
    if (correct_password != null && correct_password.length() > 0) {
      final Button okButton = (Button) pane.lookupButton(ButtonType.OK);
      okButton.addEventFilter(
          ActionEvent.ACTION,
          event -> {
            if (!checkPassword()) event.consume();
          });
    }

    setResultConverter(
        (button) -> {
          return button.getButtonData() == ButtonData.OK_DONE ? pass_entry.getText() : null;
        });

    Platform.runLater(() -> pass_entry.requestFocus());
  }
示例#7
0
  public void sendRequest(String username, String password) {

    thisStage = (Stage) logInButton.getScene().getWindow();
    Response res =
        new Request("user/login").set("username", username).set("password", password).send();

    if (res.getSuccess()) {
      Main.setSessionID((String) res.get("sessionID"));
      System.out.println("Login successful.");
      Main.userNotLoggedIn.setValue(false);

      // Save the login option if checked
      if (keepMeLoggedInCheckBox.isSelected()) {
        pc.setProp("username", usernameTextField.getText());
        pc.setProp("password", passwordPasswordField.getText());
        pc.setProp("signInCheckbox", "true");
        pc.saveProps();
      }

      HomeController.userName = usernameTextField.getText();
      thisStage.close();
    } else {
      // incorrect password
    }
  }
 private boolean checkPassword() {
   final String password = pass_entry.getText();
   if (correct_password.equals(password)) return true;
   setHeaderText(Messages.Password_Error);
   Platform.runLater(() -> pass_entry.requestFocus());
   return false;
 }
示例#9
0
  @FXML
  private void onLogInButtonClick(ActionEvent event) {

    String username = usernameTextField.getText();
    String password = passwordPasswordField.getText();

    sendRequest(username, password);
  }
  @FXML
  public void setPasswordClicked(ActionEvent event) {
    if (!pass1.getText().equals(pass2.getText())) {
      informationalAlert(tr("Passwords do not match"), tr("Try re-typing your chosen passwords."));
      return;
    }
    String password = pass1.getText();
    // This is kind of arbitrary and we could do much more to help people pick strong passwords.
    if (password.length() < 4) {
      informationalAlert(
          tr("Password too short"),
          tr("You need to pick a password at least five characters or longer."));
      return;
    }

    fadeIn(progressMeter);
    fadeOut(widgetGrid);
    fadeOut(explanationLabel);
    fadeOut(buttonHBox);

    KeyCrypterScrypt scrypt = new KeyCrypterScrypt(SCRYPT_PARAMETERS);

    // Deriving the actual key runs on a background thread. 500msec is empirical on my laptop
    // (actual val is more like 333 but we give padding time).
    KeyDerivationTasks tasks =
        new KeyDerivationTasks(scrypt, password, estimatedKeyDerivationTime) {
          @Override
          protected void onFinish(KeyParameter aesKey, int timeTakenMsec) {
            // Write the target time to the wallet so we can make the progress bar work when
            // entering the password.
            WalletPasswordController.setTargetTime(Duration.ofMillis(timeTakenMsec));
            // The actual encryption part doesn't take very long as most private keys are derived on
            // demand.
            log.info("Key derived, now encrypting");
            Main.bitcoin.wallet().encrypt(scrypt, aesKey);
            log.info("Encryption done");
            informationalAlert(
                tr("Wallet encrypted"),
                tr("You can remove the password at any time from the settings screen."));
            overlayUI.done();
          }
        };
    progressMeter.progressProperty().bind(tasks.progress);
    tasks.start();
  }
示例#11
0
  private Condomino condominoConsulta() {
    String senha = tfSenha.getText();

    Condomino c = new Condomino();
    c.setLogin(tfLogin.getText());
    c.setSenha(senha);

    return c;
  }
示例#12
0
 /** Method validate calls when LoginButton was clicked. */
 public void validate(ActionEvent event) throws IOException {
   String username = userField.getText();
   String userPassword = passwordBox.getText();
   if (username.equals("user") && userPassword.equals("user")) {
     labelInfo.setText("valid");
     loadTableScene();
   } else {
     labelInfo.setText("Username/Password is incorrect");
   }
 }
 @FXML
 void adminLoginAction(ActionEvent event) {
   if (adminUserID.getText().equals(validUserID)
       && adminPassword.getText().equals(validPassword)) {
     try {
       main.AdminEdit();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  private void doLogin() {

    if (usernameField.getText().isEmpty()) {
      showConsoleText("username missing");
      return;
    }

    if (passwordField.getText().isEmpty()) {
      showConsoleText("password missing");
      return;
    }

    if (!userService.authenticate(usernameField.getText(), passwordField.getText())) {
      showConsoleText("authentication failed");
      return;
    }

    showConsoleText("login accepted");
    Navigation.getInstance().loadScreen(MainController.getName());
  }
示例#15
0
 public Account getUpdatedAccount(Account account) {
   account.setFirstName(textFieldFirstname.getText());
   account.setLastName(textFieldLastname.getText());
   account.setUsername(textFieldUser.getText());
   RfidKey key = new RfidKey(textFieldRfid.getText());
   // key.setEnabled(true);
   account.setRfidKey(key);
   account.setPassword(passwordField.getText());
   account.setAuthorities(AuthorityUtils.createAuthorityList(AuthoritiesConstants.USER));
   System.out.println(account.toString());
   return account;
 }
示例#16
0
  @FXML
  public void login(ActionEvent e) throws SQLException {
    if (cl.checkCredenzialiClienti(user.getText(), pass.getText())) {
      username =
          user
              .getText(); // salva l'informazione dell'username da passare all'interfaccia cliente o
                          // operatore
      // setta le informazioni nelle finestre username e operatore
      nome = cl.read(user.getText()).getNome();
      cognome = cl.read(user.getText()).getCognomeCliente();
      FrontController.getIstance().setAutenticato();
      FrontController.getIstance().dispatchRequest("FinestraClienti");
    } else if (ag.checkcredenziali(user.getText(), pass.getText())) {
      FrontController.getIstance().setAutenticato();
      try {
        setDataAgente();
        // Caricamento nuova finestra e chiusura finestra login
        FrontController.getIstance().dispatchRequest("FinestraOperatore");
        Stage stage = (Stage) exit_btn.getScene().getWindow();
        stage.close();
      } catch (Exception e1) {
        e1.printStackTrace();
      }
    } else if (user.getText().equals("capone") && pass.getText().equalsIgnoreCase("capone")) {
      FrontController.getIstance().setAutenticato();
      try {
        FrontController.getIstance().dispatchRequest("FinestraAmministrazione");
        Stage stage = (Stage) exit_btn.getScene().getWindow();
        stage.close();

      } catch (Exception e1) {
        e1.printStackTrace();
      }
    } else {
      Popup.Errore("Credenziali errate", "Hai inserito credenziali sbagliate.");
    }
  }
  @FXML
  void loginAction() {
    try {
      credenciais.setLogin(textLogin.getText());
      credenciais.setSenha(textPassword.getText());
      securityContext.login();

      if (securityContext.isLoggedIn()) {
        buttonLogin.getScene().getWindow().hide();
      } else {
        errorMessage.setText(resources.getString("login.errorMessage"));
        showMessageError();
      }
    } catch (Exception exception) {
      ExceptionUtils.throwCustomerException(exception, false);
    }
  }
  /**
   * Login button event, 1) IF:- checks if nothing is null 2) IF:- Admin/Client, checks valid login
   * 3) IF:- Update Date access and process to home page
   *
   * @param ae
   */
  @FXML
  public void loginBtn(ActionEvent ae) {
    if (DropDownvalue != null && userName != null && password != null) {

      String userNameText = userName.getText().trim();
      String passwordText = password.getText().trim();

      if (DropDownvalue.equals("Admin")) {

        boolean check = new Model().getLogin("a", userNameText, passwordText);
        if (check) {
          boolean b = new Model().updateDateLogin("a", userNameText, passwordText);
          if (b) {
            new ChangeFxml().swap("/design/HomeAdmin.fxml");
          } else {
            ResetBtnClick(ae);
            userName.setPromptText("Invalid! Email");
            password.setPromptText("Invalid! Password");
          }

        } else {
          ResetBtnClick(ae);
          userName.setPromptText("Invalid! Email");
          password.setPromptText("Invalid! Password");
        }

      } else {
        boolean check = new Model().getLogin("u", userNameText, passwordText);
        if (check) {
          boolean b = new Model().updateDateLogin("u", userNameText, passwordText);
          if (b) {
            new ChangeFxml().swap("/design/Home.fxml");
          } else {
            ResetBtnClick(ae);
            userName.setPromptText("Something went wrong!");
            password.setPromptText("Invalid!");
          }

        } else {
          ResetBtnClick(ae);
          userName.setPromptText("Invalid!");
          password.setPromptText("Invalid!");
        }
      }
    }
  }
示例#19
0
 @FXML
 protected void handleSubmitButtonAction(ActionEvent event) {
   db.Connect();
   boolean test = db.userExist(username.getText().toString());
   if (test) {
     System.out.println("User Exists");
     test = db.checkPassword(username.getText().toString(), password.getText().toString());
     if (test) {
       // if username and password is correct program moves to main screen
       System.out.println("Password is correct");
       myController.setScreen(WellCheck.screenID2);
       db.patientTable();
     }
   }
   username.clear();
   password.clear();
   System.out.println(username.getText().toString());
 }
 private void saveData() throws IOException {
   Files.createDirectory(Paths.get(groupDir));
   File companyName = new File(groupDir + "\\CompanyName.txt");
   PrintWriter companyWriter = new PrintWriter(companyName);
   companyWriter.print(companyIDField.getText());
   companyWriter.close();
   File password = new File(groupDir + "\\GroupPassword.txt");
   PrintWriter passwordWriter = new PrintWriter(password);
   passwordWriter.print(groupPasswordField.getText());
   passwordWriter.close();
   File securityQ = new File(groupDir + "\\GroupSecurityQuestion.txt");
   PrintWriter securityQWriter = new PrintWriter(securityQ);
   securityQWriter.print(groupSecurityQuestion.getText());
   securityQWriter.close();
   File securityA = new File(groupDir + "\\GroupSecurityAnswer.txt");
   PrintWriter securityAWriter = new PrintWriter(securityA);
   securityAWriter.print(groupSecurityAnswer.getText());
   securityAWriter.close();
 }
  @FXML
  private void btn_sendOnAction() throws IOException {
    boolean mailSuccess = false;
    String errorMessage = "";
    try {

      Mailer.send(
          tf_login.getText(),
          pf_password.getText(),
          tf_emailFrom.getText(),
          tf_emailTo.getText(),
          tf_subject.getText(),
          ta_message.getText());

      mailSuccess = true;
    } catch (MessagingException e) {
      errorMessage = e.getMessage();
    }

    new SendingMailStage(mailSuccess, errorMessage);
  }
  @FXML
  void initialize() {
    assert syncUserName != null
        : "fx:id=\"syncUserName\" was not injected: check your FXML file 'AddUser.fxml'.";
    assert cancelButton != null
        : "fx:id=\"cancelButton\" was not injected: check your FXML file 'AddUser.fxml'.";
    assert password != null
        : "fx:id=\"password\" was not injected: check your FXML file 'AddUser.fxml'.";
    assert fullNameUnique != null
        : "fx:id=\"fullNameUnique\" was not injected: check your FXML file 'AddUser.fxml'.";
    assert roles != null : "fx:id=\"roles\" was not injected: check your FXML file 'AddUser.fxml'.";
    assert layoutPane != null
        : "fx:id=\"layoutPane\" was not injected: check your FXML file 'AddUser.fxml'.";
    assert fullName != null
        : "fx:id=\"fullName\" was not injected: check your FXML file 'AddUser.fxml'.";
    assert okButton != null
        : "fx:id=\"okButton\" was not injected: check your FXML file 'AddUser.fxml'.";
    assert userName != null
        : "fx:id=\"userName\" was not injected: check your FXML file 'AddUser.fxml'.";
    assert workflowUserName != null
        : "fx:id=\"workflowUserName\" was not injected: check your FXML file 'AddUser.fxml'.";
    assert uuid != null : "fx:id=\"uuid\" was not injected: check your FXML file 'AddUser.fxml'.";

    for (RoleOption ro : RoleOption.values()) {
      roles.getItems().add(ro.value());
    }

    upm_ = AppContext.getService(UserProfileManager.class);

    uuidValid_ =
        new ValidBooleanBinding() {
          {
            bind(uuid.textProperty());
          }

          @Override
          protected boolean computeValue() {
            if (uuid.getText().length() == 0 || Utility.isUUID(uuid.getText())) {
              if (uuid.getText().length() > 0
                  && AppContext.getService(TerminologyStoreDI.class)
                      .hasUuid(UUID.fromString(uuid.getText()))) {
                setInvalidReason("If a UUID is specified, it must be unique");
                return false;
              } else {
                clearInvalidReason();
                return true;
              }
            } else {
              setInvalidReason("Invalid uuid");
              return false;
            }
          }
        };

    ErrorMarkerUtils.setupErrorMarkerAndSwap(uuid, layoutPane, uuidValid_);

    userNameValid_ =
        new ValidBooleanBinding() {
          {
            bind(userName.textProperty());
          }

          @Override
          protected boolean computeValue() {
            if (userName.getText().length() > 0 && !upm_.doesProfileExist(userName.getText())) {
              clearInvalidReason();
              return true;
            } else {
              setInvalidReason("The user name is required, and must be unique");
              return false;
            }
          }
        };

    ErrorMarkerUtils.setupErrorMarkerAndSwap(userName, layoutPane, userNameValid_);

    fullNameUniqueValid_ =
        new ValidBooleanBinding() {
          {
            bind(fullNameUnique.textProperty(), uuid.textProperty());
          }

          @Override
          protected boolean computeValue() {
            if (fullNameUnique.getText().length() > 0) {
              UUID userUuid;
              if (uuid.getText().length() > 0) {
                if (uuidValid_.get()) {
                  userUuid = UUID.fromString(uuid.getText());
                } else {
                  setInvalidReason("If a UUID is specified, it must be valid.");
                  return false;
                }
              } else {
                userUuid = GenerateUsers.calculateUserUUID(fullNameUnique.getText());
              }

              if (AppContext.getService(TerminologyStoreDI.class).hasUuid(userUuid)) {
                setInvalidReason("The full name must be unique");
                return false;
              } else {
                clearInvalidReason();
                return true;
              }
            } else {
              setInvalidReason(
                  "The Full Name is required, and must be unique.  If a UUID is specified, it must be valid, and unique");
              return false;
            }
          }
        };

    ErrorMarkerUtils.setupErrorMarkerAndSwap(fullNameUnique, layoutPane, fullNameUniqueValid_);

    okButton.disableProperty().bind(fullNameUniqueValid_.and(userNameValid_).and(uuidValid_).not());

    cancelButton.setCancelButton(true);
    // JavaFX is silly:  https://javafx-jira.kenai.com/browse/RT-39145#comment-434189
    cancelButton.setOnKeyPressed(
        new EventHandler<KeyEvent>() {
          @Override
          public void handle(KeyEvent event) {
            if (event.getCode() == KeyCode.ENTER) {
              event.consume();
              cancelButton.fire();
            }
          }
        });
    cancelButton.setOnAction(
        (event) -> {
          layoutPane.getScene().getWindow().hide();
        });

    okButton.setDefaultButton(true);
    okButton.setOnAction(
        (event) -> {
          try {
            User u = new User();
            u.setFullName(fullName.getText());
            u.setPassword(password.getText());
            u.setSyncUserName(syncUserName.getText());
            u.setWorkflowUserName(workflowUserName.getText());
            u.setUniqueFullName(fullNameUnique.getText());
            u.setUniqueLogonName(userName.getText());
            u.setUUID(uuid.getText());
            for (String roleName : roles.getSelectionModel().getSelectedItems()) {
              u.getRoles().add(RoleOption.fromValue(roleName));
            }
            upm_.createNewUser(u);
            layoutPane.getScene().getWindow().hide();
          } catch (Exception e) {
            logger.error("Error creating user", e);
            AppContext.getCommonDialogs().showErrorDialog("Unexpected error adding user", e);
          }
        });
  }
  @Override
  public void initialize(URL url, ResourceBundle rb) {

    try { // Create a socket to connect to the server
      Socket socket = new Socket("localhost", 8000);

      FromServer = new DataInputStream(socket.getInputStream());
      // Create an output stream to send data to the server
      ToServer = new DataOutputStream(socket.getOutputStream());
    } catch (IOException ex) {
      lbout.setText(ex.toString() + '\n');
    }

    while (loged) {}
    btlogout.setOnAction(
        e -> {
          try {
            ToServer.writeUTF("Logout");
            Boolean logout = FromServer.readBoolean();
            if (logout) {
              loged = false;
              isadmin = false;
              lbloginfo.setText("Loged Out");
              tbuser.setDisable(!loged);
              tbadmin.setDisable(!isadmin);
              btlogout.setVisible(false);
              btlogin.setVisible(true);
              txaddpass.clear();
              // btlogin.setText("Login");
              tfname.setDisable(false);
              tfpass.setDisable(false);
            } else lbloginfo.setText("Logout Failed");

          } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
          }
        });
    btlogin.setOnAction(
        e -> {
          String name = tfname.getText();
          String pass = tfpass.getText();
          if (name.isEmpty() && pass.isEmpty()) lbloginfo.setText("Username and Password is empty");
          else if (name.isEmpty()) lbloginfo.setText("Username is empty");
          else if (pass.isEmpty()) lbloginfo.setText("Password is empty");
          else {
            try {
              ToServer.writeUTF(tfname.getText());
              ToServer.writeUTF(tfpass.getText());
              loged = FromServer.readBoolean();
              isadmin = FromServer.readBoolean();
              if (loged) {
                lbloginfo.setText("Logged in");
                lbloginfo.setText("Welcome Back " + name);
                // btlogin.setText("Logout");
                tfname.setDisable(true);
                tfpass.setDisable(true);
                btlogin.setVisible(false);
                btlogout.setVisible(true);
                if (isadmin) {
                  lbtypeuser.setText("Loged as Administrator");

                } else lbtypeuser.setText("Loged as User");
                // tbadmin.setDisable(!isadmin);
                tbuser.setDisable(!loged);
                tbadmin.setDisable(!isadmin);
                tb.getSelectionModel().select(tbuser);
                repo = FromServer.readUTF();
                txgroup.setText(repo);
                // getuserinfo(repo);
                getFilesinfo();
                getgroupe();
                getusers();
                gettars();
                // cbbackups.getItems().addAll(tars);
                // cbgroup.getItems().addAll(groups);
                // cbselectuser.getItems().addAll(users);
              } else lbout.setText("Failed to log in");

            } catch (IOException ex) {

            }
          }
        });
    btbackup.setOnAction(
        e -> {
          try {
            tars.clear();
            ToServer.writeUTF("Backup");
            Boolean answer = FromServer.readBoolean();
            if (answer) {
              lbadmininfo.setText("Backup finished");
              gettars();
            } else {
              lbadmininfo.setText("error accured during restore");
              gettars();
            }

          } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            try {
              gettars();
            } catch (Exception e2) {
              // TODO Auto-generated catch block
              e2.printStackTrace();
            }
          }
        });
    btrestore.setOnAction(
        e -> {
          try {
            if (!cbbackups.selectionModelProperty().get().getSelectedItem().isEmpty()) {
              ToServer.writeUTF("Restore");
              ToServer.writeUTF(cbbackups.selectionModelProperty().get().getSelectedItem());
              Boolean answer = FromServer.readBoolean();
              if (answer) lbadmininfo.setText("restore finished");
              else lbadmininfo.setText("error accured during backup");
            } else lbadmininfo.setText("please choose tar file");

          } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
          }
        });
    btcheckin.setOnAction(
        e -> {
          if (loged) {
            file = fileChooser.showOpenDialog(new Stage());
            if (file != null) {
              try {
                ToServer.writeUTF("Checkin");
                ToServer.writeUTF(file.getName());
                ToServer.writeLong(file.lastModified());
                sendFile(file);
                String choice = null;
                choice = FromServer.readUTF();
                if (choice.equals("sync")) {
                  getFilesinfo();
                  File newfile = GetFile(FromServer);

                  writeFile(file, file.getPath() + "--old");
                  String path = file.getPath();
                  file.delete();
                  writeFile(newfile, path);
                  lbout.setText("Performing Sync with the server");
                } else if (choice.contains("locked")) {
                  getFilesinfo();
                  lbout.setText(choice);
                } else if (choice.equals("not text")) {
                  getFilesinfo();
                  lbout.setText("Check in only text files");
                } else if (choice.equals("equal")) {
                  getFilesinfo();
                  lbout.setText("The file is equal to the latest version");
                } else {
                  getFilesinfo();
                  lbout.setText("The file is uploaded successfully");
                }
                // ToServer.writeUTF("Files");

                // getFilesinfo();
              } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
              }
            }
          }
        });
    btcheckout.setOnAction(
        e -> {
          try {
            ToServer.writeUTF("Checkout");
            ToServer.writeUTF(tbl.selectionModelProperty().get().getSelectedItem().getName());
            System.out.println(tbl.selectionModelProperty().get().getSelectedItem().getName());
            ToServer.writeUTF(cbversion.selectionModelProperty().get().getSelectedItem());
            System.out.println(cbversion.selectionModelProperty().get().getSelectedItem());
            Boolean answer = FromServer.readBoolean();
            if (answer) {
              String filename = FromServer.readUTF();
              Long timestamp = FromServer.readLong();
              File ver = GetFile(FromServer);
              String pa = System.getProperty("user.home") + "/" + filename;
              writeFile(ver, System.getProperty("user.home") + "/" + filename);
              File tim = new File(System.getProperty("user.home") + "/" + filename);
              tim.setLastModified(timestamp);
              lbout.setText("The file is saved on your home directory");
            } else lbout.setText("Checkout failed");
          } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
          }
        });
    tbl.getSelectionModel()
        .selectedItemProperty()
        .addListener(
            (obs, oldSelection, newSelection) -> {
              if (newSelection != null) {
                versions.clear();
                Float lastvers =
                    Float.valueOf(tbl.getSelectionModel().selectedItemProperty().get().getLastv());
                for (float i = 1f; i <= lastvers + 0.001; i += 0.001) {
                  if (i == 1f) versions.add(Float.toString(i) + "00");
                  else versions.add(Float.toString(i).substring(0, 5));
                }
                cbversion.getItems().addAll(versions);
              }
            });
    cbgroup
        .getSelectionModel()
        .selectedItemProperty()
        .addListener(
            (obs, oldSelection, newSelection) -> {
              if (newSelection != null) {
                try {

                } catch (Exception e1) {
                  // TODO Auto-generated catch block
                  e1.printStackTrace();
                }
              }
            });
    btadduser.setOnAction(
        e -> {
          try {
            if (!txaddname.getText().isEmpty()
                && !txaddpass.getText().isEmpty()
                && !txgroup.getText().isEmpty()) {
              ToServer.writeUTF("Adduser");
              ToServer.writeUTF(txaddname.getText());
              ToServer.writeUTF(txaddpass.getText());
              if (cboxadmin.isSelected()) ToServer.writeUTF("1");
              else ToServer.writeUTF("0");
              ToServer.writeUTF(txgroup.getText());
              Boolean answer = FromServer.readBoolean();
              try {
                if (answer) {
                  lbadmininfo.setText("User Added");
                  users.clear();
                  getusers();
                  // users.add(txaddname.getText());
                  txaddname.setText("");
                  txaddpass.setText("");
                  cboxadmin.setSelected(false);
                } else {
                  lbadmininfo.setText("User add failed");
                  getusers();
                }
              } catch (Exception p) {
                getusers();
              }
            } else {
              lbadmininfo.setText("All text must be field");
              getusers();
            }

          } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            try {
              getusers();
            } catch (Exception e2) {
              // TODO Auto-generated catch block
              e2.printStackTrace();
            }
          }
        });
    btdeleteuser.setOnAction(
        e -> {
          try {
            if (!cbselectuser.selectionModelProperty().get().getSelectedItem().isEmpty()) {
              ToServer.writeUTF("Deleteuser");
              ToServer.writeUTF(cbselectuser.selectionModelProperty().get().getSelectedItem());
              cbselectuser.setValue("");
              users.clear();
              Boolean answer = FromServer.readBoolean();
              if (answer) {
                lbadmininfo.setText("User deleted");
                getusers();
                // users.remove(cbselectuser.selectionModelProperty().get().getSelectedItem());
              } else {
                lbadmininfo.setText("unable to delete user");
                getusers();
              }
            } else {
              lbadmininfo.setText("All text must be field");
              getusers();
            }

          } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            try {
              getusers();
            } catch (Exception e2) {
              // TODO Auto-generated catch block
              e2.printStackTrace();
            }
          }
        });
    btaddgroup.setOnAction(
        e -> {
          try {
            if (!txgroupname.getText().isEmpty()) {
              ToServer.writeUTF("Addgroup");
              ToServer.writeUTF(txgroupname.getText());
              Boolean answer = FromServer.readBoolean();
              if (answer) {
                lbadmininfo.setText("Group Added");
                getgroupe();
              } else {
                lbadmininfo.setText("Group add failed");
                getgroupe();
              }
            } else {
              lbadmininfo.setText("All text must be field");
              getgroupe();
            }
          } catch (Exception e1) {
            // TODO Auto-generated catch block
            try {
              getgroupe();
            } catch (Exception e2) {
              // TODO Auto-generated catch block
              e2.printStackTrace();
            }
          }
        });
  }
示例#24
0
  @Override
  public void start(Stage theStage) {
    this.tStage = theStage;
    theStage.setTitle("Ball of Duty");
    theStage.setHeight(WINDOW_START_HEIGHT);
    theStage.setWidth(WINDOW_START_WIDTH);
    theStage.centerOnScreen();
    theStage.setResizable(false);
    theStage.setOnCloseRequest(
        new EventHandler<WindowEvent>() {
          public void handle(WindowEvent we) {
            gameManager.quitGame();
            System.exit(0);
          }
        });

    BorderPane startMenuRoot = new BorderPane();
    startMenu = new Scene(startMenuRoot);

    gameBox = new BorderPane();
    Scene gameScene = new Scene(gameBox);

    BorderPane createAccountRoot = new BorderPane();
    BorderPane lohInRoot = new BorderPane();

    theStage.setScene(startMenu);

    gameManager = new GameClient(getRelativeSceneLocation(theStage));

    scale = new Scale();
    scale.xProperty().bind(gameScene.widthProperty().divide(WINDOW_START_WIDTH));
    scale.yProperty().bind(gameScene.heightProperty().divide(WINDOW_START_HEIGHT));
    scale.setPivotX(0);
    scale.setPivotY(0);
    // gameBox.getTransforms().add(scale);
    // gameBox.setBackground(null);
    // TODO scaling

    theStage
        .heightProperty()
        .addListener(
            e -> {
              gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage)); // This
              // only
              // happens
              // once
              // for
              // some
              // reason.
            });
    theStage
        .widthProperty()
        .addListener(
            e -> {
              gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
            });
    theStage
        .xProperty()
        .addListener(
            e -> {
              gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
            });
    theStage
        .yProperty()
        .addListener(
            e -> {
              gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
            });
    gameScene
        .xProperty()
        .addListener(
            e -> {
              gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
            });
    gameScene
        .yProperty()
        .addListener(
            e -> {
              gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
            });
    Image image = new Image("images/frontpage.png");
    BackgroundSize backgroundSize = new BackgroundSize(100, 100, true, true, true, false);
    // new BackgroundImage(image, repeatX, repeatY, position, size)
    BackgroundImage backgroundImage =
        new BackgroundImage(
            image,
            BackgroundRepeat.REPEAT,
            BackgroundRepeat.NO_REPEAT,
            BackgroundPosition.CENTER,
            backgroundSize);
    // new Background(images...)
    Background background = new Background(backgroundImage);
    startMenuRoot.setBackground(background);

    RadioButton chooseBlaster = new RadioButton("Blaster");
    RadioButton chooseRoller = new RadioButton("Roller");
    RadioButton chooseHeavy = new RadioButton("Heavy");

    final ToggleGroup specializationGroup = new ToggleGroup();

    chooseBlaster.setToggleGroup(specializationGroup);
    chooseRoller.setToggleGroup(specializationGroup);
    chooseHeavy.setToggleGroup(specializationGroup);

    chooseBlaster.setSelected(true);

    HBox specializationBox = new HBox();
    specializationBox.setSpacing(9);
    specializationBox.getChildren().add(chooseBlaster);
    specializationBox.getChildren().add(chooseRoller);
    specializationBox.getChildren().add(chooseHeavy);

    Label lblNickname = new Label("Nickname:");
    TextField tfNickname = new TextField();
    Button loginStart = new Button("Log in");
    Button createStart = new Button("Create Account");
    theStage.getIcons().add(new Image("images/ball_red.png"));
    VBox mainButtonBox = new VBox();
    mainButtonBox.setSpacing(5);
    Button joinBtn = new Button("Join game");

    Button viewLB = new Button("Leaderboard");
    viewLB.setPrefSize(150, 50);
    viewLB.setId("viewLB");
    viewLB.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");

    BorderPane lbBorder = new BorderPane();
    VBox lbBox = new VBox();
    Scene lbScene = new Scene(lbBorder);

    Button lbBack = new Button("Start menu");
    lbBox.getChildren().add(lbBack);
    lbBorder.setLeft(lbBox);
    lbBack.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");

    Label topText = new Label("Only shows scores higher than 100!");
    topText.setStyle("-fx-font-size: 20pt;-fx-font-family: Segoe UI Semibold;");

    viewLB.setOnAction(
        ActionEvent -> {
          HighscoreLeaderboard hBoard = gameManager.getHighscoreLeaderboard();
          hBoard.setFocusTraversable(false);
          lbBorder.setCenter(hBoard);
          if (gameManager.getPlayer() != null) {
            Player client = gameManager.getPlayer();
            Label you =
                new Label(
                    "YOU:    "
                        + client.getNickname()
                        + " ["
                        + client.getId()
                        + "]    | Score: "
                        + client.getHighscore());

            you.setStyle("-fx-font-size: 15pt;-fx-font-family: Segoe UI Semibold;");
            lbBorder.setBottom(you);
          }

          BorderPane.setMargin(hBoard, new Insets(12, 12, 12, 12));

          lbBorder.setTop(topText);
          theStage.setScene(lbScene);

          lbBack.setOnAction(
              ActionEvent1 -> {
                theStage.setScene(startMenu);
                startMenuRoot.setLeft(mainButtonBox);

                BorderPane.setMargin(mainButtonBox, new Insets(350, 0, 0, 150));
              });
        });

    joinBtn.setPrefSize(150, 50);
    tfNickname.setPrefSize(150, 20);
    joinBtn.setId("joinBtn");
    joinBtn.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
    lblNickname.setId("lblNickname");
    lblNickname.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
    createStart.setId("CreateStart");
    createStart.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
    loginStart.setId("loginStart");
    loginStart.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");

    joinBtn.setOnAction(
        ActionEvent -> {
          Specializations spec;
          if (chooseRoller.isSelected()) {
            spec = Specializations.ROLLER;
          } else if (chooseHeavy.isSelected()) {
            spec = Specializations.HEAVY;
          } else // Blaster is default, if something goes wrong with radio
          // buttons
          {
            spec = Specializations.BLASTER;
          }

          theStage.setScene(gameScene);
          gameManager.joinAsGuest(gameBox, tfNickname.getText(), spec);
          gameManager.getMap().addObserver(this);
          gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
          gameBox.requestFocus();
        });
    tfNickname.setOnAction(
        ActionEvent -> {
          Specializations spec;
          if (chooseRoller.isSelected()) {
            spec = Specializations.ROLLER;
          } else if (chooseHeavy.isSelected()) {
            spec = Specializations.HEAVY;
          } else // Blaster is default, if something goes wrong with radio
          // buttons
          {
            spec = Specializations.BLASTER;
          }
          theStage.setScene(gameScene);
          gameManager.joinAsGuest(gameBox, tfNickname.getText(), spec);
          gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
          gameBox.requestFocus();
        });

    mainButtonBox.getChildren().add(lblNickname);
    mainButtonBox.getChildren().add(tfNickname);
    mainButtonBox.getChildren().add(specializationBox);
    mainButtonBox.getChildren().add(joinBtn);
    mainButtonBox.getChildren().add(loginStart);
    mainButtonBox.getChildren().add(createStart);
    mainButtonBox.getChildren().add(viewLB);
    startMenuRoot.setLeft(mainButtonBox);

    createStart.setOnAction(
        ActionEvent -> {
          VBox createAccountButtonBox = new VBox();
          Label lblNickname2 = new Label("Nickname:");
          TextField tfNickname2 = new TextField();
          Label lblUserName = new Label("Name:");
          TextField tfUserName = new TextField();
          Label lblPassword = new Label("Password:"******"Repeat password:"******"Create account");
          Button back = new Button("Start menu");

          createBtn.setId("join-yyyyy");
          createBtn.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
          lblUserName.setId("join-game");
          lblUserName.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
          lblPassword.setId("join-game");
          lblPassword.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
          lblPassword2.setId("join-game");
          lblPassword2.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
          back.setId("join-game");
          back.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");

          createAccountButtonBox.getChildren().add(lblNickname2);
          createAccountButtonBox.getChildren().add(tfNickname2);
          createAccountButtonBox.getChildren().add(lblUserName);
          createAccountButtonBox.getChildren().add(tfUserName);
          createAccountButtonBox.getChildren().add(lblPassword);
          createAccountButtonBox.getChildren().add(pf);
          createAccountButtonBox.getChildren().add(lblPassword2);
          createAccountButtonBox.getChildren().add(pf2);
          createAccountButtonBox.getChildren().add(createBtn);
          createAccountButtonBox.getChildren().add(back);

          startMenuRoot.setLeft(createAccountButtonBox);
          BorderPane.setMargin(createAccountButtonBox, new Insets(350, 0, 0, 150));

          createBtn.setOnAction(
              ActionEvent1 -> {
                gameManager.createAccount(
                    tfUserName.getText(),
                    tfNickname2.getText(),
                    pf.getText().toCharArray(),
                    pf2.getText().toCharArray());
                startMenuRoot.setLeft(mainButtonBox);
                BorderPane.setMargin(mainButtonBox, new Insets(350, 0, 0, 150));
              });

          back.setOnAction(
              ActionEvent1 -> {
                startMenuRoot.setLeft(mainButtonBox);
                BorderPane.setMargin(mainButtonBox, new Insets(350, 0, 0, 150));
              });
        });

    loginStart.setOnAction(
        ActionEvent -> {
          VBox loginButtonBox = new VBox();
          Button logInBtn = new Button("Log in");
          Label lblUserName2 = new Label("Name:");
          TextField tfUserName2 = new TextField();
          Label lblPassword2 = new Label("Password:"******"Start Menu");

          logInBtn.setId("join-game");
          logInBtn.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
          back2.setId("join-game");
          back2.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");

          loginButtonBox.getChildren().add(lblUserName2);
          loginButtonBox.getChildren().add(tfUserName2);
          loginButtonBox.getChildren().add(lblPassword2);
          loginButtonBox.getChildren().add(pf3);
          loginButtonBox.getChildren().add(logInBtn);
          loginButtonBox.getChildren().add(back2);

          startMenuRoot.setLeft(loginButtonBox);
          BorderPane.setMargin(loginButtonBox, new Insets(350, 0, 0, 150));

          logInBtn.setOnAction(
              ActionEvent1 -> {
                // TODO login
              });

          back2.setOnAction(
              ActionEvent1 -> {
                startMenuRoot.setLeft(mainButtonBox);
                BorderPane.setMargin(mainButtonBox, new Insets(350, 0, 0, 150));
              });
        });

    BorderPane.setMargin(mainButtonBox, new Insets(350, 0, 0, 150));

    Button quitBtn = new Button("Quit game");
    quitBtn.setPrefSize(80, 40);
    quitBtn.setId("quit-game");

    quitBtn.setOnAction(
        ActionEvent -> {
          gameManager.quitGame();
          theStage.setScene(startMenu);
        });

    canvas = new Canvas(CANVAS_START_WIDTH, CANVAS_START_HEIGHT);
    gameBox.setCenter(canvas);
    BorderPane.setAlignment(canvas, Pos.TOP_LEFT);

    gameBox.setBottom(quitBtn);
    BorderPane.setAlignment(quitBtn, Pos.TOP_LEFT);
    theStage.show();
  }
 /**
  * Returns a UserCredential based on the values of the login dialog's TextField and PasswordField.
  *
  * @return a UserCredential based on the values of the login dialog's TextField and PasswordField.
  */
 public UserCredential getUserCredential() {
   return new UserCredential(textField_username.getText(), passwordField_password.getText());
 }
  @FXML
  private void giris(ActionEvent event) throws IOException {
    Boolean durum = false;

    try {
      String sAdminAdi = kuladi.getText();
      String sAdminSifre = sifreleme(sifre.getText());

      if (sAdminAdi.equals("")) {

        Alert alert =
            new Alert(Alert.AlertType.WARNING, "Lütfen Kullanıcı Adını Giriniz.", ButtonType.OK);
        alert.setHeaderText(null);
        alert.setTitle("Uyarı");
        alert.showAndWait();
        kuladi.requestFocus();
        sifre.setText("");

        durum = true;

      } else if (sifre.getText().equals("")) {

        Alert alert = new Alert(Alert.AlertType.WARNING, "Lütfen Şifreyi Giriniz.", ButtonType.OK);
        alert.setHeaderText(null);
        alert.setTitle("Uyarı");
        alert.showAndWait();
        sifre.requestFocus();
        durum = true;

      } else {

        SessionFactory sf = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
        Session sess = sf.openSession();
        Transaction ts = sess.beginTransaction();

        Query qee = sess.createQuery("from SuperAdmin");
        Iterator ite = qee.iterate();

        while (ite.hasNext()) {

          SuperAdmin obj = (SuperAdmin) ite.next();
          String kuladi = obj.getKulAdi();
          String sifre = obj.getSifre();

          if (sAdminAdi.equals(kuladi) & sAdminSifre.equals(sifre)) {

            Integer sID = obj.getSuperID();
            //                label.setText(sID.toString());

            Parent root = null;
            Stage stage = new Stage();
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("yonlendir.fxml"));
            root = fxmlLoader.load();
            yonlendirController cont = fxmlLoader.getController();
            cont.getRefCode(sID);
            stage.setScene(new Scene(root));
            stage.show();
            durum = true;
          }
        }

        if (durum == false) {

          Alert alert =
              new Alert(Alert.AlertType.WARNING, "Hatalı Kullanıcı Adı veya Şifre", ButtonType.OK);
          alert.setHeaderText(null);
          alert.setTitle("Uyarı");
          alert.showAndWait();
          kuladi.setText("");
          sifre.setText("");
          kuladi.requestFocus();
        }

        ts.commit();
        sess.close();
      }
    } catch (HibernateException he) {
      System.out.println(he);
    }
  }
 public static String getPassword() {
   return password.getText();
 }