-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserService.java
More file actions
292 lines (244 loc) · 10.5 KB
/
UserService.java
File metadata and controls
292 lines (244 loc) · 10.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
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class UserService {
private static final String FILE_NAME = "users.txt";
private Scanner scanner;
public UserService() {
scanner = new Scanner(System.in);
createFileIfNotExists();
}
// Create file if not exists
private void createFileIfNotExists() {
File file = new File(FILE_NAME);
try {
if (file.createNewFile()) {
System.out.println("Created new file: " + FILE_NAME);
}
} catch (IOException e) {
System.err.println("Error creating file: " + e.getMessage());
}
}
// Register new user (CREATE)
public boolean registerUser() {
System.out.println("\n=== USER REGISTRATION ===");
String name = getValidatedInput("Enter Name (min 2 characters): ",
"^[a-zA-Z\\s]{2,}$",
"Invalid name! Use only letters and spaces, min 2 chars.");
String email = getValidatedInput("Enter Email (valid format): ",
"^[A-Za-z0-9+_.-]+@(.+)$",
"Invalid email format!");
// Check if email already exists
if (isEmailExists(email)) {
System.out.println("Error: Email already registered!");
return false;
}
String password = getValidatedInput("Enter Password (min 6 chars): ",
"^.{6,}$",
"Password must be at least 6 characters!");
String role = getValidatedInput("Enter Role (Admin/User/Guest): ",
"(?i)^(Admin|User|Guest)$",
"Invalid role! Choose: Admin, User, or Guest");
User newUser = new User(name, email, password, role);
if (saveUserToFile(newUser)) {
System.out.println("✓ User registered successfully!");
return true;
} else {
System.out.println("✗ Registration failed!");
return false;
}
}
// Save user to file
private boolean saveUserToFile(User user) {
try (FileWriter fw = new FileWriter(FILE_NAME, true);
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(user.toFileString());
bw.newLine();
return true;
} catch (IOException e) {
System.err.println("Error saving user: " + e.getMessage());
return false;
}
}
// Login user (READ for authentication)
public User loginUser() {
System.out.println("\n=== USER LOGIN ===");
String email = getValidatedInput("Enter Email: ",
"^[A-Za-z0-9+_.-]+@(.+)$",
"Invalid email format!");
String password = getValidatedInput("Enter Password: ",
"^.{1,}$",
"Password cannot be empty!");
List<User> users = getAllUsers();
for (User user : users) {
if (user.getEmail().equals(email) && user.getPassword().equals(password)) {
System.out.println("✓ Login successful! Welcome " + user.getName());
return user;
}
}
System.out.println("✗ Invalid email or password!");
return null;
}
// Search user profile by email (READ)
public User searchUserByEmail() {
System.out.println("\n=== SEARCH USER ===");
String email = getValidatedInput("Enter email to search: ",
"^[A-Za-z0-9+_.-]+@(.+)$",
"Invalid email format!");
List<User> users = getAllUsers();
for (User user : users) {
if (user.getEmail().equals(email)) {
System.out.println("\n✓ User Found:");
displayUserInfo(user);
return user;
}
}
System.out.println("✗ User not found with email: " + email);
return null;
}
// Update user profile (UPDATE)
public boolean updateProfile(User currentUser) {
if (currentUser == null) {
System.out.println("Error: No user logged in!");
return false;
}
System.out.println("\n=== UPDATE PROFILE ===");
System.out.println("Current Information:");
displayUserInfo(currentUser);
System.out.println("\nWhat would you like to update?");
System.out.println("1. Name");
System.out.println("2. Password");
System.out.println("3. Both");
System.out.print("Enter choice (1-3): ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
String newName = currentUser.getName();
String newPassword = currentUser.getPassword();
switch (choice) {
case 1:
newName = getValidatedInput("Enter new Name (min 2 chars): ",
"^[a-zA-Z\\s]{2,}$",
"Invalid name!");
break;
case 2:
newPassword = getValidatedInput("Enter new Password (min 6 chars): ",
"^.{6,}$",
"Password must be at least 6 characters!");
break;
case 3:
newName = getValidatedInput("Enter new Name (min 2 chars): ",
"^[a-zA-Z\\s]{2,}$",
"Invalid name!");
newPassword = getValidatedInput("Enter new Password (min 6 chars): ",
"^.{6,}$",
"Password must be at least 6 characters!");
break;
default:
System.out.println("Invalid choice!");
return false;
}
// Update user object
currentUser.setName(newName);
currentUser.setPassword(newPassword);
// Update file with all users
if (updateAllUsersInFile(currentUser)) {
System.out.println("✓ Profile updated successfully!");
return true;
} else {
System.out.println("✗ Failed to update profile!");
return false;
}
}
// Get all users from file
private List<User> getAllUsers() {
List<User> users = new ArrayList<>();
try (FileReader fr = new FileReader(FILE_NAME);
BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) {
if (!line.trim().isEmpty()) {
User user = User.fromFileString(line);
if (user != null) {
users.add(user);
}
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
return users;
}
// Update all users in file after modification
private boolean updateAllUsersInFile(User updatedUser) {
List<User> allUsers = getAllUsers();
// Find and update the user
for (int i = 0; i < allUsers.size(); i++) {
if (allUsers.get(i).getEmail().equals(updatedUser.getEmail())) {
allUsers.set(i, updatedUser);
break;
}
}
// Rewrite entire file
try (FileWriter fw = new FileWriter(FILE_NAME);
BufferedWriter bw = new BufferedWriter(fw)) {
for (User user : allUsers) {
bw.write(user.toFileString());
bw.newLine();
}
return true;
} catch (IOException e) {
System.err.println("Error updating file: " + e.getMessage());
return false;
}
}
// Check if email already exists
private boolean isEmailExists(String email) {
List<User> users = getAllUsers();
for (User user : users) {
if (user.getEmail().equals(email)) {
return true;
}
}
return false;
}
// Display user information
private void displayUserInfo(User user) {
System.out.println("┌─────────────────────────┐");
System.out.println("│ Name : " + user.getName());
System.out.println("│ Email : " + user.getEmail());
System.out.println("│ Role : " + user.getRole());
System.out.println("└─────────────────────────┘");
}
// Input validation method
private String getValidatedInput(String prompt, String regex, String errorMessage) {
String input;
while (true) {
System.out.print(prompt);
input = scanner.nextLine().trim();
if (input.matches(regex)) {
return input;
} else {
System.out.println("✗ " + errorMessage);
}
}
}
// Display all users (for admin purposes)
public void displayAllUsers() {
List<User> users = getAllUsers();
if (users.isEmpty()) {
System.out.println("\nNo users found in the system.");
return;
}
System.out.println("\n=== ALL REGISTERED USERS ===");
System.out.println("Total users: " + users.size());
System.out.println("┌────────────────────────────────────┐");
for (int i = 0; i < users.size(); i++) {
User user = users.get(i);
System.out.println("│ " + (i + 1) + ". " + user.getName() +
" | " + user.getEmail() +
" | " + user.getRole());
}
System.out.println("└────────────────────────────────────┘");
}
}