-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseConnection.java
More file actions
1296 lines (1115 loc) · 52.5 KB
/
Copy pathDatabaseConnection.java
File metadata and controls
1296 lines (1115 loc) · 52.5 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
// Vehicle Rental System - Complete Database Version
import java.sql.*;
import java.sql.Date;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.*;
// DATABASE CONNECTION MANAGER
class DatabaseManager {
private static final String DB_URL = "jdbc:mysql://localhost:3306/VehicleRentalDB";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "jerrome_maximof1";
private static Connection connection = null;
public static Connection getConnection() {
try {
if (connection == null || connection.isClosed()) {
initializeConnection();
}
return connection;
} catch (SQLException e) {
System.err.println("[✗] Database connection error: " + e.getMessage());
return null;
}
}
private static void initializeConnection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
System.out.println("[✓] MySQL Database connected successfully!");
// Test the connection and check if tables exist
testDatabaseSetup();
} catch (ClassNotFoundException e) {
System.err.println("[✗] MySQL JDBC Driver not found!");
System.err.println("[✗] Please add mysql-connector-java-8.0.xx.jar to your classpath");
System.exit(1);
} catch (SQLException e) {
System.err.println("[✗] Database connection failed!");
System.err.println("[✗] Error: " + e.getMessage());
System.err.println("[✗] Check if:");
System.err.println(" 1. MySQL server is running");
System.err.println(" 2. Database 'VehicleRentalDB' exists");
System.err.println(" 3. Username/password is correct");
System.exit(1);
}
}
private static void testDatabaseSetup() {
try {
// Check if UserRoles table has data
String checkSql = "SELECT COUNT(*) as count FROM UserRoles";
try (Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(checkSql)) {
if (rs.next() && rs.getInt("count") == 0) {
System.out.println("[!] Database tables are empty. Initializing default data...");
initializeDefaultData();
}
}
} catch (SQLException e) {
System.err.println("[!] Database tables might not exist. Make sure you ran the SQL script.");
}
}
private static void initializeDefaultData() {
try (Statement stmt = connection.createStatement()) {
// Insert default roles
stmt.execute("INSERT IGNORE INTO UserRoles (RoleName, Description) VALUES " +
"('ADMIN', 'System Administrator'), " +
"('CUSTOMER', 'Regular Customer'), " +
"('OWNER', 'Vehicle Owner')");
// Insert default statuses
stmt.execute("INSERT IGNORE INTO VehicleStatuses (StatusName, Description, IsAvailable) VALUES " +
"('AVAILABLE', 'Available for rent', TRUE), " +
"('RENTED', 'Currently rented', FALSE), " +
"('MAINTENANCE', 'Under maintenance', FALSE)");
// Insert default makes
stmt.execute("INSERT IGNORE INTO VehicleMakes (MakeName, Country) VALUES " +
"('Toyota', 'Japan'), ('Honda', 'Japan'), ('Ford', 'USA'), " +
"('BMW', 'Germany'), ('Tesla', 'USA'), ('Mercedes', 'Germany')");
// Insert default colors
stmt.execute("INSERT IGNORE INTO VehicleColors (ColorName) VALUES " +
"('White'), ('Black'), ('Blue'), ('Silver'), ('Red'), ('Gray')");
// Insert default admin user (password: admin123)
stmt.execute("INSERT IGNORE INTO Users (Username, PasswordHash, FullName, Email, Phone, RoleID, WalletBalance) VALUES " +
"('admin', 'admin123', 'System Admin', 'admin@rental.com', '1234567890', 1, 1000.00)");
System.out.println("[✓] Default data initialized successfully!");
} catch (SQLException e) {
System.err.println("[✗] Error initializing default data: " + e.getMessage());
}
}
public static void closeConnection() {
try {
if (connection != null && !connection.isClosed()) {
connection.close();
System.out.println("[✓] Database connection closed.");
}
} catch (SQLException e) {
System.err.println("[✗] Error closing connection: " + e.getMessage());
}
}
public static boolean testConnection() {
try {
Connection conn = getConnection();
if (conn == null) return false;
try (Statement stmt = conn.createStatement()) {
stmt.execute("SELECT 1");
return true;
}
} catch (SQLException e) {
return false;
}
}
}
// MODELS
class User {
private int userId; private String username; private String password;
private String fullName; private String email; private String phone;
private String role; private double walletBalance;
public User(int userId, String username, String password, String fullName,
String email, String phone, String role) {
this.userId = userId; this.username = username; this.password = password;
this.fullName = fullName; this.email = email; this.phone = phone;
this.role = role; this.walletBalance = 0.0;
}
// Getters
public int getUserId() { return userId; } public String getUsername() { return username; }
public String getPassword() { return password; } public String getFullName() { return fullName; }
public String getEmail() { return email; } public String getPhone() { return phone; }
public String getRole() { return role; } public double getWalletBalance() { return walletBalance; }
// Setters
public void setWalletBalance(double walletBalance) { this.walletBalance = walletBalance; }
public void addToWallet(double amount) { this.walletBalance += amount; }
public boolean deductFromWallet(double amount) {
if (this.walletBalance >= amount) { this.walletBalance -= amount; return true; }
return false;
}
@Override public String toString() {
return fullName + " (" + role + ") - Balance: $" + String.format("%.2f", walletBalance);
}
}
class Vehicle {
private int vehicleId; private String registrationNo; private String make; private String model;
private int year; private String color; private double dailyRate; private String status;
private int ownerId; private boolean isUserListed; private String location;
public Vehicle(int vehicleId, String registrationNo, String make, String model,
int year, String color, double dailyRate, String status,
int ownerId, boolean isUserListed, String location) {
this.vehicleId = vehicleId; this.registrationNo = registrationNo; this.make = make;
this.model = model; this.year = year; this.color = color; this.dailyRate = dailyRate;
this.status = status; this.ownerId = ownerId; this.isUserListed = isUserListed;
this.location = location;
}
public int getVehicleId() { return vehicleId; } public String getRegistrationNo() { return registrationNo; }
public String getMake() { return make; } public String getModel() { return model; }
public int getYear() { return year; } public String getColor() { return color; }
public double getDailyRate() { return dailyRate; } public String getStatus() { return status; }
public int getOwnerId() { return ownerId; } public boolean isUserListed() { return isUserListed; }
public String getLocation() { return location; }
public void setStatus(String status) { this.status = status; }
public void setDailyRate(double dailyRate) { this.dailyRate = dailyRate; }
@Override public String toString() {
return String.format("%d. %s %s (%d) - $%.2f/day - %s - %s - %s",
vehicleId, make, model, year, dailyRate, status,
isUserListed ? "User" : "Company", location);
}
}
class Rental {
private int rentalId; private int userId; private int vehicleId;
private LocalDate rentalDate; private LocalDate returnDate; private double totalAmount;
private String status; private String paymentStatus; private LocalDateTime createdAt;
public Rental(int rentalId, int userId, int vehicleId, LocalDate rentalDate,
LocalDate returnDate, double totalAmount, String status, String paymentStatus) {
this.rentalId = rentalId; this.userId = userId; this.vehicleId = vehicleId;
this.rentalDate = rentalDate; this.returnDate = returnDate; this.totalAmount = totalAmount;
this.status = status; this.paymentStatus = paymentStatus; this.createdAt = LocalDateTime.now();
}
public int getRentalId() { return rentalId; } public int getUserId() { return userId; }
public int getVehicleId() { return vehicleId; } public LocalDate getRentalDate() { return rentalDate; }
public LocalDate getReturnDate() { return returnDate; } public double getTotalAmount() { return totalAmount; }
public String getStatus() { return status; } public String getPaymentStatus() { return paymentStatus; }
public LocalDateTime getCreatedAt() { return createdAt; }
public void setStatus(String status) { this.status = status; }
public void setPaymentStatus(String paymentStatus) { this.paymentStatus = paymentStatus; }
@Override public String toString() {
return String.format("Rental #%d: Vehicle %d from %s to %s - $%.2f - %s - Payment: %s",
rentalId, vehicleId, rentalDate, returnDate, totalAmount, status, paymentStatus);
}
}
// DATA STORE
class DataStore {
// Helper method to get or create lookup values
private static int getOrCreateLookup(String table, String nameColumn, String idColumn, String value) {
String checkSql = "SELECT " + idColumn + " FROM " + table + " WHERE " + nameColumn + " = ?";
String insertSql = "INSERT INTO " + table + " (" + nameColumn + ") VALUES (?)";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement checkStmt = conn.prepareStatement(checkSql)) {
checkStmt.setString(1, value);
ResultSet rs = checkStmt.executeQuery();
if (rs.next()) {
return rs.getInt(1);
}
// Insert new value
try (PreparedStatement insertStmt = conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS)) {
insertStmt.setString(1, value);
insertStmt.executeUpdate();
ResultSet keys = insertStmt.getGeneratedKeys();
if (keys.next()) {
return keys.getInt(1);
}
}
} catch (SQLException e) {
System.err.println("[✗] Error in getOrCreateLookup for " + value + ": " + e.getMessage());
}
return -1;
}
// USER METHODS
public static User getUserByUsername(String username) {
String sql = "SELECT u.*, ur.RoleName FROM Users u " +
"JOIN UserRoles ur ON u.RoleID = ur.RoleID " +
"WHERE u.Username = ? AND u.IsActive = 1";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
User user = new User(
rs.getInt("UserID"),
rs.getString("Username"),
rs.getString("PasswordHash"),
rs.getString("FullName"),
rs.getString("Email"),
rs.getString("Phone"),
rs.getString("RoleName")
);
user.setWalletBalance(rs.getDouble("WalletBalance"));
return user;
}
} catch (SQLException e) {
System.err.println("[✗] Error getting user: " + e.getMessage());
}
return null;
}
public static User getUserById(int userId) {
String sql = "SELECT u.*, ur.RoleName FROM Users u " +
"JOIN UserRoles ur ON u.RoleID = ur.RoleID " +
"WHERE u.UserID = ? AND u.IsActive = 1";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, userId);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
User user = new User(
rs.getInt("UserID"),
rs.getString("Username"),
rs.getString("PasswordHash"),
rs.getString("FullName"),
rs.getString("Email"),
rs.getString("Phone"),
rs.getString("RoleName")
);
user.setWalletBalance(rs.getDouble("WalletBalance"));
return user;
}
} catch (SQLException e) {
System.err.println("[✗] Error getting user: " + e.getMessage());
}
return null;
}
public static boolean addUser(User user) {
// Check if username exists
if (getUserByUsername(user.getUsername()) != null) {
System.err.println("[✗] Username already exists!");
return false;
}
// Determine RoleID
int roleId = 2; // Default to CUSTOMER
if (user.getRole().equalsIgnoreCase("ADMIN")) {
roleId = 1;
} else if (user.getRole().equalsIgnoreCase("OWNER")) {
roleId = 3;
}
String sql = "INSERT INTO Users (Username, PasswordHash, FullName, Email, Phone, RoleID, WalletBalance) " +
"VALUES (?, ?, ?, ?, ?, ?, ?)";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
pstmt.setString(3, user.getFullName());
pstmt.setString(4, user.getEmail());
pstmt.setString(5, user.getPhone());
pstmt.setInt(6, roleId);
pstmt.setDouble(7, user.getWalletBalance());
int rows = pstmt.executeUpdate();
if (rows > 0) {
// Log the event
logEvent("USER_REGISTERED", "New user: " + user.getUsername(), 0);
return true;
}
} catch (SQLException e) {
System.err.println("[✗] Error adding user: " + e.getMessage());
}
return false;
}
public static List<User> getAllUsers() {
List<User> users = new ArrayList<>();
String sql = "SELECT u.*, ur.RoleName FROM Users u " +
"JOIN UserRoles ur ON u.RoleID = ur.RoleID " +
"WHERE u.IsActive = 1 ORDER BY u.UserID";
try (Connection conn = DatabaseManager.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
User user = new User(
rs.getInt("UserID"),
rs.getString("Username"),
rs.getString("PasswordHash"),
rs.getString("FullName"),
rs.getString("Email"),
rs.getString("Phone"),
rs.getString("RoleName")
);
user.setWalletBalance(rs.getDouble("WalletBalance"));
users.add(user);
}
} catch (SQLException e) {
System.err.println("[✗] Error getting users: " + e.getMessage());
}
return users;
}
public static boolean updateUserWallet(int userId, double amount) {
String sql = "UPDATE Users SET WalletBalance = ? WHERE UserID = ?";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setDouble(1, amount);
pstmt.setInt(2, userId);
int rows = pstmt.executeUpdate();
if (rows > 0) {
logEvent("WALLET_UPDATED", "User " + userId + " wallet: $" + amount, userId);
return true;
}
} catch (SQLException e) {
System.err.println("[✗] Error updating wallet: " + e.getMessage());
}
return false;
}
// VEHICLE METHODS
public static List<Vehicle> getAvailableVehicles() {
List<Vehicle> vehicles = new ArrayList<>();
String sql = "SELECT v.*, vm.MakeName, vc.ColorName, vs.StatusName " +
"FROM Vehicles v " +
"JOIN VehicleMakes vm ON v.MakeID = vm.MakeID " +
"JOIN VehicleColors vc ON v.ColorID = vc.ColorID " +
"JOIN VehicleStatuses vs ON v.StatusID = vs.StatusID " +
"WHERE vs.StatusName = 'AVAILABLE' " +
"ORDER BY v.DailyRate";
try (Connection conn = DatabaseManager.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
vehicles.add(new Vehicle(
rs.getInt("VehicleID"),
rs.getString("RegistrationNo"),
rs.getString("MakeName"),
rs.getString("Model"),
rs.getInt("Year"),
rs.getString("ColorName"),
rs.getDouble("DailyRate"),
rs.getString("StatusName"),
rs.getInt("OwnerID"),
rs.getBoolean("IsUserListed"),
rs.getString("Location")
));
}
} catch (SQLException e) {
System.err.println("[✗] Error getting vehicles: " + e.getMessage());
}
return vehicles;
}
public static List<Vehicle> getUserListedVehicles(int ownerId) {
List<Vehicle> vehicles = new ArrayList<>();
String sql = "SELECT v.*, vm.MakeName, vc.ColorName, vs.StatusName " +
"FROM Vehicles v " +
"JOIN VehicleMakes vm ON v.MakeID = vm.MakeID " +
"JOIN VehicleColors vc ON v.ColorID = vc.ColorID " +
"JOIN VehicleStatuses vs ON v.StatusID = vs.StatusID " +
"WHERE v.OwnerID = ? AND v.IsUserListed = TRUE";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, ownerId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
vehicles.add(new Vehicle(
rs.getInt("VehicleID"),
rs.getString("RegistrationNo"),
rs.getString("MakeName"),
rs.getString("Model"),
rs.getInt("Year"),
rs.getString("ColorName"),
rs.getDouble("DailyRate"),
rs.getString("StatusName"),
rs.getInt("OwnerID"),
rs.getBoolean("IsUserListed"),
rs.getString("Location")
));
}
} catch (SQLException e) {
System.err.println("[✗] Error getting user vehicles: " + e.getMessage());
}
return vehicles;
}
public static Vehicle getVehicleById(int id) {
String sql = "SELECT v.*, vm.MakeName, vc.ColorName, vs.StatusName " +
"FROM Vehicles v " +
"JOIN VehicleMakes vm ON v.MakeID = vm.MakeID " +
"JOIN VehicleColors vc ON v.ColorID = vc.ColorID " +
"JOIN VehicleStatuses vs ON v.StatusID = vs.StatusID " +
"WHERE v.VehicleID = ?";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return new Vehicle(
rs.getInt("VehicleID"),
rs.getString("RegistrationNo"),
rs.getString("MakeName"),
rs.getString("Model"),
rs.getInt("Year"),
rs.getString("ColorName"),
rs.getDouble("DailyRate"),
rs.getString("StatusName"),
rs.getInt("OwnerID"),
rs.getBoolean("IsUserListed"),
rs.getString("Location")
);
}
} catch (SQLException e) {
System.err.println("[✗] Error getting vehicle: " + e.getMessage());
}
return null;
}
public static boolean updateVehicleStatus(int vehicleId, String status) {
String sql = "UPDATE Vehicles SET StatusID = (SELECT StatusID FROM VehicleStatuses WHERE StatusName = ?) " +
"WHERE VehicleID = ?";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, status);
pstmt.setInt(2, vehicleId);
int rows = pstmt.executeUpdate();
if (rows > 0) {
logEvent("VEHICLE_STATUS", "Vehicle " + vehicleId + " -> " + status, 0);
return true;
}
} catch (SQLException e) {
System.err.println("[✗] Error updating vehicle status: " + e.getMessage());
}
return false;
}
public static boolean addVehicle(Vehicle vehicle) {
// Get or create MakeID
int makeId = getOrCreateLookup("VehicleMakes", "MakeName", "MakeID", vehicle.getMake());
if (makeId == -1) return false;
// Get or create ColorID
int colorId = getOrCreateLookup("VehicleColors", "ColorName", "ColorID", vehicle.getColor());
if (colorId == -1) return false;
// Get StatusID for AVAILABLE
int statusId = 1; // Default to AVAILABLE
String sql = "INSERT INTO Vehicles (RegistrationNo, MakeID, Model, Year, ColorID, " +
"DailyRate, StatusID, OwnerID, IsUserListed, Location) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, vehicle.getRegistrationNo());
pstmt.setInt(2, makeId);
pstmt.setString(3, vehicle.getModel());
pstmt.setInt(4, vehicle.getYear());
pstmt.setInt(5, colorId);
pstmt.setDouble(6, vehicle.getDailyRate());
pstmt.setInt(7, statusId);
pstmt.setInt(8, vehicle.getOwnerId());
pstmt.setBoolean(9, vehicle.isUserListed());
pstmt.setString(10, vehicle.getLocation());
int rows = pstmt.executeUpdate();
if (rows > 0) {
logEvent("VEHICLE_ADDED", vehicle.getRegistrationNo() + " added", vehicle.getOwnerId());
return true;
}
} catch (SQLException e) {
System.err.println("[✗] Error adding vehicle: " + e.getMessage());
}
return false;
}
public static boolean updateVehicleRate(int vehicleId, double newRate) {
String sql = "UPDATE Vehicles SET DailyRate = ? WHERE VehicleID = ?";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setDouble(1, newRate);
pstmt.setInt(2, vehicleId);
return pstmt.executeUpdate() > 0;
} catch (SQLException e) {
System.err.println("[✗] Error updating vehicle rate: " + e.getMessage());
return false;
}
}
// RENTAL METHODS
public static List<Rental> getRentalsByUserId(int userId) {
List<Rental> rentals = new ArrayList<>();
String sql = "SELECT r.*, rs.StatusName, ps.StatusName as PaymentStatus " +
"FROM Rentals r " +
"JOIN RentalStatuses rs ON r.StatusID = rs.StatusID " +
"JOIN PaymentStatuses ps ON r.PaymentStatusID = ps.StatusID " +
"WHERE r.UserID = ? ORDER BY r.RentalID DESC";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, userId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
rentals.add(new Rental(
rs.getInt("RentalID"),
rs.getInt("UserID"),
rs.getInt("VehicleID"),
rs.getDate("RentalDate").toLocalDate(),
rs.getDate("ReturnDate").toLocalDate(),
rs.getDouble("TotalAmount"),
rs.getString("StatusName"),
rs.getString("PaymentStatus")
));
}
} catch (SQLException e) {
System.err.println("[✗] Error getting user rentals: " + e.getMessage());
}
return rentals;
}
public static List<Rental> getPendingRentals() {
List<Rental> rentals = new ArrayList<>();
String sql = "SELECT r.*, rs.StatusName, ps.StatusName as PaymentStatus " +
"FROM Rentals r " +
"JOIN RentalStatuses rs ON r.StatusID = rs.StatusID " +
"JOIN PaymentStatuses ps ON r.PaymentStatusID = ps.StatusID " +
"WHERE rs.StatusName = 'PENDING' ORDER BY r.CreatedAt";
try (Connection conn = DatabaseManager.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
rentals.add(new Rental(
rs.getInt("RentalID"),
rs.getInt("UserID"),
rs.getInt("VehicleID"),
rs.getDate("RentalDate").toLocalDate(),
rs.getDate("ReturnDate").toLocalDate(),
rs.getDouble("TotalAmount"),
rs.getString("StatusName"),
rs.getString("PaymentStatus")
));
}
} catch (SQLException e) {
System.err.println("[✗] Error getting pending rentals: " + e.getMessage());
}
return rentals;
}
public static boolean createRentalWithProcedure(int userId, int vehicleId, LocalDate rentalDate, LocalDate returnDate) {
String sql = "{call sp_CreateRental(?, ?, ?, ?)}";
try (Connection conn = DatabaseManager.getConnection();
CallableStatement cstmt = conn.prepareCall(sql)) {
cstmt.setInt(1, userId);
cstmt.setInt(2, vehicleId);
cstmt.setDate(3, Date.valueOf(rentalDate));
cstmt.setDate(4, Date.valueOf(returnDate));
ResultSet rs = cstmt.executeQuery();
if (rs.next()) {
boolean success = rs.getString("Status").equals("SUCCESS");
if (success) {
logEvent("RENTAL_CREATED", "User " + userId + " rented vehicle " + vehicleId, userId);
}
return success;
}
} catch (SQLException e) {
System.err.println("[✗] Error creating rental: " + e.getMessage());
}
return false;
}
public static boolean approveRentalWithProcedure(int rentalId, int adminUserId) {
String sql = "{call sp_ApproveRental(?, ?)}";
try (Connection conn = DatabaseManager.getConnection();
CallableStatement cstmt = conn.prepareCall(sql)) {
cstmt.setInt(1, rentalId);
cstmt.setInt(2, adminUserId);
ResultSet rs = cstmt.executeQuery();
if (rs.next()) {
boolean success = rs.getString("Status").equals("SUCCESS");
if (success) {
logEvent("RENTAL_APPROVED", "Rental " + rentalId + " approved", adminUserId);
}
return success;
}
} catch (SQLException e) {
System.err.println("[✗] Error approving rental: " + e.getMessage());
}
return false;
}
// TRANSACTION METHODS
public static double getTotalAdminProfit() {
String sql = "SELECT SUM(AdminCommission) as TotalProfit FROM Transactions WHERE Status = 'COMPLETED'";
try (Connection conn = DatabaseManager.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
if (rs.next()) {
return rs.getDouble("TotalProfit");
}
} catch (SQLException e) {
System.err.println("[✗] Error getting admin profit: " + e.getMessage());
}
return 0.0;
}
// LOGGING
static void logEvent(String logType, String message, int userId) {
String sql = "INSERT INTO SystemLogs (LogType, LogMessage, UserID) VALUES (?, ?, ?)";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, logType);
pstmt.setString(2, message);
if (userId > 0) {
pstmt.setInt(3, userId);
} else {
pstmt.setNull(3, Types.INTEGER);
}
pstmt.executeUpdate();
} catch (SQLException e) {
System.err.println("[✗] Failed to log event: " + e.getMessage());
}
}
// DEBUG METHODS
public static void printDatabaseStats() {
System.out.println("\n=== DATABASE STATISTICS ===");
String[] tables = {"Users", "Vehicles", "Rentals", "Transactions", "SystemLogs"};
for (String table : tables) {
try (Connection conn = DatabaseManager.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) as count FROM " + table)) {
if (rs.next()) {
System.out.println(table + ": " + rs.getInt("count") + " rows");
}
} catch (SQLException e) {
System.out.println(table + ": Error - " + e.getMessage());
}
}
System.out.println("===========================\n");
}
public static void viewSystemLogs() {
String sql = "SELECT * FROM SystemLogs ORDER BY CreatedAt DESC LIMIT 20";
try (Connection conn = DatabaseManager.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
System.out.println("\n=== RECENT SYSTEM LOGS ===");
System.out.printf("%-5s %-20s %-40s %-10s %-20s\n",
"ID", "Type", "Message", "UserID", "Timestamp");
System.out.println("----------------------------------------------------------------------------------------");
while (rs.next()) {
System.out.printf("%-5d %-20s %-40s %-10d %-20s\n",
rs.getInt("LogID"),
rs.getString("LogType"),
rs.getString("LogMessage").length() > 40 ?
rs.getString("LogMessage").substring(0, 37) + "..." :
rs.getString("LogMessage"),
rs.getInt("UserID"),
rs.getTimestamp("CreatedAt").toString().substring(0, 19)
);
}
System.out.println("----------------------------------------------------------------------------------------\n");
} catch (SQLException e) {
System.err.println("[✗] Error getting logs: " + e.getMessage());
}
}
}
// CONTROLLERS
class AuthController {
private User currentUser;
public User login(String username, String password) {
User user = DataStore.getUserByUsername(username);
if (user != null && user.getPassword().equals(password)) {
currentUser = user;
System.out.println("[✓] Welcome, " + user.getFullName() + "!");
System.out.println(" Role: " + user.getRole());
System.out.println(" Wallet Balance: $" + user.getWalletBalance());
DataStore.logEvent("USER_LOGIN", user.getUsername() + " logged in", user.getUserId());
} else {
System.out.println("[-] Invalid username or password!");
DataStore.logEvent("LOGIN_FAILED", "Failed login: " + username, 0);
}
return currentUser;
}
public boolean register(String username, String password, String fullName, String email, String phone) {
// Validate input
if (username.isEmpty() || password.isEmpty() || fullName.isEmpty() || email.isEmpty()) {
System.out.println("[-] All fields are required!");
return false;
}
// Check if username exists
if (DataStore.getUserByUsername(username) != null) {
System.out.println("[-] Username already exists!");
return false;
}
// Create and add user
User newUser = new User(0, username, password, fullName, email, phone, "CUSTOMER");
newUser.setWalletBalance(0.0);
if (DataStore.addUser(newUser)) {
System.out.println("[✓] Registration successful!");
System.out.println("[✓] User '" + username + "' added to database.");
return true;
} else {
System.out.println("[-] Registration failed!");
return false;
}
}
public User getCurrentUser() { return currentUser; }
public void logout() {
if (currentUser != null) {
System.out.println("[✓] Goodbye, " + currentUser.getFullName() + "!");
DataStore.logEvent("USER_LOGOUT", currentUser.getUsername() + " logged out", currentUser.getUserId());
currentUser = null;
}
}
}
class VehicleController {
public List<Vehicle> getAvailableVehicles() {
return DataStore.getAvailableVehicles();
}
public Vehicle getVehicleById(int id) {
return DataStore.getVehicleById(id);
}
public boolean addCompanyVehicle(String regNo, String make, String model, int year,
String color, double dailyRate, String location) {
return DataStore.addVehicle(new Vehicle(0, regNo, make, model, year, color, dailyRate, "AVAILABLE", 0, false, location));
}
public boolean addUserVehicle(int ownerId, String regNo, String make, String model, int year,
String color, double dailyRate, String location) {
return DataStore.addVehicle(new Vehicle(0, regNo, make, model, year, color, dailyRate, "AVAILABLE", ownerId, true, location));
}
public List<Vehicle> getUserVehicles(int ownerId) {
return DataStore.getUserListedVehicles(ownerId);
}
public boolean updateVehicleRate(int vehicleId, double newRate) {
return DataStore.updateVehicleRate(vehicleId, newRate);
}
}
class RentalController {
public double calculateRentalCost(int vehicleId, LocalDate rentalDate, LocalDate returnDate) {
Vehicle v = DataStore.getVehicleById(vehicleId);
if (v == null) return 0;
return ChronoUnit.DAYS.between(rentalDate, returnDate) * v.getDailyRate();
}
public List<Rental> getUserRentals(int userId) {
return DataStore.getRentalsByUserId(userId);
}
public List<Rental> getPendingRentals() {
return DataStore.getPendingRentals();
}
public boolean createRental(int userId, int vehicleId, LocalDate rentalDate, LocalDate returnDate) {
return DataStore.createRentalWithProcedure(userId, vehicleId, rentalDate, returnDate);
}
public boolean approveRental(int rentalId, int adminUserId) {
return DataStore.approveRentalWithProcedure(rentalId, adminUserId);
}
}
class PaymentController {
public boolean processPayment(User user, double amount, String method) {
if (user.deductFromWallet(amount)) {
if (DataStore.updateUserWallet(user.getUserId(), user.getWalletBalance())) {
System.out.println("[✓] Payment of $" + amount + " processed via " + method);
DataStore.logEvent("PAYMENT_PROCESSED", user.getUserId() + " paid $" + amount, user.getUserId());
return true;
} else {
user.addToWallet(amount); // Rollback
}
}
System.out.println("[-] Insufficient funds!");
return false;
}
public boolean addToWallet(User user, double amount) {
user.addToWallet(amount);
if (DataStore.updateUserWallet(user.getUserId(), user.getWalletBalance())) {
System.out.println("[✓] $" + amount + " added to wallet.");
System.out.println("[✓] New balance: $" + user.getWalletBalance());
DataStore.logEvent("WALLET_ADDED", user.getUserId() + " added $" + amount, user.getUserId());
return true;
}
return false;
}
}
// MAIN APPLICATION
public class DatabaseConnection {
private static Scanner scanner = new Scanner(System.in);
private static AuthController auth = new AuthController();
private static VehicleController vehicleCtrl = new VehicleController();
private static RentalController rentalCtrl = new RentalController();
private static PaymentController paymentCtrl = new PaymentController();
public static void main(String[] args) {
System.out.println("=========================================");
System.out.println(" VEHICLE RENTAL SYSTEM (MySQL)");
System.out.println("=========================================\n");
// Initialize database connection
if (!DatabaseManager.testConnection()) {
System.err.println("[✗] Failed to connect to database. Exiting...");
return;
}
System.out.println("[✓] System ready!\n");
boolean running = true;
while (running) {
if (auth.getCurrentUser() == null) {
running = showLoginMenu();
} else {
running = auth.getCurrentUser().getRole().equals("ADMIN") ? showAdminMenu() : showCustomerMenu();
}
}
DatabaseManager.closeConnection();
System.out.println("\nThank you for using Vehicle Rental System!");
scanner.close();
}
private static boolean showLoginMenu() {
System.out.println("\n=== LOGIN / REGISTER ===");
System.out.println("1. Login");
System.out.println("2. Register");
System.out.println("3. View Database Status");
System.out.println("4. Exit");
System.out.print("Choose: ");
int choice = getIntInput();
switch (choice) {
case 1: login(); break;
case 2: register(); break;
case 3:
DataStore.printDatabaseStats();
DataStore.viewSystemLogs();
break;
case 4: return false;
default: System.out.println("[-] Invalid choice!");
}
return true;
}
private static void login() {
System.out.println("\n=== LOGIN ===");
System.out.print("Username: "); String username = scanner.nextLine();
System.out.print("Password: "); String password = scanner.nextLine();
auth.login(username, password);
}
private static void register() {
System.out.println("\n=== REGISTER ===");
System.out.print("Full Name: "); String fullName = scanner.nextLine();
System.out.print("Email: "); String email = scanner.nextLine();
System.out.print("Phone: "); String phone = scanner.nextLine();
System.out.print("Username: "); String username = scanner.nextLine();
System.out.print("Password: "); String password = scanner.nextLine();
auth.register(username, password, fullName, email, phone);
}
private static boolean showCustomerMenu() {
User u = auth.getCurrentUser();
System.out.println("\n=== CUSTOMER DASHBOARD ===");
System.out.println("User: " + u.getFullName());
System.out.println("Balance: $" + u.getWalletBalance());
System.out.println("\n1. Rent Vehicle");
System.out.println("2. List Vehicle for Rent");
System.out.println("3. My Listed Vehicles");
System.out.println("4. My Rentals");
System.out.println("5. Add Wallet Money");
System.out.println("6. View Available Vehicles");
System.out.println("7. Update Vehicle Rates");
System.out.println("8. Logout");
System.out.print("Choose: ");