-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathMain.java
More file actions
332 lines (287 loc) · 13 KB
/
Main.java
File metadata and controls
332 lines (287 loc) · 13 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
package com.example;
import java.sql.*;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static void main(String[] args) {
if (isDevMode(args)) {
DevDatabaseInitializer.start();
}
new Main().run();
}
/**
* Determines if the application is running in development mode based on system properties,
* environment variables, or command-line arguments.
*
* @param args an array of command-line arguments
* @return {@code true} if the application is in development mode; {@code 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();
}
public void run() {
// Resolve DB settings with precedence: System properties -> Environment variables
String jdbcUrl = resolveConfig("APP_JDBC_URL", "APP_JDBC_URL");
String dbUser = resolveConfig("APP_DB_USER", "APP_DB_USER");
String dbPass = resolveConfig("APP_DB_PASS", "APP_DB_PASS");
if (jdbcUrl == null || dbUser == null || dbPass == null) {
throw new IllegalStateException(
"Missing DB configuration. Provide APP_JDBC_URL, APP_DB_USER, APP_DB_PASS " +
"as system properties (-Dkey=value) or environment variables.");
}
try (Connection connection = DriverManager.getConnection(jdbcUrl, dbUser, dbPass);
Scanner scanner = new Scanner(System.in)) {
String loggedInUser = authenticateUser(connection, scanner);
if (loggedInUser == null) {
System.out.println("Invalid username or password. Exiting");
return;
}
System.out.println("\nWelcome, " + loggedInUser + "!");
boolean running = true;
while (running) {
System.out.println("""
Press a number for next assignment:
1) List moon missions.
2) Get a moon mission.
3) Count missions for a given year.
4) Create an account.
5) Update an account password.
6) Delete an account.
0) Exit.
""");
System.out.print("Choose (0-6): ");
if (!scanner.hasNextLine()) {
running = false;
break;
}
String choiceStr = scanner.nextLine().trim();
int choice;
try {
choice = Integer.parseInt(choiceStr);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a number (0-6).");
continue;
}
switch (choice) {
case 0:
System.out.println("Exiting application. Goodbye!");
running = false;
break;
case 1:
System.out.println("Executing: 1) List moon missions...");
listMoonMissions(connection);
break;
case 2:
System.out.println("Executing: 2) Get a moon mission by mission_id...");
moonMissionsById(connection, scanner);
break;
case 3:
System.out.println("Executing: 3) Count missions for a given year...");
countingMissionsForAGivenYear(connection, scanner);
break;
case 4:
System.out.println("Executing: 4) Create an account...");
createAnAccount(connection, scanner);
break;
case 5:
System.out.println("Executing: 5) Update an account password...");
updateAccountPassword(connection, scanner);
break;
case 6:
System.out.println("Executing: 6) Delete an account...");
deleteAccount(connection, scanner);
break;
default:
System.out.println("Invalid choice. Please enter a number between 0 and 6.");
}
}
} catch (SQLException e) {
throw new RuntimeException("Database operation failed. " + e.getMessage());
}
}
private String authenticateUser(Connection connection, Scanner scanner) {
System.out.print("Username: ");
if (!scanner.hasNextLine()) {
return null; // Hantera EOF i testmiljön
}
String username = scanner.nextLine().trim();
System.out.print("Password: ");
if (!scanner.hasNextLine()) {
return null; // Hantera EOF i testmiljön
}
String password = scanner.nextLine().trim();
String sql = " select name from account where name = ? and password = ? ";
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setString(1, username);
stmt.setString(2, password);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return rs.getString("name");
} else {
return null;
}
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
private void listMoonMissions(Connection connection) {
String sql = " select spacecraft from moon_mission order by spacecraft ";
try (PreparedStatement stmt = connection.prepareStatement(sql);
ResultSet rs = stmt.executeQuery()) {
boolean found = false;
while (rs.next()) {
System.out.println(rs.getString("spacecraft"));
found = true;
}
if (!found) {
System.out.println("No moon missions found.");
}
} catch (SQLException e) {
throw new RuntimeException("Error executing List Moon Missions: " + e.getMessage(), e);
}
}
private void moonMissionsById(Connection connection, Scanner scanner) {
System.out.println("Enter moon mission id: ");
if (!scanner.hasNextLine()) {
return;
}
String missionId = scanner.nextLine().trim();
long id;
try {
id = Long.parseLong(missionId);
} catch (NumberFormatException e) {
System.out.println("Invalid moon mission id. Please enter a number");
return;
}
String sql = "select spacecraft, mission_id, mission_type, launch_date from moon_mission where mission_id = ?";
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setLong(1, id);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
System.out.println("ID: " + rs.getLong("mission_id"));
System.out.println("Spacecraft: " + rs.getString("spacecraft"));
System.out.println("Mission type: " + rs.getString("mission_type"));
System.out.println("Launch date: " + rs.getString("launch_date"));
} else {
System.out.println("Mission id " + missionId + " not found. Please enter a number");
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private void countingMissionsForAGivenYear(Connection connection, Scanner scanner) {
System.out.println("Enter year: ");
if (!scanner.hasNextLine()) {
System.out.println("Invalid year");
return;
}
int year = Integer.parseInt(scanner.nextLine());
String sql = " select count(*) as mission_count from moon_mission where year(launch_date) = ?";
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setInt(1, year);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
int count = rs.getInt("mission_count");
System.out.println("Mission count for year: " + year);
System.out.println("Number of moon missions: " + count);
} else
System.out.println("No moon missions for year: " + year);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private void createAnAccount(Connection connection, Scanner scanner) {
System.out.println("Creating an account...");
System.out.print("Enter first name: ");
if (!scanner.hasNextLine()) {return;}
String firstName = scanner.nextLine().trim();
if (firstName.length() < 3) { throw new IllegalArgumentException("First name must be at least 3 characters long."); }
System.out.print("Enter last name: ");
if (!scanner.hasNextLine()) {return;}
String lastName = scanner.nextLine().trim();
if (lastName.length() < 3) { throw new IllegalArgumentException("First name must be at least 3 characters long."); }
System.out.print("Enter ssn: ");
String ssn = scanner.nextLine().trim();
System.out.print("Enter password: ");
String password = scanner.nextLine().trim();
String name = firstName.substring(0, 3) + lastName.substring(0, 3);
String sql = "INSERT INTO account (first_name, last_name, ssn, password, name) VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setString(1, firstName);
stmt.setString(2, lastName);
stmt.setString(3, ssn);
stmt.setString(4, password);
stmt.setString(5, name);
int affectedRows = stmt.executeUpdate();
if (affectedRows > 0) {
System.out.println("Successfully created an account for " + firstName + " " + lastName);
} else
System.out.println("Failed to create an account.");
} catch (SQLException e) {
throw new RuntimeException("Database operation failed. " + e.getMessage());
}
}
private void updateAccountPassword(Connection connection, Scanner scanner) {
System.out.println("Enter user_id: ");
if (!scanner.hasNextLine()) {
return;
}
String userId = scanner.nextLine();
System.out.println("Enter new password: ");
if (!scanner.hasNextLine()) {
return;
}
String newPassword = scanner.nextLine();
String sql = " update account set password = ? where user_id = ? ";
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setString(1, newPassword);
stmt.setString(2, userId);
int affectedRows = stmt.executeUpdate();
if (affectedRows > 0) {
System.out.println("Account updated successfully.");
} else {
System.out.println("Failed to update account.");
}
} catch (SQLException e) {
System.err.println("ERROR: Failed to update password.");
throw new RuntimeException("Database operation failed. " + e.getMessage());
}
}
private void deleteAccount(Connection connection, Scanner scanner) {
System.out.println("Enter user id, that you wish to delete: ");
if (!scanner.hasNextLine()) {
return;
}
String userId = scanner.nextLine();
String sql = " delete from account where user_id = ? ";
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setString(1, userId);
int affectedRows = stmt.executeUpdate();
if (affectedRows > 0) {
System.out.println("Successfully deleted the account.");
} else {
System.out.println("Failed to delete the account.");
}
} catch (SQLException e) {
throw new RuntimeException("Database operation failed. " + e.getMessage());
}
}
}