From fa8e146018790455784ceb18c1ddb6b6596d47ca Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 26 Apr 2024 01:49:30 +0330 Subject: [PATCH 01/61] add book class to project --- Answers/Add Your Projects Here.txt | 0 Answers/src/Book.java | 55 ++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) delete mode 100644 Answers/Add Your Projects Here.txt create mode 100644 Answers/src/Book.java diff --git a/Answers/Add Your Projects Here.txt b/Answers/Add Your Projects Here.txt deleted file mode 100644 index e69de29..0000000 diff --git a/Answers/src/Book.java b/Answers/src/Book.java new file mode 100644 index 0000000..d19dbf3 --- /dev/null +++ b/Answers/src/Book.java @@ -0,0 +1,55 @@ +// this class simulate books in the library +import java.util.UUID; // to generate the unique ID for books + +public class Book { + private String title; + private String author; + private String description; + // unique id is based on the title of the book + private String uniqueBookID = UUID.nameUUIDFromBytes(title.getBytes()).toString(); + public boolean availabilityStatus = true; + + // two arguments constructor + public Book(String title, String author) { + this.title = title; + this.author = author; + } + + // three arguments constructor + public Book(String title, String author, String description) { + this.title = title; + this.author = author; + this.description = description; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + + // the unique id should change + uniqueBookID = UUID.nameUUIDFromBytes(this.title.getBytes()).toString(); + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getUniqueBookID() { + return uniqueBookID; + } +} From 069d11ca64eecbabb853cc4468367c7ce39aa379 Mon Sep 17 00:00:00 2001 From: Hossein Date: Tue, 30 Apr 2024 10:27:16 +0330 Subject: [PATCH 02/61] some changes in algorithm of generate code --- Answers/src/Book.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/Answers/src/Book.java b/Answers/src/Book.java index d19dbf3..ce6bdca 100644 --- a/Answers/src/Book.java +++ b/Answers/src/Book.java @@ -1,18 +1,20 @@ -// this class simulate books in the library +""// this class simulates books in the library import java.util.UUID; // to generate the unique ID for books public class Book { private String title; private String author; private String description; - // unique id is based on the title of the book - private String uniqueBookID = UUID.nameUUIDFromBytes(title.getBytes()).toString(); + // unique id is based on the title and auther of the book + private String uniqueBookID; public boolean availabilityStatus = true; // two arguments constructor public Book(String title, String author) { this.title = title; this.author = author; + this.uniqueBookID = UUID.nameUUIDFromBytes( + String.format(title + author).getBytes()).toString(); } // three arguments constructor @@ -30,7 +32,8 @@ public void setTitle(String title) { this.title = title; // the unique id should change - uniqueBookID = UUID.nameUUIDFromBytes(this.title.getBytes()).toString(); + uniqueBookID = UUID.nameUUIDFromBytes( + String.format(title + author).getBytes()).toString(); } public String getAuthor() { @@ -52,4 +55,4 @@ public void setDescription(String description) { public String getUniqueBookID() { return uniqueBookID; } -} +} \ No newline at end of file From 28b17c249976cdb2056a7016efefc9b572c546e5 Mon Sep 17 00:00:00 2001 From: Hossein Date: Tue, 30 Apr 2024 10:27:58 +0330 Subject: [PATCH 03/61] add project files --- .idea/.gitignore | 3 +++ .idea/misc.xml | 6 ++++++ .idea/modules.xml | 8 ++++++++ .idea/vcs.xml | 6 ++++++ Library-Management-System.iml | 11 +++++++++++ 5 files changed, 34 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 Library-Management-System.iml diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..6f29fee --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..d5f086e --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Library-Management-System.iml b/Library-Management-System.iml new file mode 100644 index 0000000..c4b790b --- /dev/null +++ b/Library-Management-System.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file From a586ae112a0c8b853d35625735dbc6f26cee3098 Mon Sep 17 00:00:00 2001 From: Hossein Date: Tue, 30 Apr 2024 10:29:23 +0330 Subject: [PATCH 04/61] add basic version of users --- Answers/src/Admin.java | 14 +++++++++++++ Answers/src/NormalUser.java | 23 +++++++++++++++++++++ Answers/src/User.java | 41 +++++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 Answers/src/Admin.java create mode 100644 Answers/src/NormalUser.java create mode 100644 Answers/src/User.java diff --git a/Answers/src/Admin.java b/Answers/src/Admin.java new file mode 100644 index 0000000..65004bc --- /dev/null +++ b/Answers/src/Admin.java @@ -0,0 +1,14 @@ +public class Admin extends User { + private String password; + + public Admin(String name, String phoneNumber, String password) { + super(name, phoneNumber); + this.password = password; + } + // to verify the password + public boolean Verify(String password) { + if (this.password.equals(password)) + return true; + return false; + } +} diff --git a/Answers/src/NormalUser.java b/Answers/src/NormalUser.java new file mode 100644 index 0000000..1eb21b8 --- /dev/null +++ b/Answers/src/NormalUser.java @@ -0,0 +1,23 @@ +// this class inherits from class User +// and simulates the NormalUser +import java.time.LocalDate; +import java.time.LocalTime; + +public class NormalUser extends User { + private LocalDate registerDate; + private LocalTime registerTime; + + public NormalUser(String name, String phoneNumber) { + super(name, phoneNumber); + this.registerDate = LocalDate.now(); + this.registerTime = LocalTime.now(); + } + + public LocalDate getRegisterDate() { + return registerDate; + } + + public LocalTime getRegisterTime() { + return registerTime; + } +} \ No newline at end of file diff --git a/Answers/src/User.java b/Answers/src/User.java new file mode 100644 index 0000000..9f1b7b6 --- /dev/null +++ b/Answers/src/User.java @@ -0,0 +1,41 @@ +// this class simulates the users +// and it is superclass for NormalUser and Admin +import java.util.UUID; + +public class User { + private String name; + // unique id is based on the name of the user + private String uniqueID; + private String phoneNumber; + + // constructor + + public User(String name, String phoneNumber) { + this.name = name; + this.phoneNumber = phoneNumber; + this.uniqueID= UUID.nameUUIDFromBytes(phoneNumber.getBytes()).toString(); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + + // the unique id should change + uniqueID = UUID.nameUUIDFromBytes(this.phoneNumber.getBytes()).toString(); + } + + public String getPhoneNumber() { + return phoneNumber; + } + + public void setPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + } + + public String getUniqueID() { + return uniqueID; + } +} From 6e5a47854f69226c41b6993573109279087c8238 Mon Sep 17 00:00:00 2001 From: Hossein Date: Tue, 30 Apr 2024 10:29:51 +0330 Subject: [PATCH 05/61] add MyApp class --- Answers/src/MyApp.java | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Answers/src/MyApp.java diff --git a/Answers/src/MyApp.java b/Answers/src/MyApp.java new file mode 100644 index 0000000..970a4fe --- /dev/null +++ b/Answers/src/MyApp.java @@ -0,0 +1,38 @@ +// main class for handling the CLI +import java.util.InputMismatchException; +import java.util.Scanner; + +public class MyApp { + public static void main(String[] args) { + Scanner input = new Scanner(System.in); + + System.out.println("Welcome to LMS(Library Management System)!"); + System.out.println("enter your library name: "); + System.out.println("for more information enter command "); + System.out.println("\nEnter your command:"); + String command = ""; + while (true) { + try { + System.out.print(">>> "); + command = input.nextLine(); + CLI(command); + } catch (IllegalArgumentException e) { + System.out.printf("%s: %s%n", command, e.getMessage()); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.printf("%s: %s%n", command, "Uncompleted command"); + } + } + } + + public static void CLI(String command) throws IllegalArgumentException { + if (command.equals("lib man")) + Manual.print(); + else if (command.matches("lib return \\w*")) { + // return a book + } + else if (command.equals("lib exit")) + System.exit(0); + else + throw new IllegalArgumentException(); + } +} From b4ca2a7cd2c4a072e1cbfff2b3a822dd8358d221 Mon Sep 17 00:00:00 2001 From: Hossein Date: Tue, 30 Apr 2024 10:29:59 +0330 Subject: [PATCH 06/61] add Rent class --- Answers/src/Rent.java | 48 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Answers/src/Rent.java diff --git a/Answers/src/Rent.java b/Answers/src/Rent.java new file mode 100644 index 0000000..d1153d6 --- /dev/null +++ b/Answers/src/Rent.java @@ -0,0 +1,48 @@ +// this class for simulates renting +import java.time.LocalDate; +import java.time.LocalTime; + +public class Rent { + private Book book; + private NormalUser person; + private String rentalID; + private LocalDate rentalDate; + private LocalTime rentalTime; + + public Rent(Book book, NormalUser person) { + this.book = book; + this.person = person; + this.rentalDate = LocalDate.now(); + this.rentalTime = LocalTime.now(); + this.rentalID = CreateID(); + } + + private String CreateID() { + String result = String.valueOf(rentalTime.getSecond()); + result += String.valueOf(rentalTime.getMinute()); + result += String.valueOf(rentalTime.getHour()); + result += String.valueOf(rentalDate.getDayOfYear()); + result += String.valueOf(rentalDate.getYear()); + return result; + } + + public Book getBook() { + return book; + } + + public NormalUser getPerson() { + return person; + } + + public String getRentalID() { + return rentalID; + } + + public LocalDate getRentalDate() { + return rentalDate; + } + + public LocalTime getRentalTime() { + return rentalTime; + } +} \ No newline at end of file From 11a5df42a28d5da037df2fd924267568d508ac97 Mon Sep 17 00:00:00 2001 From: Hossein Date: Tue, 30 Apr 2024 10:30:06 +0330 Subject: [PATCH 07/61] add Manual class --- Answers/src/Manual.java | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Answers/src/Manual.java diff --git a/Answers/src/Manual.java b/Answers/src/Manual.java new file mode 100644 index 0000000..2941b7e --- /dev/null +++ b/Answers/src/Manual.java @@ -0,0 +1,34 @@ +public class Manual { + public static void print() { + System.out.println("All of commands are :\n"); + // command add + System.out.println("lib add book : Add a new book to the library."); + + // command hrs + System.out.println("lib get hrs : Retrieve library operating hours."); + + // command rent from library + System.out.println("lib rent : Rent a book from the library."); + + // command add member + System.out.println("lib add member " + + " : Add a new member to the library (admin privilege required)."); + + // command rent for member + System.out.println("lib rent " + + " : Rent a book for a specific member."); + + // command view book + System.out.println("lib get available books : View available books for rental."); + + // command remove member + System.out.println("lib remove member " + + ": Remove a member from the library (admin privilege required)."); + + // command return book + System.out.println("lib return : Return a rented book to the library."); + + // command exit + System.out.println("lib exit : exit the program"); + } +} From e2fa9d19184f01f1f7ad8fee34ac6867554b8d46 Mon Sep 17 00:00:00 2001 From: Hossein Date: Tue, 30 Apr 2024 10:30:18 +0330 Subject: [PATCH 08/61] add library class --- Answers/src/Library.java | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Answers/src/Library.java diff --git a/Answers/src/Library.java b/Answers/src/Library.java new file mode 100644 index 0000000..2feeab5 --- /dev/null +++ b/Answers/src/Library.java @@ -0,0 +1,25 @@ +import java.util.ArrayList; + +public class Library { + private String name; + private long capacity; + private String operatingHours; + private ArrayList bookRepository; + private ArrayList libraryUsers; + Library(String name, long capacity, String operatingHours, ArrayList bookRepository + , ArrayList libraryUsers) { + this.name = name; + this.capacity = capacity; + this.operatingHours = operatingHours; + this.bookRepository = bookRepository; + this.libraryUsers = libraryUsers; + } + + public ArrayList getBookRepository() { + return bookRepository; + } + + public ArrayList getLibraryUsers() { + return libraryUsers; + } +} From 7402392ea8e1a4ca7c18317cf899a2020bf5d946 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 03:18:07 +0330 Subject: [PATCH 09/61] project file --- .idea/inspectionProfiles/Project_Default.xml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .idea/inspectionProfiles/Project_Default.xml diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..0a87188 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file From 464f7bd9bff5ebee67c18df59f6ae1f4e13fb57e Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 03:20:07 +0330 Subject: [PATCH 10/61] delete UUID and add validate phoneNumber --- Answers/src/User.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Answers/src/User.java b/Answers/src/User.java index 9f1b7b6..e578dc7 100644 --- a/Answers/src/User.java +++ b/Answers/src/User.java @@ -4,16 +4,19 @@ public class User { private String name; - // unique id is based on the name of the user - private String uniqueID; + private String uniqueID; // unique id automatically creates in database private String phoneNumber; // constructor + public User(String name, String phoneNumber) throws IllegalArgumentException { + // validate phoneNumber + String regexPhoneNumber = "(\\+989|09|00989)(0[0-5]|1[0-9]|2[0-3]|3[0-9]|9[0-6]-?\\d{3}-?\\d{4})|" + + "(991[0134]{5})|(99[09]{6})|(998{6})"; + if (phoneNumber != null && !phoneNumber.matches(regexPhoneNumber)) + throw new IllegalArgumentException("Invalid phone number!"); - public User(String name, String phoneNumber) { this.name = name; this.phoneNumber = phoneNumber; - this.uniqueID= UUID.nameUUIDFromBytes(phoneNumber.getBytes()).toString(); } public String getName() { @@ -22,9 +25,6 @@ public String getName() { public void setName(String name) { this.name = name; - - // the unique id should change - uniqueID = UUID.nameUUIDFromBytes(this.phoneNumber.getBytes()).toString(); } public String getPhoneNumber() { From 56634b7ecd9633b639747cad2f9608090aab2d84 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 03:21:47 +0330 Subject: [PATCH 11/61] create class NormalUser --- Answers/src/NormalUser.java | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/Answers/src/NormalUser.java b/Answers/src/NormalUser.java index 1eb21b8..80925ef 100644 --- a/Answers/src/NormalUser.java +++ b/Answers/src/NormalUser.java @@ -1,23 +1,21 @@ -// this class inherits from class User -// and simulates the NormalUser -import java.time.LocalDate; import java.time.LocalTime; +import java.time.LocalDate; public class NormalUser extends User { - private LocalDate registerDate; - private LocalTime registerTime; + private final LocalDate registerDate; + private final LocalTime registerTime; - public NormalUser(String name, String phoneNumber) { - super(name, phoneNumber); - this.registerDate = LocalDate.now(); - this.registerTime = LocalTime.now(); - } + public NormalUser(String name, String phoneNumber) throws IllegalArgumentException { + super(name, phoneNumber); + this.registerDate = LocalDate.now(); + this.registerTime = LocalTime.now(); + } - public LocalDate getRegisterDate() { - return registerDate; - } + public LocalDate getRegisterDate() { + return registerDate; + } - public LocalTime getRegisterTime() { - return registerTime; - } -} \ No newline at end of file + public LocalTime getRegisterTime() { + return registerTime; + } + } \ No newline at end of file From d14cf3df0627eb05ecfd2548a289ace5bf420b8b Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 03:22:13 +0330 Subject: [PATCH 12/61] add some commands --- Answers/src/Manual.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Answers/src/Manual.java b/Answers/src/Manual.java index 2941b7e..f53dcf7 100644 --- a/Answers/src/Manual.java +++ b/Answers/src/Manual.java @@ -1,6 +1,13 @@ public class Manual { public static void print() { System.out.println("All of commands are :\n"); + + // command log in + System.out.println("lib login : Log in to your account"); + + // command log out + System.out.println("lib logout : Log out from your account"); + // command add System.out.println("lib add book : Add a new book to the library."); @@ -11,7 +18,7 @@ public static void print() { System.out.println("lib rent : Rent a book from the library."); // command add member - System.out.println("lib add member " + + System.out.println("lib add member " + " : Add a new member to the library (admin privilege required)."); // command rent for member From 7928064148f1080d824ff9473fa0ed9e1805363d Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 03:22:30 +0330 Subject: [PATCH 13/61] project file --- Library-Management-System.iml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Library-Management-System.iml b/Library-Management-System.iml index c4b790b..b1321ae 100644 --- a/Library-Management-System.iml +++ b/Library-Management-System.iml @@ -7,5 +7,14 @@ + + + + + + + + + \ No newline at end of file From 6aa1cffd9ead47ddb519ec3f172c45b770a9699b Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 03:23:50 +0330 Subject: [PATCH 14/61] add option to save library in file --- Answers/src/MyApp.java | 134 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 123 insertions(+), 11 deletions(-) diff --git a/Answers/src/MyApp.java b/Answers/src/MyApp.java index 970a4fe..c103a96 100644 --- a/Answers/src/MyApp.java +++ b/Answers/src/MyApp.java @@ -1,37 +1,149 @@ // main class for handling the CLI +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.Paths; +import java.nio.file.Path; +import java.nio.file.Files; import java.util.InputMismatchException; import java.util.Scanner; -public class MyApp { +public class MyApp { + public static final Library library = new Library(); // our library + public static final Path PATH = Paths.get(".library.txt"); + public static void main(String[] args) { - Scanner input = new Scanner(System.in); + // check to library is existed or not + if (!Files.exists(PATH)) { + System.out.println("Welcome to LMS(Library Management System)!"); + System.out.println("You should create your own library first\n"); + while (!createLibrary()); // first we should create a library to use it + + System.out.println("Now you should add a new admin to your library!"); + // add a new admin user + while (true) { + Scanner input = new Scanner(System.in); + + System.out.println("\nEnter these information about your admin:"); + try { + // get admin name + System.out.print("Name: "); + String name = input.nextLine(); + + // get admin phone number + System.out.print("Phone number: "); + String phoneNumber = input.nextLine(); + + // get admin password + System.out.print("Password: "); + String password = input.nextLine(); + + Admin admin = new Admin(name, phoneNumber, password); + + if (!library.addUser(admin, password)) { + // delete library file + File libraryFile = PATH.toFile(); + libraryFile.delete(); - System.out.println("Welcome to LMS(Library Management System)!"); - System.out.println("enter your library name: "); - System.out.println("for more information enter command "); + System.out.println("Terminating..."); + System.exit(1); + } + + library.user = admin; // this is log in now + System.out.println("You are now logged in!\n"); + } catch (IllegalArgumentException e) { + System.err.printf("%s%n", e.getMessage()); + System.out.println("Try again."); + continue; + } + + break; + } + } + else { + try (Scanner retrieveLibrary = new Scanner(PATH)) { + library.setName(retrieveLibrary.nextLine()); + library.setCapacity(retrieveLibrary.nextInt()); + library.setOperatingHours(retrieveLibrary.next()); + + } catch (IOException e) { + System.err.printf("%s%n", e.getMessage()); + e.printStackTrace(); + } + } + // welcome to library + System.out.printf("Welcome to %s library.%n", library.getName()); + System.out.println("For more information enter command "); System.out.println("\nEnter your command:"); - String command = ""; + while (true) { + String command = ""; + Scanner input = new Scanner(System.in); + try { System.out.print(">>> "); command = input.nextLine(); CLI(command); } catch (IllegalArgumentException e) { - System.out.printf("%s: %s%n", command, e.getMessage()); - } catch (ArrayIndexOutOfBoundsException e) { - System.out.printf("%s: %s%n", command, "Uncompleted command"); + System.err.printf("%s: %s%n", command, "Not Found."); } } } + private static boolean createLibrary() { + Scanner input = new Scanner(System.in); + + System.out.println("Please enter these information about your library:"); + try { + System.out.print("name : "); + library.setName(input.nextLine()); + + System.out.print("capacity : "); + library.setCapacity(input.nextInt()); + input.nextLine(); + + System.out.print("operating hours (format : xx-xx): "); + library.setOperatingHours(input.nextLine()); + + library.saveLibrary(); + + System.out.println("Your library was created successfully.\n"); + } catch (InputMismatchException e) { + System.err.printf("%s%n", e.getMessage()); + System.err.println("creation was not successful. Terminating program."); + System.exit(1); // creation was not successful + + } catch (IllegalArgumentException e) { + System.err.printf("%s%n%n", e.getMessage()); + System.out.println("Try again."); + return false; + } catch (SecurityException securityException) { + System.err.println("Write permission denied. Terminating."); + System.exit(1); // terminate the program + + } catch (FileNotFoundException fileNotFoundException) { + System.err.println("Error opening file. Terminating."); + System.exit(1); // terminate the program + } + return true; + } + public static void CLI(String command) throws IllegalArgumentException { if (command.equals("lib man")) Manual.print(); else if (command.matches("lib return \\w*")) { // return a book - } - else if (command.equals("lib exit")) + } else if (command.matches("lib add member \\d{7} .+")) { + if (library.user instanceof Admin) { + + } + else + System.out.println("You don't have permission to add members!"); + } else if (command.equals("lib exit")) { + System.out.println("Bye."); System.exit(0); + + } else throw new IllegalArgumentException(); } From f84a9944d1ce8342b7e67a25e5c9cd6b6c79dcd9 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 03:24:29 +0330 Subject: [PATCH 15/61] add method add book and add user --- Answers/src/Library.java | 120 +++++++++++++++++++++++++++++++++++---- 1 file changed, 108 insertions(+), 12 deletions(-) diff --git a/Answers/src/Library.java b/Answers/src/Library.java index 2feeab5..d862f6b 100644 --- a/Answers/src/Library.java +++ b/Answers/src/Library.java @@ -1,25 +1,121 @@ -import java.util.ArrayList; +import java.io.FileNotFoundException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Formatter; public class Library { private String name; - private long capacity; + private int capacity; private String operatingHours; - private ArrayList bookRepository; - private ArrayList libraryUsers; - Library(String name, long capacity, String operatingHours, ArrayList bookRepository - , ArrayList libraryUsers) { + User user; // user that log in now + + private static final String DB_URL = "jdbc:mysql://localhost/library"; + private static final String DB_USERNAME = "LMSjava"; + private static final String DB_PASSWORD = "lmsjava1234"; + + public void saveLibrary() throws FileNotFoundException, SecurityException { + Formatter output = new Formatter(MyApp.PATH.toString()); + output.format("%s%n%d%n%s", name, capacity, operatingHours); + output.close(); + } + + public void setName(String name) { this.name = name; + } + + public String getName() { + return name; + } + + public void setCapacity(int capacity) { this.capacity = capacity; + } + + public void setOperatingHours(String operatingHours) throws IllegalArgumentException { + { + // validate operating hours + if (!operatingHours.matches("\\d{2}-\\d{2}")) + throw new IllegalArgumentException("Invalid format (e.g. 08-20)."); + + String[] hours = operatingHours.split("-"); + if (Integer.parseInt(hours[0]) > 24 || Integer.parseInt(hours[1]) > 24) + throw new IllegalArgumentException("Invalid hours."); + } this.operatingHours = operatingHours; - this.bookRepository = bookRepository; - this.libraryUsers = libraryUsers; } - public ArrayList getBookRepository() { - return bookRepository; + // add normal user + public Boolean addUser(NormalUser user) { + try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); + PreparedStatement insertUser = connection.prepareStatement( + "INSERT INTO Users (Name, PhoneNumber, UserType, RegisterDate, RegisterTime)" + + "VALUES (?, ?, ?, ?, ?)")) { + + insertUser.setString(1, user.getName()); + insertUser.setString(2, user.getPhoneNumber()); + insertUser.setString(3, "'normal'"); + insertUser.setString(4, user.getRegisterDate().toString()); + insertUser.setString(5, user.getRegisterTime().toString()); + + insertUser.executeUpdate(); + + // prompt + System.out.printf("User <%s> was saved successfully!%n", user.getName()); + } catch (SQLException sqlException) { + sqlException.printStackTrace(); + System.err.print("Connection to database failed!"); + return false; + } + return true; } - public ArrayList getLibraryUsers() { - return libraryUsers; + // add admin user + public boolean addUser(User admin, String password) { + try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); + PreparedStatement insertUser = connection.prepareStatement( + "INSERT INTO Users (Name, PhoneNumber, UserType, Password) " + + "VALUES (?, ?, ?, ?)")) { + + insertUser.setString(1, admin.getName()); + insertUser.setString(2, admin.getPhoneNumber()); + insertUser.setString(3, "admin"); + insertUser.setString(4, password); + + insertUser.executeUpdate(); + + // prompt + System.out.printf("User <%s> was successfully saved!%n", admin.getName()); + } catch (SQLException sqlException) { + sqlException.printStackTrace(); + System.err.print("Connection to database failed!"); + return false; + } + return true; + } + + // add book + public boolean addBook(Book book) { + try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); + PreparedStatement insertBook = connection.prepareStatement( + "INSERT INTO books (UniqueBookID, Title, Author, Description) " + + "VALUES (?, ?, ?, ?)")) { + + insertBook.setString(1, book.getUniqueBookID()); + insertBook.setString(2, book.getTitle()); + insertBook.setString(3, book.getAuthor()); + insertBook.setString(4, book.getDescription()); + + insertBook.executeUpdate(); + + // prompt + System.out.printf("Book <%s> was successfully saved!%n", book.getTitle()); + } catch (SQLException sqlException) { + sqlException.printStackTrace(); + System.err.print("Connection to database failed!"); + return false; + } + return true; } } From c0e5e24a0bf3444b922e4dd31be99d7319f5c9c7 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 03:24:52 +0330 Subject: [PATCH 16/61] nothing --- Answers/src/Book.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Answers/src/Book.java b/Answers/src/Book.java index ce6bdca..ae568ee 100644 --- a/Answers/src/Book.java +++ b/Answers/src/Book.java @@ -1,4 +1,4 @@ -""// this class simulates books in the library +// this class simulates books in the library import java.util.UUID; // to generate the unique ID for books public class Book { From 48624a34c62b94c50a08a6fc05891d5d1e1ab73d Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 03:25:43 +0330 Subject: [PATCH 17/61] add validate password --- Answers/src/Admin.java | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/Answers/src/Admin.java b/Answers/src/Admin.java index 65004bc..61c4cf7 100644 --- a/Answers/src/Admin.java +++ b/Answers/src/Admin.java @@ -1,14 +1,21 @@ + public class Admin extends User { - private String password; + private final String password; - public Admin(String name, String phoneNumber, String password) { + public Admin(String name, String phoneNumber, String password) throws IllegalArgumentException { super(name, phoneNumber); + + // validate password + if (!password.matches(".*\\d.*") && !password.matches(".*[a-z].*") && + !password.matches(".*[A-Z].*")) + throw new IllegalArgumentException("Password should contain at least one digit," + + "one capital and small letter."); + this.password = password; } + // to verify the password - public boolean Verify(String password) { - if (this.password.equals(password)) - return true; - return false; + public boolean verify(String password) { + return this.password.equals(password); } } From 01fb444f030dd47ccf2cc7bdc68f9d51e9502339 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 04:50:04 +0330 Subject: [PATCH 18/61] change the regex in validation --- Answers/src/Admin.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Answers/src/Admin.java b/Answers/src/Admin.java index 61c4cf7..45d1d35 100644 --- a/Answers/src/Admin.java +++ b/Answers/src/Admin.java @@ -7,9 +7,9 @@ public Admin(String name, String phoneNumber, String password) throws IllegalArg // validate password if (!password.matches(".*\\d.*") && !password.matches(".*[a-z].*") && - !password.matches(".*[A-Z].*")) + !password.matches(".*[A-Z].*") && !password.matches("[^(\"\\s)]*")) throw new IllegalArgumentException("Password should contain at least one digit," + - "one capital and small letter."); + "one capital and small letter\nand should not have \" character and white spaces."); this.password = password; } From 716f555369d3ec72dbe54bfebe08abb5ed07f62b Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 04:50:31 +0330 Subject: [PATCH 19/61] delete uuid --- Answers/src/Book.java | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/Answers/src/Book.java b/Answers/src/Book.java index ae568ee..d6b4b6c 100644 --- a/Answers/src/Book.java +++ b/Answers/src/Book.java @@ -1,20 +1,16 @@ // this class simulates books in the library -import java.util.UUID; // to generate the unique ID for books public class Book { private String title; private String author; private String description; - // unique id is based on the title and auther of the book - private String uniqueBookID; + private String uniqueBookID; // unique id automatically generate in database public boolean availabilityStatus = true; // two arguments constructor public Book(String title, String author) { this.title = title; this.author = author; - this.uniqueBookID = UUID.nameUUIDFromBytes( - String.format(title + author).getBytes()).toString(); } // three arguments constructor @@ -30,10 +26,6 @@ public String getTitle() { public void setTitle(String title) { this.title = title; - - // the unique id should change - uniqueBookID = UUID.nameUUIDFromBytes( - String.format(title + author).getBytes()).toString(); } public String getAuthor() { From 1c0d0d8daed8ef19550019ac40d4213f4554a68e Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 04:50:55 +0330 Subject: [PATCH 20/61] change add normal user method to void --- Answers/src/Library.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Answers/src/Library.java b/Answers/src/Library.java index d862f6b..83883a2 100644 --- a/Answers/src/Library.java +++ b/Answers/src/Library.java @@ -47,7 +47,7 @@ public void setOperatingHours(String operatingHours) throws IllegalArgumentExcep } // add normal user - public Boolean addUser(NormalUser user) { + public void addUser(NormalUser user) { try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); PreparedStatement insertUser = connection.prepareStatement( "INSERT INTO Users (Name, PhoneNumber, UserType, RegisterDate, RegisterTime)" + @@ -66,9 +66,7 @@ public Boolean addUser(NormalUser user) { } catch (SQLException sqlException) { sqlException.printStackTrace(); System.err.print("Connection to database failed!"); - return false; } - return true; } // add admin user From dec8188eba32fcf8bd263e60f607922a6a0f011c Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 04:51:18 +0330 Subject: [PATCH 21/61] nothing special --- Answers/src/Manual.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Answers/src/Manual.java b/Answers/src/Manual.java index f53dcf7..d140743 100644 --- a/Answers/src/Manual.java +++ b/Answers/src/Manual.java @@ -9,7 +9,7 @@ public static void print() { System.out.println("lib logout : Log out from your account"); // command add - System.out.println("lib add book : Add a new book to the library."); + System.out.println("lib add book : Add a new book to the library."); // command hrs System.out.println("lib get hrs : Retrieve library operating hours."); From 49def81908166bf6c9d0ac4acf157120d1bb15a9 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 04:52:26 +0330 Subject: [PATCH 22/61] rearrange the code and add lib add member command --- Answers/src/MyApp.java | 60 +++++++++++++++++++++++++++++++----------- 1 file changed, 44 insertions(+), 16 deletions(-) diff --git a/Answers/src/MyApp.java b/Answers/src/MyApp.java index c103a96..fe00914 100644 --- a/Answers/src/MyApp.java +++ b/Answers/src/MyApp.java @@ -1,16 +1,18 @@ // main class for handling the CLI + import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; -import java.nio.file.Paths; -import java.nio.file.Path; import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.InputMismatchException; import java.util.Scanner; public class MyApp { public static final Library library = new Library(); // our library public static final Path PATH = Paths.get(".library.txt"); + public static Scanner input = new Scanner(System.in); public static void main(String[] args) { // check to library is existed or not @@ -22,8 +24,6 @@ public static void main(String[] args) { System.out.println("Now you should add a new admin to your library!"); // add a new admin user while (true) { - Scanner input = new Scanner(System.in); - System.out.println("\nEnter these information about your admin:"); try { // get admin name @@ -77,23 +77,21 @@ public static void main(String[] args) { System.out.println("\nEnter your command:"); while (true) { - String command = ""; - Scanner input = new Scanner(System.in); + String command = null; try { System.out.print(">>> "); command = input.nextLine(); - CLI(command); + CLI(command.trim()); } catch (IllegalArgumentException e) { - System.err.printf("%s: %s%n", command, "Not Found."); + System.out.printf("command <%s> %s%n", command.trim(), "Not Found."); } } } private static boolean createLibrary() { - Scanner input = new Scanner(System.in); - System.out.println("Please enter these information about your library:"); + try { System.out.print("name : "); library.setName(input.nextLine()); @@ -129,20 +127,50 @@ private static boolean createLibrary() { } public static void CLI(String command) throws IllegalArgumentException { - if (command.equals("lib man")) + if (command.matches("lib\\sman")) Manual.print(); - else if (command.matches("lib return \\w*")) { + else if (command.matches("lib\\sadd\\sbook\\s\"[^\"]+\" \"")) { + + } else if (command.matches("lib return \\w*")) { // return a book - } else if (command.matches("lib add member \\d{7} .+")) { + } else if (command.matches("lib\\sadd\\smember\\s\"?.+\"?\\s+?\\d+\\s([^(\"\\s)]*)?")) { if (library.user instanceof Admin) { - + String name, phoneNumber; + + String[] temp1 = command.split("\""); + if (temp1.length == 3) { + name = temp1[1]; + + String[] temp2 = temp1[2].split("\\s"); + phoneNumber = temp2[0]; + User user; + if (temp2.length == 2) { + user = new Admin(name, phoneNumber, temp2[1]); + library.addUser(user, temp2[1]); + } else { + user = new NormalUser(name, phoneNumber); + library.addUser((NormalUser) user); + } + } else { + String[] temp = command.split("\\s"); + name = temp[3]; + phoneNumber = temp[4]; + + User user; + if (temp.length == 6) { + user = new Admin(name, phoneNumber, temp[5]); + library.addUser(user, temp[5]); + } else { + user = new NormalUser(name, phoneNumber); + library.addUser((NormalUser) user); + } + } } else System.out.println("You don't have permission to add members!"); - } else if (command.equals("lib exit")) { + } else if (command.matches("li\\sexit")) { System.out.println("Bye."); System.exit(0); - } else throw new IllegalArgumentException(); From 2fb7b5a58ae9df8fff052970276e30bed7353546 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 04:53:17 +0330 Subject: [PATCH 23/61] nothing special --- Answers/src/User.java | 1 - 1 file changed, 1 deletion(-) diff --git a/Answers/src/User.java b/Answers/src/User.java index e578dc7..a88f89d 100644 --- a/Answers/src/User.java +++ b/Answers/src/User.java @@ -1,6 +1,5 @@ // this class simulates the users // and it is superclass for NormalUser and Admin -import java.util.UUID; public class User { private String name; From 0880efc11e2bc738557f6ee77ee2cf95a9714256 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 14:15:43 +0330 Subject: [PATCH 24/61] add command lib add book to CLI --- Answers/src/MyApp.java | 100 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 90 insertions(+), 10 deletions(-) diff --git a/Answers/src/MyApp.java b/Answers/src/MyApp.java index fe00914..c46032e 100644 --- a/Answers/src/MyApp.java +++ b/Answers/src/MyApp.java @@ -1,5 +1,6 @@ // main class for handling the CLI +import javax.naming.NoPermissionException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -84,7 +85,14 @@ public static void main(String[] args) { command = input.nextLine(); CLI(command.trim()); } catch (IllegalArgumentException e) { + if (e.getMessage() == null) + System.out.printf("command <%s> %s%n", command.trim(), "Not Found."); + else + System.out.printf("%s%n", e.getMessage()); + } catch (ArrayIndexOutOfBoundsException e) { System.out.printf("command <%s> %s%n", command.trim(), "Not Found."); + } catch (NoPermissionException e) { + System.out.printf("%s%n", e.getMessage()); } } } @@ -126,14 +134,81 @@ private static boolean createLibrary() { return true; } - public static void CLI(String command) throws IllegalArgumentException { + public static void CLI(String command) throws IllegalArgumentException, NoPermissionException { if (command.matches("lib\\sman")) Manual.print(); - else if (command.matches("lib\\sadd\\sbook\\s\"[^\"]+\" \"")) { + else if (command.matches("lib\\sadd\\sbook\\s\"?[^\"]*\"?\\s\"?[^\"]*\"?\\s?(\"?[^\"]*\"?)?")) { + // if he didn't admin user yet throw exception + if (library.user instanceof Admin) { + String title, author; + + // delete lib add book from command + command = command.substring(13); + + // find the name of the book + if (command.startsWith("\"")) { + command = command.substring(1); + title = command.substring(command.indexOf("\"")); + + // delete title of the book from command + command = command.substring(command.indexOf("\"")); + } else { + title = command.substring(command.indexOf(" ")); + + // delete title of the book from command + command = command.substring(command.indexOf(" ")); + } + + // find the author of the book + if (command.startsWith("\"")) { + command = command.substring(1); + author = command.substring(command.indexOf("\"")); + + // delete author of the book from command + command = command.substring(command.indexOf("\"")); + } else { + author = command.substring(command.indexOf(" ")); + + // delete author of the book from command + command = command.substring(command.indexOf(" ")); + } + + // if command doesn't have description + if (command == null) { + Book book = new Book(title, author); + library.addBook(book); + return; + } + + String description; + + // find the desciption of the book + if (command.startsWith("\"")) { + command = command.substring(1); + description = command.substring(command.indexOf("\"")); + + // delete description of the book from command + command = command.substring(command.indexOf("\"")); + } else { + description = command.substring(command.indexOf(" ")); + + // delete description of the book from command + command = command.substring(command.indexOf(" ")); + } + // if command has too many argument + if (command != null) + throw new IllegalArgumentException( + "You should use \" character to split string with space"); + + Book book = new Book(title, author, description); + library.addBook(book); + } else + throw new NoPermissionException("You don't have permission to add books!"); } else if (command.matches("lib return \\w*")) { // return a book - } else if (command.matches("lib\\sadd\\smember\\s\"?.+\"?\\s+?\\d+\\s([^(\"\\s)]*)?")) { + } else if (command.matches("lib\\sadd\\smember\\s\"?[^\"]*\"?\\s\\+?\\d+\\s?[^(\"\\s)]*")) { + // if he didn't admin user yet throw exception if (library.user instanceof Admin) { String name, phoneNumber; @@ -153,6 +228,11 @@ else if (command.matches("lib\\sadd\\sbook\\s\"[^\"]+\" \"")) { } } else { String[] temp = command.split("\\s"); + + if (temp.length > 6) + throw new IllegalArgumentException( + "You should use \" character to split string with space"); + name = temp[3]; phoneNumber = temp[4]; @@ -164,14 +244,14 @@ else if (command.matches("lib\\sadd\\sbook\\s\"[^\"]+\" \"")) { user = new NormalUser(name, phoneNumber); library.addUser((NormalUser) user); } - } - } - else - System.out.println("You don't have permission to add members!"); - } else if (command.matches("li\\sexit")) { - System.out.println("Bye."); + } // end if (library.user instanceof Admin) + } else + throw new NoPermissionException("You don't have permission to add members!"); + } // end lib add member + else if (command.matches("lib\\sexit")) { + System.out.print("Bye."); System.exit(0); - } + } // end lib exit else throw new IllegalArgumentException(); } From 7ba1bd55204aa04cd1b35c85343e32b1ea4818f1 Mon Sep 17 00:00:00 2001 From: aryanoor Date: Mon, 22 Apr 2024 21:44:54 +0330 Subject: [PATCH 25/61] =?UTF-8?q?project=20started=20=F0=9F=98=8E?= =?UTF-8?q?=F0=9F=96=A4=F0=9F=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit 487240713f5172fbc22b9a25adb3e4d4e33d9edf) --- Answers/Add Your Projects Here.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Answers/Add Your Projects Here.txt diff --git a/Answers/Add Your Projects Here.txt b/Answers/Add Your Projects Here.txt new file mode 100644 index 0000000..e69de29 From 9762bc69f985c82ce8d3b41cf0460fd45de6a347 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 26 Apr 2024 01:49:30 +0330 Subject: [PATCH 26/61] add login method --- Answers/src/Library.java | 55 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 5 deletions(-) diff --git a/Answers/src/Library.java b/Answers/src/Library.java index 83883a2..1766314 100644 --- a/Answers/src/Library.java +++ b/Answers/src/Library.java @@ -1,15 +1,12 @@ import java.io.FileNotFoundException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.SQLException; +import java.sql.*; import java.util.Formatter; public class Library { private String name; private int capacity; private String operatingHours; - User user; // user that log in now + private User user; // user that log in now private static final String DB_URL = "jdbc:mysql://localhost/library"; private static final String DB_USERNAME = "LMSjava"; @@ -33,6 +30,14 @@ public void setCapacity(int capacity) { this.capacity = capacity; } + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + public void setOperatingHours(String operatingHours) throws IllegalArgumentException { { // validate operating hours @@ -116,4 +121,44 @@ public boolean addBook(Book book) { } return true; } + + // login to library + public User login(String userID) { + User user = null; + + try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); + PreparedStatement loginUser = connection.prepareStatement( + "SELECT * FROM Users WHERE UserID = ?")) { + + loginUser.setString(1, userID); + + ResultSet resultSet = loginUser.executeQuery(); + + // If there is no such user + if (!resultSet.isBeforeFirst()) + return null; + + resultSet.next(); + + // get name and phone number of the user + String name = resultSet.getString("Name"); + String phoneNumber = resultSet.getString("PhoneNumber"); + + if (resultSet.getString("UserType").equals("admin")) { + String password = resultSet.getString("Password"); + user = new Admin(name, phoneNumber, password); + user.setUniqueID(userID); + } else { + Date registerDate = resultSet.getDate("RegisterDate"); + Time registerTime = resultSet.getTime("RegisterTime"); + user = new NormalUser(name, phoneNumber, registerDate, registerTime); + user.setUniqueID(userID); + } + } catch (SQLException sqlException) { + sqlException.printStackTrace(); + System.err.print("Connection to database failed! Terminating..."); + System.exit(1); + } + return user; + } } From 97bf92af1af5f7b89cea607ff3cc9e93e7acb7ba Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 19:23:53 +0330 Subject: [PATCH 27/61] add lib login and logout to CLI --- Answers/src/MyApp.java | 42 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/Answers/src/MyApp.java b/Answers/src/MyApp.java index c46032e..7f3e1d8 100644 --- a/Answers/src/MyApp.java +++ b/Answers/src/MyApp.java @@ -7,6 +7,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.security.InvalidParameterException; import java.util.InputMismatchException; import java.util.Scanner; @@ -50,7 +51,7 @@ public static void main(String[] args) { System.exit(1); } - library.user = admin; // this is log in now + library.setUser(admin); // this is log in now System.out.println("You are now logged in!\n"); } catch (IllegalArgumentException e) { System.err.printf("%s%n", e.getMessage()); @@ -81,9 +82,16 @@ public static void main(String[] args) { String command = null; try { - System.out.print(">>> "); + if (library.getUser() == null) + System.out.print(">>> "); + else if (library.getUser() instanceof Admin) + System.out.print("Admin> "); + else + System.out.printf("%s> ", library.getUser().getName()); command = input.nextLine(); CLI(command.trim()); + } catch (InvalidParameterException e) { + System.err.println("Invalid username. please try again."); } catch (IllegalArgumentException e) { if (e.getMessage() == null) System.out.printf("command <%s> %s%n", command.trim(), "Not Found."); @@ -137,9 +145,12 @@ private static boolean createLibrary() { public static void CLI(String command) throws IllegalArgumentException, NoPermissionException { if (command.matches("lib\\sman")) Manual.print(); - else if (command.matches("lib\\sadd\\sbook\\s\"?[^\"]*\"?\\s\"?[^\"]*\"?\\s?(\"?[^\"]*\"?)?")) { + else if (command.matches("lib\\slogout")) { + System.out.printf("%s logged out successfully.%n", library.getUser().getName()); + library.setUser(null); + } else if (command.matches("lib\\sadd\\sbook\\s\"?[^\"]*\"?\\s\"?[^\"]*\"?\\s?(\"?[^\"]*\"?)?")) { // if he didn't admin user yet throw exception - if (library.user instanceof Admin) { + if (library.getUser() instanceof Admin) { String title, author; // delete lib add book from command @@ -207,9 +218,30 @@ else if (command.matches("lib\\sadd\\sbook\\s\"?[^\"]*\"?\\s\"?[^\"]*\"?\\s?(\"? throw new NoPermissionException("You don't have permission to add books!"); } else if (command.matches("lib return \\w*")) { // return a book + } else if (command.matches("lib\\slogin\\s\\d+")) { + String[] temp = command.split("\\s"); + library.setUser(library.login(temp[2])); + if (library.getUser() == null) + throw new InvalidParameterException(); + else if (library.getUser() instanceof NormalUser) + System.out.printf("Hello %s!You logged in successfully.%n", library.getUser().getName()); + else { + Admin adminUser = (Admin) library.getUser(); + for (int i = 0; i < 3; i++) { + System.out.printf("Enter password for %s: ", adminUser.getName()); + String password = input.nextLine(); + if (adminUser.verify(password)) { + System.out.printf("Hello %s!You logged in successfully.%n", adminUser.getName()); + return; + } else + System.out.println("Invalid password. Try again."); + } + library.setUser(null); + throw new IllegalArgumentException("3 incorrect password attempts..."); + } } else if (command.matches("lib\\sadd\\smember\\s\"?[^\"]*\"?\\s\\+?\\d+\\s?[^(\"\\s)]*")) { // if he didn't admin user yet throw exception - if (library.user instanceof Admin) { + if (library.getUser() instanceof Admin) { String name, phoneNumber; String[] temp1 = command.split("\""); From a697bcdb3432e36ca5a1602d2aa5bd1e65814568 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 19:24:45 +0330 Subject: [PATCH 28/61] change datatype of date and time --- Answers/src/NormalUser.java | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/Answers/src/NormalUser.java b/Answers/src/NormalUser.java index 80925ef..5a0a66e 100644 --- a/Answers/src/NormalUser.java +++ b/Answers/src/NormalUser.java @@ -1,21 +1,30 @@ -import java.time.LocalTime; +import java.sql.Time; +import java.time.Instant; import java.time.LocalDate; +import java.time.LocalTime; +import java.util.Date; public class NormalUser extends User { - private final LocalDate registerDate; - private final LocalTime registerTime; + private final Date registerDate; + private final Time registerTime; + + public NormalUser(String name, String phoneNumber, Date registerDate, Time registerTime) { + super(name, phoneNumber); + this.registerDate = registerDate; + this.registerTime = registerTime; + } - public NormalUser(String name, String phoneNumber) throws IllegalArgumentException { - super(name, phoneNumber); - this.registerDate = LocalDate.now(); - this.registerTime = LocalTime.now(); + public NormalUser(String name, String phoneNumber) { + super(name, phoneNumber); + this.registerDate = Date.from(Instant.from(LocalDate.now())); + this.registerTime = Time.valueOf(LocalTime.now()); } - public LocalDate getRegisterDate() { + public Date getRegisterDate() { return registerDate; } - public LocalTime getRegisterTime() { + public Time getRegisterTime() { return registerTime; } } \ No newline at end of file From 89e869fb745aa61c84a4a4be203a6c7e6516d831 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 23:14:15 +0330 Subject: [PATCH 29/61] delete methods that doesn't have any usage --- Answers/src/Book.java | 20 +++----------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/Answers/src/Book.java b/Answers/src/Book.java index d6b4b6c..e0dfa4f 100644 --- a/Answers/src/Book.java +++ b/Answers/src/Book.java @@ -1,5 +1,3 @@ -// this class simulates books in the library - public class Book { private String title; private String author; @@ -23,27 +21,15 @@ public Book(String title, String author, String description) { public String getTitle() { return title; } - - public void setTitle(String title) { - this.title = title; - } - + public String getAuthor() { return author; } - - public void setAuthor(String author) { - this.author = author; - } - + public String getDescription() { return description; } - - public void setDescription(String description) { - this.description = description; - } - + public String getUniqueBookID() { return uniqueBookID; } From f9be69d491924e11e52ac27c07787fbd19c9efd9 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 23:14:48 +0330 Subject: [PATCH 30/61] handle time and date of register normal users --- Answers/src/Library.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/Answers/src/Library.java b/Answers/src/Library.java index 1766314..f6cb1ab 100644 --- a/Answers/src/Library.java +++ b/Answers/src/Library.java @@ -55,14 +55,13 @@ public void setOperatingHours(String operatingHours) throws IllegalArgumentExcep public void addUser(NormalUser user) { try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); PreparedStatement insertUser = connection.prepareStatement( - "INSERT INTO Users (Name, PhoneNumber, UserType, RegisterDate, RegisterTime)" + - "VALUES (?, ?, ?, ?, ?)")) { + "INSERT INTO Users (Name, PhoneNumber, UserType, RegisterTimestamp)" + + "VALUES (?, ?, ?, ?)")) { insertUser.setString(1, user.getName()); insertUser.setString(2, user.getPhoneNumber()); - insertUser.setString(3, "'normal'"); - insertUser.setString(4, user.getRegisterDate().toString()); - insertUser.setString(5, user.getRegisterTime().toString()); + insertUser.setString(3, "normal"); + insertUser.setTimestamp(4, user.getRegisterTimestamp()); insertUser.executeUpdate(); @@ -149,9 +148,8 @@ public User login(String userID) { user = new Admin(name, phoneNumber, password); user.setUniqueID(userID); } else { - Date registerDate = resultSet.getDate("RegisterDate"); - Time registerTime = resultSet.getTime("RegisterTime"); - user = new NormalUser(name, phoneNumber, registerDate, registerTime); + Timestamp registerTimestamp = resultSet.getTimestamp("RegisterTimestamp"); + user = new NormalUser(name, phoneNumber, registerTimestamp); user.setUniqueID(userID); } } catch (SQLException sqlException) { From 779a65f05ee7610e6e859622b676ab4efbe818ef Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 23:15:14 +0330 Subject: [PATCH 31/61] change time and date of register normal users --- Answers/src/NormalUser.java | 31 ++++++++++--------------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/Answers/src/NormalUser.java b/Answers/src/NormalUser.java index 5a0a66e..b00a365 100644 --- a/Answers/src/NormalUser.java +++ b/Answers/src/NormalUser.java @@ -1,30 +1,19 @@ -import java.sql.Time; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalTime; -import java.util.Date; +import java.sql.Timestamp; public class NormalUser extends User { - private final Date registerDate; - private final Time registerTime; + private Timestamp registerTimestamp; - public NormalUser(String name, String phoneNumber, Date registerDate, Time registerTime) { + public NormalUser(String name, String phoneNumber, Timestamp registerDateTime) { super(name, phoneNumber); - this.registerDate = registerDate; - this.registerTime = registerTime; + this.registerTimestamp = registerDateTime; } public NormalUser(String name, String phoneNumber) { super(name, phoneNumber); - this.registerDate = Date.from(Instant.from(LocalDate.now())); - this.registerTime = Time.valueOf(LocalTime.now()); - } - - public Date getRegisterDate() { - return registerDate; - } + this.registerTimestamp = new Timestamp(System.currentTimeMillis()); + } - public Time getRegisterTime() { - return registerTime; - } - } \ No newline at end of file + public Timestamp getRegisterTimestamp() { + return registerTimestamp; + } +} \ No newline at end of file From 20de13645c9b362b2bffab3189995b96a14b37e3 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 23:16:00 +0330 Subject: [PATCH 32/61] add setUniqueID method --- Answers/src/User.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Answers/src/User.java b/Answers/src/User.java index a88f89d..a502974 100644 --- a/Answers/src/User.java +++ b/Answers/src/User.java @@ -37,4 +37,8 @@ public void setPhoneNumber(String phoneNumber) { public String getUniqueID() { return uniqueID; } + + public void setUniqueID(String uniqueID) { + this.uniqueID = uniqueID; + } } From ba49d360c38a42b1b89a3666105e80706034454b Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 23:16:50 +0330 Subject: [PATCH 33/61] debug lib add book command --- Answers/src/MyApp.java | 49 ++++++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/Answers/src/MyApp.java b/Answers/src/MyApp.java index 7f3e1d8..754e5b4 100644 --- a/Answers/src/MyApp.java +++ b/Answers/src/MyApp.java @@ -154,39 +154,40 @@ else if (command.matches("lib\\slogout")) { String title, author; // delete lib add book from command - command = command.substring(13); + command = command.replaceFirst("lib\\sadd\\sbook\\s", ""); // find the name of the book if (command.startsWith("\"")) { - command = command.substring(1); - title = command.substring(command.indexOf("\"")); + title = command.substring(1, command.indexOf("\"", 1)); // delete title of the book from command - command = command.substring(command.indexOf("\"")); + command = command.replaceFirst("\"" + title + "\" ", ""); } else { - title = command.substring(command.indexOf(" ")); + title = command.substring(0, command.indexOf(" ")); // delete title of the book from command - command = command.substring(command.indexOf(" ")); + command = command.replaceFirst(title + " ", ""); } // find the author of the book - if (command.startsWith("\"")) { - command = command.substring(1); - author = command.substring(command.indexOf("\"")); + if (!command.contains(" ")) { + author = command; + command = ""; + } else if (command.startsWith("\"")) { + author = command.substring(1, command.indexOf("\"", 1)); // delete author of the book from command - command = command.substring(command.indexOf("\"")); + command = command.replaceFirst("\"" + author + "\" ", ""); } else { - author = command.substring(command.indexOf(" ")); + author = command.substring(0, command.indexOf(" ")); // delete author of the book from command - command = command.substring(command.indexOf(" ")); + command = command.replaceFirst(author + " ", ""); } // if command doesn't have description - if (command == null) { - Book book = new Book(title, author); + if (command.equals("")) { + Book book = new Book(title.trim(), author.trim()); library.addBook(book); return; } @@ -195,24 +196,26 @@ else if (command.matches("lib\\slogout")) { // find the desciption of the book if (command.startsWith("\"")) { - command = command.substring(1); - description = command.substring(command.indexOf("\"")); + description = command.substring(1, command.indexOf("\"", 1)); // delete description of the book from command - command = command.substring(command.indexOf("\"")); - } else { - description = command.substring(command.indexOf(" ")); + command = command.replaceFirst("\"" + description + "\"", ""); + } else if (command.contains(" ")) + throw new IllegalArgumentException( + "You should use \" character to split string with space"); + else { + description = command; // delete description of the book from command - command = command.substring(command.indexOf(" ")); + command = ""; } // if command has too many argument - if (command != null) + if (!command.equals("")) throw new IllegalArgumentException( "You should use \" character to split string with space"); - Book book = new Book(title, author, description); + Book book = new Book(title.trim(), author.trim(), description.trim()); library.addBook(book); } else throw new NoPermissionException("You don't have permission to add books!"); @@ -231,7 +234,7 @@ else if (library.getUser() instanceof NormalUser) System.out.printf("Enter password for %s: ", adminUser.getName()); String password = input.nextLine(); if (adminUser.verify(password)) { - System.out.printf("Hello %s!You logged in successfully.%n", adminUser.getName()); + System.out.printf("Hello %s! You logged in successfully.%n", adminUser.getName()); return; } else System.out.println("Invalid password. Try again."); From 2300216a6604e6bb7e51ae0b22bb749d4d6a4ac9 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 23:18:20 +0330 Subject: [PATCH 34/61] update gitignore --- .gitignore | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6cba7b4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +/.library.txt +/out/production/Library-Management-System/Admin.class +/out/production/Library-Management-System/Book.class +/out/production/Library-Management-System/Library.class +/out/production/Library-Management-System/Manual.class +/out/production/Library-Management-System/MyApp.class +/out/production/Library-Management-System/NormalUser.class +/out/production/Library-Management-System/Rent.class +/out/production/Library-Management-System/User.class From 6bade73b065c4f31613c2e2a9c0530516f0a19c3 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 23:53:12 +0330 Subject: [PATCH 35/61] save sql command in final string --- Answers/src/Library.java | 55 +++++++++++++++++++++------------------- 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/Answers/src/Library.java b/Answers/src/Library.java index f6cb1ab..6146007 100644 --- a/Answers/src/Library.java +++ b/Answers/src/Library.java @@ -8,10 +8,6 @@ public class Library { private String operatingHours; private User user; // user that log in now - private static final String DB_URL = "jdbc:mysql://localhost/library"; - private static final String DB_USERNAME = "LMSjava"; - private static final String DB_PASSWORD = "lmsjava1234"; - public void saveLibrary() throws FileNotFoundException, SecurityException { Formatter output = new Formatter(MyApp.PATH.toString()); output.format("%s%n%d%n%s", name, capacity, operatingHours); @@ -53,10 +49,12 @@ public void setOperatingHours(String operatingHours) throws IllegalArgumentExcep // add normal user public void addUser(NormalUser user) { - try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); - PreparedStatement insertUser = connection.prepareStatement( - "INSERT INTO Users (Name, PhoneNumber, UserType, RegisterTimestamp)" + - "VALUES (?, ?, ?, ?)")) { + final String SQL_COMMAND = "INSERT INTO Users (Name, PhoneNumber, UserType," + + " RegisterTimestamp) VALUES (?, ?, ?, ?)"; + + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, + MyApp.DB_USERNAME, MyApp.DB_PASSWORD); + PreparedStatement insertUser = connection.prepareStatement(SQL_COMMAND)) { insertUser.setString(1, user.getName()); insertUser.setString(2, user.getPhoneNumber()); @@ -74,11 +72,13 @@ public void addUser(NormalUser user) { } // add admin user - public boolean addUser(User admin, String password) { - try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); - PreparedStatement insertUser = connection.prepareStatement( - "INSERT INTO Users (Name, PhoneNumber, UserType, Password) " - + "VALUES (?, ?, ?, ?)")) { + // return the unique ID of the user + public String addUser(User admin, String password) { + final String SQL_COMMAND = "INSERT INTO Users (Name, PhoneNumber, UserType, Password) " + + "VALUES (?, ?, ?, ?)"; + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, + MyApp.DB_USERNAME, MyApp.DB_PASSWORD); + PreparedStatement insertUser = connection.prepareStatement(SQL_COMMAND)) { insertUser.setString(1, admin.getName()); insertUser.setString(2, admin.getPhoneNumber()); @@ -92,17 +92,21 @@ public boolean addUser(User admin, String password) { } catch (SQLException sqlException) { sqlException.printStackTrace(); System.err.print("Connection to database failed!"); - return false; + return null; } - return true; + + // get the unique id from database + admin.uniqueIDUpdate(); + return admin.getUniqueID(); } // add book public boolean addBook(Book book) { - try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); - PreparedStatement insertBook = connection.prepareStatement( - "INSERT INTO books (UniqueBookID, Title, Author, Description) " + - "VALUES (?, ?, ?, ?)")) { + final String SQL_COMMAND = "INSERT INTO books (UniqueBookID, Title, Author, Description) " + + "VALUES (?, ?, ?, ?)"; + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, + MyApp.DB_USERNAME, MyApp.DB_PASSWORD); + PreparedStatement insertBook = connection.prepareStatement(SQL_COMMAND)) { insertBook.setString(1, book.getUniqueBookID()); insertBook.setString(2, book.getTitle()); @@ -124,19 +128,18 @@ public boolean addBook(Book book) { // login to library public User login(String userID) { User user = null; + final String SQL_COMMAND = "SELECT * FROM Users WHERE UserID = ?"; - try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); - PreparedStatement loginUser = connection.prepareStatement( - "SELECT * FROM Users WHERE UserID = ?")) { + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, + MyApp.DB_USERNAME, MyApp.DB_PASSWORD); + PreparedStatement loginUser = connection.prepareStatement(SQL_COMMAND)) { loginUser.setString(1, userID); - ResultSet resultSet = loginUser.executeQuery(); // If there is no such user if (!resultSet.isBeforeFirst()) return null; - resultSet.next(); // get name and phone number of the user @@ -146,11 +149,11 @@ public User login(String userID) { if (resultSet.getString("UserType").equals("admin")) { String password = resultSet.getString("Password"); user = new Admin(name, phoneNumber, password); - user.setUniqueID(userID); + user.uniqueIDUpdate(); } else { Timestamp registerTimestamp = resultSet.getTimestamp("RegisterTimestamp"); user = new NormalUser(name, phoneNumber, registerTimestamp); - user.setUniqueID(userID); + user.uniqueIDUpdate(); } } catch (SQLException sqlException) { sqlException.printStackTrace(); From 2a5e7d321172e69eacc6ed9e421b69536691e102 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 23:54:10 +0330 Subject: [PATCH 36/61] save database information with final string --- Answers/src/MyApp.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Answers/src/MyApp.java b/Answers/src/MyApp.java index 754e5b4..ae5948c 100644 --- a/Answers/src/MyApp.java +++ b/Answers/src/MyApp.java @@ -12,8 +12,16 @@ import java.util.Scanner; public class MyApp { + // database information + public static final String DB_URL = "jdbc:mysql://localhost/library"; + public static final String DB_USERNAME = "LMSjava"; + public static final String DB_PASSWORD = "lmsjava1234"; + + // library information public static final Library library = new Library(); // our library public static final Path PATH = Paths.get(".library.txt"); + + // scanner for input from client public static Scanner input = new Scanner(System.in); public static void main(String[] args) { @@ -42,7 +50,7 @@ public static void main(String[] args) { Admin admin = new Admin(name, phoneNumber, password); - if (!library.addUser(admin, password)) { + if (library.addUser(admin, password) == null) { // delete library file File libraryFile = PATH.toFile(); libraryFile.delete(); @@ -222,6 +230,10 @@ else if (command.matches("lib\\slogout")) { } else if (command.matches("lib return \\w*")) { // return a book } else if (command.matches("lib\\slogin\\s\\d+")) { + if (library.getUser() != null) + throw new NoPermissionException("Another account is still logged in! " + + "Log out and try again."); + String[] temp = command.split("\\s"); library.setUser(library.login(temp[2])); if (library.getUser() == null) From b1757c09c85b16cd456befe711dbcb85255f5b39 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 10 May 2024 23:54:43 +0330 Subject: [PATCH 37/61] add uniqueIDUpdate method --- Answers/src/User.java | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/Answers/src/User.java b/Answers/src/User.java index a502974..7985ddd 100644 --- a/Answers/src/User.java +++ b/Answers/src/User.java @@ -1,6 +1,8 @@ // this class simulates the users // and it is superclass for NormalUser and Admin +import java.sql.*; + public class User { private String name; private String uniqueID; // unique id automatically creates in database @@ -18,27 +20,33 @@ public User(String name, String phoneNumber) throws IllegalArgumentException { this.phoneNumber = phoneNumber; } - public String getName() { - return name; + public void uniqueIDUpdate() { + final String SQL_COMMAND = "SELECT UserID FROM Users WHERE PhoneNumber = ?"; + + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, + MyApp.DB_USERNAME, MyApp.DB_PASSWORD); + PreparedStatement selectID = connection.prepareStatement(SQL_COMMAND)) { + + selectID.setString(1, this.phoneNumber); + + ResultSet resultSet = selectID.executeQuery(); + this.uniqueID = resultSet.getString(1); + } catch (SQLException sqlException) { + sqlException.printStackTrace(); + System.err.print("Connection to database failed! Terminating..."); + System.exit(1); + } } - public void setName(String name) { - this.name = name; + public String getName() { + return name; } public String getPhoneNumber() { return phoneNumber; } - public void setPhoneNumber(String phoneNumber) { - this.phoneNumber = phoneNumber; - } - public String getUniqueID() { return uniqueID; } - - public void setUniqueID(String uniqueID) { - this.uniqueID = uniqueID; - } } From c5ae50ab30952dae63643eec1d35dadf0b0d44ff Mon Sep 17 00:00:00 2001 From: Hossein Date: Sat, 11 May 2024 02:52:18 +0330 Subject: [PATCH 38/61] add removeUser and getAvailableBooks methods --- Answers/src/Library.java | 101 ++++++++++++++++++++++++++++++++++----- 1 file changed, 88 insertions(+), 13 deletions(-) diff --git a/Answers/src/Library.java b/Answers/src/Library.java index 6146007..9a87c8c 100644 --- a/Answers/src/Library.java +++ b/Answers/src/Library.java @@ -1,3 +1,6 @@ +import javax.naming.NoPermissionException; +import javax.sql.rowset.JdbcRowSet; +import javax.sql.rowset.RowSetProvider; import java.io.FileNotFoundException; import java.sql.*; import java.util.Formatter; @@ -34,6 +37,10 @@ public void setUser(User user) { this.user = user; } + public String getOperatingHours() { + return operatingHours; + } + public void setOperatingHours(String operatingHours) throws IllegalArgumentException { { // validate operating hours @@ -48,7 +55,8 @@ public void setOperatingHours(String operatingHours) throws IllegalArgumentExcep } // add normal user - public void addUser(NormalUser user) { + // return the unique ID of the user + public int addUser(NormalUser user) { final String SQL_COMMAND = "INSERT INTO Users (Name, PhoneNumber, UserType," + " RegisterTimestamp) VALUES (?, ?, ?, ?)"; @@ -62,18 +70,19 @@ public void addUser(NormalUser user) { insertUser.setTimestamp(4, user.getRegisterTimestamp()); insertUser.executeUpdate(); - - // prompt - System.out.printf("User <%s> was saved successfully!%n", user.getName()); } catch (SQLException sqlException) { sqlException.printStackTrace(); System.err.print("Connection to database failed!"); + return 0; } + + user.uniqueIDUpdate(); + return user.getUniqueID(); } // add admin user // return the unique ID of the user - public String addUser(User admin, String password) { + public int addUser(User admin, String password) { final String SQL_COMMAND = "INSERT INTO Users (Name, PhoneNumber, UserType, Password) " + "VALUES (?, ?, ?, ?)"; try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, @@ -86,13 +95,10 @@ public String addUser(User admin, String password) { insertUser.setString(4, password); insertUser.executeUpdate(); - - // prompt - System.out.printf("User <%s> was successfully saved!%n", admin.getName()); } catch (SQLException sqlException) { sqlException.printStackTrace(); System.err.print("Connection to database failed!"); - return null; + return 0; } // get the unique id from database @@ -100,9 +106,38 @@ public String addUser(User admin, String password) { return admin.getUniqueID(); } + public int removeUser(int userID) throws NoPermissionException { + if (user == null || user instanceof NormalUser) + throw new NoPermissionException("You don't have permission to remove members!"); + + for (int i = 0; i < 3; i++) { + System.out.print("Enter your password: "); + String password = MyApp.input.nextLine(); + if (((Admin) user).verify(password)) + break; + else if (i == 2) + throw new IllegalArgumentException("3 incorrect password attempts..."); + else + System.out.println("Invalid password. Try again."); + } + + final String SQL_COMMAND = "DELETE FROM Users WHERE UserID = ?"; + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, + MyApp.DB_USERNAME, MyApp.DB_PASSWORD); + PreparedStatement deleteUser = connection.prepareStatement(SQL_COMMAND)) { + + deleteUser.setInt(1, userID); + return deleteUser.executeUpdate(); + } catch (SQLException sqlException) { + sqlException.printStackTrace(); + System.err.print("Connection to database failed!"); + return 0; + } + } + // add book - public boolean addBook(Book book) { - final String SQL_COMMAND = "INSERT INTO books (UniqueBookID, Title, Author, Description) " + + public void addBook(Book book) { + final String SQL_COMMAND = "INSERT INTO books (BookID, Title, Author, Description) " + "VALUES (?, ?, ?, ?)"; try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, MyApp.DB_PASSWORD); @@ -120,9 +155,7 @@ public boolean addBook(Book book) { } catch (SQLException sqlException) { sqlException.printStackTrace(); System.err.print("Connection to database failed!"); - return false; } - return true; } // login to library @@ -162,4 +195,46 @@ public User login(String userID) { } return user; } + + public void getAvailableBooks() { + final String SQl_COMMAND = "SELECT BookID, Title, Author, Description " + + "FROM books WHERE AvailabilityStatus = 1"; + // connect to database books and query database + try (JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet()) { + + rowSet.setUrl(MyApp.DB_URL); + rowSet.setUsername(MyApp.DB_USERNAME); + rowSet.setPassword(MyApp.DB_PASSWORD); + rowSet.setCommand(SQl_COMMAND); + rowSet.execute(); + + // process query results + ResultSetMetaData metaData = rowSet.getMetaData(); + int numberOfColumns = metaData.getColumnCount(); + System.out.printf("Available books:%n%n"); + // display rowset header + for (int i = 1; i <= numberOfColumns; i++) { + if (i > 2) + System.out.printf("%-20s\t", metaData.getColumnName(i)); + else + System.out.printf("%-15s\t", metaData.getColumnName(i)); + } + System.out.println(); + // display each row + while (rowSet.next()) + { + for (int i = 1; i <= numberOfColumns; i++) { + if (i > 2) + System.out.printf("%-20s\t", rowSet.getObject(i)); + else + System.out.printf("%-15s\t", rowSet.getObject(i)); + } + System.out.println(); + } + } catch (SQLException e) { + e.printStackTrace(); + System.err.print("Connection to database failed! Terminating..."); + System.exit(1); + } + } } From 8f17f5a8458e4f62495f1ad153ae7dff11d38d13 Mon Sep 17 00:00:00 2001 From: Hossein Date: Sat, 11 May 2024 02:52:53 +0330 Subject: [PATCH 39/61] Change order of commands --- Answers/src/Manual.java | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/Answers/src/Manual.java b/Answers/src/Manual.java index d140743..29e679b 100644 --- a/Answers/src/Manual.java +++ b/Answers/src/Manual.java @@ -8,34 +8,35 @@ public static void print() { // command log out System.out.println("lib logout : Log out from your account"); - // command add - System.out.println("lib add book : Add a new book to the library."); - // command hrs System.out.println("lib get hrs : Retrieve library operating hours."); + // command view book + System.out.println("lib get available books : View available books for rental."); + // command rent from library System.out.println("lib rent : Rent a book from the library."); + // command exit + System.out.println("lib exit : exit the program"); + + // command add book + System.out.println("lib add book : " + + "Add a new book to the library."); + // command add member System.out.println("lib add member " + " : Add a new member to the library (admin privilege required)."); - // command rent for member - System.out.println("lib rent " + - " : Rent a book for a specific member."); - - // command view book - System.out.println("lib get available books : View available books for rental."); - // command remove member System.out.println("lib remove member " + ": Remove a member from the library (admin privilege required)."); + // command rent for member + System.out.println("lib rent " + + " : Rent a book for a specific member."); + // command return book System.out.println("lib return : Return a rented book to the library."); - - // command exit - System.out.println("lib exit : exit the program"); } } From 1db5010f4d0abe4286ba52e89ca0dd7899c1f8ea Mon Sep 17 00:00:00 2001 From: Hossein Date: Sat, 11 May 2024 02:54:59 +0330 Subject: [PATCH 40/61] add getavailable and remove user commands --- Answers/src/MyApp.java | 75 ++++++++++++++++++++++++++++-------------- 1 file changed, 51 insertions(+), 24 deletions(-) diff --git a/Answers/src/MyApp.java b/Answers/src/MyApp.java index ae5948c..53b6408 100644 --- a/Answers/src/MyApp.java +++ b/Answers/src/MyApp.java @@ -8,6 +8,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.security.InvalidParameterException; +import java.sql.ResultSet; import java.util.InputMismatchException; import java.util.Scanner; @@ -50,7 +51,7 @@ public static void main(String[] args) { Admin admin = new Admin(name, phoneNumber, password); - if (library.addUser(admin, password) == null) { + if (library.addUser(admin, password) == 0) { // delete library file File libraryFile = PATH.toFile(); libraryFile.delete(); @@ -60,7 +61,8 @@ public static void main(String[] args) { } library.setUser(admin); // this is log in now - System.out.println("You are now logged in!\n"); + System.out.printf("You are now logged in! Your ID is %s.%n", + library.getUser().getUniqueID()); } catch (IllegalArgumentException e) { System.err.printf("%s%n", e.getMessage()); System.out.println("Try again."); @@ -151,12 +153,32 @@ private static boolean createLibrary() { } public static void CLI(String command) throws IllegalArgumentException, NoPermissionException { + // command lib man if (command.matches("lib\\sman")) Manual.print(); - else if (command.matches("lib\\slogout")) { - System.out.printf("%s logged out successfully.%n", library.getUser().getName()); - library.setUser(null); + // command lib get hrs + else if (command.matches("lib\\sget\\shrs")) + System.out.print(library.getOperatingHours()); + else if (command.matches("lib\\sget\\savailable\\sbooks")) + library.getAvailableBooks(); + // command lib remove member + else if (command.matches("lib\\sremove\\smember\\s\\d{7,}")) { + // get user id from command + int userID = Integer.parseInt(command.substring(18)); + + if (library.removeUser(userID) == 0) + throw new IllegalArgumentException("User with " + userID + " not found!"); + + System.out.printf("Account with ID = %d deleted successfully.%n", userID); + } else if (command.matches("lib\\slogout")) { + if (library.getUser() == null) + System.out.println("No one has logged in yet"); + else { + System.out.printf("%s logged out successfully.%n", library.getUser().getName()); + library.setUser(null); + } } else if (command.matches("lib\\sadd\\sbook\\s\"?[^\"]*\"?\\s\"?[^\"]*\"?\\s?(\"?[^\"]*\"?)?")) { + // command lib add book // if he didn't admin user yet throw exception if (library.getUser() instanceof Admin) { String title, author; @@ -230,10 +252,10 @@ else if (command.matches("lib\\slogout")) { } else if (command.matches("lib return \\w*")) { // return a book } else if (command.matches("lib\\slogin\\s\\d+")) { + //command lib login if (library.getUser() != null) throw new NoPermissionException("Another account is still logged in! " + "Log out and try again."); - String[] temp = command.split("\\s"); library.setUser(library.login(temp[2])); if (library.getUser() == null) @@ -254,24 +276,26 @@ else if (library.getUser() instanceof NormalUser) library.setUser(null); throw new IllegalArgumentException("3 incorrect password attempts..."); } - } else if (command.matches("lib\\sadd\\smember\\s\"?[^\"]*\"?\\s\\+?\\d+\\s?[^(\"\\s)]*")) { + } else if (command.matches("lib\\sadd\\smember\\s\"?[^\"]*\"?\\s\\+?[\\d-]+\\s?[^(\"\\s)]*")) { + // commadn lib add member // if he didn't admin user yet throw exception if (library.getUser() instanceof Admin) { String name, phoneNumber; + int userID; String[] temp1 = command.split("\""); if (temp1.length == 3) { - name = temp1[1]; + name = temp1[1].trim(); - String[] temp2 = temp1[2].split("\\s"); - phoneNumber = temp2[0]; + String[] temp2 = temp1[2].trim().split("\\s"); + phoneNumber = temp2[0].trim(); User user; if (temp2.length == 2) { - user = new Admin(name, phoneNumber, temp2[1]); - library.addUser(user, temp2[1]); + user = new Admin(name, phoneNumber, temp2[1].trim()); + userID = library.addUser(user, temp2[1].trim()); } else { user = new NormalUser(name, phoneNumber); - library.addUser((NormalUser) user); + userID = library.addUser((NormalUser) user); } } else { String[] temp = command.split("\\s"); @@ -280,26 +304,29 @@ else if (library.getUser() instanceof NormalUser) throw new IllegalArgumentException( "You should use \" character to split string with space"); - name = temp[3]; - phoneNumber = temp[4]; + name = temp[3].trim(); + phoneNumber = temp[4].trim(); User user; if (temp.length == 6) { - user = new Admin(name, phoneNumber, temp[5]); - library.addUser(user, temp[5]); + user = new Admin(name, phoneNumber, temp[5].trim()); + userID = library.addUser(user, temp[5].trim()); } else { user = new NormalUser(name, phoneNumber); - library.addUser((NormalUser) user); + userID = library.addUser((NormalUser) user); } - } // end if (library.user instanceof Admin) - } else + } + + // prompt the user + System.out.printf("User %s with ID = %d added to library.%n", name, userID); + } // end if (library.user instanceof Admin) + else throw new NoPermissionException("You don't have permission to add members!"); - } // end lib add member - else if (command.matches("lib\\sexit")) { + } else if (command.matches("lib\\sexit")) { + //command lib exit System.out.print("Bye."); System.exit(0); - } // end lib exit - else + } else throw new IllegalArgumentException(); } } From 4a3f71aaa3e1849e67fcc4fb62008d0229ec0799 Mon Sep 17 00:00:00 2001 From: Hossein Date: Wed, 15 May 2024 01:25:00 +0330 Subject: [PATCH 41/61] add method UniqueIDUpdate --- Answers/src/Book.java | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/Answers/src/Book.java b/Answers/src/Book.java index e0dfa4f..1c040e2 100644 --- a/Answers/src/Book.java +++ b/Answers/src/Book.java @@ -1,8 +1,10 @@ +import java.sql.*; + public class Book { private String title; private String author; private String description; - private String uniqueBookID; // unique id automatically generate in database + private int uniqueID; // unique id automatically generate in database public boolean availabilityStatus = true; // two arguments constructor @@ -18,6 +20,26 @@ public Book(String title, String author, String description) { this.description = description; } + public void uniqueIDUpdate() { + final String SQL_COMMAND = "SELECT BookID FROM BOOKS WHERE Title = ? AND Author = ?"; + + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, + MyApp.DB_USERNAME, MyApp.DB_PASSWORD); + PreparedStatement selectID = connection.prepareStatement(SQL_COMMAND)) { + + selectID.setString(1, this.title); + selectID.setString(2, this.author); + + ResultSet resultSet = selectID.executeQuery(); + if (resultSet.next()) + this.uniqueID = resultSet.getInt("BookID"); + } catch (SQLException sqlException) { + sqlException.printStackTrace(); + System.err.print("Connection to database failed! Terminating..."); + System.exit(1); + } + } + public String getTitle() { return title; } @@ -30,7 +52,7 @@ public String getDescription() { return description; } - public String getUniqueBookID() { - return uniqueBookID; + public int getUniqueID() { + return uniqueID; } } \ No newline at end of file From 241e1e6e86b664043ad97c92316378ede8d8ec4d Mon Sep 17 00:00:00 2001 From: Hossein Date: Wed, 15 May 2024 01:28:01 +0330 Subject: [PATCH 42/61] Nothing Special --- Answers/src/Book.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Answers/src/Book.java b/Answers/src/Book.java index 1c040e2..4f7faea 100644 --- a/Answers/src/Book.java +++ b/Answers/src/Book.java @@ -21,7 +21,7 @@ public Book(String title, String author, String description) { } public void uniqueIDUpdate() { - final String SQL_COMMAND = "SELECT BookID FROM BOOKS WHERE Title = ? AND Author = ?"; + final String SQL_COMMAND = "SELECT BookID FROM books WHERE Title = ? AND Author = ?"; try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, MyApp.DB_PASSWORD); From cc5cbe4315f1df6a820a55e676bca9f5a0108fe8 Mon Sep 17 00:00:00 2001 From: Hossein Date: Wed, 15 May 2024 01:28:44 +0330 Subject: [PATCH 43/61] add some feature --- Answers/src/Manual.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/Answers/src/Manual.java b/Answers/src/Manual.java index 29e679b..3dde612 100644 --- a/Answers/src/Manual.java +++ b/Answers/src/Manual.java @@ -1,6 +1,7 @@ public class Manual { - public static void print() { - System.out.println("All of commands are :\n"); + public static void printNormalUser() { + // command who am I + System.out.println("whoami: show who are you"); // command log in System.out.println("lib login : Log in to your account"); @@ -20,6 +21,11 @@ public static void print() { // command exit System.out.println("lib exit : exit the program"); + // command return book + System.out.println("lib return : Return a rented book to the library."); + } + + public static void printAdmin() { // command add book System.out.println("lib add book : " + "Add a new book to the library."); @@ -35,8 +41,5 @@ public static void print() { // command rent for member System.out.println("lib rent " + " : Rent a book for a specific member."); - - // command return book - System.out.println("lib return : Return a rented book to the library."); } } From 5104f8148fca644cb82a32b058ad3e6e94e158dc Mon Sep 17 00:00:00 2001 From: Hossein Date: Wed, 15 May 2024 01:29:13 +0330 Subject: [PATCH 44/61] add command whoami --- Answers/src/MyApp.java | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/Answers/src/MyApp.java b/Answers/src/MyApp.java index 53b6408..87efe61 100644 --- a/Answers/src/MyApp.java +++ b/Answers/src/MyApp.java @@ -1,5 +1,4 @@ // main class for handling the CLI - import javax.naming.NoPermissionException; import java.io.File; import java.io.FileNotFoundException; @@ -86,7 +85,7 @@ public static void main(String[] args) { // welcome to library System.out.printf("Welcome to %s library.%n", library.getName()); System.out.println("For more information enter command "); - System.out.println("\nEnter your command:"); + System.out.println("Enter your command:"); while (true) { String command = null; @@ -153,9 +152,19 @@ private static boolean createLibrary() { } public static void CLI(String command) throws IllegalArgumentException, NoPermissionException { + if (command.equals("whoami")) + if (library.getUser() == null) + System.out.println("No one one has logged in yet."); + else + System.out.println(library.getUser()); // command lib man - if (command.matches("lib\\sman")) - Manual.print(); + else if (command.matches("lib\\sman")) { + System.out.println("You can use these commands :\n"); + if (library.getUser() instanceof Admin) + Manual.printAdmin(); + + Manual.printNormalUser(); + } // command lib get hrs else if (command.matches("lib\\sget\\shrs")) System.out.print(library.getOperatingHours()); @@ -218,7 +227,10 @@ else if (command.matches("lib\\sremove\\smember\\s\\d{7,}")) { // if command doesn't have description if (command.equals("")) { Book book = new Book(title.trim(), author.trim()); - library.addBook(book); + int bookID = library.addBook(book); + if (bookID != 0) + System.out.printf("Book %s with ID = %d added to library.%n", book.getTitle(), + bookID); return; } @@ -246,7 +258,10 @@ else if (command.matches("lib\\sremove\\smember\\s\\d{7,}")) { "You should use \" character to split string with space"); Book book = new Book(title.trim(), author.trim(), description.trim()); - library.addBook(book); + int bookID = library.addBook(book); + if (bookID != 0) + System.out.printf("Book %s with ID = %d added to library.%n", book.getTitle(), + bookID); } else throw new NoPermissionException("You don't have permission to add books!"); } else if (command.matches("lib return \\w*")) { From 15004590d65576abc429cbfe7bd7c017ff38da17 Mon Sep 17 00:00:00 2001 From: Hossein Date: Wed, 15 May 2024 04:03:16 +0330 Subject: [PATCH 45/61] add Updatable interface to project --- Answers/src/Updatable.java | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Answers/src/Updatable.java diff --git a/Answers/src/Updatable.java b/Answers/src/Updatable.java new file mode 100644 index 0000000..9d7467f --- /dev/null +++ b/Answers/src/Updatable.java @@ -0,0 +1,3 @@ +public interface Updatable { + void update(); +} From b75b0a382a40853c989d239f5aac1f0ac4f01f08 Mon Sep 17 00:00:00 2001 From: Hossein Date: Wed, 15 May 2024 04:03:40 +0330 Subject: [PATCH 46/61] add getStatus method --- Answers/src/Book.java | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/Answers/src/Book.java b/Answers/src/Book.java index 4f7faea..22240e8 100644 --- a/Answers/src/Book.java +++ b/Answers/src/Book.java @@ -5,7 +5,7 @@ public class Book { private String author; private String description; private int uniqueID; // unique id automatically generate in database - public boolean availabilityStatus = true; + private boolean availabilityStatus = true; // two arguments constructor public Book(String title, String author) { @@ -20,8 +20,9 @@ public Book(String title, String author, String description) { this.description = description; } - public void uniqueIDUpdate() { - final String SQL_COMMAND = "SELECT BookID FROM books WHERE Title = ? AND Author = ?"; + public void update() { + final String SQL_COMMAND = "SELECT BookID, AvailabilityStatus FROM books WHERE Title = ? " + + "AND Author = ?"; try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, MyApp.DB_PASSWORD); @@ -31,8 +32,10 @@ public void uniqueIDUpdate() { selectID.setString(2, this.author); ResultSet resultSet = selectID.executeQuery(); - if (resultSet.next()) + if (resultSet.next()) { this.uniqueID = resultSet.getInt("BookID"); + this.availabilityStatus = resultSet.getBoolean("AvailabilityStatus"); + } } catch (SQLException sqlException) { sqlException.printStackTrace(); System.err.print("Connection to database failed! Terminating..."); @@ -40,6 +43,23 @@ public void uniqueIDUpdate() { } } + public void getStatus(boolean availabilityStatus) { + final String SQL_COMMAND = "UPDATE books SET AvailabilityStatus = ? WHERE BookID = ?;"; + + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, + MyApp.DB_PASSWORD); + PreparedStatement changeStatusCommand = connection.prepareStatement(SQL_COMMAND)){ + + changeStatusCommand.setBoolean(1, availabilityStatus); + changeStatusCommand.setInt(2, this.uniqueID); + changeStatusCommand.executeUpdate(); + + this.availabilityStatus = false; + } catch (SQLException e) { + e.printStackTrace(); + System.err.print("Connection to database failed! Terminating..."); + } + } public String getTitle() { return title; } From e87fa24e8df730ec3af617da95f5c529c00fd670 Mon Sep 17 00:00:00 2001 From: Hossein Date: Wed, 15 May 2024 04:04:15 +0330 Subject: [PATCH 47/61] add addRent method --- Answers/src/Library.java | 90 +++++++++++++++++++++++++++++++++------- 1 file changed, 76 insertions(+), 14 deletions(-) diff --git a/Answers/src/Library.java b/Answers/src/Library.java index 9a87c8c..55b7c88 100644 --- a/Answers/src/Library.java +++ b/Answers/src/Library.java @@ -3,6 +3,7 @@ import javax.sql.rowset.RowSetProvider; import java.io.FileNotFoundException; import java.sql.*; +import java.util.ArrayList; import java.util.Formatter; public class Library { @@ -57,7 +58,7 @@ public void setOperatingHours(String operatingHours) throws IllegalArgumentExcep // add normal user // return the unique ID of the user public int addUser(NormalUser user) { - final String SQL_COMMAND = "INSERT INTO Users (Name, PhoneNumber, UserType," + + final String SQL_COMMAND = "INSERT INTO users (Name, PhoneNumber, UserType," + " RegisterTimestamp) VALUES (?, ?, ?, ?)"; try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, @@ -76,15 +77,16 @@ public int addUser(NormalUser user) { return 0; } - user.uniqueIDUpdate(); + user.update(); return user.getUniqueID(); } // add admin user // return the unique ID of the user public int addUser(User admin, String password) { - final String SQL_COMMAND = "INSERT INTO Users (Name, PhoneNumber, UserType, Password) " + final String SQL_COMMAND = "INSERT INTO users (Name, PhoneNumber, UserType, Password) " + "VALUES (?, ?, ?, ?)"; + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, MyApp.DB_PASSWORD); PreparedStatement insertUser = connection.prepareStatement(SQL_COMMAND)) { @@ -102,7 +104,7 @@ public int addUser(User admin, String password) { } // get the unique id from database - admin.uniqueIDUpdate(); + admin.update(); return admin.getUniqueID(); } @@ -110,7 +112,10 @@ public int removeUser(int userID) throws NoPermissionException { if (user == null || user instanceof NormalUser) throw new NoPermissionException("You don't have permission to remove members!"); - for (int i = 0; i < 3; i++) { + if (userID < this.user.getUniqueID()) + throw new NoPermissionException("You don't have permission to remove this member!"); + + for (int i = 0;; i++) { System.out.print("Enter your password: "); String password = MyApp.input.nextLine(); if (((Admin) user).verify(password)) @@ -121,7 +126,7 @@ else if (i == 2) System.out.println("Invalid password. Try again."); } - final String SQL_COMMAND = "DELETE FROM Users WHERE UserID = ?"; + final String SQL_COMMAND = "DELETE FROM users WHERE UserID = ?"; try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, MyApp.DB_PASSWORD); PreparedStatement deleteUser = connection.prepareStatement(SQL_COMMAND)) { @@ -136,32 +141,36 @@ else if (i == 2) } // add book - public void addBook(Book book) { + public int addBook(Book book) { final String SQL_COMMAND = "INSERT INTO books (BookID, Title, Author, Description) " + "VALUES (?, ?, ?, ?)"; + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, MyApp.DB_PASSWORD); PreparedStatement insertBook = connection.prepareStatement(SQL_COMMAND)) { - insertBook.setString(1, book.getUniqueBookID()); + insertBook.setInt(1, book.getUniqueID()); insertBook.setString(2, book.getTitle()); insertBook.setString(3, book.getAuthor()); insertBook.setString(4, book.getDescription()); insertBook.executeUpdate(); - - // prompt - System.out.printf("Book <%s> was successfully saved!%n", book.getTitle()); } catch (SQLException sqlException) { sqlException.printStackTrace(); System.err.print("Connection to database failed!"); + return 0; } + + // get the unique id from database + book.update(); + + return book.getUniqueID(); } // login to library public User login(String userID) { User user = null; - final String SQL_COMMAND = "SELECT * FROM Users WHERE UserID = ?"; + final String SQL_COMMAND = "SELECT * FROM users WHERE UserID = ?"; try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, MyApp.DB_PASSWORD); @@ -182,11 +191,11 @@ public User login(String userID) { if (resultSet.getString("UserType").equals("admin")) { String password = resultSet.getString("Password"); user = new Admin(name, phoneNumber, password); - user.uniqueIDUpdate(); + user.update(); } else { Timestamp registerTimestamp = resultSet.getTimestamp("RegisterTimestamp"); user = new NormalUser(name, phoneNumber, registerTimestamp); - user.uniqueIDUpdate(); + user.update(); } } catch (SQLException sqlException) { sqlException.printStackTrace(); @@ -199,6 +208,7 @@ public User login(String userID) { public void getAvailableBooks() { final String SQl_COMMAND = "SELECT BookID, Title, Author, Description " + "FROM books WHERE AvailabilityStatus = 1"; + // connect to database books and query database try (JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet()) { @@ -237,4 +247,56 @@ public void getAvailableBooks() { System.exit(1); } } + + // search books by name + public ArrayList searchBook(String bookName) { + final String SQL_COMMAND = "SELECT * FROM books WHERE Title = ? AND AvailabilityStatus = ?"; + ArrayList resultBooks = new ArrayList<>(); + + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, + MyApp.DB_PASSWORD); + PreparedStatement searchStatement = connection.prepareStatement(SQL_COMMAND)) { + + searchStatement.setString(1, bookName); + searchStatement.setBoolean(2, true); + + ResultSet resultSet = searchStatement.executeQuery(); + + while (resultSet.next()) { + Book book = new Book(bookName, resultSet.getString("Author"), + resultSet.getString("Description")); + book.update(); + resultBooks.add(book); + } + + return resultBooks; + } catch (SQLException e) { + e.printStackTrace(); + System.err.print("Connection to database failed!"); + return null; + } + } + + // add rent to library + public int addRent(Rent rent) { + final String SQL_COMMAND = "INSERT INTO rents (UserID, BookID, RentalDate) VALUES (?, ?, ?);"; + + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, + MyApp.DB_PASSWORD); + PreparedStatement addRentCommand = connection.prepareStatement(SQL_COMMAND)){ + + addRentCommand.setInt(1, rent.getPerson().getUniqueID()); + addRentCommand.setInt(2, rent.getBook().getUniqueID()); + addRentCommand.setTimestamp(3, rent.getRentalTimestamp()); + addRentCommand.executeUpdate(); + + rent.update(); + rent.getBook().getStatus(false); + return rent.getRentalID(); + } catch (SQLException e) { + e.printStackTrace(); + System.err.print("Connection to database failed!"); + return 0; + } + } } From 7e3a4ca4bb77b141a965f0f060dc378ebad85d97 Mon Sep 17 00:00:00 2001 From: Hossein Date: Wed, 15 May 2024 04:04:48 +0330 Subject: [PATCH 48/61] add lib rent command to CLI --- Answers/src/MyApp.java | 59 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/Answers/src/MyApp.java b/Answers/src/MyApp.java index 87efe61..bd4fdb1 100644 --- a/Answers/src/MyApp.java +++ b/Answers/src/MyApp.java @@ -8,6 +8,7 @@ import java.nio.file.Paths; import java.security.InvalidParameterException; import java.sql.ResultSet; +import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Scanner; @@ -110,6 +111,8 @@ else if (library.getUser() instanceof Admin) System.out.printf("command <%s> %s%n", command.trim(), "Not Found."); } catch (NoPermissionException e) { System.out.printf("%s%n", e.getMessage()); + } catch (InputMismatchException e) { + System.out.printf("Invalid input. proccess cancled..."); } } } @@ -151,7 +154,8 @@ private static boolean createLibrary() { return true; } - public static void CLI(String command) throws IllegalArgumentException, NoPermissionException { + public static void CLI(String command) throws IllegalArgumentException, NoPermissionException, + InputMismatchException { if (command.equals("whoami")) if (library.getUser() == null) System.out.println("No one one has logged in yet."); @@ -337,6 +341,59 @@ else if (library.getUser() instanceof NormalUser) } // end if (library.user instanceof Admin) else throw new NoPermissionException("You don't have permission to add members!"); + } else if (command.matches("lib\\srent\\s.+")) { + if (library.getUser() == null) + System.out.println("You should first login to rent a book."); + else if (library.getUser() instanceof Admin) + System.out.println("You are admin!You can't rent a book:)"); + else { + String bookName = command.substring(8).trim(); + if (bookName.startsWith("\"")) + bookName = bookName.substring(1, bookName.length() - 1); + + ArrayList books = library.searchBook(bookName); + Rent rent; + if (books.size() == 0) { + System.out.printf("book %s not found or not available!%n", bookName); + return; + } else if (books.size() == 1) + rent = new Rent(books.get(0), (NormalUser) library.getUser()); + else { + System.out.println("Which book do you want?"); + + // show selections + int numberOfRows = 1; + for (Book book : books) { + System.out.printf("%d. ID = %d, Author = %d", numberOfRows, + book.getUniqueID(), book.getAuthor()); + numberOfRows++; + } + + // select choice + int choice = 1; + for (int i = 0; i < 3; i++) { + System.out.print(">>>"); + choice = input.nextInt(); + if (choice > numberOfRows) { + if (i == 2) { + System.out.println("3 invalid choice..."); + return; + } + System.out.printf("Invalid choice. please try again."); + } + else + break; + } + + // create rent class + rent = new Rent(books.get(choice - 1), (NormalUser) library.getUser()); + } + int rentalID = library.addRent(rent); + if (rentalID == 0) + return; + System.out.println("You rented this book successfully."); + System.out.printf("rental ID = %d%n", rentalID); + } } else if (command.matches("lib\\sexit")) { //command lib exit System.out.print("Bye."); From 974c2abcc7e8b5f90378be0fa8fa6ab012c6814c Mon Sep 17 00:00:00 2001 From: Hossein Date: Wed, 15 May 2024 04:05:08 +0330 Subject: [PATCH 49/61] add update method --- Answers/src/Rent.java | 55 +++++++++++++++++++++++++------------------ 1 file changed, 32 insertions(+), 23 deletions(-) diff --git a/Answers/src/Rent.java b/Answers/src/Rent.java index d1153d6..c584974 100644 --- a/Answers/src/Rent.java +++ b/Answers/src/Rent.java @@ -1,31 +1,44 @@ // this class for simulates renting -import java.time.LocalDate; -import java.time.LocalTime; +import java.sql.*; -public class Rent { +public class Rent implements Updatable { private Book book; private NormalUser person; - private String rentalID; - private LocalDate rentalDate; - private LocalTime rentalTime; + private int rentalID; + private Timestamp rentalTimestamp; public Rent(Book book, NormalUser person) { this.book = book; this.person = person; - this.rentalDate = LocalDate.now(); - this.rentalTime = LocalTime.now(); - this.rentalID = CreateID(); + this.rentalTimestamp = new Timestamp(System.currentTimeMillis()); } - private String CreateID() { - String result = String.valueOf(rentalTime.getSecond()); - result += String.valueOf(rentalTime.getMinute()); - result += String.valueOf(rentalTime.getHour()); - result += String.valueOf(rentalDate.getDayOfYear()); - result += String.valueOf(rentalDate.getYear()); - return result; + public Rent(Book book, NormalUser person, Timestamp rentalTimestamp) { + this.book = book; + this.person = person; + this.rentalTimestamp = rentalTimestamp; } + public void update() { + final String SQL_COMMAND = "SELECT RentalID FROM rents WHERE UserID = ? AND BookID = ?" + + "AND ReturnDate = NULL;"; + + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, + MyApp.DB_USERNAME, MyApp.DB_PASSWORD); + PreparedStatement updateRent = connection.prepareStatement(SQL_COMMAND)) { + + updateRent.setInt(1, this.person.getUniqueID()); + updateRent.setInt(2, this.book.getUniqueID()); + + ResultSet resultSet = updateRent.executeQuery(); + if (resultSet.next()) + this.rentalID = resultSet.getInt("RentalID"); + } catch (SQLException sqlException) { + sqlException.printStackTrace(); + System.err.print("Connection to database failed! Terminating..."); + System.exit(1); + } + } public Book getBook() { return book; } @@ -34,15 +47,11 @@ public NormalUser getPerson() { return person; } - public String getRentalID() { + public int getRentalID() { return rentalID; } - public LocalDate getRentalDate() { - return rentalDate; - } - - public LocalTime getRentalTime() { - return rentalTime; + public Timestamp getRentalTimestamp() { + return rentalTimestamp; } } \ No newline at end of file From b41e6a1e5e53e81b556d72adb14e641000bd6059 Mon Sep 17 00:00:00 2001 From: Hossein Date: Wed, 15 May 2024 04:06:03 +0330 Subject: [PATCH 50/61] add user.toString method --- Answers/src/User.java | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/Answers/src/User.java b/Answers/src/User.java index 7985ddd..abb3d67 100644 --- a/Answers/src/User.java +++ b/Answers/src/User.java @@ -1,18 +1,17 @@ // this class simulates the users // and it is superclass for NormalUser and Admin - import java.sql.*; -public class User { +public class User implements Updatable { private String name; - private String uniqueID; // unique id automatically creates in database + private int uniqueID; // unique id automatically creates in database private String phoneNumber; // constructor public User(String name, String phoneNumber) throws IllegalArgumentException { // validate phoneNumber - String regexPhoneNumber = "(\\+989|09|00989)(0[0-5]|1[0-9]|2[0-3]|3[0-9]|9[0-6]-?\\d{3}-?\\d{4})|" + - "(991[0134]{5})|(99[09]{6})|(998{6})"; + String regexPhoneNumber = "(\\+989|09|00989)((0[0-5]|1[0-9]|2[0-3]|3[0-9]|9[0-6])-?\\d{3}-?\\d{4})|" + + "(99-?1[0134]{2}-?[0134]{4})|(99-?[09]{3}-?[09]{4})"; if (phoneNumber != null && !phoneNumber.matches(regexPhoneNumber)) throw new IllegalArgumentException("Invalid phone number!"); @@ -20,8 +19,8 @@ public User(String name, String phoneNumber) throws IllegalArgumentException { this.phoneNumber = phoneNumber; } - public void uniqueIDUpdate() { - final String SQL_COMMAND = "SELECT UserID FROM Users WHERE PhoneNumber = ?"; + public void update() { + final String SQL_COMMAND = "SELECT UserID FROM users WHERE PhoneNumber = ?"; try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, MyApp.DB_PASSWORD); @@ -30,7 +29,8 @@ public void uniqueIDUpdate() { selectID.setString(1, this.phoneNumber); ResultSet resultSet = selectID.executeQuery(); - this.uniqueID = resultSet.getString(1); + if (resultSet.next()) + this.uniqueID = resultSet.getInt("UserID"); } catch (SQLException sqlException) { sqlException.printStackTrace(); System.err.print("Connection to database failed! Terminating..."); @@ -46,7 +46,13 @@ public String getPhoneNumber() { return phoneNumber; } - public String getUniqueID() { + public int getUniqueID() { return uniqueID; } + + @Override + // to string method of admins + public String toString() { + return String.format("You are "+ this.getName() + " with id = " + this.getUniqueID()); + } } From 2b12c43f3242a04aa3aab99dab57c34900964d89 Mon Sep 17 00:00:00 2001 From: Hossein Date: Wed, 15 May 2024 04:07:22 +0330 Subject: [PATCH 51/61] update .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 6cba7b4..f4b8cf3 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ /out/production/Library-Management-System/NormalUser.class /out/production/Library-Management-System/Rent.class /out/production/Library-Management-System/User.class +/out/production/Library-Management-System/Updatable.class From 2048767ec10c2047c657b47f9d67340bd911f977 Mon Sep 17 00:00:00 2001 From: Hossein Date: Thu, 16 May 2024 16:48:10 +0330 Subject: [PATCH 52/61] add new constructor to book class --- Answers/src/Book.java | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/Answers/src/Book.java b/Answers/src/Book.java index 22240e8..0dbb580 100644 --- a/Answers/src/Book.java +++ b/Answers/src/Book.java @@ -1,6 +1,6 @@ import java.sql.*; -public class Book { +public class Book implements Updatable { private String title; private String author; private String description; @@ -20,6 +20,33 @@ public Book(String title, String author, String description) { this.description = description; } + public Book(int bookID) throws Exception { + final String SQL_COMMAND = "SELECT * FROM books WHERE BookID = ?;"; + + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, + MyApp.DB_PASSWORD); + PreparedStatement selectBook = connection.prepareStatement(SQL_COMMAND)){ + + selectBook.setInt(1, bookID); + + ResultSet resultSet = selectBook.executeQuery(); + + if (resultSet.next()) { + this.uniqueID = bookID; + this.title = resultSet.getString("Title"); + this.author = resultSet.getString("Author"); + this.description = resultSet.getString("Description"); + this.availabilityStatus = resultSet.getBoolean("AvailabilityStatus"); + } else + throw new Exception("Book with ID = " + bookID + " not found."); + } catch (SQLException e) { + e.printStackTrace(); + System.err.print("Connection to database failed! Terminating..."); + System.exit(1); + } + } + + @Override public void update() { final String SQL_COMMAND = "SELECT BookID, AvailabilityStatus FROM books WHERE Title = ? " + "AND Author = ?"; @@ -43,7 +70,7 @@ public void update() { } } - public void getStatus(boolean availabilityStatus) { + public void setStatus(boolean availabilityStatus) { final String SQL_COMMAND = "UPDATE books SET AvailabilityStatus = ? WHERE BookID = ?;"; try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, @@ -54,7 +81,7 @@ public void getStatus(boolean availabilityStatus) { changeStatusCommand.setInt(2, this.uniqueID); changeStatusCommand.executeUpdate(); - this.availabilityStatus = false; + this.availabilityStatus = availabilityStatus; } catch (SQLException e) { e.printStackTrace(); System.err.print("Connection to database failed! Terminating..."); From 5b3b79638303c92d02c536ff47dc584270bd21fa Mon Sep 17 00:00:00 2001 From: Hossein Date: Thu, 16 May 2024 16:49:01 +0330 Subject: [PATCH 53/61] add returnBook method --- Answers/src/Library.java | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/Answers/src/Library.java b/Answers/src/Library.java index 55b7c88..df96f87 100644 --- a/Answers/src/Library.java +++ b/Answers/src/Library.java @@ -170,7 +170,7 @@ public int addBook(Book book) { // login to library public User login(String userID) { User user = null; - final String SQL_COMMAND = "SELECT * FROM users WHERE UserID = ?"; + final String SQL_COMMAND = "SELECT * FROM users WHERE UserID = ?"; try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, MyApp.DB_PASSWORD); @@ -277,26 +277,28 @@ public ArrayList searchBook(String bookName) { } } - // add rent to library - public int addRent(Rent rent) { - final String SQL_COMMAND = "INSERT INTO rents (UserID, BookID, RentalDate) VALUES (?, ?, ?);"; + public void returnBook(int bookID) { + // set rental date in database + final String SQL_COMMAND1 = "UPDATE rents SET ReturnDate = ? WHERE BookID = ?;"; + + // change availability status of the book + final String SQL_COMMAND2 = "UPDATE books SET AvailabilityStatus = 1 WHERE BookID = ?;"; try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, MyApp.DB_PASSWORD); - PreparedStatement addRentCommand = connection.prepareStatement(SQL_COMMAND)){ - - addRentCommand.setInt(1, rent.getPerson().getUniqueID()); - addRentCommand.setInt(2, rent.getBook().getUniqueID()); - addRentCommand.setTimestamp(3, rent.getRentalTimestamp()); - addRentCommand.executeUpdate(); - - rent.update(); - rent.getBook().getStatus(false); - return rent.getRentalID(); + PreparedStatement returnCommand = connection.prepareStatement(SQL_COMMAND1); + PreparedStatement changeStatus = connection.prepareStatement(SQL_COMMAND2)) { + // set rental date + returnCommand.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + returnCommand.setInt(2, bookID); + returnCommand.executeUpdate(); + + // change availability status of the book + changeStatus.setInt(1, bookID); + changeStatus.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); System.err.print("Connection to database failed!"); - return 0; } } } From 0281db84d44cd25a488e45d7e3c606453fcdee51 Mon Sep 17 00:00:00 2001 From: Hossein Date: Thu, 16 May 2024 16:49:25 +0330 Subject: [PATCH 54/61] add return book command --- Answers/src/MyApp.java | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/Answers/src/MyApp.java b/Answers/src/MyApp.java index bd4fdb1..1f5f7c1 100644 --- a/Answers/src/MyApp.java +++ b/Answers/src/MyApp.java @@ -268,8 +268,23 @@ else if (command.matches("lib\\sremove\\smember\\s\\d{7,}")) { bookID); } else throw new NoPermissionException("You don't have permission to add books!"); - } else if (command.matches("lib return \\w*")) { + } else if (command.matches("lib\\sreturn\\s.+")) { // return a book + String bookName = command.substring(11); + ArrayList books = ((NormalUser) library.getUser()).getRentBooks(); + boolean hasBook = false; + int bookID = 0; + for (Book book:books) + if (book.getTitle().equals(bookName)) { + hasBook = true; + bookID = book.getUniqueID(); + } + if (hasBook) { + library.returnBook(bookID); + System.out.printf("Book <%s> returned to library.%n", bookName); + } + else + System.out.println("You didn't rent this book:)"); } else if (command.matches("lib\\slogin\\s\\d+")) { //command lib login if (library.getUser() != null) @@ -388,7 +403,7 @@ else if (library.getUser() instanceof Admin) // create rent class rent = new Rent(books.get(choice - 1), (NormalUser) library.getUser()); } - int rentalID = library.addRent(rent); + int rentalID = ((NormalUser) library.getUser()).rentBook(rent); if (rentalID == 0) return; System.out.println("You rented this book successfully."); From 0c3939e2bb4efe74ce224645c17c2d934dee2f88 Mon Sep 17 00:00:00 2001 From: Hossein Date: Thu, 16 May 2024 16:51:20 +0330 Subject: [PATCH 55/61] add rentBook and update command --- Answers/src/NormalUser.java | 60 +++++++++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/Answers/src/NormalUser.java b/Answers/src/NormalUser.java index b00a365..d8365f8 100644 --- a/Answers/src/NormalUser.java +++ b/Answers/src/NormalUser.java @@ -1,7 +1,9 @@ -import java.sql.Timestamp; +import java.sql.*; +import java.util.ArrayList; -public class NormalUser extends User { +public class NormalUser extends User implements Updatable { private Timestamp registerTimestamp; + private ArrayList rentBooks = new ArrayList<>(); public NormalUser(String name, String phoneNumber, Timestamp registerDateTime) { super(name, phoneNumber); @@ -16,4 +18,58 @@ public NormalUser(String name, String phoneNumber) { public Timestamp getRegisterTimestamp() { return registerTimestamp; } + + // rent a book + public int rentBook(Rent rent) { + final String SQL_COMMAND = "INSERT INTO rents (UserID, BookID, RentalDate) VALUES (?, ?, ?);"; + + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, + MyApp.DB_PASSWORD); + PreparedStatement addRentCommand = connection.prepareStatement(SQL_COMMAND)){ + + addRentCommand.setInt(1, rent.getPerson().getUniqueID()); + addRentCommand.setInt(2, rent.getBook().getUniqueID()); + addRentCommand.setTimestamp(3, rent.getRentalTimestamp()); + addRentCommand.executeUpdate(); + + rent.update(); + rent.getBook().setStatus(false); + rentBooks.add(rent.getBook()); + return rent.getRentalID(); + } catch (SQLException e) { + e.printStackTrace(); + System.err.print("Connection to database failed!"); + return 0; + } + } + + @Override + public void update() { + super.update(); + final String SQL_COMMAND = "SELECT * FROM rents WHERE UserID = ? AND ReturnDate IS NULL;"; + + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, + MyApp.DB_PASSWORD); + PreparedStatement selectRentBooks = connection.prepareStatement(SQL_COMMAND)) { + + selectRentBooks.setInt(1, this.getUniqueID()); + + ResultSet resultSet = selectRentBooks.executeQuery(); + + while (resultSet.next()) { + Book book = new Book(resultSet.getInt("BookID")); + rentBooks.add(book); + } + } catch (SQLException e) { + e.printStackTrace(); + System.err.print("Connection to database failed!"); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } + + public ArrayList getRentBooks() { + update(); + return rentBooks; + } } \ No newline at end of file From 45d5694401f53c83d558d10add275706f035959a Mon Sep 17 00:00:00 2001 From: Hossein Date: Thu, 16 May 2024 23:58:09 +0330 Subject: [PATCH 56/61] add command lib get rented books --- Answers/src/Manual.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Answers/src/Manual.java b/Answers/src/Manual.java index 3dde612..469de3e 100644 --- a/Answers/src/Manual.java +++ b/Answers/src/Manual.java @@ -18,6 +18,9 @@ public static void printNormalUser() { // command rent from library System.out.println("lib rent : Rent a book from the library."); + // command lib get rented books + System.out.println("lib get rented books : shows your rented books"); + // command exit System.out.println("lib exit : exit the program"); From 5105a6cb8dac0abf03b22d69488098849865c5b4 Mon Sep 17 00:00:00 2001 From: Hossein Date: Thu, 16 May 2024 23:58:29 +0330 Subject: [PATCH 57/61] add command lib get rented books --- Answers/src/MyApp.java | 363 +++++++++++++++++++++++++++++------------ 1 file changed, 260 insertions(+), 103 deletions(-) diff --git a/Answers/src/MyApp.java b/Answers/src/MyApp.java index 1f5f7c1..e3f763d 100644 --- a/Answers/src/MyApp.java +++ b/Answers/src/MyApp.java @@ -1,4 +1,5 @@ // main class for handling the CLI + import javax.naming.NoPermissionException; import java.io.File; import java.io.FileNotFoundException; @@ -7,7 +8,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.security.InvalidParameterException; -import java.sql.ResultSet; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Scanner; @@ -169,20 +169,56 @@ else if (command.matches("lib\\sman")) { Manual.printNormalUser(); } + else if (command.matches("lib\\sget\\srented\\sbooks")) { + if (library.getUser() == null) + throw new NoPermissionException("You should first login."); + else if (library.getUser() instanceof Admin) + throw new NoPermissionException("You are admin!You can't rent a book:)"); + + ArrayList books = ((NormalUser) library.getUser()).getRentBooks(); + + if (books.size() == 1) + System.out.println("Your rented book is :"); + else + System.out.println("Your rented books are: "); + + int numberOfRows = 1; + for (Book book : books) { + System.out.printf("%d.%s", numberOfRows++, book.getTitle()); + System.out.println(); + } + } // command lib get hrs else if (command.matches("lib\\sget\\shrs")) System.out.print(library.getOperatingHours()); else if (command.matches("lib\\sget\\savailable\\sbooks")) library.getAvailableBooks(); // command lib remove member - else if (command.matches("lib\\sremove\\smember\\s\\d{7,}")) { - // get user id from command - int userID = Integer.parseInt(command.substring(18)); - - if (library.removeUser(userID) == 0) - throw new IllegalArgumentException("User with " + userID + " not found!"); - - System.out.printf("Account with ID = %d deleted successfully.%n", userID); + else if (command.matches("lib\\slogin\\s\\d+")) { + //command lib login + if (library.getUser() != null) + throw new NoPermissionException("Another account is still logged in! " + + "Log out and try again."); + String[] temp = command.split("\\s"); + library.setUser(library.login(temp[2])); + if (library.getUser() == null) + throw new InvalidParameterException(); + else if (library.getUser() instanceof NormalUser) + System.out.printf("Hello %s!You logged in successfully.%n", library.getUser().getName()); + else { + Admin adminUser = (Admin) library.getUser(); + for (int i = 0; i < 3; i++) { + System.out.printf("Enter password for %s: ", adminUser.getName()); + String password = input.nextLine(); + if (adminUser.verify(password)) { + System.out.printf("Hello %s! You logged in successfully.%n", adminUser.getName()); + return; + } else + System.out.println("Invalid password. Try again."); + } + library.setUser(null); + throw new IllegalArgumentException("3 incorrect password attempts..."); + } } else if (command.matches("lib\\slogout")) { if (library.getUser() == null) System.out.println("No one has logged in yet"); @@ -190,6 +226,207 @@ else if (command.matches("lib\\sremove\\smember\\s\\d{7,}")) { System.out.printf("%s logged out successfully.%n", library.getUser().getName()); library.setUser(null); } + } else if (command.matches("lib\\sreturn\\s.+")) { + // return a book + String bookName = command.substring(11); + ArrayList books = ((NormalUser) library.getUser()).getRentBooks(); + boolean hasBook = false; + int bookID = 0; + for (Book book : books) + if (book.getTitle().equals(bookName)) { + hasBook = true; + bookID = book.getUniqueID(); + } + if (hasBook) { + library.returnBook(bookID); + System.out.printf("Book <%s> returned to library.%n", bookName); + } else + System.out.println("You didn't rent this book:)"); + } else if (command.matches("lib\\srent\\s\"?[^\"]*\"?\\s\"?[^\"]*\"?\\s\\d{7,}")) { + if (library.getUser() == null) + throw new NoPermissionException("You should first login."); + else if (library.getUser() instanceof NormalUser) + throw new NoPermissionException("You don't have permission to rent a book for " + + "another person."); + else + for (int i = 0; i < 3; i++) { + System.out.printf("Enter password for %s: ", library.getUser().getName()); + String password = input.nextLine(); + if (((Admin) library.getUser()).verify(password)) + break; + else if (i == 2) { + System.out.println("3 incorrect password attempts..."); + library.setUser(null); + return; + } else + System.out.println("Invalid password. Try again."); + } + command = command.substring(9); + + String[] temp = new String[2]; + for (int i = 0; i < 2; i++) { + if (command.startsWith("\"")) { + command = command.substring(1); + temp[i] = command.substring(0, command.indexOf("\"")); + command = command.replaceFirst(temp[i] + "\" ", ""); + } else { + temp[i] = command.substring(0, command.indexOf(" ")); + command = command.replaceFirst(temp[i] + " ", ""); + } + } + + String bookName = temp[0], memberName = temp[1]; + int memberID = Integer.parseInt(command); + + // get books with this name + ArrayList books = library.searchBook(bookName); + + if (books.size() == 0) { + System.out.printf("book %s not found or not available!%n", bookName); + return; + } + + Rent rent = null; + NormalUser user = null; + + try { + user = new NormalUser(memberID, memberName); + } catch (Exception e) { + System.out.println(e.getMessage()); + return; + } + + if (books.size() == 1) + rent = new Rent(books.get(0), user); + else if (user.getRentBooks().size() >= 5) { + System.out.println("You have already rented 5 books and you can no longer " + + "rent a book"); + return; + } else { + System.out.println("Which book?"); + + // show selections + int numberOfRows = 1; + for (Book book : books) { + System.out.printf("%d. ID = %d, Author = %d", numberOfRows, + book.getUniqueID(), book.getAuthor()); + numberOfRows++; + } + + // select choice + int choice = 1; + for (int i = 0; i < 3; i++) { + if (library.getUser() == null) + System.out.print(">>> "); + else if (library.getUser() instanceof Admin) + System.out.print("Admin> "); + else + System.out.printf("%s> ", library.getUser().getName()); + choice = input.nextInt(); + if (choice > numberOfRows) { + if (i == 2) { + System.out.println("3 invalid choice..."); + return; + } + System.out.print("Invalid choice. please try again."); + } else + break; + } + + // create rent class + rent = new Rent(books.get(choice - 1), user); + + } + int rentalID = user.rentBook(rent); + if (rentalID == 0) + return; + System.out.printf("Book %s was rented for %s successfully.", bookName, user.getName()); + System.out.printf("rental ID = %d%n", rentalID); + } else if (command.matches("lib\\sadd\\smember\\s\"?[^\"]*\"?\\s\\+?[\\d-]+\\s?[^(\"\\s)]*")) { + // commadn lib add member + // if he didn't admin user yet throw exception + if (library.getUser() instanceof Admin) { + for (int i = 0; i < 3; i++) { + System.out.printf("Enter password for %s: ", library.getUser().getName()); + String password = input.nextLine(); + if (((Admin) library.getUser()).verify(password)) + break; + else if (i == 2) { + System.out.println("3 incorrect password attempts..."); + library.setUser(null); + return; + } else + System.out.println("Invalid password. Try again."); + } + + String name, phoneNumber; + int userID; + + String[] temp1 = command.split("\""); + if (temp1.length == 3) { + name = temp1[1].trim(); + + String[] temp2 = temp1[2].trim().split("\\s"); + phoneNumber = temp2[0].trim(); + User user; + if (temp2.length == 2) { + user = new Admin(name, phoneNumber, temp2[1].trim()); + userID = library.addUser(user, temp2[1].trim()); + } else { + user = new NormalUser(name, phoneNumber); + userID = library.addUser((NormalUser) user); + } + } else { + String[] temp = command.split("\\s"); + + if (temp.length > 6) + throw new IllegalArgumentException( + "You should use \" character to split string with space"); + + name = temp[3].trim(); + phoneNumber = temp[4].trim(); + + User user; + if (temp.length == 6) { + user = new Admin(name, phoneNumber, temp[5].trim()); + userID = library.addUser(user, temp[5].trim()); + } else { + user = new NormalUser(name, phoneNumber); + userID = library.addUser((NormalUser) user); + } + } + + // prompt the user + System.out.printf("User %s with ID = %d added to library.%n", name, userID); + } // end if (library.user instanceof Admin) + else + throw new NoPermissionException("You don't have permission to add members!"); + } else if (command.matches("lib\\sremove\\smember\\s\\d{7,}")) { + if (library.getUser() == null) + throw new NoPermissionException("You should first login."); + else if (library.getUser() instanceof NormalUser) + throw new NoPermissionException("You don't have permission to remove members."); + else + for (int i = 0; i < 3; i++) { + System.out.printf("Enter password for %s: ", library.getUser().getName()); + String password = input.nextLine(); + if (((Admin) library.getUser()).verify(password)) + break; + else if (i == 2) { + System.out.println("3 incorrect password attempts..."); + library.setUser(null); + return; + } else + System.out.println("Invalid password. Try again."); + } + + // get user id from command + int userID = Integer.parseInt(command.substring(18)); + + if (library.removeUser(userID) == 0) + throw new IllegalArgumentException("User with " + userID + " not found!"); + + System.out.printf("Account with ID = %d deleted successfully.%n", userID); } else if (command.matches("lib\\sadd\\sbook\\s\"?[^\"]*\"?\\s\"?[^\"]*\"?\\s?(\"?[^\"]*\"?)?")) { // command lib add book // if he didn't admin user yet throw exception @@ -268,94 +505,6 @@ else if (command.matches("lib\\sremove\\smember\\s\\d{7,}")) { bookID); } else throw new NoPermissionException("You don't have permission to add books!"); - } else if (command.matches("lib\\sreturn\\s.+")) { - // return a book - String bookName = command.substring(11); - ArrayList books = ((NormalUser) library.getUser()).getRentBooks(); - boolean hasBook = false; - int bookID = 0; - for (Book book:books) - if (book.getTitle().equals(bookName)) { - hasBook = true; - bookID = book.getUniqueID(); - } - if (hasBook) { - library.returnBook(bookID); - System.out.printf("Book <%s> returned to library.%n", bookName); - } - else - System.out.println("You didn't rent this book:)"); - } else if (command.matches("lib\\slogin\\s\\d+")) { - //command lib login - if (library.getUser() != null) - throw new NoPermissionException("Another account is still logged in! " + - "Log out and try again."); - String[] temp = command.split("\\s"); - library.setUser(library.login(temp[2])); - if (library.getUser() == null) - throw new InvalidParameterException(); - else if (library.getUser() instanceof NormalUser) - System.out.printf("Hello %s!You logged in successfully.%n", library.getUser().getName()); - else { - Admin adminUser = (Admin) library.getUser(); - for (int i = 0; i < 3; i++) { - System.out.printf("Enter password for %s: ", adminUser.getName()); - String password = input.nextLine(); - if (adminUser.verify(password)) { - System.out.printf("Hello %s! You logged in successfully.%n", adminUser.getName()); - return; - } else - System.out.println("Invalid password. Try again."); - } - library.setUser(null); - throw new IllegalArgumentException("3 incorrect password attempts..."); - } - } else if (command.matches("lib\\sadd\\smember\\s\"?[^\"]*\"?\\s\\+?[\\d-]+\\s?[^(\"\\s)]*")) { - // commadn lib add member - // if he didn't admin user yet throw exception - if (library.getUser() instanceof Admin) { - String name, phoneNumber; - int userID; - - String[] temp1 = command.split("\""); - if (temp1.length == 3) { - name = temp1[1].trim(); - - String[] temp2 = temp1[2].trim().split("\\s"); - phoneNumber = temp2[0].trim(); - User user; - if (temp2.length == 2) { - user = new Admin(name, phoneNumber, temp2[1].trim()); - userID = library.addUser(user, temp2[1].trim()); - } else { - user = new NormalUser(name, phoneNumber); - userID = library.addUser((NormalUser) user); - } - } else { - String[] temp = command.split("\\s"); - - if (temp.length > 6) - throw new IllegalArgumentException( - "You should use \" character to split string with space"); - - name = temp[3].trim(); - phoneNumber = temp[4].trim(); - - User user; - if (temp.length == 6) { - user = new Admin(name, phoneNumber, temp[5].trim()); - userID = library.addUser(user, temp[5].trim()); - } else { - user = new NormalUser(name, phoneNumber); - userID = library.addUser((NormalUser) user); - } - } - - // prompt the user - System.out.printf("User %s with ID = %d added to library.%n", name, userID); - } // end if (library.user instanceof Admin) - else - throw new NoPermissionException("You don't have permission to add members!"); } else if (command.matches("lib\\srent\\s.+")) { if (library.getUser() == null) System.out.println("You should first login to rent a book."); @@ -367,13 +516,17 @@ else if (library.getUser() instanceof Admin) bookName = bookName.substring(1, bookName.length() - 1); ArrayList books = library.searchBook(bookName); - Rent rent; + Rent rent = null; + if (books.size() == 0) { System.out.printf("book %s not found or not available!%n", bookName); return; } else if (books.size() == 1) rent = new Rent(books.get(0), (NormalUser) library.getUser()); - else { + else if (((NormalUser) library.getUser()).getRentBooks().size() >= 5) { + System.out.println("You have already rented 5 books and you can no longer " + + "rent a book"); + } else { System.out.println("Which book do you want?"); // show selections @@ -387,16 +540,20 @@ else if (library.getUser() instanceof Admin) // select choice int choice = 1; for (int i = 0; i < 3; i++) { - System.out.print(">>>"); + if (library.getUser() == null) + System.out.print(">>> "); + else if (library.getUser() instanceof Admin) + System.out.print("Admin> "); + else + System.out.printf("%s> ", library.getUser().getName()); choice = input.nextInt(); if (choice > numberOfRows) { if (i == 2) { System.out.println("3 invalid choice..."); return; } - System.out.printf("Invalid choice. please try again."); - } - else + System.out.print("Invalid choice. please try again."); + } else break; } From fca39936713772d314dc4e14c17649c23584561c Mon Sep 17 00:00:00 2001 From: Hossein Date: Thu, 16 May 2024 23:58:46 +0330 Subject: [PATCH 58/61] add new constructor --- Answers/src/NormalUser.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Answers/src/NormalUser.java b/Answers/src/NormalUser.java index d8365f8..558faa2 100644 --- a/Answers/src/NormalUser.java +++ b/Answers/src/NormalUser.java @@ -15,6 +15,29 @@ public NormalUser(String name, String phoneNumber) { this.registerTimestamp = new Timestamp(System.currentTimeMillis()); } + public NormalUser(int userID, String name) throws Exception { + super(userID, name); + final String SQL_COMMAND = "SELECT RegisterTimeStamp FROM users WHERE UserID = ? " + + "AND UserType = 'normal';"; + + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, + MyApp.DB_PASSWORD); + PreparedStatement selectUser = connection.prepareStatement(SQL_COMMAND)){ + + selectUser.setInt(1, userID); + ResultSet resultSet = selectUser.executeQuery(); + + if (resultSet.next()) { + registerTimestamp = resultSet.getTimestamp("RegisterTimeStamp"); + } else + throw new Exception("User with ID = " + userID + "is not a normal user."); + } catch (SQLException e) { + e.printStackTrace(); + System.err.print("Connection to database failed! Terminating..."); + System.exit(1); + } + } + public Timestamp getRegisterTimestamp() { return registerTimestamp; } @@ -47,6 +70,7 @@ public int rentBook(Rent rent) { public void update() { super.update(); final String SQL_COMMAND = "SELECT * FROM rents WHERE UserID = ? AND ReturnDate IS NULL;"; + rentBooks.clear(); try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, MyApp.DB_PASSWORD); From 97e67cfa3c0bbbdf51a2431381326359d0eaabfb Mon Sep 17 00:00:00 2001 From: Hossein Date: Thu, 16 May 2024 23:58:57 +0330 Subject: [PATCH 59/61] debug --- Answers/src/Rent.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Answers/src/Rent.java b/Answers/src/Rent.java index c584974..8d7316d 100644 --- a/Answers/src/Rent.java +++ b/Answers/src/Rent.java @@ -20,8 +20,8 @@ public Rent(Book book, NormalUser person, Timestamp rentalTimestamp) { } public void update() { - final String SQL_COMMAND = "SELECT RentalID FROM rents WHERE UserID = ? AND BookID = ?" + - "AND ReturnDate = NULL;"; + final String SQL_COMMAND = "SELECT RentalID FROM rents WHERE UserID = ? AND BookID = ? " + + "AND ReturnDate IS NULL;"; try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, MyApp.DB_PASSWORD); From a2300539a3cd0422829fa3a8e0f3417bcc3f1e82 Mon Sep 17 00:00:00 2001 From: Hossein Date: Thu, 16 May 2024 23:59:15 +0330 Subject: [PATCH 60/61] add new constructor --- Answers/src/User.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/Answers/src/User.java b/Answers/src/User.java index abb3d67..8d34632 100644 --- a/Answers/src/User.java +++ b/Answers/src/User.java @@ -19,6 +19,33 @@ public User(String name, String phoneNumber) throws IllegalArgumentException { this.phoneNumber = phoneNumber; } + protected User(int uniqueID, String name) throws Exception { + final String SQL_COMMAND = "SELECT Name, PhoneNumber FROM users WHERE UserID = ?;"; + + try (Connection connection = DriverManager.getConnection(MyApp.DB_URL, MyApp.DB_USERNAME, + MyApp.DB_PASSWORD); + PreparedStatement selectUser = connection.prepareStatement(SQL_COMMAND)) { + + selectUser.setInt(1, uniqueID); + ResultSet resultSet = selectUser.executeQuery(); + + if (resultSet.next()) { + if (name.equals(resultSet.getString("Name"))) + this.name = name; + else + throw new Exception("The username does not match the ID"); + this.uniqueID = uniqueID; + this.phoneNumber = resultSet.getString("PhoneNumber"); + } else + throw new Exception("User with ID = " + uniqueID + "not found."); + } catch (SQLException e) { + e.printStackTrace(); + System.err.print("Connection to database failed! Terminating..."); + System.exit(1); + } + } + + @Override public void update() { final String SQL_COMMAND = "SELECT UserID FROM users WHERE PhoneNumber = ?"; From a42328285ea440283a182d3ca6c9cf2ddc0c1d04 Mon Sep 17 00:00:00 2001 From: Hossein Date: Fri, 17 May 2024 00:10:33 +0330 Subject: [PATCH 61/61] debug --- Answers/src/MyApp.java | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Answers/src/MyApp.java b/Answers/src/MyApp.java index e3f763d..a092cd2 100644 --- a/Answers/src/MyApp.java +++ b/Answers/src/MyApp.java @@ -296,13 +296,13 @@ else if (i == 2) { return; } - if (books.size() == 1) - rent = new Rent(books.get(0), user); - else if (user.getRentBooks().size() >= 5) { + if (user.getRentBooks().size() >= 5) { System.out.println("You have already rented 5 books and you can no longer " + "rent a book"); return; - } else { + } if (books.size() == 1) + rent = new Rent(books.get(0), user); + else { System.out.println("Which book?"); // show selections @@ -521,12 +521,13 @@ else if (library.getUser() instanceof Admin) if (books.size() == 0) { System.out.printf("book %s not found or not available!%n", bookName); return; - } else if (books.size() == 1) - rent = new Rent(books.get(0), (NormalUser) library.getUser()); - else if (((NormalUser) library.getUser()).getRentBooks().size() >= 5) { + } else if (((NormalUser) library.getUser()).getRentBooks().size() >= 5) { System.out.println("You have already rented 5 books and you can no longer " + "rent a book"); - } else { + return; + } else if (books.size() == 1) + rent = new Rent(books.get(0), (NormalUser) library.getUser()); + else { System.out.println("Which book do you want?"); // show selections