-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMain.java
More file actions
349 lines (309 loc) · 13.8 KB
/
Main.java
File metadata and controls
349 lines (309 loc) · 13.8 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
package com.example;
import java.sql.*;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
public class Main {
private final Scanner scanner = new Scanner(System.in);
private AccountRepository accountRepository;
private MoonMissionRepository moonMissionRepository;
private DataSource dataSource; /**
* Starts the application: initializes a development database when dev mode is detected and runs the interactive Main flow.
*
* Uses system properties, environment variables, and command-line arguments to determine dev mode before constructing and running the Main instance.
*/
public static void main(String[] args) {
if (isDevMode(args)) {
DevDatabaseInitializer.start();
}
new Main().run();
}
/**
* Initializes application resources, verifies database configuration and connectivity, then starts the interactive login and main menu flow.
*
* <p>Specifically, this method resolves JDBC configuration, initializes the data source and repositories, tests a database connection, and proceeds to prompt for user login. If login succeeds it enters the main menu loop; otherwise it handles an invalid login. If required configuration is missing the method prints an error and exits early.</p>
*/
public void run() {
String JDBC_URL = resolveConfig("APP_JDBC_URL", "APP_JDBC_URL");
String DB_USER = resolveConfig("APP_DB_USER", "APP_DB_USER");
String DB_PASS = resolveConfig("APP_DB_PASS", "APP_DB_PASS");
if (JDBC_URL == null || DB_USER == null || DB_PASS == null) {
System.err.println("Database configuration environment variables not set.");
return;
}
// --- Konfigurera Repository Pattern ---
dataSource = new SimpleDriverManagerDataSource(JDBC_URL, DB_USER, DB_PASS);
accountRepository = new JdbcAccountRepository(dataSource);
moonMissionRepository = new JdbcMoonMissionRepository(dataSource);
// --- Slut Konfiguration ---
System.out.println("Application initialized.");
try {
// Vi använder dataSource.getConnection() här för att testa uppkopplingen
// och bekräfta att den fungerar.
try (Connection testConnection = dataSource.getConnection()) {
System.out.println("Database connection established.");
}
if (login()) {
mainMenu();
} else {
handleInvalidLogin();
}
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
// Vi behöver inte stänga en global 'connection' längre,
// eftersom varje Repository-metod hanterar sin egen Connection.
}
/**
* Prompts the user for a username and password and authenticates them using the account repository.
*
* @return `true` if authentication succeeds, `false` otherwise.
* @throws SQLException if a database access error occurs while validating credentials.
*/
private boolean login() throws SQLException {
System.out.print("Username: ");
String username = scanner.nextLine();
System.out.print("Password: ");
String password = scanner.nextLine();
// Använder AccountRepository
return accountRepository.findByNameAndPassword(username, password);
}
/**
* Shows an invalid-credentials message and waits for the user to confirm exit by entering "0".
*
* Prints a prompt and consumes input lines until the user types exactly "0".
*/
private void handleInvalidLogin() {
System.out.println("Invalid username or password. Press 0 to exit.");
while (true) {
System.out.print("Choice: ");
String choice = scanner.nextLine().trim();
if ("0".equals(choice)) {
break;
}
}
}
/**
* Present the interactive main menu, read user choices, and invoke the corresponding actions.
*
* Repeatedly displays the menu and processes selections until the user chooses 0 to exit.
* Supported choices:
* 1 — list moon missions; 2 — get moon mission by ID; 3 — count missions by year;
* 4 — create an account; 5 — update an account password; 6 — delete an account.
* Handles non-numeric input by prompting the user and reports database operation errors to stderr.
*/
private void mainMenu() {
// ... (mainMenu och printMenu förblir oförändrade, förutom anropen nedan) ...
int choice = -1;
while (choice != 0) {
printMenu();
try {
System.out.print("Choice: ");
choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
listMoonMissions();
break;
case 2:
getMoonMissionById();
break;
case 3:
countMissionsByYear();
break;
case 4:
createAccount();
break;
case 5:
updateAccountPassword();
break;
case 6:
deleteAccount();
break;
case 0:
System.out.println("Exiting application.");
break;
default:
System.out.println("Invalid choice. Try again.");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a number.");
scanner.nextLine();
} catch (SQLException e) {
System.err.println("Database operation failed: " + e.getMessage());
}
}
}
/**
* Displays the main interactive menu options to the user.
*
* The menu lists available numeric commands used by the application's main loop.
*/
private void printMenu() {
System.out.println("\n--- Menu ---");
System.out.println("1) List moon missions (spacecraft names)");
System.out.println("2) Get a moon mission by mission_id (details)");
System.out.println("3) Count missions for a given year");
System.out.println("4) Create an account (first name, last name, ssn, password)");
System.out.println("5) Update an account password (user_id, new password)");
System.out.println("6) Delete an account (user_id)");
System.out.println("0) Exit");
System.out.println("------------");
}
/**
* Prints the spacecraft names of all moon missions to standard output.
*
* Prints a header line ("--- Moon Missions ---") followed by each spacecraft name
* on its own line, prefixed with " - ".
*
* @throws SQLException if a database access error occurs while retrieving missions
*/
private void listMoonMissions() throws SQLException {
// Använder MoonMissionRepository
List<String> spacecrafts = moonMissionRepository.findAllSpacecraftNames();
System.out.println("--- Moon Missions ---");
for (String name : spacecrafts) {
System.out.println(" - " + name);
}
}
/**
* Prompts the user for a mission ID and displays that mission's details if a record exists.
*
* If the entered mission ID is not a valid number, the method prints a warning and returns
* without querying the database.
*
* @throws SQLException if a database access error occurs while retrieving the mission
*/
private void getMoonMissionById() throws SQLException {
System.out.print("Enter mission_id: ");
long missionId;
try {
missionId = scanner.nextLong();
scanner.nextLine();
}catch (InputMismatchException e){
System.out.println("Please enter a number");
return;
}
try (Connection connection = dataSource.getConnection();
ResultSet rs = moonMissionRepository.findMissionById(missionId, connection)) {
if (rs.next()) {
System.out.println("--- Mission Details (ID: " + missionId + ") ---");
System.out.println("Spacecraft: " + rs.getString("spacecraft"));
System.out.println("Launch Date: " + rs.getDate("launch_date"));
System.out.println("Outcome: " + rs.getString("outcome"));
} else {
System.out.println("Mission with ID " + missionId + " not found.");
}
}
}
/**
* Prompts for a year, queries the repository for the number of moon missions launched that year, and prints the result.
*
* @throws SQLException if a database error occurs while counting missions
*/
private void countMissionsByYear() throws SQLException {
System.out.print("Enter year: ");
int year = scanner.nextInt();
scanner.nextLine();
// Använder MoonMissionRepository
int count = moonMissionRepository.countMissionsByYear(year);
System.out.println("Found " + count + " missions launched in " + year + ".");
}
/**
* Creates a new account by prompting the user for first name, last name, SSN and password,
* generates a username from up to the first three characters of the first and last names,
* and persists the account via the AccountRepository.
*
* If the generated username is empty (both names empty) the method prints an error and returns
* without creating an account.
*
* @throws SQLException if the repository fails to perform the database operation
*/
private void createAccount() throws SQLException {
System.out.print("Enter first name: ");
String firstName = scanner.nextLine();
System.out.print("Enter last name: ");
String lastName = scanner.nextLine();
System.out.print("Enter ssn: ");
String ssn = scanner.nextLine();
System.out.print("Enter password: ");
String password = scanner.nextLine();
String username = firstName.substring(0, Math.min(firstName.length(), 3))
+ lastName.substring(0, Math.min(lastName.length(), 3));
if (username.isEmpty()) {
System.out.println("Cannot create account: first name and last name cannot both be empty.");
return;
}
// Använder AccountRepository
int rowsAffected = accountRepository.create(firstName, lastName, ssn, password, username);
if (rowsAffected > 0) {
System.out.println("Account created successfully. Username is " + username + ".");
} else {
System.out.println("Failed to create account.");
}
}
/**
* Prompts for a user ID and a new password, updates that account's password, and reports success or absence.
*
* @throws SQLException if the database update fails
*/
private void updateAccountPassword() throws SQLException {
System.out.print("Enter user_id to update: ");
long userId = scanner.nextLong();
scanner.nextLine();
System.out.print("Enter new password: ");
String newPassword = scanner.nextLine();
// Använder AccountRepository
int rowsAffected = accountRepository.updatePassword(userId, newPassword);
if (rowsAffected > 0) {
System.out.println("Account password updated successfully for user_id " + userId + ".");
} else {
System.out.println("No account found with user_id " + userId + " to update.");
}
}
/**
* Prompts for a user ID, deletes the corresponding account via the account repository,
* and prints whether the deletion succeeded or no matching account was found.
*
* @throws SQLException if a database access error occurs during the delete operation
*/
private void deleteAccount() throws SQLException {
System.out.print("Enter user_id to delete: ");
long userId = scanner.nextLong();
scanner.nextLine();
// Använder AccountRepository
int rowsAffected = accountRepository.delete(userId);
if (rowsAffected > 0) {
System.out.println("Account deleted successfully for user_id " + userId + ".");
} else {
System.out.println("No account found with user_id " + userId + " to delete.");
}
}
/**
* Detects whether the application should run in development mode.
*
* @param args the command-line arguments; the presence of the `--dev` flag enables dev mode
* @return `true` if development mode is enabled via the `devMode` JVM system property (e.g. `-DdevMode=true`),
* the `DEV_MODE` environment variable (case-insensitive), or the `--dev` command-line flag;
* `false` otherwise
*/
private static boolean isDevMode(String[] args) {
if (Boolean.getBoolean("devMode")) //Add VM option -DdevMode=true
return true;
if ("true".equalsIgnoreCase(System.getenv("DEV_MODE"))) //Environment variable DEV_MODE=true
return true;
return Arrays.asList(args).contains("--dev"); //Argument --dev
}
/**
* Reads configuration with precedence: Java system property first, then environment variable.
* Returns trimmed value or null if neither source provides a non-empty value.
*/
private static String resolveConfig(String propertyKey, String envKey) {
String v = System.getProperty(propertyKey);
if (v == null || v.trim().isEmpty()) {
v = System.getenv(envKey);
}
return (v == null || v.trim().isEmpty()) ? null : v.trim();
}
}