-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPittSocial.java
More file actions
1841 lines (1564 loc) · 75.1 KB
/
Copy pathPittSocial.java
File metadata and controls
1841 lines (1564 loc) · 75.1 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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//Java class to manage the Postgres server for
//CS1555 Project
//Make sure you have postgresql-42.2.5.jar in local directory
// ----------------------------------------------------- //
//Compile with: javac PittSocial.java
//Run with: java -cp postgresql-42.2.5.jar:. PittSocial
// ----------------------------------------------------- //
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import javax.lang.model.util.ElementScanner6;
import java.sql.*; //import the file containing definitions for the parts
//needed by java for database connection and manipulation
public class PittSocial {
private static Connection connection; // used to hold the jdbc connection to the DB
private static String lastLoginDate;
static String DB_username = "postgres";
static String DB_password = "zhao139";
static String url = "jdbc:postgresql://localhost:5432/pitt_social?currentSchema=public";
static Boolean driverMode = false;
static PittSocial ps = new PittSocial(url, DB_username, DB_password,false); // Create a static connection class to use in
// main
public static void main(String[] args) throws SQLException {
Scanner sc = new Scanner(System.in);
int choice = -1;
System.out.println("Welcome to Pitt Social");
while (true) {
System.out.println("Please Choose an Option:\n1. Create a User \n2. Login \n3. Exit");
System.out.print("-> ");
if (sc.hasNextInt()) {
choice = sc.nextInt();
if (choice < 1 && choice > 3) {
System.out.println("Invalid choice");
continue;
}
} else {
System.out.println("Invalid choice");
continue;
}
switch (choice) {
case 1: {
// Go to create user interface
ps.createUserHelper();
break;
}
case 2: {
System.out.println(" --- Log In ---");
String login_email, login_pass;
Scanner login_scanner = new Scanner(System.in);
System.out.print("Email Address: ");
login_email = login_scanner.next();
System.out.print("Password: ");
login_pass = login_scanner.next();
// Pass values into login
int userID = ps.login(login_email, login_pass);
if (userID == 0) {
break;
}
// For more IO go to after login, pass the userID
after_login(userID);
break;
}
case 3: {
System.out.println("Exit");
try {
connection.close();
} catch (Exception Ex) {
System.out.println("Error connecting to DB, Machine Error" + Ex.toString());
}
System.exit(0);
break;
}
}
}
}
// Constructor class to call and init connection / connection values from driver
// to DB
PittSocial(String dburl, String dbuser, String dbpass, Boolean driverMode) {
this.driverMode = driverMode;
this.DB_password = dbpass;
this.DB_username = dbuser;
this.url = dburl;
try {
// Register the PostgreSQL driver
Class.forName("org.postgresql.Driver");
// connect to DB...
connection = DriverManager.getConnection(url, DB_username, DB_password);
} catch (Exception Ex) {
System.out.println("Error connecting to database. Machine Error: " + Ex.toString());
System.exit(0);
}
}
public static boolean inputDateChecker(String inputDateString, DateTimeFormatter df) {
boolean dateValid = true;
try {
LocalDate ld = LocalDate.parse(inputDateString, df);
System.out.println(inputDateString + " good");
} catch (DateTimeParseException e) {
System.out.println(inputDateString + " is invalid");
System.out.println("Error " + e);
return false;
}
return true;
}
/*******************1.createUser***********************/
public void createUserHelper() {
DateTimeFormatter df = DateTimeFormatter.ofPattern("uuuu-MM-dd");
df = df.withResolverStyle(ResolverStyle.STRICT);
Scanner user_scanner = new Scanner(System.in);
//If create user option is chosen we need to get a name, email address, and DOB for the Database
String name, email_address, password, date_of_birth;
System.out.println("Creating new user..");
//Reading Name
System.out.print("Name: ");
name = user_scanner.nextLine();
while (name.length() > 51 || name.length() == 0) {
System.out.println("Name must be less than 51 charecters or above 0 charecters");
System.out.print("Name: ");
name = user_scanner.nextLine();
}
//Reading Email Address
System.out.print("Email Address: ");
email_address = user_scanner.nextLine();
while (email_address.length() > 51 || email_address.length() == 0) {
System.out.println("Email must be less than 51 charecters or above 0 charecters");
System.out.print("Email Address: ");
email_address = user_scanner.nextLine();
}
//Reading Password
System.out.print("Password: ");
password = user_scanner.nextLine();
while (password.length() > 51 || password.length() == 0) {
System.out.println("Email must be less than 51 charecters or above 0 charecters");
System.out.print("Email Address: ");
password = user_scanner.nextLine();
}
//Reading DOB
System.out.print("Date of Birth (yyyy-mm-dd): ");
date_of_birth = user_scanner.nextLine();
while (!inputDateChecker(date_of_birth, df)) {//regular expression check ////!date_of_birth.matches("\\d{4}-\\d{2}-\\d{2}")
System.out.println("The format of Date of Birth is wrong.");
System.out.println("Date of Birth (yyyy-mm-dd):");
date_of_birth = user_scanner.nextLine();
}
//make a call to createUser with given information
createUser(name, email_address, password, date_of_birth);
}
public void createUser(String name, String email_address, String password, String date_of_birth) {
try {
Statement statement;
connection.setAutoCommit(false); // turn off the Auto Commit
connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
//Serializable prevents if there are two transactions want to create user at the same time with same email address.
//or prevents to read same last userID.
statement = connection.createStatement();
//Helper formatter for last login timestamp
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date now = new Date();
String now_format = formatter.format(now);
java.sql.Timestamp date_reg = new java.sql.Timestamp(formatter.parse(now_format).getTime());
//Need to make sure the userID is not the same as one in the data base.
//Do this by doing a query to the profile Table
//grabbing the last profile ID #.
//Adding 1 to it. and putting into profile db
String query = "select UserID from profile order by userID desc LIMIT 1;";
ResultSet rs = statement.executeQuery(query);
int newUserID = 0;
if (rs.next())
newUserID = rs.getInt("userid");
//result returns the most recently used user ID, so we add 1 to it and use it as the new profile id for our new user
newUserID = newUserID + 1;
String create_user_input = "insert into profile values(?,?,?,?,?,?)";
PreparedStatement insert_profile = connection.prepareStatement(create_user_input);
insert_profile.setInt(1, newUserID);
insert_profile.setString(2, name);
insert_profile.setString(3, email_address);
insert_profile.setString(4, password);
Date dob = new SimpleDateFormat("yyyy-mm-dd").parse(date_of_birth);
java.sql.Date dob_sql = new java.sql.Date(dob.getTime());
insert_profile.setDate(5, dob_sql);
insert_profile.setTimestamp(6, date_reg);
insert_profile.executeUpdate();
connection.commit();
System.out.println("Create User Successfully!");
rs.close();
return;
} catch (Exception Ex) {
try {
connection.rollback();
} catch (SQLException E) {
System.out.println("Failure: " + E.toString());
}
System.out.println("Fail to send message," + Ex.toString());
}
}
/*******************2.login***********************/
// Returns the userID of the given log in request
public int login(String login_email, String login_pass) {
try {
connection.setAutoCommit(false);
connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
int userID;
Scanner sc = new Scanner(System.in);
// Prepared Statement to avoid Injection
PreparedStatement query_profiles = connection
.prepareStatement("select * from profile where email = ? and password = ?");
query_profiles.setString(1, login_email);
query_profiles.setString(2, login_pass);
ResultSet loginResult = query_profiles.executeQuery();
if (loginResult.next() == false) {
connection.rollback();
System.out.println("Email and/or Password is wrong / not found in our Database");
return 0;
} else {
System.out.println("Login Successful");
System.out.println("Loading information");
// need to update last login for the current user
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date d = new Date();
userID = loginResult.getInt("userid");
// store the last login info and
Statement getLastLogin = connection.createStatement();
String getLastLoginQuery = "select lastlogin from profile where userid = " + userID + ";";
ResultSet lastLogin = getLastLogin.executeQuery(getLastLoginQuery);
lastLogin.next();
SimpleDateFormat fm = new SimpleDateFormat("MM-dd-YYYY HH:mm:ss");
lastLoginDate = fm.format(lastLogin.getTimestamp("lastlogin"));
// then update
String login_updater = "update profile set lastlogin = to_timestamp('" + formatter.format(d)
+ "', 'DD-MM-YYYY HH24:MI:SS') where userid = " + userID + ";";
Statement loginTimerUpdate;
loginTimerUpdate = connection.createStatement();
loginTimerUpdate.executeUpdate(login_updater);
//Thread.sleep(1500);// sleep for 2 seconds, so that we have time to switch to the other transaction
}
connection.commit();
return userID;
} catch (Exception Ex) {
try {
connection.rollback();
} catch (SQLException E) {
System.out.println("Failure: " + E.toString());
}
System.out.println("Machine Error: " + Ex.toString());
}
return 0;
}
// Function to simply provide the logged in user a list of options and return
// the option chosen
private static int loggedInInterface() {
Scanner choice = new Scanner(System.in);
int userChoice = 0;
// Start User log in interface here
System.out.println(" --- User Interface --- ");
System.out.println(
"1. Initiate Friendship \t 2. Create Group \t 3. Initiate Adding Group \n4. Confirm Requests \t 5. Send Message To User \t 6. Send Message to Group\t 7. Display Messages"
+ "\n 8. Display New Messages \t 9. Display Friends \t 10. Search for User \t 11. Three Degrees \n12.Top messages\t13. Logout \t 14. Drop User \t 15. Exit Application");
System.out.print("->");
userChoice = choice.nextInt();
return userChoice;
}
// UI for post login
private static void after_login(int userID) {
Scanner sc = new Scanner(System.in);
while (true) {
int userChoice = loggedInInterface();
while (userChoice < 1 || userChoice > 15) {
System.out.println("Invalid choice -> Try again \n");
userChoice = loggedInInterface();
}
switch (userChoice) {
case 1: {
System.out.println(" --- Initiate Friendship --- "); // done
ps.initFriendshipHelper(userID);
break;
}
case 2: {
System.out.println(" --- Create a Group --- "); // done
ps.creategroupHelper(userID);
break;
}
case 3: {
System.out.println(" --- Initiate Into a Group --- "); // done
ps.initiateAddingGroupHelper(userID);
break;
}
case 4: {
System.out.println(" --- Confirm Requests --- ");
//set 2nd param to 0 to tell confirmRequests that we want user input and not driver input
ps.confirmRequests(userID, 0);
break;
}
case 5: {
System.out.println(" --- Send a Message To User --- ");
ps.sendMessageToUserHelper(userID);
break;
}
case 6: {
System.out.println(" --- Send a Message To Group --- ");
ps.sendMessageToGroupHelper(userID);
break;
}
case 7: {
System.out.println(" --- Display Messages --- ");
ps.displayMessagesHelper(userID);
break;
}
case 8: {
System.out.println(" --- Display New Messages");
ps.displayNewMessagesHelper(userID);
break;
}
case 9: {
System.out.println(" --- Display Friends --- ");
ps.displayFriendsHelper(userID);
break;
}
case 10: {
System.out.println(" --- Search For A User --- ");
ps.searchForUserHelper(userID);
break;
}
case 11: {
System.out.println(" --- Three Degrees --- ");
Scanner scan3 = new Scanner(System.in);
System.out.println("To ID:");
int toID = scan3.nextInt();
ps.threeDegrees(userID, toID);
break;
}
case 12: {
System.out.println("---Top messages---");
Scanner tpInputScanner = new Scanner(System.in);
System.out.println("For how many user`s messages do you want to display (int x):");
int x = tpInputScanner.nextInt();
System.out.println("For how many months messages do you want to trace back (int k):");
int k = tpInputScanner.nextInt();
System.out.println("Showing results of top " + x + " users` messages within past " + k + " months");
ps.topMessages(userID, x, k);
break;
}
case 13: {
System.out.println("--- Logout ---");
ps.logout(userID);
return;
}
case 14: {
System.out.println("--- Drop User---");
ps.dropUser(userID);
return;
}
case 15: {
System.out.println("--- Exit Application ---");
ps.exit();
break;
}
}
}
}
/*******************3. initiateFriendship***********************/
public void initFriendshipHelper(int fromUserID) {
Scanner toScane = new Scanner(System.in);
System.out.println("Please enter a User ID to send a friend request to");
System.out.print("->");
int user_id_to_find = toScane.nextInt();
Scanner fresh_scan = new Scanner(System.in);
System.out.println("Write a message with the friend request (200 Charecters or less)");
System.out.print("->");
String user_message = fresh_scan.nextLine();
while (user_message.length() > 200) {
System.out.println("Message must be 200 charecters or less");
System.out.print("->");
user_message = fresh_scan.nextLine();
}
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
// System.out.println("Class not found exception caught: " + ex.getMessage());
}
// Establishing Connection
try {
String user_finder = "select * \nfrom profile \nwhere userID = ?;";
PreparedStatement find_user = connection.prepareStatement(user_finder);
find_user.setInt(1, user_id_to_find);
ResultSet user_result = find_user.executeQuery();
boolean cont = user_result.next();
String user_to_be_requested = null;
if (cont == true && user_id_to_find != fromUserID) {
user_to_be_requested = user_result.getString("name");
} else {
System.out.println("Not a valid user ID.");
System.out.println("Failure");
connection.rollback();
return;
}
String check_if_already_friend_query = "select * from friend where (userid1 = ? and userid2 = ?) or (userid1 = ? and userid2 = ?)";
PreparedStatement check_if_already_friend_statement = connection.prepareStatement(check_if_already_friend_query);
check_if_already_friend_statement.setInt(1, user_id_to_find);
check_if_already_friend_statement.setInt(2, fromUserID);
check_if_already_friend_statement.setInt(3, fromUserID);
check_if_already_friend_statement.setInt(4, user_id_to_find);
ResultSet check_if_already_friend_rs = check_if_already_friend_statement.executeQuery();
if (check_if_already_friend_rs.next()) {
System.out.println("He/She is already your friend!");
System.out.println("Failure");
connection.rollback();
return;
}
System.out
.println("Send Friend Request to '" + user_to_be_requested + "'\nWith Message: '" + user_message + "' ?");
System.out.print("(Y/N): ");
String response = toScane.next();
int userID = fromUserID;
connection.commit();
//Pass all the information in function for DB
String confirmation = ps.initiateFriendship(userID, user_id_to_find, user_message, response);
System.out.println(confirmation);
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException E) {
System.out.println("Failure: " + E.toString());
}
e.printStackTrace();
}
}
//Function to make a friend request
public String initiateFriendship(int fromUserId, int user_id_to_find, String user_message, String confirm) {
// Getting class file
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
// System.out.println("Class not found exception caught: " + ex.getMessage());
}
try {
connection.setAutoCommit(false);
connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
if (confirm.equalsIgnoreCase("Y")) {
System.out.println("Sending friend request");
//fromusedId, Useridtofind, user_message
String insert_string = "insert into pendingFriend\n" + "values(?,?,?);";
PreparedStatement insert_friend_req = connection.prepareStatement(insert_string);
insert_friend_req.setInt(1, fromUserId);
insert_friend_req.setInt(2, user_id_to_find);
insert_friend_req.setString(3, user_message);
insert_friend_req.executeUpdate();
connection.commit();
return "Success";
} else if (confirm.equalsIgnoreCase("N")) {
//System.out.println("NOT Sending Friend Request");
connection.rollback();
return "Failure";
} else {
System.out.println("Not an option");
connection.rollback();
return "Failure";
}
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException E) {
System.out.println("Failure: " + E.toString());
}
return "Failure: " + e.toString();
}
}
/*******************4. createGroup***********************/
public void creategroupHelper(int userID) {
//Getting the values need to create the new group
Scanner group_scanner = new Scanner(System.in);
System.out.print("Group Name (Max 50 Charecters): ");
String group_name = group_scanner.nextLine();
while (group_name.length() > 50) {
System.out.println("Group Name Must Be 50 Chars or less");
System.out.print("Group Name: ");
group_name = group_scanner.nextLine();
}
System.out.print("Group Limit (Enter an integer): ");
int group_limit = group_scanner.nextInt();
Scanner fresh_Scan = new Scanner(System.in);
System.out.print("Enter a group description (Max 200 Charecters): ");
String group_description = fresh_Scan.nextLine();
ps.createGroup(userID, group_name, group_limit, group_description);
}
public void createGroup(int userID, String group_name, int group_limit, String group_description) {
//Getting class file
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
System.out.println("Class not found exception caught: " + ex.getMessage());
}
//Establishing Connection
try {
Statement get_groupID_number;
connection.setAutoCommit(false);
connection.setTransactionIsolation(connection.TRANSACTION_SERIALIZABLE);
//Getting most recently used group ID
get_groupID_number = connection.createStatement();
//Get the most recent gID
String query = "select gID \n from groupInfo \n order by gID desc \n LIMIT 1;";
ResultSet rs = get_groupID_number.executeQuery(query);
int result = 0;
if (rs.next()) {
result = rs.getInt("gID");
}
result = result + 1;
//creating the new group with all the values we currently have
String insert_string = "insert into groupInfo values(?,?,?,?);";
PreparedStatement insert_group = connection.prepareStatement(insert_string);
insert_group.setInt(1, result);
insert_group.setString(2, group_name);
insert_group.setInt(3, group_limit);
insert_group.setString(4, group_description);
insert_group.executeUpdate();
System.out.println("'" + group_name + "' was created with a limit of " + group_limit + ", and a description of '" + group_description + "'");
//Need to add the currently logged in user as the first member of this group
String user_insert_string = "insert into groupMember values (?,?,?);";
PreparedStatement insert_user_to_group;
insert_user_to_group = connection.prepareStatement(user_insert_string);
insert_user_to_group.setInt(1, result);
insert_user_to_group.setInt(2, userID);
insert_user_to_group.setString(3, "manager");
insert_user_to_group.executeUpdate();
connection.commit();
rs.close();
System.out.println("Current logged in user (" + userID + ") was added to '" + group_name + "' as the Manager");
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException E) {
System.out.println("Failure: " + E.toString());
}
System.out.println("Fail to send message," + e.toString());
}
}
/*******************5. initiateAddingGroup ***********************/
public void initiateAddingGroupHelper(int userID) {
Scanner groupreq_scanner = new Scanner(System.in);
System.out.print("Group ID: ");
int groupID = groupreq_scanner.nextInt();
Scanner fresh_scanner = new Scanner(System.in);
System.out.print("Message (Max 200 Characters): ");
String message_req = fresh_scanner.nextLine();
ps.initiateAddingGroup(userID, groupID, message_req);
}
public void initiateAddingGroup(int userID, int groupID, String message_req) {
//Getting class file
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
}
//Establishing Connection
try {
connection.setAutoCommit(false);
connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
//check if the user is already in the group
String checkUserInGroupQuery = "select * from groupmember where userid = " + userID;
Statement checkUserInGroup;
checkUserInGroup = connection.createStatement();
ResultSet checkUserInGroupRS = checkUserInGroup.executeQuery(checkUserInGroupQuery);
while (checkUserInGroupRS.next()) {
if (checkUserInGroupRS.getInt("gid") == groupID) {
System.out.println("You are already in this Group " + groupID);
System.out.println("Fail to initiate into group.");
connection.rollback();
return;
}
}
//Getting most recently used group ID
//Back end - no chance of SQL injection
Statement get_groupID_number;
get_groupID_number = connection.createStatement();
String query = "select gID \n from groupInfo \n order by gID desc \n LIMIT 1;";
ResultSet rs = get_groupID_number.executeQuery(query);
int result = 0;
rs.next();
result = rs.getInt("gid");
//groupID, userID, message_req
String req_string = "insert into pendingGroupMember\nvalues (?,?,?);";
PreparedStatement insert_group_req = connection.prepareStatement(req_string);
insert_group_req.setInt(1, groupID);
insert_group_req.setInt(2, userID);
insert_group_req.setString(3, message_req);
insert_group_req.executeUpdate();
connection.commit();
System.out.println("Current user (" + userID + ") has sent a group request to group #" + groupID + " with message '" + message_req + "'");
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException E) {
System.out.println("Failure: " + E.toString());
}
System.out.println("Failure: " + e.toString());
}
}
/*******************6. confirmRequests ***********************/
//Simple function to get user input on confirmation choice
public int confirmer() {
Scanner sc = new Scanner(System.in);
System.out.println("Would you like to \n1. Confirm a specific request \n2. Confirm All Requests");
System.out.print("->");
int confirm_choice = sc.nextInt();
while (confirm_choice > 2 || confirm_choice < 1) {
System.out.println("Invalid choice. Please choose \n1. Specific Confirmation \n2. Confirm all");
System.out.print("->");
confirm_choice = sc.nextInt();
}
return confirm_choice;
}
//Helper function called to make DBMS movements for friend requests. Returns true if done correctly and fully
public boolean friendConfirmer(int fromId, int toId, String fromMessage) {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
//System.out.println("Class not found exception caught: " + ex.getMessage());
}
//Establishing Connection
try {
connection.setAutoCommit(false);
connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
String mover = "Delete\nfrom pendingFriend\nwhere fromid = ? and toid = ? ;";
PreparedStatement move_friend_req = connection.prepareStatement(mover);
move_friend_req.setInt(1, fromId);
move_friend_req.setInt(2, toId);
//Deleting tuple from pendingFriend
move_friend_req.executeUpdate();
//Add the information into table friend
Date d = new Date();
java.sql.Date d_sql = new java.sql.Date(d.getTime());
String adder = "Insert into friend\nvalues (?, ?,?,?);";
PreparedStatement add_f_r = connection.prepareStatement(adder);
add_f_r.setInt(1, fromId);
add_f_r.setInt(2, toId);
add_f_r.setDate(3, d_sql);
add_f_r.setString(4, fromMessage);
add_f_r.executeUpdate();
connection.commit();
return true;
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException E) {
System.out.println("Failure: " + E.toString());
}
System.out.println("Failure" + e.toString());
return false;
}
}
//Helper function called to make DBMS movements for group requests. Returns true if done correctly and fully
public boolean groupConfirmer(int fromID, int groupID) {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
//System.out.println("Class not found exception caught: " + ex.getMessage());
}
//Establishing Connection
try {
connection.setAutoCommit(false);
connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
//delete the tuple from pendingGroupMember and add the tuple into groupMember
String mover = "Delete\nfrom pendingGroupMember\nwhere userID = ? and gID = ? ;";
PreparedStatement move_group_req = connection.prepareStatement(mover);
move_group_req.setInt(1, fromID);
move_group_req.setInt(2, groupID);
//Deleting tuple from pendingGroupMember
move_group_req.executeUpdate();
//Check Group Limit with full SQL Query
String limit_check = "SELECT CASE\n" +
"when (select count(gID) from groupMember where gID = ? ) < (select size from groupInfo where gID = ? )\n" +
"then 1 \nelse 0 \n END as Result;";
PreparedStatement lim = connection.prepareStatement(limit_check);
lim.setInt(1, groupID);
lim.setInt(2, groupID);
ResultSet rsLim = lim.executeQuery();
rsLim.next();
int result = rsLim.getInt("Result"); //Returns 1 if we can add. 0 if limit is reached or over
if (result == 1) {
//Add the information into table groupMember with role 'member'
String adder = "Insert into groupMember\nvalues (?,?, 'member');";
PreparedStatement inser_group_member = connection.prepareStatement(adder);
inser_group_member.setInt(1, groupID);
inser_group_member.setInt(2, fromID);
inser_group_member.executeUpdate();
connection.commit();
return true;
} else if (result == 0) {
System.out.println("Group #" + groupID + " has reached its limit.");
connection.rollback();
return false;
} else {
connection.rollback();
return false;
}
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException E) {
System.out.println("Failure: " + E.toString());
}
System.out.println("Failure: " + e.toString());
return false;
}
}
//Full Helper Function
public void confirmRequests(int userID, int confirm_choice) {
//Getting class file
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
System.out.println("Class not found exception caught: " + ex.getMessage());
}
//Establishing Connection
try {
connection.setAutoCommit(false);
connection.setTransactionIsolation(connection.TRANSACTION_SERIALIZABLE);
//Start here
//Get all friend request for given user
String select_requests = "Select *\nfrom pendingFriend\nwhere toID = ? ";
PreparedStatement get_friend_requests = connection.prepareStatement(select_requests);
get_friend_requests.setInt(1, userID);
ResultSet request_set = get_friend_requests.executeQuery();
//Use arrays to store the fromIDs and the from Messages
int[] fromIDs = new int[20];
String[] fromMessages = new String[20];
int[] gIDs = new int[10];
int i = 0;
int group_id = 0;
System.out.println(" --- Friend Requests --- ");
//Display the user# and message, to the logged in user
while (request_set.next()) {
fromIDs[i] = request_set.getInt("fromid");
fromMessages[i] = request_set.getString("message");
System.out.println((i + 1) + ". Friend Request from User #" + fromIDs[i] + ": '" + fromMessages[i] + "'");
i++;
}
//System.out.println(fromIDs[i - 1]);
//Need to see if the current logged in user is a Manager of any groups
String group_requests = "Select *\nfrom groupMember\nwhere userid = ? and role = 'manager'";
PreparedStatement get_group_requests = connection.prepareStatement(group_requests);
get_group_requests.setInt(1, userID);
ResultSet group_set = get_group_requests.executeQuery();
connection.commit();
int checker = 0;
System.out.println(" --- Group Requests --- ");
//Pull the group # that they mangage
while (group_set.next()) {
group_id = group_set.getInt("gid");
//use that group # to do a select on pendingGroupMember to pull all requests given the group #
String get_requests = "Select *\nfrom pendingGroupMember\nwhere gID = ? ;";
PreparedStatement final_group_requests = connection.prepareStatement(get_requests);
final_group_requests.setInt(1, group_id);
ResultSet group_resulter = final_group_requests.executeQuery();
while (group_resulter.next()) {
gIDs[i] = group_resulter.getInt("gid");
fromIDs[i] = group_resulter.getInt("userid");
fromMessages[i] = group_resulter.getString("message");
System.out.println((i + 1) + ". Request to join group #" + gIDs[i] + " from User #" + fromIDs[i] + ": '" + fromMessages[i] + "'");
i++;
checker++;
}
}
if (i == 0) {
System.out.println("No Outstanding Requests");
connection.commit();
return;
}
int friend_req_num = i - checker;
Scanner sc = new Scanner(System.in);
//This if else Bypasses user input so driver works
if (confirm_choice == 0) {
confirm_choice = confirmer();
} else {
//continues
}
switch (confirm_choice) {
case 1: {
//Confirm a specific request
System.out.println("Choose a specific request # to confirm (Enter 0 to be done)");
System.out.print("->");
int req_number = sc.nextInt();
int friend_num = friend_req_num;
int group_num = i - friend_req_num;
int[] already_used = new int[i];
int pointer = 0;
while (req_number != 0) {
//make sure request is valid
while (req_number > i || req_number < 1) {
System.out.println("Invalid Request Number Please choose one between 1 and " + i);
System.out.print("->");
req_number = sc.nextInt();
}
//For loop to make sure the same request isnt confirmed twice
for (int chk = 0; chk < already_used.length; chk++) {
while (already_used[chk] == req_number) {
System.out.println("Request #" + already_used[chk] + " was already used");
System.out.println("Please enter an unanswered request");
System.out.print("->");
req_number = sc.nextInt();
}
}
//put the new request into the already used array, to be checked later
already_used[pointer] = req_number;
if (req_number <= friend_req_num) {
//Were confirming a friend request
System.out.println("Confirming Friend Request #" + req_number);
connection.commit();
boolean b = friendConfirmer(fromIDs[req_number - 1], userID, fromMessages[req_number - 1]);
System.out.println("Done: " + b);
friend_num--;
} else if (req_number > friend_req_num) {
//were confirming a group request
System.out.println("Confirming Group Request #" + req_number);
connection.commit();
boolean b = groupConfirmer(fromIDs[req_number - 1], gIDs[req_number - 1]);
System.out.println("Done: " + b);
group_num--;
}
//No more requests to be handled
//returns the user back to main UI
if (friend_num == 0 && group_num == 0) {
connection.commit();
System.out.println("No more outstanding requests");
return;
}
System.out.println("Choose a specific request # to confirm (Enter 0 to be done)");
System.out.print("->");
req_number = sc.nextInt();
pointer++;
}
//Done confirming requests
//Deleting all remaining things in the request arrays
System.out.println("Deleting Remaining Requests...");
for (int z = 1; z <= i; z++) {
//delete the remaining tuples from pendingFriend