· 6 years ago · May 11, 2019, 03:58 AM
1package Main;
2
3import Datatypes.*;
4import java.io.File;
5import java.io.FileNotFoundException;
6import java.sql.ResultSet;
7import java.sql.SQLException;
8import java.util.ArrayList;
9import java.util.HashMap;
10import java.util.List;
11import java.util.Scanner;
12
13// class that contains all of the data that is taken from the database
14public class Library {
15 public DB_Connection DB;
16 public HashMap<Integer, Book> books = new HashMap<Integer, Book>();// Book table
17 public HashMap<Integer, Author> authors = new HashMap<Integer, Author>();// Author table
18 public HashMap<Integer, Publisher> publishers = new HashMap<Integer, Publisher>();// Publisher table
19 public HashMap<Integer, Genre> genres = new HashMap<Integer, Genre>();// Genre table
20 public HashMap<Integer, User> users = new HashMap<Integer, User>();// User table
21 public HashMap<Integer, Rental> rentals = new HashMap<Integer, Rental>();// Rental table
22
23 public Library(DB_Connection db) {
24 this.DB = db;
25 GetAuthors();
26 GetPublishers();
27 GetGenres();
28 GetBooks();
29 GetUsers();
30 }
31
32 // Query database for all books and our tables to match the database
33 public void GetBooks() {
34 books.clear();
35 try {
36 ResultSet res = DB.SelectData("BOOK", "*");
37 while (res.next())
38 new Book(this, res);
39 } catch (SQLException e) {
40 e.printStackTrace();
41 }
42 }
43 // Query database for all authors and our tables to match the database
44 public void GetAuthors() {
45 authors.clear();
46 try {
47 ResultSet res = DB.SelectData("AUTHOR", "*");
48 while (res.next())
49 new Author(this, res);
50 } catch (SQLException e) {
51 e.printStackTrace();
52 }
53 }
54 // Query database for all publishers and our tables to match the database
55 public void GetPublishers() {
56 publishers.clear();
57 try {
58 ResultSet res = DB.SelectData("PUBLISHER", "*");
59 while (res.next())
60 new Publisher(this, res);
61 } catch (SQLException e) {
62 e.printStackTrace();
63 }
64 }
65 // Query database for all genres and our tables to match the database
66 public void GetGenres() {
67 genres.clear();
68 try {
69 ResultSet res = DB.SelectData("GENRE", "*");
70 while (res.next())
71 new Genre(this, res);
72 } catch (SQLException e) {
73 e.printStackTrace();
74 }
75 }
76 // Query database for all users and our tables to match the database
77 public void GetUsers() {
78 users.clear();
79 try {
80 ResultSet res = DB.SelectData("USER", "*");
81 while (res.next())
82 new User(this, res);
83 } catch (SQLException e) {
84 e.printStackTrace();
85 } catch (Exception e) {
86 e.printStackTrace();
87 }
88 }
89 // Query database for all rentals and our tables to match the database
90 public void GetRentals() {
91 rentals.clear();
92 try {
93 ResultSet res = DB.SelectData("RENTAL", "*");
94 while (res.next())
95 new Rental(this, res);
96 } catch (SQLException e) {
97 e.printStackTrace();
98 } catch (Exception e) {
99 e.printStackTrace();
100 }
101 }
102
103 // Create guest user account with given email and password
104 public User CreateUser(String email, String password) throws Exception {
105 if (GetUser(email) != null)
106 throw new Exception("User with email already exists.");
107 return new User(this, email, password, Permission_Group.Guest);
108 }
109 // Attempt to login to the database with given email and password
110 public User Login(String email, String password) throws Exception {
111 User candidate = GetUser(email);
112 if (candidate == null) throw new Exception("User with email does not exist.");
113 if (!password.equals(candidate.getPassword()))
114 throw new Exception("Incorrect password");
115 return candidate;
116 }
117
118 // Clear all entries in given table
119 public void ClearTable(String table) {
120 table = table.toUpperCase();
121 DB.ClearTable(table);
122
123 switch (table) {
124 case "BOOK":
125 books.clear();
126 break;
127 case "AUTHOR":
128 authors.clear();
129 break;
130 case "PUBLISHER":
131 publishers.clear();
132 break;
133 case "GENRE":
134 genres.clear();
135 break;
136 case "USER":
137 users.clear();
138 break;
139 case "RENTAL":
140 rentals.clear();
141 break;
142 }
143 }
144 // Clear all entries in the database
145 public void ClearTables() {
146 ClearTable("BOOK");
147 ClearTable("AUTHOR");
148 ClearTable("PUBLISHER");
149 ClearTable("GENRE");
150 ClearTable("USER");
151 ClearTable("RENTAL");
152 }
153
154 // Check if an ID is valid (basic check)
155 public static boolean InvalidID(int id) {
156 return id <= 0;
157 }
158 // Check for valid ID, making sure the ID ins't in use
159 public static boolean InvalidID(int id, HashMap<?, ?> table) {
160 return InvalidID(id) || table.containsKey(id);
161 }
162
163 // Get random unique ID that isn't in use
164 private static int GetUniqueID(HashMap<?, ?> table) {
165 while (true) {
166 int id = (int) (Math.random() * Integer.MAX_VALUE);
167 if (!table.containsKey(id)) return id;
168 }
169 }
170 // Get unique id based on given string, to create a consistent generated ID
171 public static int GetUniqueID(HashMap<?, ?> table, String hash) {
172 int id = Math.abs(hash.hashCode());
173 if (!table.containsKey(id)) return id;
174 return GetUniqueID(table);
175 }
176
177 // Make sure string meets the length requirement of the SQL field
178 public static String Truncate(String str, int len, boolean dots) {
179 if (str.length() > len) {
180 if (dots) return str.substring(0, len - 3) + "...";
181 return str.substring(0, len);
182 }
183 return str;
184 }
185
186 // Import books into database from a file, optional random stock values for testing
187 public ArrayList<Book> ImportBooks(String filename, boolean randStock)
188 throws FileNotFoundException {
189 ArrayList<Book> added = new ArrayList<Book>();
190 List<List<String>> records = new ArrayList<>();
191 try (Scanner scanner = new Scanner(new File(filename))) {
192 while (scanner.hasNextLine()) {
193 List<String> values = new ArrayList<String>();
194 try (Scanner rowScanner = new Scanner(scanner.nextLine())) {
195 rowScanner.useDelimiter("\t");
196 while (rowScanner.hasNext())
197 values.add(rowScanner.next().trim());
198
199 records.add(values);
200 }
201 }
202 }
203
204 List<String> header = records.get(0);
205 int headerLen = header.size();
206 for (int i = 0; i < headerLen; i++)
207 header.set(i, header.get(i).toUpperCase());
208
209 int len = records.size();
210 for (int i = 1; i < len; i++) {
211 List<String> bookRecord = records.get(i);
212
213 Book book = new Book(this);
214 Author auth = new Author(this);
215 Publisher pub = new Publisher(this);
216 Genre gen = new Genre(this);
217
218 for (int j = 0; j < headerLen; j++) {
219 String val = bookRecord.get(j);
220 switch (header.get(j)) {
221 case "ID:":
222 book.id = Integer.parseInt(val);
223 break;
224 case "TITLE":
225 book.setTitle(val);
226 break;
227 case "DESCRIPTION":
228 book.setDescription(val);
229 break;
230 case "PAGES":
231 book.setPages(Integer.parseInt(val));
232 break;
233 case "DATE":
234 book.setDate(val);
235 break;
236 case "AUTHOR_ID":
237 auth.id = Integer.parseInt(val);
238 case "FIRSTNAME":
239 auth.setFirstname(val);
240 break;
241 case "LASTNAME":
242 auth.setLastname(val);
243 break;
244 case "PUBLISHER_ID":
245 pub.id = Integer.parseInt(val);
246 break;
247 case "PUBLISHER":
248 pub.setName(val);
249 break;
250 case "GENRE_ID":
251 gen.id = Integer.parseInt(val);
252 break;
253 case "GENRE":
254 gen.setName(val);
255 break;
256 case "STOCK":
257 book.setStock(Integer.parseInt(val));
258 break;
259 case "PRICE":
260 book.setPrice(Float.parseFloat(val));
261 break;
262 }
263 }
264
265 Author a = GetAuthor(auth.getFullName());
266 if (a != null) auth = a;
267 else auth.Insert();
268
269 Publisher p = GetPublisher(pub.getName());
270 if (p != null) pub = p;
271 else pub.Insert();
272
273 Genre g = GetGenre(gen.getName());
274 if (g != null) gen = g;
275 else gen.Insert();
276
277 if (randStock) book.setStock((int) (Math.random() * 20));
278
279 book.author = auth;
280 book.publisher = pub;
281 book.genre = gen;
282 book.Insert();
283 added.add(book);
284 }
285
286 return added;
287 }
288
289 // Find author in database with given name
290 public Author GetAuthor(String fullname) {
291 for (Author a : authors.values())
292 if (a.getFullName().equals(fullname))
293 return a;
294 return null;
295 }
296 // Find publisher in database with given name
297 public Publisher GetPublisher(String name) {
298 for (Publisher p : publishers.values())
299 if (p.getName().equals(name))
300 return p;
301 return null;
302 }
303 // Find genre in database with given name
304 public Genre GetGenre(String name) {
305 for (Genre g : genres.values())
306 if (g.getName().equals(name))
307 return g;
308 return null;
309 }
310 // Find user in database with given email
311 public User GetUser(String email) {
312 for (User u : users.values())
313 if (u.getEmail().equals(email))
314 return u;
315 return null;
316 }
317
318 // Return filtered list of books
319 public ArrayList<Book> SearchBooks(String filter) {
320 GetBooks();
321
322 ArrayList<Book> results = new ArrayList<Book>();
323
324 for (Book b : books.values()) {
325 if (b.getTitle().toLowerCase().contains(filter)
326 || b.getDescription().toLowerCase().contains(filter)
327 || b.getDate().contains(filter)
328 || Integer.toString(b.getPages()).contains(filter) ||
329 b.author.getFullName().toLowerCase().contains(filter)
330 || b.publisher.getName().toLowerCase().contains(filter)
331 || b.genre.getName().toLowerCase().contains(filter) ||
332 Integer.toString(b.getStock()).contains(filter)
333 || b.priceToString().contains(filter))
334 results.add(b);
335 }
336
337 return results;
338 }
339 // Return filtered list of users
340 public ArrayList<User> SearchUsers(String filter) {
341 GetUsers();
342 filter = filter.toUpperCase();
343
344 ArrayList<User> results = new ArrayList<User>();
345
346 for (User u : users.values()) {
347 if (u.getEmail().toUpperCase().contains(filter))
348 results.add(u);
349 }
350
351 return results;
352 }
353 /// Return filtered list of rentals
354 public ArrayList<Rental> SearchRentals(String filter) {
355 GetRentals();
356 filter = filter.toUpperCase();
357
358 ArrayList<Rental> results = new ArrayList<Rental>();
359
360 for (Rental r : rentals.values()) {
361 if (r.book.getTitle().toUpperCase().contains(filter)
362 | r.user.getEmail().toUpperCase().contains(filter))
363 results.add(r);
364 }
365
366 return results;
367 }
368}