File UserManagement
File UserManagement
java
package UI.Sidebar.UserManagement;
import CsvFile.AppendDataToFile;
import CsvFile.GetDataFromFile;
import CsvFile.UpdateDataFromListToFile;
import UI.Sidebar.UserManagement.AccountData.Account;
import Controller.AppController;
import UI.Sidebar.UserManagement.AccountData.AccountList;
import UI.Sidebar.UserManagement.AccountData.UserInfo;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.util.List;
import java.util.Optional;
/**
* Constructor to create userManagement.
*
* @param controller the main controller
*/
public userManagement(AppController controller) {
data = FXCollections.observableArrayList();
filteredData = new FilteredList<>(data, p -> true);
tableView = new TableView<>(filteredData);
tableView.getStylesheets().add(getClass()
.getResource("/styles/userManagement.css").toExternalForm());
tableView.getStyleClass().add("table-view");
tableView.setLayoutX(100);
tableView.setLayoutY(20);
initializeTableColumns();
loadAccountData();
addTableContextMenu();
}
/**
* Init table column with Cell Value.
*
*/
private void initializeTableColumns() {
TableColumn<Account, String> usernameColumn = new TableColumn<>("Username");
usernameColumn.getStyleClass().add("username-column");
usernameColumn.setCellValueFactory(cellData ->
new SimpleStringProperty(cellData.getValue().getUsername()));
/**
* Read file and load accounts data to ObservableList.
*
*/
private void loadAccountData() {
List<Account> accounts = new GetDataFromFile().getAccountsFromFile("accounts.csv");
data.addAll(accounts);
}
/**
* Get User Management GUI Stackpane.
* @param currentAccount current Account
* @return StackPane
*/
public StackPane getUserStackPane(Account currentAccount) {
// Top AnchorPane for search
AnchorPane topPane = new AnchorPane();
topPane.getStyleClass().add("top-pane");
// Set up filtering
searchField.textProperty().addListener((observable, oldValue, newValue) -> {
String searchMode = searchModeComboBox.getValue();
filteredData.setPredicate(account -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
switch (searchMode) {
case "Full Name":
return account.getInfo().getFullName().toLowerCase()
.contains(lowerCaseFilter);
case "Age":
return String.valueOf(account.getInfo().getAge())
.contains(lowerCaseFilter);
case "Gender":
return (account.getInfo().getGender() ? "male" : "female")
.contains(lowerCaseFilter);
case "Admin Status":
return (account.isAdmin() ? "yes" : "no")
.contains(lowerCaseFilter);
default:
return account.getUsername().toLowerCase()
.contains(lowerCaseFilter);
}
});
});
AnchorPane centerPane = new AnchorPane(tableView);
return pane;
}
/**
* Open Pop-up stage to add account.
*
*/
private void openAddAccountStage() {
Stage stage = new Stage();
stage.setTitle("Add New Account");
doneButton.getStylesheets().add(getClass().getResource("/styles/userManagement.css").toExtern
alForm());
doneButton.getStyleClass().add("button");
doneButton.setOnAction(e -> {
try {
String username = usernameField.getText();
String password = passwordField.getText();
String fullName = fullNameField.getText();
String ageText = ageField.getText();
if (!username.matches("^[a-zA-Z0-9]{6,20}$")) {
showAlert(Alert.AlertType.ERROR, "Invalid Username", "Username must be 6-20
alphanumeric characters without special characters.");
return;
}
if (!password.matches("^[a-zA-Z0-9!@#$%^&*()_+]{6,20}$")) {
showAlert(Alert.AlertType.ERROR, "Invalid Password", "Password must be 6-20
characters and can include special characters.");
return;
}
if (!fullName.matches("^[A-Z][a-z]+( [A-Z][a-z]+)+$")) {
showAlert(Alert.AlertType.ERROR, "Invalid Full Name", "Full name must contain
at least two words, each starting with an uppercase letter.");
return;
}
int age;
try {
age = Integer.parseInt(ageText);
} catch (NumberFormatException ex) {
showAlert(Alert.AlertType.ERROR, "Invalid Age", "Age must be a valid number.");
return;
}
if (age <= 0 || age >= 100) {
showAlert(Alert.AlertType.ERROR, "Invalid Age", "Age must be between 1 and
99.");
return;
}
appendAccountToCSV(newAccount);
data.add(newAccount);
showAlert(Alert.AlertType.INFORMATION, "Success", "Account added
successfully!");
stage.close();
} catch (Exception ex) {
showAlert(Alert.AlertType.ERROR, "Error", "An unexpected error occurred: " +
ex.getMessage());
}
});
/**
* Append new account to file.
* @param account new account to be appended
*/
private void appendAccountToCSV(Account account) {
AppendDataToFile csvReader = new AppendDataToFile();
csvReader.appendAccount("accounts.csv", account);
}
/**
* Method to add context menu to table rows.
*/
private void addTableContextMenu() {
tableView.setRowFactory(tv -> {
TableRow<Account> row = new TableRow<>();
ContextMenu contextMenu = new ContextMenu();
row.contextMenuProperty().bind(
javafx.beans.binding.Bindings.when(row.emptyProperty())
.then((ContextMenu) null)
.otherwise(contextMenu)
);
return row;
});
}
if (account.getInfo().getGender()) {
maleButton.setSelected(true);
} else {
femaleButton.setSelected(true);
}
if (account.isAdmin()) {
adminYesButton.setSelected(true);
} else {
adminNoButton.setSelected(true);
}
if (!newUsername.matches("^[a-zA-Z0-9]{6,20}$")) {
showAlert(Alert.AlertType.ERROR, "Invalid Username", "Username must be 6-20
alphanumeric characters without special characters.");
return;
}
if (!newPassword.matches("^[a-zA-Z0-9!@#$%^&*()_+]{6,20}$")) {
showAlert(Alert.AlertType.ERROR, "Invalid Password", "Password must be 6-20
characters and can include special characters.");
return;
}
if (!newFullName.matches("^[A-Z][a-z]+( [A-Z][a-z]+)+$")) {
showAlert(Alert.AlertType.ERROR, "Invalid Full Name", "Full name must contain at
least two words, each starting with an uppercase letter.");
return;
}
int newAge;
try {
newAge = Integer.parseInt(newAgeText);
} catch (NumberFormatException ex) {
showAlert(Alert.AlertType.ERROR, "Invalid Age", "Age must be a number.");
return;
}
if (newAge <= 0 || newAge >= 100) {
showAlert(Alert.AlertType.ERROR, "Invalid Age", "Age must be between 1 and 99.");
return;
}
account.setUsername(newUsername);
account.setPassword(newPassword);
account.setAdmin(newIsAdmin);
account.setInfo(new UserInfo(newFullName, newAge, newGender));
updateAccountInCsv(account);
tableView.refresh();
stage.close();
} catch (Exception ex) {
showAlert(Alert.AlertType.ERROR, "Error", "An unexpected error occurred: " +
ex.getMessage());
}
});
/**
* Method to show book details in a new stage.
* @param account the selected book to display details for.
*/
private void showAccountDetails(Account account) {
Stage stage = new Stage();
stage.setTitle("Book Details");
RegisterStage.java
package UI.AccessApp;
import CsvFile.AppendDataToFile;
import UI.Sidebar.UserManagement.AccountData.Account;
import UI.Sidebar.UserManagement.AccountData.AccountList;
import UI.Sidebar.UserManagement.AccountData.UserInfo;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
* Constructor.
*
*/
public RegisterStage() {
register = new Stage();
register.setTitle("Register");
register.setResizable(false);
VBox vbox = new VBox(10);
vbox.getStyleClass().add("vbox");
if (!username.matches("^[a-zA-Z0-9]{6,20}$")) {
showAlert(Alert.AlertType.ERROR, "Invalid Username", "Username must be 6-20
alphanumeric characters without special characters.");
return;
}
if (!password.matches("^[a-zA-Z0-9!@#$%^&*()_+]{6,20}$")) {
showAlert(Alert.AlertType.ERROR, "Invalid Password", "Password must be 6-20
characters and can include special characters.");
return;
}
if (!fullName.matches("^[A-Z][a-z]+( [A-Z][a-z]+)+$")) {
showAlert(Alert.AlertType.ERROR, "Invalid Full Name", "Full name must contain
at least two words, each starting with an uppercase letter.");
return;
}
int age;
try {
age = Integer.parseInt(ageText);
} catch (NumberFormatException ex) {
showAlert(Alert.AlertType.ERROR, "Invalid Age", "Age must be a number.");
return;
}
/**
* Append new Account to accounts's storage file.
* @param account account to be appended
*/
private void appendAccountToCSV(Account account) {
AppendDataToFile csvReader = new AppendDataToFile();
csvReader.appendAccount("accounts.csv", account);
}
/**
* Show alert pop-up.
* @param alertType type of alert
* @param title title of alert
* @param message message
*/
private void showAlert(Alert.AlertType alertType, String title, String message) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.showAndWait();
}
}