Guest User

Untitled

a guest
Dec 7th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.69 KB | None | 0 0
  1. /*
  2. 1. Create first this database to your MySQL server:
  3. create schema javafxsample;
  4. use javafxsample;
  5. create table if not exists user(
  6. id int(11) not null auto_increment,
  7. username varchar(255) not null unique,
  8. last_name varchar(255) not null,
  9. first_name varchar(255) not null,
  10. password varchar(255) not null,
  11. created_at datetime not null default current_timestamp,
  12. primary key(id)
  13. );
  14. 2. Add mysql-connector-java-6.0.6.jar to your dependencies.
  15. 3. Update database credentials on Database.class.
  16. */
  17.  
  18. package io.github.julianjupiter.javafx;
  19.  
  20. import java.io.Serializable;
  21. import java.sql.Connection;
  22. import java.sql.DriverManager;
  23. import java.sql.PreparedStatement;
  24. import java.sql.ResultSet;
  25. import java.sql.SQLException;
  26. import java.sql.Statement;
  27. import java.util.ArrayList;
  28. import java.util.List;
  29. import java.util.logging.Level;
  30. import java.util.logging.Logger;
  31.  
  32. import javafx.application.Application;
  33. import javafx.geometry.Insets;
  34. import javafx.geometry.Pos;
  35. import javafx.scene.Scene;
  36. import javafx.scene.control.Alert;
  37. import javafx.scene.control.Alert.AlertType;
  38. import javafx.scene.control.Button;
  39. import javafx.scene.control.Label;
  40. import javafx.scene.control.PasswordField;
  41. import javafx.scene.control.TextField;
  42. import javafx.scene.layout.GridPane;
  43. import javafx.scene.layout.HBox;
  44. import javafx.scene.text.Font;
  45. import javafx.scene.text.FontWeight;
  46. import javafx.scene.text.Text;
  47. import javafx.stage.Stage;
  48.  
  49. public class JApps extends Application {
  50.  
  51. private static final Logger logger = Logger.getLogger(JApps.class.getName());
  52. private UserRepository userRepository = new UserRepository();
  53.  
  54. @Override
  55. public void start(Stage primaryStage) {
  56. primaryStage.setTitle("JavaFX Welcome");
  57.  
  58. GridPane grid = new GridPane();
  59. grid.setAlignment(Pos.CENTER);
  60. grid.setHgap(10);
  61. grid.setVgap(10);
  62. grid.setPadding(new Insets(25, 25, 25, 25));
  63.  
  64. Text scenetitle = new Text("Add User");
  65. scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
  66. grid.add(scenetitle, 0, 0, 2, 1);
  67.  
  68. Label userNameLabel = new Label("Username:");
  69. grid.add(userNameLabel, 0, 1);
  70.  
  71. TextField usernameTextField = new TextField();
  72. grid.add(usernameTextField, 1, 1);
  73.  
  74. Label lastNameLabel = new Label("Last Name:");
  75. grid.add(lastNameLabel, 0, 2);
  76.  
  77. TextField lastNameTextField = new TextField();
  78. grid.add(lastNameTextField, 1, 2);
  79.  
  80. Label firstNameLabel = new Label("First Name:");
  81. grid.add(firstNameLabel, 0, 3);
  82.  
  83. TextField firstNameTextField = new TextField();
  84. grid.add(firstNameTextField, 1, 3);
  85.  
  86. Label passwordLabel = new Label("Password:");
  87. grid.add(passwordLabel, 0, 4);
  88.  
  89. PasswordField passwordField = new PasswordField();
  90. grid.add(passwordField, 1, 4);
  91.  
  92. Button saveButton = new Button("Save");
  93. HBox hBox = new HBox(10);
  94. hBox.setAlignment(Pos.BOTTOM_RIGHT);
  95. hBox.getChildren().add(saveButton);
  96. grid.add(hBox, 1, 5);
  97.  
  98. saveButton.setOnAction(actionEvent -> {
  99. String username = usernameTextField.getText().trim();
  100. String lastName = lastNameTextField.getText().trim();
  101. String firstName = firstNameTextField.getText().trim();
  102. String password = passwordField.getText();
  103. if (!StringPool.BLANK.equals(username) && !StringPool.BLANK.equals(lastName) && !StringPool.BLANK.equals(firstName) && !StringPool.BLANK.equals(password)) {
  104. try {
  105. if (!userRepository.userExists(username)) {
  106. User user = this.createUserObject(username, lastName, firstName, password);
  107. int userId = userRepository.saveUser(user);
  108. if (userId > 0) {
  109. this.alert("Save", "Successful!", AlertType.INFORMATION);
  110. } else {
  111. this.alert("Error", "Failed!", AlertType.ERROR);
  112. }
  113. } else {
  114. this.alert("Error", "User already exists!", AlertType.ERROR);
  115. }
  116. } catch (Exception exception) {
  117. logger.log(Level.SEVERE, exception.getMessage());
  118. }
  119. } else {
  120. this.alert("Error", "Please complete fields!", AlertType.ERROR);
  121. }
  122.  
  123. });
  124.  
  125. Scene scene = new Scene(grid, 300, 275);
  126. primaryStage.setScene(scene);
  127.  
  128. primaryStage.show();
  129. }
  130.  
  131. public void alert(String title, String message, AlertType alertType) {
  132. Alert alert = new Alert(alertType);
  133. alert.setTitle(title);
  134. alert.setHeaderText(null);
  135. alert.setContentText(message);
  136.  
  137. alert.showAndWait();
  138. }
  139.  
  140. public User createUserObject(String username, String lastName, String firstName, String password) {
  141. User user = new User();
  142. user.setUsername(username);
  143. user.setLastName(lastName);
  144. user.setFirstName(firstName);
  145. user.setPassword(password);
  146.  
  147. return user;
  148. }
  149.  
  150. public static void main(String[] args) {
  151. launch(args);
  152. }
  153.  
  154. }
  155.  
  156. // Domain object
  157. class User implements Serializable {
  158.  
  159. private static final long serialVersionUID = 3789909326487155148L;
  160. private int id;
  161. private String username;
  162. private String lastName;
  163. private String firstName;
  164. private String password;
  165.  
  166. public int getId() {
  167. return id;
  168. }
  169.  
  170. public void setId(int id) {
  171. this.id = id;
  172. }
  173.  
  174. public String getUsername() {
  175. return username;
  176. }
  177.  
  178. public void setUsername(String username) {
  179. this.username = username;
  180. }
  181.  
  182. public String getLastName() {
  183. return lastName;
  184. }
  185.  
  186. public void setLastName(String lastName) {
  187. this.lastName = lastName;
  188. }
  189.  
  190. public String getFirstName() {
  191. return firstName;
  192. }
  193.  
  194. public void setFirstName(String firstName) {
  195. this.firstName = firstName;
  196. }
  197.  
  198. public String getPassword() {
  199. return password;
  200. }
  201.  
  202. public void setPassword(String password) {
  203. this.password = password;
  204. }
  205.  
  206. }
  207.  
  208. // Data access/repository
  209. class UserRepository {
  210.  
  211. private static final Logger logger = Logger.getLogger(UserRepository.class.getName());
  212.  
  213. public boolean userExists(String username) throws SQLException {
  214. Connection connection = null;
  215. PreparedStatement statement = null;
  216. List<User> users = new ArrayList<>();
  217.  
  218. try {
  219. connection = Database.getDBConnection();
  220. connection.setAutoCommit(false);
  221. String query = "SELECT id, username, last_name, first_name, password FROM user WHERE username = ?";
  222. statement = connection.prepareStatement(query);
  223. int counter = 1;
  224. statement.setString(counter++, username);
  225. ResultSet resultSet = statement.executeQuery();
  226. while (resultSet.next()){
  227. User user = new User();
  228. user.setId(resultSet.getInt(1));
  229. user.setUsername(resultSet.getString(2));
  230. user.setLastName(resultSet.getString(3));
  231. user.setFirstName(resultSet.getString(4));
  232. user.setPassword(resultSet.getString(5));
  233. users.add(user);
  234. }
  235.  
  236. return users.isEmpty() ? false : true;
  237. } catch (SQLException exception) {
  238. logger.log(Level.SEVERE, exception.getMessage());
  239. } finally {
  240. if (null != statement) {
  241. statement.close();
  242. }
  243.  
  244. if (null != connection) {
  245. connection.close();
  246. }
  247. }
  248.  
  249. return users.isEmpty() ? false : true;
  250. }
  251.  
  252. public int saveUser(User user) throws SQLException {
  253. Connection connection = null;
  254. PreparedStatement statement = null;
  255. ResultSet resultSet = null;
  256. try {
  257. connection = Database.getDBConnection();
  258. connection.setAutoCommit(false);
  259. String query = "INSERT INTO user(username, last_name, first_name, password) VALUES(?, ?, ?, ?)";
  260. statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
  261. int counter = 1;
  262. statement.setString(counter++, user.getUsername());
  263. statement.setString(counter++, user.getLastName());
  264. statement.setString(counter++, user.getFirstName());
  265. statement.setString(counter++, user.getPassword());
  266. statement.executeUpdate();
  267. connection.commit();
  268. resultSet = statement.getGeneratedKeys();
  269. if (resultSet.next()){
  270. return resultSet.getInt(1);
  271. }
  272. } catch (SQLException exception) {
  273. logger.log(Level.SEVERE, exception.getMessage());
  274. connection.rollback();
  275. } finally {
  276. if (null != resultSet) {
  277. resultSet.close();
  278. }
  279.  
  280. if (null != statement) {
  281. statement.close();
  282. }
  283.  
  284. if (null != connection) {
  285. connection.close();
  286. }
  287. }
  288.  
  289. return 0;
  290. }
  291.  
  292. }
  293.  
  294. // Database connection utility
  295. class Database {
  296.  
  297. private static final Logger logger = Logger.getLogger(Database.class.getName());
  298. private static final String DB_DRIVER = "com.mysql.cj.jdbc.Driver";
  299. private static final String DB_CONNECTION = "jdbc:mysql://localhost/javafxsample";
  300. private static final String DB_USER = "root";
  301. private static final String DB_PASSWORD = "admin";
  302.  
  303. public static Connection getDBConnection() throws SQLException {
  304. Connection connection = null;
  305.  
  306. try {
  307. Class.forName(DB_DRIVER);
  308. } catch (ClassNotFoundException exception) {
  309. logger.log(Level.SEVERE, exception.getMessage());
  310. }
  311.  
  312. try {
  313. connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
  314. return connection;
  315. } catch (SQLException exception) {
  316. logger.log(Level.SEVERE, exception.getMessage());
  317. }
  318.  
  319. return connection;
  320. }
  321.  
  322. }
  323.  
  324. // String utility
  325. class StringPool {
  326. public static final String BLANK = "";
  327. }
Add Comment
Please, Sign In to add comment