-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.java
More file actions
1697 lines (1399 loc) · 69.6 KB
/
Copy pathUtils.java
File metadata and controls
1697 lines (1399 loc) · 69.6 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
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.net.http.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.List;
import java.util.Map;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.*;
// JSON parsing
import com.google.gson.Gson;
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
// PDF Export
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
class HelperFunctions {
public static Map<String, List<String>> loadConfigMap(String JDBC_URL_local) {
Map<String, List<String>> map = new LinkedHashMap<>(); // preserves the order of categories
String confTable = ConfigLoader.config.getProperty("CONFIGURATION_TABLE");
try (Connection conn = DriverManager.getConnection(JDBC_URL_local);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT category, item_value FROM " + confTable + " ORDER BY category, item_value")) {
while (rs.next()) {
String category = rs.getString("category");
String value = rs.getString("item_value");
// If it's a new category, initialize the list with the category name as the first item (Header)
map.computeIfAbsent(category, k -> {
List<String> list = new ArrayList<>();
list.add(k);
return list;
});
map.get(category).add(value);
}
} catch (SQLException e) {
System.err.println("Error loading configMap from local DB");
e.printStackTrace();
}
return map;
}
public static void performSyncWithProgress(Window parent, Runnable syncTask, Runnable onComplete) {
JDialog syncDialog = new JDialog(parent, "Data Sync", Dialog.ModalityType.APPLICATION_MODAL);
syncDialog.setUndecorated(true);
JPanel panel = new JPanel(new BorderLayout(10, 10));
panel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));
JLabel label = new JLabel("\u27F3 Syncing with Cloud... Please wait.", JLabel.CENTER);
JProgressBar progressBar = new JProgressBar();
progressBar.setIndeterminate(true); // Spinning effect
panel.add(label, BorderLayout.NORTH);
panel.add(progressBar, BorderLayout.CENTER);
panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
syncDialog.add(panel);
syncDialog.pack();
syncDialog.setLocationRelativeTo(parent);
// Start the background thread
new Thread(() -> {
try {
syncTask.run();
} finally {
SwingUtilities.invokeLater(() -> {
syncDialog.dispose();
onComplete.run(); // when background thread finishes
});
}
}).start();
// Show the dialog until background thread is running to avoid user interaction
syncDialog.setVisible(true);
}
public static void showSyncStatusDialog(String message, int messageType) {
javax.swing.SwingUtilities.invokeLater(() -> {
javax.swing.JOptionPane.showMessageDialog(
null,
message,
"Sync Status",
messageType
);
});
}
public static Map<String, String> getCurrentFilters() {
Map<String, String> filters = new HashMap<>();
for (JComboBox<String> combo : DataPlace.dynamicCombos) {
String category = combo.getName();
String selected = combo.getSelectedItem().toString().trim();
filters.put(category, selected);
}
return filters;
}
public static Map<String, String> parseJsonToMap(String json) {
Map<String, String> map = new HashMap<>();
if (json == null || json.isEmpty() || json.equals("{}")) return map;
// Remove curly braces and split by ","
String clean = json.substring(1, json.length() - 1);
String[] pairs = clean.split(",");
for (String pair : pairs) {
String[] keyValue = pair.split(":");
if (keyValue.length == 2) {
// Strip quotes and whitespace
String key = keyValue[0].replaceAll("\"", "").trim();
String value = keyValue[1].replaceAll("\"", "").trim();
map.put(key, value);
}
}
return map;
}
public static void showCategoryManagerDialog(JPanel parent, Runnable onRefresh) {
Window parentWindow = SwingUtilities.getWindowAncestor(parent);
JDialog dialog = new JDialog(parentWindow, "Manage Categories", Dialog.ModalityType.APPLICATION_MODAL);
dialog.setLayout(new BorderLayout());
// 1. Get current categories from the keys of your memory map
List<String> categories = new ArrayList<>(DataPlace.configMap.keySet());
final boolean[] dataChanged = {false};
JPanel listPanel = new JPanel();
listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.Y_AXIS));
listPanel.setBackground(Color.WHITE);
// Initial render of categories
renderCategoryRows(listPanel, categories, dataChanged);
// 2. Footer for adding a New Category
JPanel footer = new JPanel(new BorderLayout(5, 5));
footer.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JTextField inputField = new JTextField();
inputField.setBorder(BorderFactory.createTitledBorder("New Category Name"));
JButton addBtn = new JButton("+ Create");
addBtn.addActionListener(e -> {
String newCat = inputField.getText().trim();
if (!newCat.isEmpty() && !categories.contains(newCat)) {
// Initialize in DB with an empty list so it exists as a key
categories.add(newCat);
dataChanged[0] = true;
inputField.setText("");
renderCategoryRows(listPanel, categories, dataChanged);
new Thread(() -> {
OptionsManager.saveCategoryItems(newCat, new ArrayList<>(List.of("")), new ArrayList<>());
}).start();
}
});
footer.add(inputField, BorderLayout.CENTER);
footer.add(addBtn, BorderLayout.EAST);
dialog.add(new JScrollPane(listPanel), BorderLayout.CENTER);
dialog.add(footer, BorderLayout.SOUTH);
// 3. Update UI on close if changed
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (dataChanged[0]) {
onRefresh.run(); // Call the UI update trigger
}
dialog.dispose();
}
});
dialog.setSize(350, 450);
dialog.setLocationRelativeTo(parent);
dialog.setVisible(true);
}
private static void renderCategoryRows(JPanel panel, List<String> categories, boolean[] dataChanged) {
panel.removeAll();
for (String cat : categories) {
JPanel row = new JPanel(new BorderLayout());
row.setMaximumSize(new Dimension(Integer.MAX_VALUE, 45));
row.setBackground(Color.WHITE);
row.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY));
JLabel nameLabel = new JLabel(" " + cat);
nameLabel.setFont(new Font("SansSerif", Font.PLAIN, 14));
JButton delBtn = new JButton("\uD83D\uDDD1"); // Trash bin icon
delBtn.setForeground(Color.RED);
delBtn.setContentAreaFilled(false);
delBtn.setBorderPainted(false);
delBtn.addActionListener(e -> {
int confirm = JOptionPane.showConfirmDialog(panel,
"Delete '" + cat + "' and all its items?", "Confirm Delete", JOptionPane.YES_NO_OPTION);
if (confirm == JOptionPane.YES_OPTION) {
OptionsManager.saveCategoryItems(cat,new ArrayList<>(),DataPlace.configMap.get(cat));
categories.remove(cat);
dataChanged[0] = true;
renderCategoryRows(panel, categories, dataChanged);
}
});
row.add(nameLabel, BorderLayout.CENTER);
row.add(delBtn, BorderLayout.EAST);
panel.add(row);
}
panel.revalidate();
panel.repaint();
}
public static void addItemtoConfigurationUI(JPanel listPanel, String val,String filter, boolean[] isChanged,
List<String> localItems,List<String> itemsToAdd,List<String> itemsToDelete) {
// Add element to UI
JPanel row = new JPanel(new BorderLayout());
row.setBackground(Color.WHITE);
row.setMaximumSize(new Dimension(Integer.MAX_VALUE, 40));
row.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY));
JLabel label = new JLabel(" " + val);
boolean matches = label.getText().trim().toLowerCase().contains(filter.toLowerCase()); // to match filter while adding
JButton removeBtn = new JButton("\uD83D\uDDD1"); // Trash can icon
removeBtn.setForeground(Color.RED);
removeBtn.setBorderPainted(false);
removeBtn.setContentAreaFilled(false);
removeBtn.addActionListener(ee -> {
localItems.remove(val);
if (!itemsToAdd.remove(val)) {
itemsToDelete.add(val);
}
isChanged[0] = true; // Mark as changed
listPanel.remove(row);
listPanel.revalidate();
listPanel.repaint();
});
row.add(label, BorderLayout.CENTER);
row.add(removeBtn, BorderLayout.EAST);
row.setVisible(matches); // set visibility to current filter
listPanel.add(row);
listPanel.revalidate();
listPanel.repaint();
}
public static void showEditDialog(String category, JPanel parent) {
Window parentWindow = SwingUtilities.getWindowAncestor(parent);
JDialog dialog = new JDialog(parentWindow, "Edit " + category, Dialog.ModalityType.APPLICATION_MODAL);
dialog.setLayout(new BorderLayout());
// Keep track of added and deleted items
List<String> itemsToAdd = new ArrayList<>();
List<String> itemsToDelete = new ArrayList<>();
List<String> localItems = OptionsManager.getCategoryItems(category);
final boolean[] isChanged = {false}; // variables accessed inside lambdas or inner classes must be effectively final, hence create an array and change
// Search Bar
JTextField searchField = new JTextField();
searchField.setBorder(BorderFactory.createTitledBorder("Search " + category));
JPanel listPanel = new JPanel();
listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.Y_AXIS));
listPanel.setBackground(Color.WHITE);
searchField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) { updateListUI(listPanel, localItems, searchField.getText(), isChanged, false, itemsToAdd, itemsToDelete); }
public void removeUpdate(DocumentEvent e) { updateListUI(listPanel, localItems, searchField.getText(), isChanged, false, itemsToAdd, itemsToDelete); }
public void changedUpdate(DocumentEvent e) { updateListUI(listPanel, localItems, searchField.getText(), isChanged, false, itemsToAdd, itemsToDelete); }
});
JScrollPane scrollPane = new JScrollPane(listPanel);
scrollPane.getViewport().setBackground(Color.WHITE);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
// Footer (Input + Save Button)
JPanel footer = new JPanel(new BorderLayout(5, 5));
footer.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JTextField inputField = new JTextField();
JButton addBtn = new JButton("+ Add");
JButton saveBtn = new JButton("Save & Close");
saveBtn.setBackground(new Color(40, 167, 69)); // Green
saveBtn.setForeground(Color.WHITE);
saveBtn.setOpaque(true);
saveBtn.setBorderPainted(false);
addBtn.addActionListener(e -> {
String val = inputField.getText().trim().toUpperCase();
if (!val.isEmpty() && !localItems.contains(val)) {
localItems.add(val);
boolean wasJustRemoved = itemsToDelete.remove(val);
if (!wasJustRemoved) {
itemsToAdd.add(val);
}
isChanged[0] = true;
inputField.setText("");
addItemtoConfigurationUI(listPanel, val, searchField.getText(), isChanged, localItems,itemsToAdd, itemsToDelete);
}
});
saveBtn.addActionListener(e -> {
if (!itemsToAdd.isEmpty() || !itemsToDelete.isEmpty()) {
// Update locally and cloud
OptionsManager.saveCategoryItems(category, itemsToAdd, itemsToDelete);
isChanged[0] = false;
}
dialog.dispose();
});
JPanel inputRow = new JPanel(new BorderLayout(5, 0));
inputRow.add(inputField, BorderLayout.CENTER);
inputRow.add(addBtn, BorderLayout.EAST);
footer.add(inputRow, BorderLayout.NORTH);
footer.add(saveBtn, BorderLayout.SOUTH);
// Safety Net: Window Listener
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (isChanged[0]) {
int choice = JOptionPane.showConfirmDialog(dialog,
"You have unsaved changes. Save before closing?", "Unsaved Changes",
JOptionPane.YES_NO_CANCEL_OPTION);
if (choice == JOptionPane.YES_OPTION) {
if (!itemsToAdd.isEmpty() || !itemsToDelete.isEmpty()) {
// Update locally and cloud
OptionsManager.saveCategoryItems(category, itemsToAdd, itemsToDelete);
isChanged[0] = false;
}
dialog.dispose();
} else if (choice == JOptionPane.NO_OPTION) {
dialog.dispose();
}
} else dialog.dispose();
}
});
// Final Assembly
dialog.add(searchField, BorderLayout.NORTH);
dialog.add(scrollPane, BorderLayout.CENTER);
dialog.add(footer, BorderLayout.SOUTH);
updateListUI(listPanel, localItems, "", isChanged, true, itemsToAdd, itemsToDelete); // Initial render
dialog.setSize(350, 500);
dialog.setLocationRelativeTo(parent);
dialog.setVisible(true);
}
public static void updateListUI(JPanel listPanel, List<String> localItems, String filter, boolean[] isChanged,
boolean initialRender, List<String> itemsToAdd, List<String> itemsToDelete) {
if (initialRender) {
listPanel.removeAll();
for (String item : localItems) {
addItemtoConfigurationUI(listPanel, item,filter,isChanged,localItems, itemsToAdd, itemsToDelete);
}
} else {
String lowerFilter = filter.toLowerCase();
for (Component comp : listPanel.getComponents()) {
if (comp instanceof JPanel row) {
JLabel label = (JLabel) row.getComponent(0); //get Label to get text
boolean matches = label.getText().trim().toLowerCase().contains(lowerFilter);
row.setVisible(matches); // set visibility depending on filters match
}
}
}
listPanel.revalidate();
listPanel.repaint();
}
}
class CloudAPI {
public static boolean verifyConnection(String URL, String anonKey, String adminKey) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(URL+"/functions/v1/server-api"))
.header("Authorization", "Bearer " + anonKey)
.header("X-SERVER-HEADER", adminKey)
.header("X-Function", "verify-connection")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{}"))
.build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 400) {
System.err.println("Cloud Error (" + response.statusCode() + "): " + response.body());
return false;
}
// Connection Validated
return true;
} catch (Exception e) {
System.err.println("Network/Parsing Error: " + e.getMessage());
return false;
}
}
public static Object callEdgeFunction(String func, String jsonData) {
String anonKey = ConfigLoader.getAnonKey();
final String BASE_URL = ConfigLoader.getProjectUrl()+"/functions/v1/server-api";
final String SERVER_HEADER = ConfigLoader.config.getProperty("server.header");
// Parse the json to List of records
Gson gson = new Gson();
Type listType = new TypeToken<List<Map<String, Object>>>(){}.getType();
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL))
.header("Authorization", "Bearer " + anonKey)
.header("X-SERVER-HEADER", SERVER_HEADER)
.header("X-Function", func)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData))
.build();
try {
// Receive response after sending request
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 400) {
System.err.println("Cloud Error (" + response.statusCode() + "): " + response.body());
return null;
}
String body = response.body();
// Parse the body into list
if (body.trim().startsWith("[")) {
return gson.fromJson(body, listType);
} else {
return gson.fromJson(body, Map.class);
}
} catch (Exception e) {
System.err.println("Network/Parsing Error: " + e.getMessage());
return null;
}
}
}
class CloudDataBaseInfo {
/**
* Attempts to verify the database connection using the provided credentials.
* This method is purely for connection checking and returns the status.
* It does NOT save the configuration or display dialogs.
* * @return true if the connection is successful, false otherwise.
*/
public static boolean verification(String cloudUrl, String cloudKey, String adminKey) {
// We send an empty request to see if the cloud responds
try {
boolean result = CloudAPI.verifyConnection(cloudUrl, cloudKey, adminKey);
// If the function returns, the keys are valid
if (result) {
JOptionPane.showMessageDialog(null,
"Cloud Connection Validated.\nConfiguration saved.",
"Success", JOptionPane.INFORMATION_MESSAGE);
return true;
} else {
throw new Exception("Invalid response from Cloud.");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"Verification Failed.\nPlease check your URL, Anon Key, and Admin Key.",
"Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
public static void fetchConfigurationFromCloud() {
String localDbUrl = ConfigLoader.getLocalDBUrl();
String confTable = ConfigLoader.config.getProperty("CONFIGURATION_TABLE");
// Fetch data from cloud
Object response = CloudAPI.callEdgeFunction("fetch-all-config", "{}");
if (!(response instanceof List)) {
System.err.println("Configuration Sync Failed: Invalid response or Cloud Unreachable.");
return;
}
@SuppressWarnings("unchecked")
List<Map<String, Object>> cloudData = (List<Map<String, Object>>) response;
try (Connection localConn = DriverManager.getConnection(localDbUrl)) {
localConn.setAutoCommit(false);
// Clear local table
try (Statement st = localConn.createStatement()) {
st.executeUpdate("DELETE FROM " + confTable);
}
// Insert (sync)
String insertLocalSql = "INSERT INTO " + confTable + " (category, item_value) VALUES (?, ?)";
try (PreparedStatement insertStmt = localConn.prepareStatement(insertLocalSql)) {
for (Map<String, Object> row : cloudData) {
String category = String.valueOf(row.get("category"));
String itemValue = String.valueOf(row.get("item_value"));
insertStmt.setString(1, category);
insertStmt.setString(2, itemValue.toUpperCase());
insertStmt.addBatch();
}
insertStmt.executeBatch();
localConn.commit();
System.out.println("✓ Synced " + cloudData.size() + " config items from Cloud.");
}
} catch (SQLException e) {
System.err.println("Database Error during config sync: " + e.getMessage());
}
// Update memory cache so UI reflects changes immediately
DataPlace.configMap = HelperFunctions.loadConfigMap(localDbUrl);
}
public static void createTables() {
Object rawResponse = CloudAPI.callEdgeFunction("setup-db", "{}"); // get configTable row count
OptionsManager.syncPendingConfigurations();
//parse rawResponse to retrive count
if (rawResponse instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> responseMap = (Map<String, Object>) rawResponse;
int configRowCount = 0; // default to 0 if something goes wrong
if (responseMap.containsKey("configRowCount") && responseMap.get("configRowCount") != null) {
// cast to Number first, then get the int value.
configRowCount = ((Number) responseMap.get("configRowCount")).intValue();
}
System.out.println("Cloud Config Table Row Count: " + configRowCount);
if (configRowCount != 0)
HelperFunctions.performSyncWithProgress(
null,
()->fetchConfigurationFromCloud(), // sync cloud -> application
()-> {}
);
} else {
System.err.println("Setup check failed or returned unexpected format.");
}
}
}
class ConfigLoader {
// A single, static instance of Properties accessible application-wide
static final Properties config = new Properties();
// --- Persistence Setup (Safe Location ) ---
private static final String APP_DIR_NAME = "DigiLogBook";
private static final String CONFIG_FILE_NAME = "config.properties";
protected static final Path CONFIG_DIR_PATH = Paths.get(System.getProperty("user.home"), "." + APP_DIR_NAME);
private static final Path CONFIG_FILE_PATH = CONFIG_DIR_PATH.resolve(CONFIG_FILE_NAME);
// The internal name of the template file inside the JAR
private static final String CONFIG_TEMPLATE_NAME = "config.properties";
static {
File persistentConfigFile = CONFIG_FILE_PATH.toFile();
System.out.println("Checking for persistent config file");
// --- PHASE 1: Try to read the persistent (user-edited) file ---
if (persistentConfigFile.exists()) {
try (FileReader reader = new FileReader(persistentConfigFile)) {
config.load(reader);
System.out.println("Persistent configuration loaded successfully.");
} catch (IOException e) {
// If we found it but couldn't read it (e.g., permissions issue)
System.err.println("Error reading existing persistent config file: " + e.getMessage());
}
} else {
// --- PHASE 2: If persistent file is missing, load the default template ---
System.out.println("Persistent file not found. Loading default template.");
// USE CLASSLOADER for reading the resource from inside the JAR
try (InputStream templateStream = ConfigLoader.class.getClassLoader().getResourceAsStream(CONFIG_TEMPLATE_NAME)) {
if (templateStream == null) {
throw new FileNotFoundException("\u26A0 CRITICAL: Default template file " + CONFIG_TEMPLATE_NAME + " not found inside the application!");
} else {
config.load(templateStream);
System.out.println("Default configuration loaded successfully.");
// Immediately create the persistent file based on the template content
saveProperties();
System.out.println("New persistent config file created from deafult template.");
}
} catch (IOException e) {
System.err.println("Error reading template or creating new file: " + e.getMessage());
}
}
// ---- PHASE 3: Initialise Database if not exist ---
File dbFile = CONFIG_DIR_PATH.resolve(config.getProperty("JDBC_URL_local")).toFile();
if (!dbFile.exists()) {
System.out.println("First run detected: Initializing Database...");
// Initialize the SQLite table structure
OptionsManager.createConfigurationTableLocal(getLocalDBUrl());
// Use capitalized keys to match your JComboBox headers and JSON extraction logic
OptionsManager.saveCategoryItems("Subject", new ArrayList<>(List.of("1.1 BXLX101","1.2 BXLX102","1.3 BXXX3L3","1.5 BXXX5L5", "OTHERS")), new ArrayList<>());
OptionsManager.saveCategoryItems("Department", new ArrayList<>(List.of("CSE (cs)","ISE (is)","AIML (ai)","DS (cd)","ECE (ec)","MECH (me)","CIVIL (cv)")), new ArrayList<>());
OptionsManager.saveCategoryItems("Batch", new ArrayList<>(List.of("I", "II")), new ArrayList<>());
OptionsManager.saveCategoryItems("Sem", new ArrayList<>(List.of("1","2","3","4","5","6","7","8")), new ArrayList<>());
OptionsManager.saveCategoryItems("SysNo", new ArrayList<>(List.of("M-11","M-12","M-13","M-14","M-15","M-16","M-17","M-18","M-19","M-20")), new ArrayList<>());
OptionsManager.saveCategoryItems("LabName", new ArrayList<>(List.of("314","205 A","304","309","205 B")), new ArrayList<>());
// Refresh the memory map immediately so the UI is ready
DataPlace.configMap = HelperFunctions.loadConfigMap(getLocalDBUrl());
}
}
/*
Delete Application Folder created.
*/
public static void deleteConfigFolder(Path path) {
if (!Files.exists(path)) {
System.out.println("No configuration folder found at: " + path);
return;
}
try {
Files.walk(path)
.sorted(Comparator.reverseOrder()) // Delete children before parents
.map(Path::toFile)
.forEach(File::delete);
System.out.println("\u26A0 CRITICAL: Deleted Application Configuration Folder");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Failed to delete Application Configuration Folder");
}
}
/**
* Saves the current state of the properties object to the config file.
*/
public static void saveProperties() {
try (FileWriter writer = new FileWriter(CONFIG_FILE_PATH.toFile())) { // Use try-with-resources
config.store(writer, "Configuration settings updated by user interface");
} catch (IOException ioException) {
ioException.printStackTrace();
// Use a standard Swing way to notify the user of a critical failure
JOptionPane.showMessageDialog(null, "Failed to write config file.", "File Save Error", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Centralized method to update and save all cloud DB properties.
*/
public static void saveCloudDbConfig(String url, String key,String adminKey, boolean verified) {
config.setProperty("project.url", url);
config.setProperty("anon.key", key);
config.setProperty("server.header", adminKey);
config.setProperty("CLOUD_DB_VERIFIED", String.valueOf(verified));
saveProperties();
}
public static LocalDate getLocalLastRunDate() {
String dateStr = config.getProperty("local.auto.delete.last.run.date");
if (dateStr == null) {
return null;
}
return LocalDate.parse(dateStr);
}
public static String getLocalDBUrl() {
final String DB_FILE_NAME = config.getProperty("JDBC_URL_local");
return "jdbc:sqlite:" + CONFIG_DIR_PATH.resolve(DB_FILE_NAME).toString();
}
public static String getAnonKey() {
return config.getProperty("anon.key");
}
public static String getProjectUrl() {
return config.getProperty("project.url");
}
public static void setLocalLastRunDateToNow() throws IOException {
config.setProperty("local.auto.delete.last.run.date", LocalDate.now().toString());
try (FileWriter writer = new FileWriter(CONFIG_FILE_PATH.toFile())) {
config.store(writer, "Configuration settings updated by user interface");
}
}
public static LocalDate getCloudLastRunDate() {
String dateStr = config.getProperty("cloud.auto.delete.last.run.date");
if (dateStr == null) {
return null;
}
return LocalDate.parse(dateStr);
}
public static void setCloudLastRunDateToNow() throws IOException {
config.setProperty("cloud.auto.delete.last.run.date", LocalDate.now().toString());
try (FileWriter writer = new FileWriter(CONFIG_FILE_PATH.toFile())) {
config.store(writer, "Configuration settings updated by user interface");
}
}
public static void setAutoSaveDirectory(String location) {
config.setProperty("auto.save.records.directory", location);
try (FileWriter writer = new FileWriter(CONFIG_FILE_PATH.toFile())) {
config.store(writer, "Configuration settings updated by user interface");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void setAutoDeleteDuration(String property,String duration) {
config.setProperty(property, duration);
try (FileWriter writer = new FileWriter(CONFIG_FILE_PATH.toFile())) {
config.store(writer, "Configuration settings updated by user interface");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void setAutoSaveFeature(String property, String isSelected) {
config.setProperty(property, isSelected);
try (FileWriter writer = new FileWriter(CONFIG_FILE_PATH.toFile())) {
config.store(writer, "Configuration settings updated by user interface");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class OptionsManager {
public static void createConfigurationTableLocal(String JDBC_URL_local) {
String confTable = ConfigLoader.config.getProperty("CONFIGURATION_TABLE");
// SQLite uses INTEGER PRIMARY KEY AUTOINCREMENT instead of SERIAL
// SQLite uses DATETIME instead of TIMESTAMP WITH TIME ZONE
// SQLite uses CURRENT_TIMESTAMP instead of NOW()
String sql = "CREATE TABLE IF NOT EXISTS " + confTable + " (" +
" id INTEGER PRIMARY KEY AUTOINCREMENT," +
" category TEXT NOT NULL," +
" item_value TEXT NOT NULL," +
" created_at DATETIME DEFAULT CURRENT_TIMESTAMP," +
" UNIQUE(category, item_value)" +
");";
try (Connection conn = DriverManager.getConnection(JDBC_URL_local);
Statement stmt = conn.createStatement()) {
stmt.executeUpdate(sql);
System.out.println("✓ Local Configuration Table initialized.");
} catch (SQLException e) {
System.err.println("\u26A0 CRITICAL: FAILED TO CREATE LOCAL CONFIGURATION TABLE");
e.printStackTrace();
}
}
public static void createRecordsTableLocal(Connection localConn) {
String localTable = ConfigLoader.config.getProperty("LOCAL_TABLE");
try (Statement stmt = localConn.createStatement()) {
// 1. Create Table if not exist
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS " + localTable + " (" +
"session_id TEXT PRIMARY KEY, " +
"login_time TEXT, " +
"logout_time TEXT, " +
"usn TEXT, " +
"name TEXT, " +
"details TEXT" + // JSON stored as TEXT in SQLite
");");
// 2. Add the Index for each category (Fast seaching => Binary Search)
for (String category : DataPlace.configMap.keySet()) {
// unique name for each index
String indexName = "idx_details_" + category;
String indexSql = "CREATE INDEX IF NOT EXISTS " + indexName +
" ON " + localTable + " (json_extract(details, '$." + category + "'));";
stmt.executeUpdate(indexSql);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
Update OptionsData
*/
public static List<String> getCategoryItems(String category) {
List<String> items = new ArrayList<>();
String confTable = ConfigLoader.config.getProperty("CONFIGURATION_TABLE");
// Use PreparedStatement to handle the quotes and prevent SQL injection automatically
String sql = "SELECT item_value FROM " + confTable + " WHERE category = ?";
try (Connection localCon = DriverManager.getConnection(ConfigLoader.getLocalDBUrl());
PreparedStatement pstmt = localCon.prepareStatement(sql)) {
pstmt.setString(1, category);
try (ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
items.add(rs.getString("item_value"));
}
}
} catch (SQLException e) {
System.err.println("Error fetching items for category: " + category);
e.printStackTrace();
}
return items;
}
public static void saveCategoryItems(String category, List<String> toAdd, List<String> toDelete) {
String confTable = ConfigLoader.config.getProperty("CONFIGURATION_TABLE");
try (Connection localCon = DriverManager.getConnection(ConfigLoader.getLocalDBUrl())) {
localCon.setAutoCommit(false);
// Deletion
if (!toDelete.isEmpty()) {
String deleteSql = "DELETE FROM " + confTable + " WHERE category = ? AND item_value = ?";
try (PreparedStatement deleteStmt = localCon.prepareStatement(deleteSql)) {
for (String item : toDelete) {
deleteStmt.setString(1, category);
deleteStmt.setString(2, item.toUpperCase());
deleteStmt.addBatch();
}
deleteStmt.executeBatch();
}
}
// Insertion
if (!toAdd.isEmpty()) {
String insertSql = "INSERT OR IGNORE INTO " + confTable + " (category, item_value) VALUES (?, ?)";
try (PreparedStatement localStm = localCon.prepareStatement(insertSql)) {
for (String option : toAdd) {
localStm.setString(1, category);
localStm.setString(2, option.toUpperCase());
localStm.addBatch();
}
localStm.executeBatch();
}
}
localCon.commit();
System.out.println("✓ Local " + category + " updated. Added: " + toAdd.size() + ", Removed: " + toDelete.size());
// Sync cloud
if (Boolean.parseBoolean(ConfigLoader.config.getProperty("CLOUD_DB_VERIFIED", "false"))) syncConfiguration(category, toAdd, toDelete);
else {
String json = new Gson().toJson(Map.of(
"category", category,
"toAdd", toAdd,
"toDelete", toDelete
));
String currentQueue = ConfigLoader.config.getProperty("pending.sync", "");
// Use "|||" as a separator between JSON objects
if (!currentQueue.isEmpty()) {
currentQueue += "|||";
}
currentQueue += json;
ConfigLoader.config.setProperty("pending.sync", currentQueue);
ConfigLoader.saveProperties();
}
} catch (SQLException e) {
System.err.println("Failed to save category items locally.");
e.printStackTrace();
}
// Update global memory map
DataPlace.configMap = HelperFunctions.loadConfigMap(ConfigLoader.getLocalDBUrl());
}
public static void syncConfiguration(String category, List<String> itemsToAdd, List<String> itemsToDelete) {
String json = new Gson().toJson(Map.of(
"category", category,
"toAdd", itemsToAdd,
"toDelete", itemsToDelete
));
if (!itemsToAdd.isEmpty() || !itemsToDelete.isEmpty()) {
new Thread(() -> {
try {
Object response = CloudAPI.callEdgeFunction("sync-categories", json);
if (response == null) throw new Exception("Cloud rejected the sync.");
System.out.println("✓ Cloud Sync Successful for " + category);
} catch (Exception ex) {
// If it fails, save in config file
String currentQueue = ConfigLoader.config.getProperty("pending.sync", "");
// Use "|||" as a separator between JSON objects
if (!currentQueue.isEmpty()) {
currentQueue += "|||";
}
currentQueue += json;
ConfigLoader.config.setProperty("pending.sync", currentQueue);
ConfigLoader.saveProperties();
// pop an error back on the UI thread
HelperFunctions.showSyncStatusDialog(
"Cloud sync failed for " + category + ". Local changes saved.",
javax.swing.JOptionPane.WARNING_MESSAGE
);
ex.printStackTrace();
}
}).start();
}
}
public static void syncPendingConfigurations() {
String pending = ConfigLoader.config.getProperty("pending.sync", "");
if (pending.isEmpty()) return;
// Convert "{...}|||{...}" into "[{...},{...}]"