-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSettingsController.java
More file actions
794 lines (637 loc) · 31 KB
/
SettingsController.java
File metadata and controls
794 lines (637 loc) · 31 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
// Copyright 2019 doubleSlash Net Business GmbH
//
// This file is part of KeepTime.
// KeepTime is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package de.doubleslash.keeptime.view;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import de.doubleslash.keeptime.controller.HeimatController;
import de.doubleslash.keeptime.exceptions.FXMLLoaderException;
import de.doubleslash.keeptime.model.settings.HeimatSettings;
import de.doubleslash.keeptime.rest.integration.heimat.JwtDecoder;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.stage.Modality;
import org.h2.tools.RunScript;
import org.h2.tools.Script;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import de.doubleslash.keeptime.ApplicationProperties;
import de.doubleslash.keeptime.common.*;
import de.doubleslash.keeptime.common.Resources.RESOURCE;
import de.doubleslash.keeptime.controller.Controller;
import de.doubleslash.keeptime.model.Model;
import de.doubleslash.keeptime.view.license.LicenseTableRow;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import static de.doubleslash.keeptime.App.showErrorDialogAndWait;
import static de.doubleslash.keeptime.view.ViewController.createFXMLLoader;
@Component
public class SettingsController {
@FXML
private ColorPicker hoverBackgroundColor;
@FXML
private ColorPicker hoverFontColor;
@FXML
private ColorPicker defaultBackgroundColor;
@FXML
private ColorPicker defaultFontColor;
@FXML
private ColorPicker taskBarColor;
@FXML
private Button resetHoverBackgroundButton;
@FXML
private Button resetHoverFontButton;
@FXML
private Button resetDefaultBackgroundButton;
@FXML
private Button resetDefaultFontButton;
@FXML
private Button resetTaskBarFontButton;
@FXML
private CheckBox useHotkeyCheckBox;
@FXML
private CheckBox displayProjectsRightCheckBox;
@FXML
private CheckBox hideProjectsOnMouseExitCheckBox;
@FXML
private CheckBox saveWindowPositionCheckBox;
@FXML
private CheckBox emptyNoteReminderCheckBox;
@FXML
private CheckBox emptyNoteReminderOnlyForWorkEntryCheckBox;
@FXML
private CheckBox confirmCloseCheckBox;
@FXML
private Button saveButton;
@FXML
private Button cancelButton;
@FXML
private Button exportButton;
@FXML
private Button importButton;
@FXML
private Label hotkeyLabel;
@FXML
private Label globalKeyloggerLabel;
@FXML
private AnchorPane settingsRoot;
@FXML
private Hyperlink gitHubHyperlink;
@FXML
private Button reportBugButton;
@FXML
private Region bugIcon;
@FXML
private Label versionNumberLabel;
@FXML
private Hyperlink ourLicenseHyperLink;
@FXML
private TableView<LicenseTableRow> licenseTableView;
@FXML
private Region colorIcon;
@FXML
private Region layoutIcon;
@FXML
private Region generalIcon;
@FXML
private Region aboutIcon;
@FXML
private Region importExportIcon;
@FXML
private Region licensesIcon;
@FXML
private Region restAPIIcon;
@FXML
private Region heimatIcon;
@FXML
private TextField authName;
@FXML
private PasswordField authPassword;
@FXML
private CheckBox activateRestApiCheckBox;
@FXML
private Hyperlink swaggerHyperLink;
@FXML
private TextField authPort;
@FXML
private CheckBox heimatActivationCheckbox;
@FXML
private TextField heimatUrlTextField;
@FXML
private Label heimatUrlPreviewLabel;
@FXML
private PasswordField heimatPatTextField;
@FXML
private Label heimatExpiresLabel;
@FXML
private Button heimatValidateConnectionButton;
@FXML
private Label heimatValidateConnectionLabel;
@FXML
private Button heimatMapProjectsButton;
@FXML
private Label mapProjectsButtonLabel;
private static final String propertiesFilePath = "application.properties";
private static final String GITHUB_PAGE = "https://www.github.com/doubleSlashde/KeepTime";
private static final String GITHUB_ISSUE_PAGE = GITHUB_PAGE + "/issues";
private static final Color HYPERLINK_COLOR = Color.rgb(0, 115, 170);
private final ApplicationProperties applicationProperties;
private final HeimatController heimatController;
private static final Logger LOG = LoggerFactory.getLogger(SettingsController.class);
private final Controller controller;
private final Model model;
private Stage thisStage;
@Autowired
ViewController mainscreen;
public SettingsController(final Model model, final Controller controller,
ApplicationProperties applicationProperties, HeimatController heimatController) {
this.model = model;
this.controller = controller;
this.applicationProperties = applicationProperties;
this.heimatController = heimatController;
}
@FXML
private void initialize() {
LOG.debug("start init");
LOG.info("OS: {}", OS.getOSName());
LOG.debug("set versionLabel text");
LOG.debug("load substages");
LOG.debug("set version label text");
if (!OS.isWindows()) {
LOG.info("Disabling unsupported settings (hotkey) for non windows feature.");
useHotkeyCheckBox.setDisable(true);
hotkeyLabel.setDisable(true);
globalKeyloggerLabel.setDisable(true);
hideProjectsOnMouseExitCheckBox.setDisable(true);
}
double requiredWidth = 15.0;
double requiredHeight = 15.0;
setRegionSvg(colorIcon, requiredWidth, requiredHeight, RESOURCE.SVG_COLOR_ICON);
setRegionSvg(layoutIcon, requiredWidth, requiredHeight, RESOURCE.SVG_LAYOUT_ICON);
setRegionSvg(generalIcon, requiredWidth, requiredHeight, RESOURCE.SVG_SETTINGS_ICON);
setRegionSvg(aboutIcon, requiredWidth, requiredHeight, RESOURCE.SVG_ABOUT_ICON);
setRegionSvg(importExportIcon, requiredWidth, requiredHeight, RESOURCE.SVG_IMPORT_EXPORT_ICON);
setRegionSvg(licensesIcon, requiredWidth, requiredHeight, RESOURCE.SVG_LICENSES_ICON);
setRegionSvg(restAPIIcon, requiredWidth, requiredHeight, RESOURCE.SVG_GLOBE_ICON);
setRegionSvg(heimatIcon, requiredWidth, requiredHeight, RESOURCE.SVG_ROTATE_ICON);
initExportButton();
initImportButton();
try (FileInputStream input = new FileInputStream(propertiesFilePath)) {
Properties properties = new Properties();
properties.load(input);
String apiStatus = properties.getProperty("api");
if (apiStatus != null) {
if (apiStatus.equals("ON")) {
activateRestApiCheckBox.setSelected(true);
String port = properties.getProperty("server.port");
String userName = properties.getProperty("spring.security.user.name");
String userPassword = properties.getProperty("spring.security.user.password");
if (port != null) {
authPort.setText(port);
}
if (userName!= null) {
authName.setText(userName);
authPassword.setText(userPassword);
}
} else if (apiStatus.equals("OFF")) {
activateRestApiCheckBox.setSelected(false);
}
}
} catch (IOException e) {
LOG.debug(
"There is currently no additional '{}' file available. This is fine as it should only be present when rest-api is used.",
propertiesFilePath, e);
}
LOG.debug("saveButton.setOnAction");
saveButton.setOnAction(ae -> {
LOG.info("Save clicked");
if (activateRestApiCheckBox.isSelected()) {
handleApiOn();
} else {
handleApiOff();
}
if (!OS.isWindows()) {
if (hoverBackgroundColor.getValue().getOpacity() < 0.5) {
hoverBackgroundColor.setValue(Color.rgb((int) (hoverBackgroundColor.getValue().getRed() * 255),
(int) (hoverBackgroundColor.getValue().getGreen() * 255),
(int) (hoverBackgroundColor.getValue().getBlue() * 255), 0.51));
final Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("Warning!");
alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
alert.setHeaderText("Color setting not supported!");
alert.setContentText(
"The level of opacity on your hover background is to low (<0.5) for non Windows system. Resetting it.");
alert.showAndWait();
}
if (defaultBackgroundColor.getValue().getOpacity() < 0.5) {
defaultBackgroundColor.setValue(Color.rgb((int) (defaultBackgroundColor.getValue().getRed() * 255),
(int) (defaultBackgroundColor.getValue().getGreen() * 255),
(int) (defaultBackgroundColor.getValue().getBlue() * 255), 0.51));
final Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("Warning!");
alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
alert.setHeaderText("Color settings not supported!");
alert.setContentText(
"The level of opacity on your default background is to low (<0.5) for non Windows system. Resetting it.");
alert.showAndWait();
}
if (hideProjectsOnMouseExitCheckBox.isSelected()) {
hideProjectsOnMouseExitCheckBox.setSelected(false);
}
}
if (saveWindowPositionCheckBox.isSelected()) {
// UPDATE POSITION
mainscreen.savePosition();
}
controller.updateColorSettings(hoverBackgroundColor.getValue(), hoverFontColor.getValue(),
defaultBackgroundColor.getValue(), defaultFontColor.getValue(), taskBarColor.getValue());
controller.updateLayoutSettings(
displayProjectsRightCheckBox.isSelected(),
hideProjectsOnMouseExitCheckBox.isSelected(), model.screenSettings.proportionalX.get(),
model.screenSettings.proportionalY.get(), model.screenSettings.screenHash.get(),
saveWindowPositionCheckBox.isSelected());
controller.updateFeatureSettings(useHotkeyCheckBox.isSelected(), emptyNoteReminderCheckBox.isSelected(),
emptyNoteReminderOnlyForWorkEntryCheckBox.isSelected(), confirmCloseCheckBox.isSelected());
updateHeimatSettings();
thisStage.close();
});
LOG.debug("cancelButton.setOnAction");
cancelButton.setOnAction(ae -> {
LOG.info("Cancel clicked");
thisStage.close();
});
LOG.debug("resetButton.setOnAction");
resetHoverBackgroundButton.setOnAction(
ae -> hoverBackgroundColor.setValue(Model.ORIGINAL_HOVER_BACKGROUND_COLOR));
resetHoverFontButton.setOnAction(ae -> hoverFontColor.setValue(Model.ORIGINAL_HOVER_Font_COLOR));
resetDefaultBackgroundButton.setOnAction(
ae -> defaultBackgroundColor.setValue(Model.ORIGINAL_DEFAULT_BACKGROUND_COLOR));
resetDefaultFontButton.setOnAction(ae -> defaultFontColor.setValue(Model.ORIGINAL_DEFAULT_FONT_COLOR));
resetTaskBarFontButton.setOnAction(ae -> taskBarColor.setValue(Model.ORIGINAL_TASK_BAR_FONT_COLOR));
LOG.debug("aboutButton.setOnAction");
initializeAbout();
initializeHeimat();
}
private void initializeHeimat() {
heimatValidateConnectionButton.disableProperty().bind(
Bindings.createBooleanBinding(
() -> Boolean.valueOf(
heimatUrlTextField.getText().trim().isEmpty() || heimatPatTextField.getText().trim().isEmpty()),
heimatUrlTextField.textProperty(),
heimatPatTextField.textProperty()
)
);
heimatPatTextField.textProperty().addListener((observable, oldValue, newValue)->{
try{
final JwtDecoder.JWTTokenAttributes jwt = JwtDecoder.parse(newValue);
heimatExpiresLabel.setText(jwt.expiration().toString());
} catch(Exception e){
heimatExpiresLabel.setText("Does not seem to be valid");
}
});
heimatValidateConnectionLabel.setText("Not validated.");
heimatValidateConnectionButton.setOnAction(ae -> {
updateHeimatSettings();
try {
heimatController.tryLogin();
heimatValidateConnectionLabel.setText("Connection is valid.");
}catch(Exception e){
LOG.error("Error while validating Heimat connection", e);
heimatValidateConnectionLabel.setText("Invalid connection: " + e.getMessage());
heimatValidateConnectionLabel.setTooltip(new Tooltip(e.getMessage()));
}
});
heimatUrlPreviewLabel.setText("<url>/heimat-core/api/v1/");
heimatUrlTextField.textProperty().addListener((observable, oldValue, newValue)->{
heimatUrlPreviewLabel.setText(newValue + "/heimat-core/api/v1/");
});
final HeimatSettings heimatSettings = model.getHeimatSettings();
heimatActivationCheckbox.setSelected(heimatSettings.isHeimatActive());
heimatUrlTextField.setText(heimatSettings.getHeimatUrl());
heimatPatTextField.setText(heimatSettings.getHeimatPat());
heimatMapProjectsButton.disableProperty().bind(heimatActivationCheckbox.selectedProperty().not());
heimatMapProjectsButton.setOnAction((ae) -> {
try {
showMapProjectsStage();
} catch (FXMLLoaderException e) {
LOG.error("Error while loading map stage", e);
showErrorDialogAndWait("Error", "Could not load mapping stage", "Try to save settings first. Make sure you have internet.", e, thisStage);
}
});
}
private void updateHeimatSettings() {
controller.updateHeimatSettings(
heimatActivationCheckbox.isSelected(),
heimatUrlTextField.getText(),
heimatPatTextField.getText());
heimatController.refreshConnection();
}
private void showMapProjectsStage() {
try{
// Settings stage
final FXMLLoader fxmlLoader2 = createFXMLLoader(RESOURCE.FXML_EXT_PROJECT_MAPPING);
fxmlLoader2.setControllerFactory(model.getSpringContext()::getBean);
final Parent settingsRoot = fxmlLoader2.load();
ExternalProjectsMapController settingsController = fxmlLoader2.getController();
Stage settingsStage = new Stage();
settingsController.setStage(settingsStage);
settingsStage.initModality(Modality.APPLICATION_MODAL);
settingsStage.setTitle("External Project Mappings");
settingsStage.setResizable(false);
settingsStage.getIcons().add(new Image(Resources.getResource(RESOURCE.ICON_MAIN).toString()));
final Scene settingsScene = new Scene(settingsRoot);
settingsScene.setOnKeyPressed(ke -> {
if (ke.getCode() == KeyCode.ESCAPE) {
LOG.info("pressed ESCAPE");
settingsStage.close();
}
});
settingsStage.setScene(settingsScene);
settingsStage.showAndWait();
} catch (final Exception e) {
throw new FXMLLoaderException(e);
}
}
private static void setRegionSvg(Region region, double requiredWidth, double requiredHeight, RESOURCE resource) {
region.setShape(SvgNodeProvider.getSvgNodeWithScale(resource, 1.0, 1.0));
region.setMinSize(requiredWidth, requiredHeight);
region.setPrefSize(requiredWidth, requiredHeight);
region.setMaxSize(requiredWidth, requiredHeight);
region.setStyle("-fx-background-color: black;");
}
public void initializeAbout() {
LOG.debug("set version label");
versionNumberLabel.setText(applicationProperties.getBuildVersion());
ourLicenseHyperLink.setFocusTraversable(false);
ourLicenseHyperLink.setOnAction(ae -> showLicense(Licenses.GPLV3));
LOG.debug("set up table");
// name column
TableColumn<LicenseTableRow, String> nameColumn;
nameColumn = new TableColumn<>("Name");
nameColumn.setMinWidth(160);
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
// set SvgPath content
setRegionSvg(bugIcon, 20.0, 20.0, RESOURCE.SVG_BUG_ICON);
// licenseColumn
final TableColumn<LicenseTableRow, String> licenseColumn = new TableColumn<>("License");
licenseColumn.setMinWidth(260);
licenseColumn.setCellFactory(param -> new TableCell<LicenseTableRow, String>() {
@Override
protected void updateItem(final String item, final boolean empty) {
super.updateItem(item, empty);
setText(empty ? null : item);
setTextFill(HYPERLINK_COLOR);
setOnMouseEntered(e -> setUnderline(true));
setOnMouseExited(e -> setUnderline(false));
setOnMouseClicked(eventOnMouseClicked -> {
if (!empty && eventOnMouseClicked.getButton() == MouseButton.PRIMARY) {
final LicenseTableRow row = (LicenseTableRow) getTableRow().getItem();
final Licenses license = row.getLicense();
LOG.debug("License file name: {}", license);
showLicense(license);
}
});
}
});
licenseColumn.setCellValueFactory(new PropertyValueFactory<>("licenseName"));
final ObservableList<LicenseTableRow> licenses = loadLicenseRows();
licenseTableView.setItems(licenses);
licenseTableView.getColumns().add(nameColumn);
licenseTableView.getColumns().add(licenseColumn);
gitHubHyperlink.setOnAction(ae -> {
BrowserHelper.openURL(GITHUB_PAGE);
});
reportBugButton.setOnAction(ae -> {
BrowserHelper.openURL(GITHUB_ISSUE_PAGE);
});
swaggerHyperLink.setOnAction(ae -> {
String port = authPort.getText().isEmpty() ? "8080" : authPort.getText();
BrowserHelper.openURL("http://localhost:" + port + "/api/swagger");
});
}
private void initImportButton() {
LOG.debug("Initialize importButton.");
importButton.setOnAction(event -> {
try {
Alert confirmationAlert = new Alert(AlertType.CONFIRMATION, "", ButtonType.YES, ButtonType.NO);
Stage importConfirmationStage = (Stage) confirmationAlert.getDialogPane().getScene().getWindow();
importConfirmationStage.getIcons().add(new Image(Resources.getResource(RESOURCE.ICON_MAIN).toString()));
confirmationAlert.setTitle("Import");
confirmationAlert.setHeaderText("Do you want to Override current Data ?");
confirmationAlert.getDialogPane().setContent(new Label("""
Import previously exported .sql file. This will overwrite the currently used database contents - all current data will be lost!
If you do not have a .sql file yet you need to open the previous version of KeepTime and in the settings dialog press "Export".
You will need to restart the application after this action. If you proceed you need to select the previous exported .sql file.\
"""));
confirmationAlert.showAndWait();
if (confirmationAlert.getResult() == ButtonType.NO) {
LOG.info("User canceled import");
return;
}
final FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Exported SQl Script");
fileChooser.getExtensionFilters().add(new ExtensionFilter("SQL script files.", "*.sql"));
File file = fileChooser.showOpenDialog(thisStage);
if (file == null) {
LOG.info("User canceled import.");
return;
}
final String url = applicationProperties.getSpringDataSourceUrl();
final String username = applicationProperties.getSpringDataSourceUserName();
final String password = applicationProperties.getSpringDataSourcePassword();
if (file.getName().contains("H2-version-1")) {
new RunScript().runTool("-url", url, "-user", username, "-password", password, "-script",
file.toString(), "-options", "FROM_1X");
LOG.info("FROM_1X feature is used");
} else {
new RunScript().runTool("-url", url, "-user", username, "-password", password, "-script",
file.toString());
}
Alert informationDialog = new Alert(AlertType.INFORMATION);
Stage informationStage = (Stage) informationDialog.getDialogPane().getScene().getWindow();
informationStage.getIcons().add(new Image(Resources.getResource(RESOURCE.ICON_MAIN).toString()));
informationDialog.setTitle("Import done");
informationDialog.setHeaderText("The data was imported.");
informationDialog.getDialogPane().setContent(new Label("""
KeepTime will now be CLOSED!
You have to RESTART it again to see the changes\
"""));
informationDialog.showAndWait();
Platform.exit();
} catch (SQLException e) {
LOG.error("Could not import script file to db.", e);
Alert errorDialog = new Alert(AlertType.ERROR);
errorDialog.setTitle("Import failed");
errorDialog.setHeaderText("The current data could not be imported.");
errorDialog.setContentText("Please inform a developer and provide your log file.");
errorDialog.showAndWait();
}
});
}
private void initExportButton() {
LOG.debug("Initialize exportButton.");
exportButton.setOnAction(actionEvent -> {
LOG.info("Button pressed: exportButton");
try {
final String h2Version = applicationProperties.getH2Version();
final FileChooser fileChooser = new FileChooser();
fileChooser.setInitialDirectory(Paths.get(".").toFile());
fileChooser.setInitialFileName("KeepTime_database-export_H2-version-%s.sql".formatted(h2Version));
fileChooser.getExtensionFilters().add(new ExtensionFilter("SQL script files.", "*.sql"));
final File fileToSave = fileChooser.showSaveDialog(thisStage);
if (fileToSave == null) {
LOG.info("User canceled export.");
return;
}
final String url = applicationProperties.getSpringDataSourceUrl();
final String username = applicationProperties.getSpringDataSourceUserName();
final String password = applicationProperties.getSpringDataSourcePassword();
LOG.info("Exporting database to '{}'.", fileToSave);
Script.process(url, username, password, fileToSave.getAbsolutePath(), "DROP", "");
LOG.info("Export done.");
Alert informationDialog = new Alert(AlertType.INFORMATION);
Stage informationStage = (Stage) informationDialog.getDialogPane().getScene().getWindow();
informationStage.getIcons().add(new Image(Resources.getResource(RESOURCE.ICON_MAIN).toString()));
informationDialog.setTitle("Export done");
informationDialog.setHeaderText("The current data was exported.");
informationDialog.getDialogPane().setContent(new Label("The data was exported to '\n" + fileToSave + "'."));
informationDialog.showAndWait();
} catch (final SQLException e) {
LOG.error("Could not export db to script file.", e);
Alert errorDialog = new Alert(AlertType.ERROR);
errorDialog.setTitle("Export failed");
errorDialog.setHeaderText("The current data could not be exported.");
errorDialog.setContentText("Please inform a developer and provide your log file.");
errorDialog.showAndWait();
}
});
}
void update() {
// needed to close stage on esc
settingsRoot.requestFocus();
hoverBackgroundColor.setValue(model.hoverBackgroundColor.get());
hoverFontColor.setValue(model.hoverFontColor.get());
defaultBackgroundColor.setValue(model.defaultBackgroundColor.get());
defaultFontColor.setValue(model.defaultFontColor.get());
taskBarColor.setValue(model.taskBarColor.get());
useHotkeyCheckBox.setSelected(model.useHotkey.get());
displayProjectsRightCheckBox.setSelected(model.displayProjectsRight.get());
hideProjectsOnMouseExitCheckBox.setSelected(model.hideProjectsOnMouseExit.get());
saveWindowPositionCheckBox.setSelected(model.screenSettings.saveWindowPosition.get());
emptyNoteReminderCheckBox.setSelected(model.remindIfNotesAreEmpty.get());
emptyNoteReminderOnlyForWorkEntryCheckBox.disableProperty()
.bind(emptyNoteReminderCheckBox.selectedProperty().not());
emptyNoteReminderOnlyForWorkEntryCheckBox.setSelected(model.remindIfNotesAreEmptyOnlyForWorkEntry.get());
confirmCloseCheckBox.setSelected(model.confirmClose.get());
heimatValidateConnectionLabel.setText("Not validated.");
}
public void setStage(final Stage thisStage) {
this.thisStage = thisStage;
}
public ObservableList<LicenseTableRow> loadLicenseRows() {
final ObservableList<LicenseTableRow> licenseRows = FXCollections.observableArrayList();
licenseRows.add(new LicenseTableRow("Open Sans", Licenses.APACHEV2));
licenseRows.add(new LicenseTableRow("jnativehook", Licenses.GPLV3));
licenseRows.add(new LicenseTableRow("jnativehook", Licenses.LGPLV3));
licenseRows.add(new LicenseTableRow("commons-lang3", Licenses.APACHEV2));
licenseRows.add(new LicenseTableRow("flyway-maven-plugin", Licenses.APACHEV2));
licenseRows.add(new LicenseTableRow("spring-boot-starter-data-jpa", Licenses.APACHEV2));
licenseRows.add(new LicenseTableRow("mockito-core", Licenses.MIT));
licenseRows.add(new LicenseTableRow("h2", Licenses.EPLV1));
licenseRows.add(new LicenseTableRow("Font Awesome Icons", Licenses.CC_4_0));
licenseRows.add(new LicenseTableRow("mapstruct", Licenses.APACHEV2));
licenseRows.add(new LicenseTableRow("mapstruct-processor", Licenses.APACHEV2));
licenseRows.add(new LicenseTableRow("spring-boot-starter-web", Licenses.APACHEV2));
licenseRows.add(new LicenseTableRow("spring-boot-starter-validation", Licenses.APACHEV2));
licenseRows.add(new LicenseTableRow("spring-boot-starter-security", Licenses.APACHEV2));
licenseRows.sort(Comparator.comparing(LicenseTableRow::getName));
return licenseRows;
}
private void showLicense(final Licenses license) {
if (!FileOpenHelper.openFile(license.getPath())) {
final Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Ooops");
alert.setHeaderText("Could not find the license file");
alert.setContentText(
"We could not find the license file at \"%s\". Did you remove it?%nPlease redownload or visit \"%s\".".formatted(
license.getPath(), license.getUrl()));
alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
alert.show();
}
}
private void handleApiOff() {
Map<String, String> propertiesToUpdate = new HashMap<>();
propertiesToUpdate.put("spring.main.web-application-type", "none");
propertiesToUpdate.put("api", "OFF");
propertyWrite(propertiesToUpdate);
}
private void handleApiOn() {
String username = authName.getText();
String password = authPassword.getText();
PasswordEncoder passwordEncoder = DefaultPasswordEncoder.getPasswordEncoder();
String encodedPassword = passwordEncoder.encode(password);
Map<String, String> propertiesToUpdate = new HashMap<>();
propertiesToUpdate.put("spring.main.web-application-type", "");
propertiesToUpdate.put("server.port", authPort.getText());
propertiesToUpdate.put("api", "ON");
propertiesToUpdate.put("spring.security.user.name", username);
propertiesToUpdate.put("spring.security.user.password", encodedPassword);
propertyWrite(propertiesToUpdate);
}
private void propertyWrite(Map<String, String> propertiesToUpdate) {
Properties properties = new Properties();
try (InputStream inputStream = new FileInputStream(propertiesFilePath)){
properties.load(inputStream);
} catch (IOException e) {
LOG.debug("Could not open '{}' file. This is most likely fine as it was just not needed before and will be created next.", propertiesFilePath, e);
}
try(FileOutputStream outputStream = new FileOutputStream(propertiesFilePath)) {
for (Map.Entry<String, String> entry : propertiesToUpdate.entrySet()) {
properties.setProperty(entry.getKey(), entry.getValue());
}
properties.store(outputStream, "REST-API settings");
} catch (IOException e) {
LOG.error("Error while persisting properties: '{}'.", propertiesToUpdate, e);
}
}
}