-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabase.java
More file actions
469 lines (455 loc) · 20 KB
/
Copy pathDatabase.java
File metadata and controls
469 lines (455 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
/**
* Project 5 - Database.java
*
* Class that handles all database access and modification functionality related
* to the application.
*
* @author Shafer Anthony Hofmann, Qihang Gan, Shreyas Viswanathan, Nathan Pasic
* Miller, Oliver Long
*
* @version December 6, 2023
*/
public class Database {
private final String databasesDirectory = "databases/";
private final String usersDatabaseHeaders = "ID,Email,Password,Role";
private final String storesDatabaseHeaders = "Store ID,Seller ID,Store Name,Number of Products";
private final String productsDatabaseHeaders = "Seller ID,Store ID,Product ID,Store Name,Product Name," +
"Available Quantity,Price,Description,Order Limit,Reviews,Sale Quantity,Sale Price";
private final String purchaseHistoryDatabaseHeaders = "Customer ID,Seller ID,Store ID,Product ID,Store "
+ "Name,Product Name,Purchase Quantity,Price";
private final String shoppingCartDatabaseHeaders = "Customer ID,Seller ID,Store ID,Product ID,Store Name,"
+ "Product Name,Purchase Quantity,Price";
static Object lock = new Object();
/**
* Takes in the name of the file as input and returns a string containing all
* the headers associated with that file.
*
* @param fileName The name of the file that the user wants to update
* @return The headers that are associated with that specific CSV file.
*/
public String getFileHeaders(String fileName) {
String fileHeaders = "";
switch (fileName) {
case "users.csv" -> fileHeaders = usersDatabaseHeaders;
case "stores.csv" -> fileHeaders = storesDatabaseHeaders;
case "products.csv" -> fileHeaders = productsDatabaseHeaders;
case "shoppingCarts.csv" -> fileHeaders = shoppingCartDatabaseHeaders;
case "purchaseHistories.csv" -> fileHeaders = purchaseHistoryDatabaseHeaders;
}
return fileHeaders;
}
/**
* Takes in the name of the file and a column index and returns whether that
* index is within bounds of how many ever columns exist in the given file
*
* @param fileName The file using which the validity of the index will be
* determined
* @param index The index of the specified column
* @return If the column index is within bounds of the total number of columns
* in the file
*/
public boolean checkColumnBounds(String fileName, int index) {
String[] columns = getFileHeaders(fileName).split(",");
return ((index >= 0) && (index <= columns.length - 1));
}
/**
* Takes in a user's ID and returns the corresponding user's email in the database
*
* @param userID The ID to check for a match in the users.csv database
*
* @return The email associated with the ID in the users.csv database
*/
public String retrieveUserEmail(String userID) {
for (String entry: getDatabaseContents("users.csv")) {
if (entry.split(",")[0].equals(userID)) {
return entry.split(",")[1];
}
}
return null;
}
/**
* Takes in an ID and a file name and checks whether that ID is already
* associated with an entry
*
* @param idToCheck The ID to compare with the entries in the file
* @param fileName The file to check for the existence of the ID
* @return The existence of the ID in the specified file
*/
public boolean checkIDMatch(int idToCheck, String fileName) {
synchronized (lock) {
ArrayList<String> correspondingEntries = new ArrayList<>();
int comparisonIndex = 0;
int startIDSubstring = 0;
switch (fileName) {
case "users.csv":
correspondingEntries = getDatabaseContents("users.csv");
comparisonIndex = 0;
startIDSubstring = 1;
break;
case "stores.csv":
correspondingEntries = getDatabaseContents("stores.csv");
comparisonIndex = 0;
startIDSubstring = 2;
break;
case "products.csv":
correspondingEntries = getDatabaseContents("products.csv");
comparisonIndex = 2;
startIDSubstring = 2;
break;
}
if (correspondingEntries.isEmpty()) {
return false;
} else {
for (int i = 0; i < correspondingEntries.size(); i++) {
String[] userRepresentation = correspondingEntries.get(i).split(",");
String matchedID = userRepresentation[comparisonIndex].substring(startIDSubstring);
if (idToCheck == Integer.parseInt(matchedID)) {
return true;
}
}
}
return false;
}
}
/**
* Takes in the user's email and password and retrieves a match for the
* credentials in the users.csv database. Used for when the user is logging into
* the application. A null value signifies that no user with the given
* credentials was found in the database.
*
* @param email The user's email to compare with an existing entry in the
* users.csv database
* @param password The user's password to compare with an existing entry in the
* users.csv database
* @return A comma-separated string containing the matched user's information in
* the users.csv database
*/
public String retrieveUserMatchForLogin(String email, String password) throws Exception {
synchronized (lock) {
String matchedUser = "";
boolean fullMatchFound = false;
boolean partialMatchFound = false;
email = email.toLowerCase();
password = password.toLowerCase();
ArrayList<String> userEntries = getDatabaseContents("users.csv");
// If the very first user in the application tries logging in instead of signing up
if (userEntries.isEmpty()) {
throw new Exception("Both the email and password are non-existent. Please try again");
} else {
for (int j = 0; j < userEntries.size(); j++) {
String[] userRepresentation = userEntries.get(j).split(",");
String comparisonEmail = userRepresentation[1].toLowerCase();
String comparisonPassword = userRepresentation[2].toLowerCase();
if (comparisonEmail.equals(email) && comparisonPassword.equals(password)) {
fullMatchFound = true;
matchedUser = userEntries.get(j);
break;
} else if (comparisonEmail.equals(email) && !(comparisonPassword.equals(password))) {
partialMatchFound = true;
throw new Exception("Wrong password. Please try again");
}
}
// After going through the non-empty database, if no entries match the credentials provided
if (!fullMatchFound && !partialMatchFound) {
throw new Exception("Login failed. Please try again!");
}
return matchedUser;
}
}
}
/**
* Takes in the user's email and retrieves a match for the credential in the
* users.csv database. Used for when the user is creating a new account. A null
* value signifies that no user with the given email was found in the database.
*
* @param email The user's email to compare with an existing entry in the
* users.csv database
* @return A comma-separated string containing the matched user's information in
* the users.csv database
*/
public String retrieveUserMatchForSignUp(String email) {
synchronized (lock) {
ArrayList<String> userEntries = getDatabaseContents("users.csv");
// If the very first user in the application tries creating an account, no matches found yet
if (userEntries.isEmpty()) {
return null;
}
for (int j = 0; j < userEntries.size(); j++) {
String[] userRepresentation = userEntries.get(j).split(",");
if (email.toLowerCase().equals(userRepresentation[1].toLowerCase())) {
return userEntries.get(j);
}
}
return null;
}
}
/**
* Takes in a comma-separated string as an entry and appends it to the file
* specified by the file name
*
* @param fileName The name of the file to append the entry to
* @param entry The entry to be appended to the file
*/
public void addToDatabase(String fileName, String entry) {
synchronized (lock) {
ArrayList<String> relevantContents = getDatabaseContents(fileName);
switch (fileName) {
case "users.csv":
if (!checkEntryExists(fileName, entry)) {
relevantContents.add(entry);
updateDatabaseContents(fileName, relevantContents);
}
break;
case "stores.csv":
if (!checkEntryExists(fileName, entry)) {
relevantContents.add(entry);
updateDatabaseContents(fileName, relevantContents);
}
break;
case "products.csv":
if (!checkEntryExists(fileName, entry)) {
relevantContents.add(entry);
updateDatabaseContents(fileName, relevantContents);
}
break;
case "shoppingCarts.csv":
if (!checkEntryExists(fileName, entry)) {
relevantContents.add(entry);
updateDatabaseContents(fileName, relevantContents);
}
break;
case "purchaseHistories.csv":
if (!checkEntryExists(fileName, entry)) {
relevantContents.add(entry);
updateDatabaseContents(fileName, relevantContents);
}
break;
}
}
}
/**
* Takes in a comma-separated string as an entry and removes it from the file
* specified by the file name
*
* @param fileName The name of the file to remove the entry from
* @param entry The entry to be removed from the file
*/
public void removeFromDatabase(String fileName, String entry) {
synchronized (lock) {
ArrayList<String> relevantContents = getDatabaseContents(fileName);
switch (fileName) {
case "users.csv":
boolean userRemoved = relevantContents.remove(entry);
if (userRemoved) {
updateDatabaseContents(fileName, relevantContents);
}
break;
case "stores.csv":
boolean storeRemoved = relevantContents.remove(entry);
if (storeRemoved) {
updateDatabaseContents(fileName, relevantContents);
}
break;
case "products.csv":
boolean productRemoved = relevantContents.remove(entry);
if (productRemoved) {
updateDatabaseContents(fileName, relevantContents);
}
break;
case "shoppingCarts.csv":
boolean shoppingCartRemoved = relevantContents.remove(entry);
if (shoppingCartRemoved) {
updateDatabaseContents(fileName, relevantContents);
}
break;
case "purchaseHistories.csv":
boolean purchaseHistoryRemoved = relevantContents.remove(entry);
if (purchaseHistoryRemoved) {
updateDatabaseContents(fileName, relevantContents);
}
break;
}
}
}
/**
* Takes in two comma separated strings, one representing the previous entry in
* the file specified and one representing the modified entry and updates that
* specified entry in the file with the modified entry
*
* @param fileName The name of the file to be updated with the modified entry
* @param prevEntry The entry that already exists in the file
* @param newEntry The entry that will replace the previous entry in the
* specified file
*/
public boolean modifyDatabase(String fileName, String prevEntry, String newEntry) {
synchronized (lock) {
ArrayList<String> relevantContents = getDatabaseContents(fileName);
boolean databaseModified = false;
switch (fileName) {
case "users.csv":
int prevUserIdx = relevantContents.indexOf(prevEntry);
if (prevUserIdx != -1) {
relevantContents.set(prevUserIdx, newEntry);
updateDatabaseContents(fileName, relevantContents);
databaseModified = true;
}
break;
case "stores.csv":
int prevStoreIdx = relevantContents.indexOf(prevEntry);
if (prevStoreIdx != -1) {
relevantContents.set(prevStoreIdx, newEntry);
updateDatabaseContents(fileName, relevantContents);
databaseModified = true;
}
break;
case "products.csv":
int prevProductIdx = relevantContents.indexOf(prevEntry);
if (prevProductIdx != -1) {
relevantContents.set(prevProductIdx, newEntry);
updateDatabaseContents(fileName, relevantContents);
databaseModified = true;
}
break;
case "shoppingCarts.csv":
int prevShoppingCartIdx = relevantContents.indexOf(prevEntry);
if (prevShoppingCartIdx != -1) {
relevantContents.set(prevShoppingCartIdx, newEntry);
updateDatabaseContents(fileName, relevantContents);
databaseModified = true;
}
break;
case "purchaseHistories.csv":
int prevPurchaseHistoryIdx = relevantContents.indexOf(prevEntry);
if (prevPurchaseHistoryIdx != -1) {
relevantContents.set(prevPurchaseHistoryIdx, newEntry);
updateDatabaseContents(fileName, relevantContents);
databaseModified = true;
}
break;
}
return databaseModified;
}
}
/**
* Searches for the entry parameter in the file specified by filename and
* returns whether it exists or not
*
* @param fileName The name of the file to within which to look for
* @param entry A comma-separated string representing a possible entry in the
* file
* @return The existence of the entry in the specified file
*/
public boolean checkEntryExists(String fileName, String entry) {
synchronized (lock) {
File target = new File(databasesDirectory + fileName);
try (BufferedReader br = new BufferedReader(new FileReader(target))) {
br.readLine(); // skip the header
String line;
while ((line = br.readLine()) != null) {
if (line.equals(entry)) {
return true;
}
}
return false;
} catch (IOException e) {
return false;
}
}
}
/**
* Searches the column specified by the index in the specified file and returns
* all rows where the value in that column matches the value of the search
* parameter
*
* @param fileName The file to search for
* @param index The index of the column to search for
* @param searchParam The parameter to compare a value in the specified column
* to
* @return An arraylist of the matched rows
*/
public ArrayList<String> getMatchedEntries(String fileName, int index, String searchParam) {
synchronized (lock) {
ArrayList<String> matchedEntries = new ArrayList<>();
try {
if (checkColumnBounds(fileName, index)) {
File target = new File(databasesDirectory + fileName);
BufferedReader br = new BufferedReader(new FileReader(target));
br.readLine(); // skip the header
String line;
while ((line = br.readLine()) != null) {
String[] contents = line.split(",");
if (contents[index].equals(searchParam)) {
matchedEntries.add(line);
}
}
br.close();
}
} catch (Exception e) {
return new ArrayList<String>();
}
return matchedEntries;
}
}
/**
* Takes in the name of the file as input and extracts all of its contents
* line-by-line
*
* @param fileName The filename to extract the contents from
* @return An arraylist containing all the entries in the specified file
*/
public ArrayList<String> getDatabaseContents(String fileName) {
synchronized (lock) {
ArrayList<String> fileContents = new ArrayList<String>();
File output = new File(databasesDirectory + fileName);
try {
BufferedReader br = new BufferedReader(new FileReader(output));
br.readLine(); // skipping the headers
String line;
while ((line = br.readLine()) != null) {
fileContents.add(line);
}
br.close();
} catch (IOException e) {
return new ArrayList<String>();
}
return fileContents;
}
}
/**
* Takes in the name of the file and overwrites it completely with the contents
* specified by the contents in the arraylist
*
* @param fileName The name of the file whose contents need to be updated
* @param contents An arraylist representing the modified contents to be written
* to the file
*/
public void updateDatabaseContents(String fileName, ArrayList<String> contents) {
synchronized (lock) {
File dir = new File(databasesDirectory);
try {
if (!dir.exists()) {
dir.mkdir();
}
File output = new File(dir, fileName);
String fileHeaders = getFileHeaders(fileName);
PrintWriter bw = new PrintWriter(new FileWriter(output));
bw.println(fileHeaders);
for (int i = 0; i < contents.size(); i++) {
bw.println(contents.get(i));
}
bw.flush();
bw.close();
} catch (IOException e) {
System.out.println("There was an error when updating the contents of " +
fileName);
}
}
}
}