-
Notifications
You must be signed in to change notification settings - Fork 0
/
AdminApp.java
510 lines (436 loc) · 20.7 KB
/
AdminApp.java
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
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.Timer;
import com.onlinevotingsystem.candidate.Candidate;
import com.onlinevotingsystem.db.DBConnection;
public class AdminApp {
private static final String ADMIN_USERNAME = "admin";
private static final String ADMIN_PASSWORD = "admin";
private static boolean electionsEnded = false;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame loginFrame = new JFrame("Admin Login");
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginFrame.setSize(300, 150);
loginFrame.setLayout(new BorderLayout());
loginFrame.setLocationRelativeTo(null);
JPanel loginPanel = new JPanel(new GridLayout(3, 2, 5, 5));
loginPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel usernameLabel = new JLabel("Username:");
JTextField usernameField = new JTextField();
JLabel passwordLabel = new JLabel("Password:");
JPasswordField passwordField = new JPasswordField();
JButton loginButton = new JButton("Login");
loginPanel.add(usernameLabel);
loginPanel.add(usernameField);
loginPanel.add(passwordLabel);
loginPanel.add(passwordField);
loginPanel.add(new JLabel()); // Empty label for spacing
loginPanel.add(loginButton);
loginFrame.add(loginPanel, BorderLayout.CENTER);
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = String.valueOf(passwordField.getPassword());
if (isAdminAuthenticated(username, password)) {
loginFrame.dispose();
showAdminInterface();
} else {
JOptionPane.showMessageDialog(loginFrame,
"Invalid username or password",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
});
loginFrame.setVisible(true);
});
}
private static boolean isAdminAuthenticated(String username, String password) {
return username.equals(ADMIN_USERNAME) && password.equals(ADMIN_PASSWORD);
}
private static void showAdminInterface() {
JFrame frame = new JFrame("Admin Interface");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 400);
frame.setLayout(new BorderLayout());
frame.setLocationRelativeTo(null);
JTextArea logArea = new JTextArea();
logArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(logArea);
JButton addCandidateButton = new JButton("Add Candidate");
JButton removeCandidateButton = new JButton("Remove Candidate");
JButton updateCandidateButton = new JButton("Update Candidate");
JButton viewVotesButton = new JButton("View Votes");
JButton endElectionsButton = new JButton("End Elections");
JButton publishResultButton = new JButton("Publish Result");
JButton newElectionsButton = new JButton("New Elections");
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(addCandidateButton);
buttonPanel.add(removeCandidateButton);
buttonPanel.add(updateCandidateButton);
buttonPanel.add(viewVotesButton);
buttonPanel.add(endElectionsButton);
buttonPanel.add(publishResultButton);
buttonPanel.add(newElectionsButton);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);
// Display existing candidates
displayCandidates(logArea);
// Display votes received by candidates
displayVotes(logArea);
// Set up a timer to refresh the data every 10 seconds
Timer timer = new Timer(10000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Refresh the displayed candidates and votes
displayCandidates(logArea);
displayVotes(logArea);
}
});
timer.setInitialDelay(0); // Start immediately
timer.start();
addCandidateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
logArea.append("Add Candidate button clicked\n");
addCandidate();
// Refresh the candidate list after adding a new candidate
displayCandidates(logArea);
}
});
removeCandidateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
logArea.append("Remove Candidate button clicked\n");
String candidateIdString = JOptionPane.showInputDialog(frame, "Enter Candidate ID to Remove:");
if (candidateIdString != null && !candidateIdString.isEmpty()) {
try {
int candidateId = Integer.parseInt(candidateIdString);
if (removeCandidate(candidateId)) {
logArea.append("Candidate removed successfully.\n");
// Refresh the candidate list after removing a candidate
displayCandidates(logArea);
} else {
logArea.append("Failed to remove candidate.\n");
}
} catch (NumberFormatException ex) {
logArea.append("Invalid Candidate ID format.\n");
}
} else {
logArea.append("Candidate ID is required.\n");
}
}
});
updateCandidateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
logArea.append("Update Candidate button clicked\n");
String candidateIdString = JOptionPane.showInputDialog(frame, "Enter Candidate ID to Update:");
if (candidateIdString != null && !candidateIdString.isEmpty()) {
try {
int candidateId = Integer.parseInt(candidateIdString);
updateCandidate(candidateId);
// Refresh the candidate list after updating a candidate
displayCandidates(logArea);
} catch (NumberFormatException ex) {
logArea.append("Invalid Candidate ID format.\n");
}
} else {
logArea.append("Candidate ID is required.\n");
}
}
});
viewVotesButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
logArea.append("View Votes button clicked\n");
// Display votes received by candidates
displayVotes(logArea);
}
});
endElectionsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
logArea.append("End Elections button clicked\n");
endElections();
electionsEnded = true;
}
});
publishResultButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
logArea.append("Publish Result button clicked\n");
publishResult();
}
});
newElectionsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
logArea.append("New Elections button clicked\n");
newElections();
electionsEnded = false;
}
});
frame.setVisible(true);
}
private static boolean addCandidate() {
JFrame addFrame = new JFrame("Add Candidate");
addFrame.setSize(300, 150);
addFrame.setLayout(new BorderLayout());
addFrame.setLocationRelativeTo(null);
JPanel addPanel = new JPanel(new GridLayout(3, 2, 5, 5));
addPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel nameLabel = new JLabel("Name:");
JTextField nameField = new JTextField();
JLabel partyLabel = new JLabel("Party:");
JTextField partyField = new JTextField();
JLabel platformLabel = new JLabel("Platform:");
JTextField platformField = new JTextField();
JButton addButton = new JButton("Add");
addPanel.add(nameLabel);
addPanel.add(nameField);
addPanel.add(partyLabel);
addPanel.add(partyField);
addPanel.add(platformLabel);
addPanel.add(platformField);
addPanel.add(new JLabel()); // Empty label for spacing
addPanel.add(addButton);
addFrame.add(addPanel, BorderLayout.CENTER);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String party = partyField.getText();
String platform = platformField.getText();
// Create Candidate object
Candidate candidate = new Candidate(name, party, platform);
// Add candidate to the database
if (addCandidateToDatabase(candidate)) {
JOptionPane.showMessageDialog(addFrame,
"Candidate added successfully",
"Success", JOptionPane.INFORMATION_MESSAGE);
addFrame.dispose(); // Close add window after successful addition
} else {
JOptionPane.showMessageDialog(addFrame,
"Failed to add candidate",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
});
addFrame.setVisible(true);
return false;
}
private static boolean addCandidateToDatabase(Candidate candidate) {
try (Connection connection = DBConnection.getConnection()) {
String query = "INSERT INTO candidates (name, party, platform) VALUES (?, ?, ?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setString(1, candidate.getName());
preparedStatement.setString(2, candidate.getParty());
preparedStatement.setString(3, candidate.getPlatform());
int rowsAffected = preparedStatement.executeUpdate();
return rowsAffected > 0;
}
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
}
private static boolean removeCandidate(int candidateId) {
try (Connection connection = DBConnection.getConnection()) {
String query = "DELETE FROM candidates WHERE id = ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setInt(1, candidateId);
int rowsAffected = preparedStatement.executeUpdate();
return rowsAffected > 0;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
private static void updateCandidate(int candidateId) {
JFrame updateFrame = new JFrame("Update Candidate");
updateFrame.setSize(300, 150);
updateFrame.setLayout(new BorderLayout());
updateFrame.setLocationRelativeTo(null);
JPanel updatePanel = new JPanel(new GridLayout(3, 2, 5, 5));
updatePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel nameLabel = new JLabel("Name:");
JTextField nameField = new JTextField();
JLabel partyLabel = new JLabel("Party:");
JTextField partyField = new JTextField();
JLabel platformLabel = new JLabel("Platform:");
JTextField platformField = new JTextField();
JButton updateButton = new JButton("Update");
updatePanel.add(nameLabel);
updatePanel.add(nameField);
updatePanel.add(partyLabel);
updatePanel.add(partyField);
updatePanel.add(platformLabel);
updatePanel.add(platformField);
updatePanel.add(new JLabel()); // Empty label for spacing
updatePanel.add(updateButton);
updateFrame.add(updatePanel, BorderLayout.CENTER);
updateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String party = partyField.getText();
String platform = platformField.getText();
// Update candidate details in the database
if (updateCandidateDetails(candidateId, name, party, platform)) {
JOptionPane.showMessageDialog(updateFrame,
"Candidate details updated successfully",
"Success", JOptionPane.INFORMATION_MESSAGE);
updateFrame.dispose(); // Close update window after successful update
} else {
JOptionPane.showMessageDialog(updateFrame,
"Failed to update candidate details",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
});
updateFrame.setVisible(true);
}
private static boolean updateCandidateDetails(int candidateId, String name, String party, String platform) {
try (Connection connection = DBConnection.getConnection()) {
String query = "UPDATE candidates SET name = ?, party = ?, platform = ? WHERE id = ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setString(1, name);
preparedStatement.setString(2, party);
preparedStatement.setString(3, platform);
preparedStatement.setInt(4, candidateId);
int rowsAffected = preparedStatement.executeUpdate();
return rowsAffected > 0;
}
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
}
private static void displayCandidates(JTextArea logArea) {
try (Connection connection = DBConnection.getConnection()) {
String query = "SELECT * FROM candidates";
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
try (ResultSet resultSet = preparedStatement.executeQuery()) {
logArea.setText(""); // Clear the existing content
logArea.append("Existing Candidates:\n");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String party = resultSet.getString("party");
String platform = resultSet.getString("platform");
logArea.append("ID: " + id + ", Name: " + name + ", Party: " + party + ", Platform: " + platform + "\n");
}
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
private static void displayVotes(JTextArea logArea) {
try (Connection connection = DBConnection.getConnection()) {
String query = "SELECT c.name, COUNT(v.candidate_id) as vote_count " +
"FROM candidates c " +
"LEFT JOIN appvotes v ON c.id = v.candidate_id " +
"GROUP BY c.id, c.name";
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
try (ResultSet resultSet = preparedStatement.executeQuery()) {
logArea.append("\nVotes Received:\n");
while (resultSet.next()) {
String candidateName = resultSet.getString("name");
int voteCount = resultSet.getInt("vote_count");
logArea.append("Candidate: " + candidateName + ", Votes: " + voteCount + "\n");
}
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
private static void endElections() {
try (Connection connection = DBConnection.getConnection()) {
// Delete votes
String deleteVotesQuery = "DELETE FROM appvotes";
try (PreparedStatement deleteVotesStatement = connection.prepareStatement(deleteVotesQuery)) {
deleteVotesStatement.executeUpdate();
}
// Delete candidates
String deletecmdVotesQuery = "DELETE FROM votes";
try (PreparedStatement deletecmdVotesStatement = connection.prepareStatement(deletecmdVotesQuery)) {
deletecmdVotesStatement.executeUpdate();
}
// Delete candidates
String deleteCandidatesQuery = "DELETE FROM candidates";
try (PreparedStatement deleteCandidatesStatement = connection.prepareStatement(deleteCandidatesQuery)) {
deleteCandidatesStatement.executeUpdate();
}
JOptionPane.showMessageDialog(null, "Elections Ended", "Info", JOptionPane.INFORMATION_MESSAGE);
electionsEnded = true;
} catch (SQLException e) {
e.printStackTrace();
// Handle database exceptions
JOptionPane.showMessageDialog(null, "Error ending elections", "Error", JOptionPane.ERROR_MESSAGE);
}
}
private static void publishResult() {
// Store election results with date and name
String resultSummary = JOptionPane.showInputDialog("Enter Result Summary");;
String electionName = JOptionPane.showInputDialog("Enter Election Name:");
if (electionName != null && !electionName.isEmpty()) {
storeResult(electionName, resultSummary);
} else {
JOptionPane.showMessageDialog(null, "Election Name is required.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
private static void newElections() {
// Clear votes for new elections
clearVotes();
// Perform actions to prepare for new elections
}
private static void clearVotes() {
try (Connection connection = DBConnection.getConnection()) {
// Clear the appvotes table
String clearVotesQuery = "DELETE FROM appvotes";
try (PreparedStatement clearVotesStatement = connection.prepareStatement(clearVotesQuery)) {
clearVotesStatement.executeUpdate();
}
// Unfreeze the voting process
electionsEnded = false;
// Display message
JOptionPane.showMessageDialog(null, "Votes cleared for new elections", "Success", JOptionPane.INFORMATION_MESSAGE);
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Failed to clear votes", "Error", JOptionPane.ERROR_MESSAGE);
}
}
private static void storeResult(String electionName, String resultSummary) {
try (Connection connection = DBConnection.getConnection()) {
String query = "INSERT INTO election_results (election_name, result_summary) VALUES (?, ?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setString(1, electionName);
preparedStatement.setString(2, resultSummary);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
JOptionPane.showMessageDialog(null, "Result stored for election: " + electionName, "Success", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Failed to store result for election: " + electionName, "Error", JOptionPane.ERROR_MESSAGE);
}
}
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Error storing result for election: " + electionName, "Error", JOptionPane.ERROR_MESSAGE);
}
}
private static String getResultSummary() {
// ... (existing code)
return "";
}
}