· 4 years ago · May 19, 2021, 01:24 PM
1package Beans;
2
3import java.sql.Date;
4import java.util.Calendar;
5import java.util.Objects;
6
7public class Repair implements Comparable<Repair> {
8 //fields
9 private Date readyOn; //estimated time that the drone will be ready.
10 private Date entered; //when the drone waas entered to the lab...
11 private String memo; //some data for the drone
12 private String sn; //serial number of the drone
13 private boolean importent; //VIP customer (like aviv)
14 private boolean poped; //we show the message that the drone is ready
15 private int id; //id from the DB;
16
17 //C'tor
18 public Repair(int id,Date readyOn, String memo, String sn, boolean importent, boolean poped) {
19 this.readyOn = readyOn;
20 this.memo = memo;
21 this.sn = sn;
22 this.importent = importent;
23 this.poped = poped;
24 this.entered = new Date(Calendar.getInstance().getTime().getTime()); //enter the current date time....
25 this.id=id;
26 }
27
28 public Repair() {
29 this.entered = new Date(Calendar.getInstance().getTime().getTime()); //enter the current date time....
30 }
31
32 public Date getReadyOn() {
33 return readyOn;
34 }
35
36 public void setReadyOn(Date readyOn) {
37 this.readyOn = readyOn;
38 }
39
40 public Date getEntered() {
41 return entered;
42 }
43
44 public void setEntered(Date entered) {
45 this.entered = entered;
46 }
47
48 public String getMemo() {
49 return memo;
50 }
51
52 public void setMemo(String memo) {
53 this.memo = memo;
54 }
55
56 public String getSn() {
57 return sn;
58 }
59
60 public void setSn(String sn) {
61 this.sn = sn;
62 }
63
64 public boolean isImportent() {
65 return importent;
66 }
67
68 public void setImportent(boolean importent) {
69 this.importent = importent;
70 }
71
72 public boolean isPoped() {
73 return poped;
74 }
75
76 public void setPoped(boolean poped) {
77 this.poped = poped;
78 }
79
80 //if we will use the all mighty new shiny ArrayList (List)
81 //we can not use the comperator, becuase it's only for set collection
82 //we will sort the list by time :)
83
84 @Override
85 public int compareTo(Repair o) {
86 //lets check if we have the same object
87 if (equals(o)) {
88 return 0;
89 }
90 //equals compare if the object date is before, same , after
91 // -1 0 1
92 return readyOn.compareTo(o.readyOn);
93 }
94
95 @Override
96 public boolean equals(Object o) {
97 if (this == o) return true;
98 if (o == null || getClass() != o.getClass()) return false;
99 Repair repair = (Repair) o;
100 return importent == repair.importent && poped == repair.poped && Objects.equals(readyOn, repair.readyOn) && Objects.equals(entered, repair.entered) && Objects.equals(memo, repair.memo) && Objects.equals(sn, repair.sn);
101 }
102
103 @Override
104 public int hashCode() {
105 return Objects.hash(readyOn, entered, memo, sn, importent, poped);
106 }
107
108 /*
109 @Override
110 public String toString() {
111 StringBuffer sb = new StringBuffer();
112 // eta(day/month/year hh:mm) - done
113 // memo - done
114 // s/n importent
115
116 sb.append("eta: [")
117 .append(readyOn.get(Calendar.DAY_OF_MONTH-1)+"/")
118 .append(readyOn.get(Calendar.MONTH) + "/")
119 .append(readyOn.get(Calendar.YEAR) + " ")
120 .append(readyOn.get(Calendar.HOUR) + ":")
121 .append(readyOn.get(Calendar.MINUTE))
122 .append("]\n")
123 .append(memo + "\n")
124 .append("S/N:" + sn + " VIP customer (not natan):" + importent);
125
126 return sb.toString();
127 }
128 */
129
130
131 @Override
132 public String toString() {
133 return "Repair{" +
134 "readyOn=" + readyOn +
135 ", entered=" + entered +
136 ", memo='" + memo + '\'' +
137 ", sn='" + sn + '\'' +
138 ", importent=" + importent +
139 ", poped=" + poped +
140 ", id=" + id +
141 '}';
142 }
143
144 public int getId() {
145 return id;
146 }
147
148 public void setId(int id) {
149 this.id = id;
150 }
151}
152-----------------------------------------------------------------------------------------
153package Facade;
154
155import Beans.Repair;
156import DBDAO.RepairsDB;
157import Threads.RepairScanner;
158
159import java.sql.SQLException;
160import java.util.ArrayList;
161import java.util.Calendar;
162import java.util.List;
163import java.util.Scanner;
164
165public class RepairLab {
166 //fields
167 //get input from user
168 private Scanner scanner = new Scanner(System.in);
169 //list of repairs with sort by eta time
170 private List<Repair> repairs;
171 //a thread that will use to run background service
172 //each time a drone is ready, pop up a message
173 RepairScanner repairScanner;
174
175 //Repairs DB
176 RepairsDB rdb;
177
178 //c'tor
179 public RepairLab() {
180 repairs = new ArrayList<>();
181 repairScanner = new RepairScanner(repairs);
182 //start the task
183 new Thread(repairScanner).start();
184 //open connection to DB
185 rdb = new RepairsDB();
186 //run the menu...
187 repairMenu();
188
189 }
190
191 private void repairMenu() {
192 int choice=0; //1 create , 2 view, 3 quit
193 do{
194 System.out.println("REPAIR MENU (1-3)");
195 System.out.println("-----------------");
196 System.out.println("1 - Create a new repair");
197 System.out.println("2 - View Repairs");
198 System.out.println("3 - quit");
199 choice = scanner.nextInt();
200 switch (choice){
201 case 1:
202 handleNewRepair();
203 break;
204
205 case 2:
206 handleRepairList();
207 break;
208
209 case 3:
210 handleEndProgram();
211 break;
212
213 default:
214 System.out.println("Wrong choice");
215 }
216 } while (choice!=3);
217 }
218
219 private void handleNewRepair() {
220 System.out.println("\nCreate a new repair (ETA):\n-----------------------");
221 //enter date tmie for ready on (eta for fix)
222 System.out.println("enter a day of month:");
223 int day = scanner.nextInt();
224 System.out.println("enter month:");
225 int month = scanner.nextInt();
226 System.out.println("enter year:");
227 int year=scanner.nextInt();
228 System.out.println("enter hours (0-23):");
229 int hour = scanner.nextInt();
230 System.out.println("enter monutes (0-59):");
231 int minutes = scanner.nextInt();
232 System.out.println("enter memo:");
233 scanner.nextLine(); //clean the buffer
234 String memo = scanner.nextLine();
235 System.out.println("Enter S/N:");
236 String sn = scanner.nextLine();
237 System.out.println("Set as important ? (y/n)");
238 char c = scanner.next().charAt(0);
239 boolean importent = (c == 'Y' || c== 'y');
240
241 //handle ready on set the estimated date of fix to user input date
242 Calendar readyOn = Calendar.getInstance();
243 readyOn.set(Calendar.DAY_OF_MONTH,day);
244 readyOn.set(Calendar.MONTH,month);
245 readyOn.set(Calendar.YEAR,year);
246 readyOn.set(Calendar.HOUR,hour);
247 readyOn.set(Calendar.MINUTE,minutes);
248
249 //Repair repair = new Repair(readyOn,memo,sn,importent,false);
250
251 //local
252 //repairs.add(repair);
253
254 //SQL
255 }
256
257 private void handleRepairList() {
258 /*
259 //junior
260 for (Repair item:repairs){
261 System.out.println(item);
262 }
263
264 */
265
266 //senios - LIKE A BOSS
267 repairs.forEach(System.out::println);
268 }
269
270 private void handleEndProgram() {
271 SQL.ConnectionPool cp = null;
272 try {
273 /*
274 cp = SQL.ConnectionPool.getInstance();
275 cp.closeAllConnection();
276 */
277
278 //Like a BOSS
279 SQL.ConnectionPool.getInstance().closeAllConnection();
280
281 } catch (SQLException | InterruptedException throwables) {
282 throwables.printStackTrace();
283 }
284
285 System.out.println("Chao Bella !!!!");
286 System.exit(200);
287
288 }
289
290
291 //method
292
293}
294
295------------------------------------------------------------------------------------------
296package Threads;
297
298import Beans.Repair;
299import Utils.ArtUtils;
300
301import java.util.Calendar;
302import java.util.List;
303
304public class RepairScanner implements Runnable {
305
306 private List<Repair> repairs;
307
308 public RepairScanner(List<Repair> repairs) {
309 this.repairs = repairs;
310 }
311
312 @Override
313 public void run() {
314 //thread sleep -> 1 minute
315 while (true) {
316 //iterate on entire collection
317 for (Repair item:repairs){
318 //first of all, did the repair was already shown (popped)
319 if (!item.isPoped()){
320 // 01/01/2020 01/01/2021
321 /*
322 if (item.getReadyOn().before(Calendar.getInstance())){
323 //print the drone info, it is ready
324 System.out.println(item);
325 // set popped to true, because we have already popped the info
326 item.setPoped(true);
327 //check if we have a VIP person (not natan)
328 if (item.isImportent()){
329 //thread !!!!!!!!!!!!!!!!!!!!!
330 //anonymous thread
331 new Thread(new Runnable() {
332 @Override
333 public void run() {
334 try {
335 Thread.sleep(30*1000);
336 System.out.println(ArtUtils.vip);
337 System.out.println(item);
338 Thread.sleep(30*1000);
339 System.out.println(ArtUtils.vip);
340 System.out.println(item);
341 } catch (InterruptedException e) {
342 e.printStackTrace();
343 }
344 }
345 }).start();
346 }
347 }*/
348 }
349 }
350
351 try {
352 Thread.sleep(60 * 1000);
353 } catch (InterruptedException err) {
354 System.out.println("Repair scanner has been stopped");
355 }
356 }
357 }
358}
359
360------------------------------------------------------------------------------------------
361
362package SQL;
363
364import java.sql.Connection;
365import java.sql.DriverManager;
366import java.sql.SQLException;
367import java.util.Stack;
368
369/**
370 * connection pool class
371 */
372public class ConnectionPool {
373 //File->Project Structure->Libraries -> + -> from maven ...
374 //mysql:mysql-connector-java:jar:8.0.25
375 /**
376 * connection pool instance
377 */
378 private static ConnectionPool instance = null;
379 /**
380 maximum connection
381 */
382 public static final int NUM_OF_CONNECTION = 10;
383 /**
384 * stack of connection
385 */
386 private Stack<Connection> connections = new Stack<>();
387
388 //fields
389
390 //cto'r
391
392 /**
393 * Constructor for creating instance of class (SingleTon)
394 * @throws SQLException if we have an exception regarding SQL
395 */
396 private ConnectionPool() throws SQLException {
397 //open all connections
398 openAllConnections();
399 }
400
401 /**
402 * get instance of connection pool (SingleTon)
403 * @return a connection to mySQL database
404 * @throws SQLException throws SQL exception
405 */
406 public static ConnectionPool getInstance() throws SQLException {
407 if (instance == null) {
408 synchronized (ConnectionPool.class) {
409 //double check
410 if (instance == null){
411 instance = new ConnectionPool();
412 }
413 }
414 }
415 return instance;
416 }
417
418 /**
419 * open all connection to data base
420 * @throws SQLException exception handler for SQL exceptions
421 */
422 public void openAllConnections() throws SQLException {
423 for (int index=0;index < NUM_OF_CONNECTION;index+=1){
424 //DATABASE credentials
425 Connection connection = DriverManager.getConnection(DataBaseManager.URL,DataBaseManager.USER_NAME,DataBaseManager.PASSWORD);
426 connections.push(connection);
427 }
428 }
429
430 /**
431 * get a single connection
432 * @return a connection to the database
433 * @throws InterruptedException throws interrupt exception
434 */
435 public Connection getConnection() throws InterruptedException {
436 synchronized (connections){
437 //check if the stack is empty
438 if (connections.isEmpty()){
439 //wait until we will get a connection back
440 connections.wait();
441 }
442 return connections.pop();
443 }
444 }
445
446 /**
447 * return a connection from user
448 * @param connection get an existing connection
449 */
450 public void returnConnection(Connection connection){
451 synchronized (connections){
452 connections.push(connection);
453 //notify that we got back a connection from the user...
454 //notify all connections that are waiting to connection to be release..
455 connections.notify();
456 }
457 }
458
459 /**
460 * close all connections
461 * @throws InterruptedException handle stop of thread
462 */
463 public void closeAllConnection() throws InterruptedException {
464 synchronized (connections){
465 while (connections.size()<NUM_OF_CONNECTION){
466 connections.wait();
467 }
468 connections.removeAllElements();
469 }
470 }
471}
472
473------------------------------------------------------------------------------------------
474package SQL;
475
476import java.sql.SQLException;
477
478public class DataBaseManager {
479 //connection DB
480 public static final String URL="jdbc:mysql://localhost:3306?createDatabaseIfNotExist=FALSE";
481 public static final String USER_NAME="root";
482 public static final String PASSWORD="12345678";
483
484 //create & drop database
485 private static final String CREATE_DB="CREATE SCHEMA if not exists droneLab";
486 private static final String DROP_DB="DROP droneLab";
487
488 //create & drop tables
489 private static final String CREATE_TABLE="CREATE TABLE if not exists `droneLab`.`repairs` " +
490 "(`id` INT NOT NULL AUTO_INCREMENT," +
491 "`memo` VARCHAR(150) NOT NULL," +
492 "`sn` VARCHAR(50) NOT NULL," +
493 "`entered` DATE NOT NULL," +
494 "`readyOn` DATE NOT NULL," +
495 "`isImportant` BOOLEAN NOT NULL," +
496 "`isPoped` BOOLEAN NOT NULL," +
497 "PRIMARY KEY (`id`));";
498
499 public static void createDataBase(){
500 try {
501 DButils.runQuery(CREATE_DB);
502 } catch (SQLException throwables) {
503 throwables.printStackTrace();
504 }
505 }
506
507 public static void createTables(){
508 try {
509 DButils.runQuery(CREATE_TABLE);
510 } catch (SQLException throwables) {
511 throwables.printStackTrace();
512 }
513 }
514}
515
516------------------------------------------------------------------------------------------
517package SQL;
518
519import java.sql.Connection;
520import java.sql.PreparedStatement;
521import java.sql.SQLException;
522
523public class DButils {
524 public static void runQuery(String sql) throws SQLException {
525 Connection connection = null;
526 try {
527 //take a connection for connection pool.
528 connection = ConnectionPool.getInstance().getConnection();
529 //run the sql command
530 PreparedStatement statement = connection.prepareStatement(sql);
531 statement.execute();
532 } catch (InterruptedException | SQLException e) {
533 e.printStackTrace();
534 } finally {
535 ConnectionPool.getInstance().returnConnection(connection);
536 }
537 }
538}
539
540------------------------------------------------------------------------------------------
541package DAO;
542
543import Beans.Repair;
544
545import java.sql.SQLException;
546import java.util.List;
547import java.util.Set;
548
549public interface Dao {
550 //add a new repair to DB
551 Boolean addRepair(Repair repair) throws SQLException;
552 //get list of repairs as list collection
553 List<Repair> getRepairList();
554 //get a list of repairs as Set collection
555 Set<Repair> getRepairSet();
556}
557----------------------------------------------------------------------------------
558
559package DBDAO;
560
561import Beans.Repair;
562import DAO.Dao;
563import SQL.ConnectionPool;
564
565import java.sql.*;
566import java.util.ArrayList;
567import java.util.List;
568import java.util.Set;
569
570public class RepairsDB implements Dao {
571 /*
572 ███████╗ ██████╗ ██╗
573 ██╔════╝██╔═══██╗██║
574 ███████╗██║ ██║██║
575 ╚════██║██║▄▄ ██║██║
576 ███████║╚██████╔╝███████╗
577 ╚══════╝ ╚══▀▀═╝ ╚══════╝
578 */
579
580 private static final String ADD_REPAIR = "INSERT INTO `droneLab`.`repairs` (`memo`,`sn`,`entered`,`readyOn`, `isImportant`, `isPoped`) VALUES (?,?,?,?,?,?)";
581 private static final String UPDATE_REPAIR = "UPDATE `droneLab`.`repairs` set memo=?, readyOn=?, isImportant=?, isPoped=? WHERE id=?";
582 private static final String GET_ONE_REPAIR_BY_ID = "SELECT * FROM `droneLab`.`repairs` WHERE id=?";
583 private static final String GET_ALL_REPAIR_BY_SN = "";
584 private static final String GET_ALL_REPAIR = "SELECT * FROM `droneLab`.`repairs`";
585 private static final String DELETE_BY_ID = "DELETE FROM `droneLab`.`repairs` where id=?";
586 //connection to the data base
587 Connection connection;
588
589 public RepairsDB() {
590 try {
591 ConnectionPool.getInstance();
592 } catch (SQLException throwables) {
593 throwables.printStackTrace();
594 }
595 }
596
597 @Override
598 public Boolean addRepair(Repair repair) throws SQLException {
599 try {
600 //get connection to the database
601 connection = ConnectionPool.getInstance().getConnection();
602
603 //create a prepared sql statement
604 PreparedStatement statement = connection.prepareStatement(ADD_REPAIR);
605 statement.setString(1, repair.getMemo());
606 statement.setString(2, repair.getSn());
607 statement.setDate(3, repair.getEntered());
608 statement.setDate(4, repair.getReadyOn());
609 statement.setBoolean(5, repair.isImportent());
610 statement.setBoolean(6, repair.isPoped());
611 statement.execute();
612 return true;
613 } catch (InterruptedException | SQLException e) {
614 return false;
615 } finally {
616 ConnectionPool.getInstance().returnConnection(connection);
617 }
618 }
619
620 public boolean updateDrone(Repair repair) throws SQLException {
621 try {
622 //get connection to the database
623 connection = ConnectionPool.getInstance().getConnection();
624
625 //create a prepared sql statement
626 PreparedStatement statement = connection.prepareStatement(ADD_REPAIR);
627 statement.setString(1, repair.getMemo());
628 statement.setDate(2, repair.getReadyOn());
629 statement.setBoolean(3, repair.isImportent());
630 statement.setBoolean(4, repair.isPoped());
631 statement.setInt(5, repair.getId());
632 statement.execute();
633 return true;
634 } catch (InterruptedException | SQLException e) {
635 return false;
636 } finally {
637 ConnectionPool.getInstance().returnConnection(connection);
638 }
639 }
640
641 @Override
642 public List<Repair> getRepairList() {
643 List<Repair> repairs = new ArrayList<>();
644
645 try {
646 connection = ConnectionPool.getInstance().getConnection();
647 PreparedStatement statement = connection.prepareStatement(GET_ALL_REPAIR);
648 ResultSet resultSet = statement.executeQuery();
649 while (resultSet.next()) {
650 Repair repair = new Repair(resultSet.getInt(1), resultSet.getDate(5), resultSet.getString(2), resultSet.getString(3), resultSet.getBoolean(6), resultSet.getBoolean(7));
651 //System.out.println(repair);
652 repairs.add(repair);
653 }
654 } catch (InterruptedException e) {
655 e.printStackTrace();
656 } catch (SQLException throwables) {
657 throwables.printStackTrace();
658 }
659 return repairs;
660 }
661
662 public Repair getSingleById(int id) {
663 Repair repair = null;
664 try {
665 connection = ConnectionPool.getInstance().getConnection();
666 PreparedStatement statement = connection.prepareStatement(GET_ONE_REPAIR_BY_ID);
667 statement.setInt(1,id); //where id = ? => select * from repair where id = 1
668 ResultSet resultSet = statement.executeQuery();
669 while (resultSet.next()) {
670 repair = new Repair(resultSet.getInt("id"), resultSet.getDate("entered"), resultSet.getString("memo"), resultSet.getString("sn"), resultSet.getBoolean("isImportant"), resultSet.getBoolean("isPoped"));
671 }
672 } catch (InterruptedException e) {
673 e.printStackTrace();
674 } catch (SQLException throwables) {
675 throwables.printStackTrace();
676 }
677 return repair;
678 }
679
680 public void deleteRepairById(int id){
681 try {
682 connection = ConnectionPool.getInstance().getConnection();
683 PreparedStatement statement = connection.prepareStatement(DELETE_BY_ID);
684 statement.setInt(1,id);
685 statement.execute();
686 } catch (InterruptedException e) {
687 e.printStackTrace();
688 } catch (SQLException throwables) {
689 throwables.printStackTrace();
690 }
691
692 }
693
694 @Override
695 public Set<Repair> getRepairSet() {
696 return null;
697 }
698
699
700}
701--------------------------------------------------------------------------------------------------
702package Utils;
703
704public class ArtUtils {
705 public static final String vip= "" +
706 "██╗ ██╗██╗██████╗ \n" +
707 "██║ ██║██║██╔══██╗\n" +
708 "██║ ██║██║██████╔╝\n" +
709 "╚██╗ ██╔╝██║██╔═══╝ \n" +
710 " ╚████╔╝ ██║██║ \n" +
711 " ╚═══╝ ╚═╝╚═╝ \n" +
712 " not Natan ";
713
714 public static final String finished = "" +
715 "███████╗██╗███╗ ██╗██╗███████╗██╗ ██╗███████╗██████╗ \n" +
716 "██╔════╝██║████╗ ██║██║██╔════╝██║ ██║██╔════╝██╔══██╗\n" +
717 "█████╗ ██║██╔██╗ ██║██║███████╗███████║█████╗ ██║ ██║\n" +
718 "██╔══╝ ██║██║╚██╗██║██║╚════██║██╔══██║██╔══╝ ██║ ██║\n" +
719 "██║ ██║██║ ╚████║██║███████║██║ ██║███████╗██████╔╝\n" +
720 "╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ \n" +
721 " ";
722}
723
724--------------------------------------------------------------------------------------------------
725package Tester;
726
727import Beans.Repair;
728import Facade.RepairLab;
729
730public class MyTest {
731 public static void main(String[] args) {
732 new RepairLab();
733 }
734}
735----------------------------------------------------------------------------------------------
736package Tester;
737
738import Beans.Repair;
739import DBDAO.RepairsDB;
740import SQL.ConnectionPool;
741import SQL.DataBaseManager;
742import Utils.ArtUtils;
743
744import java.sql.Date;
745import java.sql.SQLException;
746import java.util.List;
747
748public class DBtest {
749 public static void main(String[] args) throws SQLException {
750 // ConnectionPool.getInstance().openAllConnections();
751 // DataBaseManager.createDataBase();
752 // DataBaseManager.createTables();
753
754
755
756 RepairsDB rdb = new RepairsDB();
757 /*
758 Repair repair = new Repair();
759 repair.setPoped(false);
760 repair.setEntered(Date.valueOf("2021-05-12"));
761 repair.setImportent(false);
762 repair.setSn("34534");
763 repair.setMemo("broken body");
764 repair.setReadyOn(Date.valueOf("2021-06-09"));
765
766 rdb.addRepair(repair);
767 */
768
769 /*
770 List<Repair> repairs = rdb.getRepairList();
771 repairs.forEach(System.out::println); // LIKE A BOSS
772
773 */
774
775 //Repair repair = rdb.getSingleById(3);
776 //System.out.println(repair);
777
778 rdb.deleteRepairById(3);
779 List<Repair> repairs = rdb.getRepairList();
780 repairs.forEach(System.out::println); // LIKE A BOSS
781
782
783
784 System.out.println(ArtUtils.finished);
785 }
786}
787