· 4 years ago · Jul 22, 2021, 05:40 PM
1package com.company;
2
3import com.company.DBConnector;
4import com.company.LoginScreen;
5
6import java.util.Scanner;
7
8public class Main {
9 public static void main(String[] args) {
10 Scanner sc = new Scanner(System.in);
11 DBConnector dbc = new DBConnector("jdbc:mysql://192.168.0.116:3306",
12 "martin",
13 "password");
14
15 dbc.createDB();
16 LoginScreen loginScreen = new LoginScreen();
17 }
18}
19
20package com.company;
21
22import java.sql.*;
23import java.util.*;
24
25public class DBConnector {
26 /**
27 * Fields
28 */
29
30
31 /**
32 * jdbcURL resets every time!!!
33 */
34 private static String jdbcURL; //"jdbc:mysql://192.168.0.116:3306"
35 private static String user; //"martin"
36 private static String password; //"password"
37 private static Connection connection = null;
38
39 private Scanner sc = new Scanner(System.in);
40 private static boolean hasConnected = false;
41 private static String tableName = null; //"projectDB.accounts"
42 private static StringBuilder sql = new StringBuilder();
43
44 private static Statement statement;
45 private static ResultSet result;
46 private static PreparedStatement preparedStatement;
47
48
49 /**
50 * Getting all accounts from the DB
51 */
52 private static Map<String, String> accounts = new HashMap<>();
53
54
55 /**
56 * Constructor
57 */
58 public DBConnector(String jdbcURL, String user, String password) {
59 this.jdbcURL = jdbcURL;
60 this.user = user;
61 this.password = password;
62 }
63
64
65 /**
66 * Constructor Chaining
67 */
68 public DBConnector(String jdbcURL, String user, String password, String tableName) {
69 //constructor chaining...
70 this.tableName = tableName;
71 }
72
73
74 /**
75 * Getter for the HashMap
76 */
77 public static Map<String, String> getMap() {
78 return accounts;
79 }
80
81
82 /**
83 * Connect to DB server
84 */
85 private static void connect() {
86 try {
87 Class.forName("com.mysql.cj.jdbc.Driver");
88 connection = DriverManager.getConnection(jdbcURL, user, password);
89
90 if (connection != null) {
91 System.out.println("Successfully connected to MySQL database test.");
92 hasConnected = true;
93 }
94 } catch (SQLException | ClassNotFoundException ex) {
95 System.out.println("An error occurred while connecting MySQL database.");
96 ex.printStackTrace();
97 }
98 }
99
100
101 /**
102 * Create DB if table with the tableName name doesn't exists
103 */
104 public void createDB() {
105 if (hasConnected) {
106 try {
107 if (tableName == null) {
108 setTableName();
109 }
110 resetLengthOfSQL(sql);
111
112 sql.append("CREATE DATABASE IF NOT EXISTS ").append(tableName.split("[.]")[0]); //.append(tableName);
113// .append(tableName);//"test.test_table"
114 statement = connection.createStatement();
115
116 statement.execute(String.valueOf(sql));
117
118 fillMap();
119 } catch (SQLException e) { //SQLSyntaxErrorException
120 System.out.println("Database creation failed.");
121 e.printStackTrace();
122 }
123 } else {
124 connect();
125 createDB();
126 }
127 }
128
129
130 /**
131 * Set the table name of the DB (custom name) / can be removed
132 */
133 private static void setTableName() {
134// System.out.println("Please type down your Database name:");
135// tableName = sc.nextLine();
136
137 tableName = "default";
138 if (tableName.equals("Default".toLowerCase())) {
139 tableName = "projectDB.accounts";
140 }
141 }
142
143
144 /**
145 * SQL string re-setter
146 */
147 private static void resetLengthOfSQL(StringBuilder sql) {
148 sql.setLength(0);
149 }
150
151
152 /**
153 * Fill the HashMap with DB data
154 */
155 public void fillMap() {
156 if (hasConnected) {
157 resetLengthOfSQL(sql);
158// resetMap();
159
160 sql.append("SELECT * FROM ").append(tableName);
161 try {
162 statement = connection.createStatement();
163 result = statement.executeQuery(String.valueOf(sql));
164 while (result.next()) {
165// int id = result.getInt("id");
166// String first_name = result.getString("first_name");
167// String last_name = result.getString("last_name");
168 String username = result.getString("username");
169 String password = result.getString("password");
170
171 accounts.put(username, password);
172 }
173 } catch (SQLException e) {
174 e.printStackTrace();
175 }
176 } else {
177 connect();
178 fillMap();
179 }
180 }
181
182
183 /**
184 * Reset the map
185 */
186 private void resetMap() {
187 accounts.clear();
188 }
189
190
191 /**
192 * Register account / add to DB user and have them to login after registering
193 */
194 protected static void registerUser(String... str) {
195 if (hasConnected) {
196 if (tableName == null) {
197 setTableName();
198 }
199
200 String id = getID();
201 resetLengthOfSQL(sql);
202
203 sql.append("INSERT INTO ")
204 .append(tableName)
205 .append(" VALUES (")
206 .append(id)
207 .append(", ?, ?, ?, ?, ?)"); //DEFAULT | id + 1 -> method to find the gap
208 try {
209 preparedStatement = connection.prepareStatement(sql.toString());
210 preparedStatement.setString(1, str[0]); //first_name
211 preparedStatement.setString(2, str[1]); //last_name
212 preparedStatement.setString(3, str[2]); //username
213 preparedStatement.setString(4, str[3]); //password
214 preparedStatement.setString(5, "no"); //admin
215
216 preparedStatement.execute();
217 accounts.put(str[2], str[3]);
218 System.out.println("User Registered Successfully!");
219 } catch (SQLException e) {
220 e.printStackTrace();
221 }
222 } else {
223 connect();
224 registerUser(str);
225 }
226 }
227
228
229 /**
230 * Get ID based on the gap (When account is removed - ID is skipped)
231 */
232
233 private static String getID() {
234 resetLengthOfSQL(sql);
235
236 List<Integer> IDs = new ArrayList<Integer>();
237 try {
238 sql.append("SELECT id FROM ").append(tableName);
239 statement = connection.createStatement();
240 result = statement.executeQuery(String.valueOf(sql));
241
242 while (result.next()) {
243 int id = result.getInt("id");
244 IDs.add(id);
245 }
246 } catch (SQLException e) {
247 e.printStackTrace();
248 }
249
250 if(IDs.size() > 1) {
251 for (int i = 0; i < IDs.size() - 1; i++) {
252 if (IDs.get(i) + 1 != IDs.get(i + 1)) {
253 return String.valueOf(IDs.get(i) + 1);
254 }
255 }
256 }
257 return "DEFAULT";
258 }
259
260
261 /**
262 * Insert a row in DB
263 */
264// protected static void insertData(String... data) {
265//
266// }
267
268
269 /**
270 * Delete ALL DATA in DB
271 */
272 public void resetDB() { //clear the DB
273
274 }
275
276
277 /**
278 * Modify to get specific data (first / last name | username / password | everything)
279 */
280 public void getData() {
281 if (hasConnected) {
282 try {
283 statement = connection.createStatement();
284 resetLengthOfSQL(sql);
285
286 if (tableName == null) {
287 setTableName();
288 }
289
290 sql.append("SELECT * FROM ").append(tableName);
291
292 result = statement.executeQuery(sql.toString());
293 while ((result.next())) {
294 System.out.println(result.getString("first_name") + " " + result.getString("last_name"));
295 }
296 } catch (SQLException e) {
297 System.out.println("An error occurred while getting data from the MySQL database.");
298 e.printStackTrace();
299 }
300 } else {
301 connect();
302 getData();
303 }
304 }
305}
306
307
308package com.company;
309
310import com.company.DBConnector;
311
312import javax.swing.*;
313import java.awt.*;
314import java.awt.event.ActionEvent;
315import java.awt.event.ActionListener;
316import java.awt.event.MouseAdapter;
317import java.awt.event.MouseEvent;
318import java.util.Map;
319
320public class LoginScreen implements ActionListener {
321
322 /**
323 * Fields
324 */
325 private JButton button;
326 private JFrame frame;
327 private JPanel panel;
328 private JLabel usernameLabel;
329 private JLabel passwordLabel;
330 private JLabel hyperlink;
331 private JTextField userText;
332 private JPasswordField passwordText;
333
334 Map<String, String> accounts = DBConnector.getMap();
335
336 public LoginScreen() {
337 frame = new JFrame();
338 panel = new JPanel();
339
340 /**Frame setting*/
341 frame.setSize(350, 200);
342 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
343 frame.setTitle("User Verification");
344 frame.add(panel, BorderLayout.CENTER);
345
346 panel.setLayout(null);
347
348 /**Username Label*/
349 usernameLabel = new JLabel("Username:");
350 usernameLabel.setBounds(10, 20, 80, 25);
351 panel.add(usernameLabel);
352
353 /**Password Label*/
354 passwordLabel = new JLabel("Password:");
355 passwordLabel.setBounds(10, 50, 80, 25);
356 panel.add(passwordLabel);
357
358 /**Username Text Box*/
359 userText = new JTextField();
360 userText.setBounds(100, 20, 170, 25);
361 panel.add(userText);
362
363 /**Password Text Box*/
364 passwordText = new JPasswordField();
365 passwordText.setBounds(100, 50, 170, 25);
366 panel.add(passwordText);
367
368 /**Hyperlink text - Register*/
369 hyperlink = new JLabel("Don't have an account? Register here.");
370 hyperlink.setBounds(75, 115, 265, 25);
371 hyperlink.setForeground(Color.BLUE.darker());
372 hyperlink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
373 hyperlink.addMouseListener(new MouseAdapter() {
374 @Override
375 /**Open the register screen and close the login window*/
376 public void mouseClicked(MouseEvent e) {
377 frame.setVisible(false);
378 RegisterScreen registerScreen = new RegisterScreen();
379 }
380 });
381 panel.add(hyperlink);
382
383 /**Button*/
384 button = new JButton("Login");
385 button.setBounds(145, 80, 80, 25);
386 button.addActionListener(this);
387 panel.add(button);
388
389 frame.setVisible(true);
390 }
391
392
393 @Override
394 public void actionPerformed(ActionEvent e) {
395 String username = userText.getText();
396 String password = passwordText.getText();
397
398 /**FillMap*/
399
400 boolean isValidAccount = false;
401 String usernameMap, passwordMap;
402 for(int i = 0; i < accounts.size(); i++){
403 usernameMap = accounts.keySet().toArray()[i].toString();
404 passwordMap = accounts.values().toArray()[i].toString();
405 if(username.equals(usernameMap) && password.equals(passwordMap)){
406 System.out.println("Successfully logged in!");
407 isValidAccount = true;
408
409 ToDoListScreen toDoListScreen = new ToDoListScreen();
410 frame.setVisible(false);
411 break;
412 }
413 }
414 if(!isValidAccount){
415 System.out.println("Incorrect Username or Password.");
416 }
417 }
418}
419
420package com.company;
421
422import com.company.DBConnector;
423import com.company.LoginScreen;
424
425import javax.swing.*;
426import java.awt.*;
427import java.awt.event.ActionEvent;
428import java.awt.event.ActionListener;
429
430
431public class RegisterScreen implements ActionListener {
432
433 /**
434 * Fields
435 */
436 private JButton button;
437 private JFrame frame;
438 private JPanel panel;
439 private JLabel first_nameLabel;
440 private JLabel last_nameLabel;
441 private JLabel usernameLabel;
442 private JLabel passwordLabel;
443 private JLabel hyperlink;
444 private JTextField first_nameText;
445 private JTextField last_nameText;
446 private JTextField userText;
447 private JPasswordField passwordText;
448 private Checkbox checkbox;
449
450 public RegisterScreen() {
451 frame = new JFrame();
452 panel = new JPanel();
453
454 /**Frame setting*/
455 frame.setSize(350, 300);
456 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
457 frame.setTitle("Registration Window");
458 frame.add(panel, BorderLayout.CENTER);
459
460 panel.setLayout(null);
461
462 //20, 50, 80, 110
463 /**First_name Label*/
464 first_nameLabel = new JLabel("First Name:");
465 first_nameLabel.setBounds(10, 20, 80, 25);
466 panel.add(first_nameLabel);
467
468 /**First_name Label*/
469 last_nameLabel = new JLabel("Last Name:");
470 last_nameLabel.setBounds(10, 50, 80, 25);
471 panel.add(last_nameLabel);
472
473 /**Username Label*/
474 usernameLabel = new JLabel("Username:");
475 usernameLabel.setBounds(10, 80, 80, 25);
476 panel.add(usernameLabel);
477
478 /**Password Label*/
479 passwordLabel = new JLabel("Password:");
480 passwordLabel.setBounds(10, 110, 80, 25);
481 panel.add(passwordLabel);
482
483 /**First_name Text Box*/
484 first_nameText = new JTextField();
485 first_nameText.setBounds(100, 20, 170, 25);
486 panel.add(first_nameText);
487
488 /**Last_name Text Box*/
489 last_nameText = new JTextField();
490 last_nameText.setBounds(100, 50, 170, 25);
491 panel.add(last_nameText);
492
493 /**Username Text Box*/
494 userText = new JTextField();
495 userText.setBounds(100, 80, 170, 25);
496 panel.add(userText);
497
498 /**Password Text Box*/
499 passwordText = new JPasswordField();
500 passwordText.setBounds(100, 110, 170, 25);
501 panel.add(passwordText);
502
503// /**Checkbox*/
504// checkbox = new Checkbox();
505// checkbox.setBounds(100, 130, 170, 25);
506// checkbox.setSize(30, 30);
507// panel.add(checkbox);
508
509 /**Button*/
510 button = new JButton("Register");
511 button.setBounds(125, 170, 120, 25);
512 button.addActionListener(this);
513 panel.add(button);
514
515 /**Fill the map with accounts*/
516 //auto filled
517 frame.setVisible(true);
518 }
519
520 /**
521 * When button is clicked
522 */
523 @Override
524 public void actionPerformed(ActionEvent e) {
525 String first_name = first_nameText.getText();
526 String last_name = last_nameText.getText();
527 String username = userText.getText();
528 String password = passwordText.getText();
529
530 boolean isValidAccount = checkIfAccountIsValid(first_name, last_name, username, password);
531
532 if (!isValidAccount) {
533 System.out.println("Incorrect Data. Please try again. Check for Typos.");
534 } else {
535 /**Put account into DB*/
536 DBConnector.registerUser(first_name, last_name, username, password);
537
538 /**Close the window and re-open the login screen*/
539 frame.setVisible(false);
540 LoginScreen loginScreen = new LoginScreen();
541 }
542 }
543
544 /**
545 * Check for valid input
546 */
547 private boolean checkIfAccountIsValid(String first_name, String last_name, String username, String password) {
548 if (!first_name.isEmpty() && !last_name.isEmpty() && !username.isEmpty() && checkIfPasswordIsValid(password)) {
549 System.out.println("Account is valid.");
550 return true;
551 }
552 return false;
553 }
554
555
556 /**
557 * Password Validators
558 */
559
560 /**
561 * Valid password -> >= 7 length, 1 digit, 1 upperCase letter.
562 */
563 private boolean checkIfPasswordIsValid(String password) {
564 if (checkLength(password) && hasDigits(password) && hasUpperCaseLetter(password)) {
565 System.out.println("Password is valid.");
566 return true;
567 }
568 return false;
569 }
570
571 private boolean checkLength(String text) {
572 if (text.length() >= 7) {
573 return true;
574 }
575 System.out.println("Password length is less than 7 characters!");
576 return false;
577 }
578
579 private boolean hasUpperCaseLetter(String text) {
580 for (int i = 0; i < text.length(); i++) {
581 if (Character.isUpperCase(text.charAt(i))) {
582 return true;
583 }
584 }
585 System.out.println("Password missing an upper case letter!");
586 return false;
587 }
588
589 private boolean hasDigits(String text) {
590 for (int i = 0; i < text.length(); i++) {
591 if (Character.isDigit(text.charAt(i))) {
592 return true;
593 }
594 }
595 System.out.println("Password missing a number!");
596 return false;
597 }
598}
599
600package com.company;
601
602public class ToDoListScreen {
603
604}
605
606
607import jdk.swing.interop.SwingInterOpUtils;
608
609import java.util.*;
610
611class Scratch {
612 public static void main(String[] args) {
613 Map<String, String> accounts = new HashMap<>();
614 Thread th = new Thread();
615
616 accounts.put("username", "password");
617 accounts.put("mrBeast", "youtube");
618 accounts.put("destroyerOfPu$$y123", "s3x");
619 accounts.put("martin_koleff", "parolawe");
620 accounts.put("Boyko_Tikvata", "gerber");
621
622// Set passwords = accounts.keySet();
623// Collection<String> userNames = accounts.values();
624 //Collections.singleton(accounts.values());
625
626 int counter = 0;
627 for(int i = 0; i < accounts.size(); i++){
628 System.out.println(accounts.keySet().toArray()[i] + " " + accounts.values().toArray()[i]);
629 }
630
631// for(Object username : userNames){
632// System.out.println(username);
633// }
634 }
635}
636