diff --git a/src/main/java/de/deadlocker8/smarttime/charts/BarChartGenerator.java b/src/main/java/de/deadlocker8/smarttime/charts/BarChartGenerator.java index 753d0c21713137ac2664865bdcc9b385a6cb5f38..892248e7ce52ccfb7e0a12c80913c802e27448bc 100644 --- a/src/main/java/de/deadlocker8/smarttime/charts/BarChartGenerator.java +++ b/src/main/java/de/deadlocker8/smarttime/charts/BarChartGenerator.java @@ -1,14 +1,10 @@ package de.deadlocker8.smarttime.charts; -import java.util.ArrayList; -import java.util.Calendar; - import de.deadlocker8.smarttime.core.LogObject; import de.deadlocker8.smarttime.core.SQL; import de.deadlocker8.smarttime.core.Utils; import javafx.geometry.Point2D; import javafx.scene.Node; -import javafx.event.*; import javafx.scene.chart.BarChart; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; @@ -16,7 +12,9 @@ import javafx.scene.chart.XYChart; import javafx.scene.chart.XYChart.Data; import javafx.scene.chart.XYChart.Series; import javafx.scene.control.Tooltip; -import javafx.scene.input.MouseEvent; + +import java.util.ArrayList; +import java.util.Calendar; public class BarChartGenerator { @@ -34,8 +32,8 @@ public class BarChartGenerator private String getHours(int minutes) { - int hours = (int)minutes / 60; - int min = (int)minutes % 60; + int hours = (int) minutes / 60; + int min = (int) minutes % 60; return "" + hours + " h " + min + " min"; } @@ -44,11 +42,9 @@ public class BarChartGenerator Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); - calendar.set(Calendar.DATE, - 1); + calendar.set(Calendar.DATE, -1); - int numDays = calendar.getActualMaximum(Calendar.DATE); - - return numDays; + return calendar.getActualMaximum(Calendar.DATE); } @SuppressWarnings("unchecked") @@ -56,7 +52,7 @@ public class BarChartGenerator { final CategoryAxis xAxis = new CategoryAxis(); final NumberAxis yAxis = new NumberAxis(); - final BarChart<String, Number> chart = new BarChart<String, Number>(xAxis, yAxis); + final BarChart<String, Number> chart = new BarChart<>(xAxis, yAxis); chart.setTitle(project + " - " + task + " - " + Utils.getMonthName(month - 1) + " " + year); xAxis.setLabel("Tag"); yAxis.setLabel("Zeit in Minuten"); @@ -74,7 +70,7 @@ public class BarChartGenerator times[i] = 0L; for(LogObject current : objects) { - if(current.getDay() == i+1) + if(current.getDay() == i + 1) { times[i] += getMinute(current.getDuration()); } @@ -83,7 +79,7 @@ public class BarChartGenerator for(int l = 0; l < getMax(year, month); l++) { - series.getData().add(new XYChart.Data<String, Number>(String.valueOf(l + 1), times[l])); + series.getData().add(new XYChart.Data<>(String.valueOf(l + 1), times[l])); } chart.getData().addAll(series); @@ -95,23 +91,13 @@ public class BarChartGenerator String stunden = getHours(data.getYValue().intValue()); tooltip.setText(stunden); Node node = data.getNode(); - node.setOnMouseEntered(new EventHandler<MouseEvent>() - { - @Override - public void handle(MouseEvent event) - { - Point2D p = node.localToScreen(event.getX() + 5, event.getY() + 7); - tooltip.show(node, p.getX(), p.getY()); - } - }); - node.setOnMouseExited(new EventHandler<MouseEvent>() - { - @Override - public void handle(MouseEvent event) - { - tooltip.hide(); - } + + node.setOnMouseEntered(event -> { + Point2D p = node.localToScreen(event.getX() + 5, event.getY() + 7); + tooltip.show(node, p.getX(), p.getY()); }); + + node.setOnMouseExited(event -> tooltip.hide()); } } return chart; diff --git a/src/main/java/de/deadlocker8/smarttime/charts/ChartGUIController.java b/src/main/java/de/deadlocker8/smarttime/charts/ChartGUIController.java index b4a555808ebec16efb604e96e16096671c901216..6361c11c67c838df8e9872183c468718c1645333 100644 --- a/src/main/java/de/deadlocker8/smarttime/charts/ChartGUIController.java +++ b/src/main/java/de/deadlocker8/smarttime/charts/ChartGUIController.java @@ -6,15 +6,12 @@ import de.deadlocker8.smarttime.core.Settings; import de.deadlocker8.smarttime.core.Utils; import de.thecodelabs.logger.Logger; import de.thecodelabs.utils.ui.Alerts; -import javafx.beans.value.ChangeListener; -import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.chart.BarChart; import javafx.scene.chart.PieChart; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; -import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; @@ -26,33 +23,37 @@ import java.util.HashSet; @SuppressWarnings("rawtypes") public class ChartGUIController { - @FXML private Button showButton; - @FXML private ComboBox<String> projectBox; - @FXML private ComboBox<String> taskBox; - @FXML private ComboBox<String> yearBox; - @FXML private ComboBox<String> monthBox; - @FXML private AnchorPane chartPane; + @FXML + private Button showButton; + @FXML + private ComboBox<String> projectBox; + @FXML + private ComboBox<String> taskBox; + @FXML + private ComboBox<String> yearBox; + @FXML + private ComboBox<String> monthBox; + @FXML + private AnchorPane chartPane; private Stage stage; private ArrayList<String> tasks; private ArrayList<String> years; private ArrayList<String> months; private SQL sql; - private Image icon; private PieChartGenerator generator; private SummaryGenerator summaryGenerator; - private BarChartGenerator barChartGenertator; - - public void init(Settings settings, Stage stage, Image icon) + private BarChartGenerator barChartGenertator; + + public void init(Settings settings, Stage stage) { try { - this.stage = stage; - this.icon = icon; + this.stage = stage; String savePath = settings.getSavePath() + "/" + Utils.DATABASE_NAME; sql = new SQL(savePath); - ArrayList<String> projects = new ArrayList<String>(); + ArrayList<String> projects = new ArrayList<>(); projects.add("Alle Projekte"); ArrayList<String> projectNames = sql.getProjectNames(); projects.addAll(projectNames); @@ -68,7 +69,7 @@ public class ChartGUIController generator = new PieChartGenerator(savePath); summaryGenerator = new SummaryGenerator(savePath); barChartGenertator = new BarChartGenerator(savePath); - + years = sql.getYears(); Collections.sort(years); yearBox.getItems().clear(); @@ -77,89 +78,162 @@ public class ChartGUIController yearBox.getSelectionModel().select(0); showPieChart(generator.getChart0000("Alle Projekte")); - projectBox.valueProperty().addListener(new ChangeListener<String>() - { - @Override - public void changed(ObservableValue ov, String t, String t1) + projectBox.valueProperty().addListener((ov, t, t1) -> { + String selectedProject = projectBox.getValue(); + if(selectedProject.equals("Alle Projekte")) { - String selectedProject = projectBox.getValue(); - if(selectedProject.equals("Alle Projekte")) + try { - try - { - taskBox.getItems().clear(); - years = sql.getYears(); - Collections.sort(years); - yearBox.getItems().clear(); - yearBox.getItems().add("Alle Jahre"); - yearBox.getItems().addAll(years); - yearBox.getSelectionModel().select(0); - monthBox.getItems().clear(); - - showPieChart(generator.getChart0000("Alle Projekte")); - } - catch(Exception e) - { - Logger.error(e); - showErrorMessage(); - } + taskBox.getItems().clear(); + years = sql.getYears(); + Collections.sort(years); + yearBox.getItems().clear(); + yearBox.getItems().add("Alle Jahre"); + yearBox.getItems().addAll(years); + yearBox.getSelectionModel().select(0); + monthBox.getItems().clear(); + + showPieChart(generator.getChart0000("Alle Projekte")); } - else + catch(Exception e) { - try + Logger.error(e); + showErrorMessage(); + } + } + else + { + try + { + tasks = getTasks(sql.getByProject(selectedProject)); + taskBox.getItems().clear(); + taskBox.getItems().add("Alle Tasks"); + Collections.sort(tasks); + taskBox.getItems().addAll(tasks); + taskBox.getSelectionModel().select(0); + + years = getYears(sql.getByProject(selectedProject)); + Collections.sort(years); + yearBox.getItems().clear(); + yearBox.getItems().add("Alle Jahre"); + yearBox.getItems().addAll(years); + yearBox.getSelectionModel().select(0); + + monthBox.getItems().clear(); + + showPieChart(generator.getChart1000(selectedProject, selectedProject)); + } + catch(Exception e) + { + Logger.error(e); + showErrorMessage(); + } + } + }); + + taskBox.valueProperty().addListener((ov, t, t1) -> { + + String selectedProject = projectBox.getValue(); + String selectedTask = taskBox.getValue(); + + if(selectedProject != null && selectedTask != null) + { + if(!selectedProject.equals("Alle Projekte")) + { + if(selectedTask.equals("Alle Tasks")) { - tasks = getTasks(sql.getByProject(selectedProject)); - taskBox.getItems().clear(); - taskBox.getItems().add("Alle Tasks"); - Collections.sort(tasks); - taskBox.getItems().addAll(tasks); - taskBox.getSelectionModel().select(0); - - years = getYears(sql.getByProject(selectedProject)); - Collections.sort(years); - yearBox.getItems().clear(); - yearBox.getItems().add("Alle Jahre"); - yearBox.getItems().addAll(years); - yearBox.getSelectionModel().select(0); - - monthBox.getItems().clear(); - - showPieChart(generator.getChart1000(selectedProject, selectedProject)); + try + { + years = getYears(sql.getByProject(selectedProject)); + Collections.sort(years); + yearBox.getItems().clear(); + yearBox.getItems().add("Alle Jahre"); + yearBox.getItems().addAll(years); + yearBox.getSelectionModel().select(0); + monthBox.getItems().clear(); + + showPieChart(generator.getChart1000(selectedProject, selectedProject)); + } + catch(Exception e) + { + Logger.error(e); + showErrorMessage(); + } } - catch(Exception e) + else { - Logger.error(e); - showErrorMessage(); + try + { + years = getYears(sql.getByProjectAndTask(selectedProject, selectedTask)); + Collections.sort(years); + yearBox.getItems().clear(); + yearBox.getItems().add("Alle Jahre"); + yearBox.getItems().addAll(years); + yearBox.getSelectionModel().select(0); + monthBox.getItems().clear(); + + showSummary(summaryGenerator.getSummaryByProjectAndTask(selectedProject, selectedTask)); + } + catch(Exception e) + { + Logger.error(e); + showErrorMessage(); + } } } } }); - taskBox.valueProperty().addListener(new ChangeListener<String>() - { - @Override - public void changed(ObservableValue ov, String t, String t1) - { + yearBox.valueProperty().addListener((ov, t, t1) -> { + String selectedProject = projectBox.getValue(); + String selectedTask = taskBox.getValue(); + String selectedYear = yearBox.getValue(); - String selectedProject = projectBox.getValue(); - String selectedTask = taskBox.getValue(); + if(selectedProject != null && selectedYear != null) + { + if(selectedProject.equals("Alle Projekte")) + { + if(selectedYear.equals("Alle Jahre")) + { + try + { + monthBox.getItems().clear(); + showPieChart(generator.getChart0000(selectedProject)); + } + catch(Exception e) + { + Logger.error(e); + showErrorMessage(); + } + } + else + { + try + { + months = getMonths(sql.getLogObjects()); + monthBox.getItems().clear(); + monthBox.getItems().add("Alle Monate"); + monthBox.getItems().addAll(months); + monthBox.getSelectionModel().select(0); - if(selectedProject != null && selectedTask != null) + showPieChart(generator.getChart0010(Integer.parseInt(selectedYear), "Alle Projekte - " + selectedYear)); + } + catch(Exception e) + { + Logger.error(e); + showErrorMessage(); + } + } + } + else { - if( ! selectedProject.equals("Alle Projekte")) + if(selectedTask.equals("Alle Tasks")) { - if(selectedTask.equals("Alle Tasks")) + if(selectedYear.equals("Alle Jahre")) { try { - years = getYears(sql.getByProject(selectedProject)); - Collections.sort(years); - yearBox.getItems().clear(); - yearBox.getItems().add("Alle Jahre"); - yearBox.getItems().addAll(years); - yearBox.getSelectionModel().select(0); monthBox.getItems().clear(); - showPieChart(generator.getChart1000(selectedProject, selectedProject)); } catch(Exception e) @@ -172,15 +246,13 @@ public class ChartGUIController { try { - years = getYears(sql.getByProjectAndTask(selectedProject, selectedTask)); - Collections.sort(years); - yearBox.getItems().clear(); - yearBox.getItems().add("Alle Jahre"); - yearBox.getItems().addAll(years); - yearBox.getSelectionModel().select(0); + months = getMonths(sql.getByProjectAndYear(selectedProject, Integer.parseInt(selectedYear))); monthBox.getItems().clear(); - - showSummary(summaryGenerator.getSummaryByProjectAndTask(selectedProject, selectedTask)); + monthBox.getItems().add("Alle Monate"); + monthBox.getItems().addAll(months); + monthBox.getSelectionModel().select(0); + + showPieChart(generator.getChart1010(selectedProject, Integer.parseInt(selectedYear), selectedProject + " - " + selectedYear)); } catch(Exception e) { @@ -189,29 +261,14 @@ public class ChartGUIController } } } - } - } - }); - - yearBox.valueProperty().addListener(new ChangeListener<String>() - { - @Override - public void changed(ObservableValue ov, String t, String t1) - { - String selectedProject = projectBox.getValue(); - String selectedTask = taskBox.getValue(); - String selectedYear = yearBox.getValue(); - - if(selectedProject != null && selectedYear != null) - { - if(selectedProject.equals("Alle Projekte")) + else { if(selectedYear.equals("Alle Jahre")) { try { monthBox.getItems().clear(); - showPieChart(generator.getChart0000(selectedProject)); + showSummary(summaryGenerator.getSummaryByProjectAndTask(selectedProject, selectedTask)); } catch(Exception e) { @@ -222,14 +279,14 @@ public class ChartGUIController else { try - { - months = getMonths(sql.getLogObjects()); + { + months = getMonths(sql.getByProjectAndTaskAndYear(selectedProject, selectedTask, Integer.parseInt(selectedYear))); monthBox.getItems().clear(); monthBox.getItems().add("Alle Monate"); - monthBox.getItems().addAll(months); + monthBox.getItems().addAll(months); monthBox.getSelectionModel().select(0); - showPieChart(generator.getChart0010(Integer.parseInt(selectedYear), "Alle Projekte - " + selectedYear)); + showSummary(summaryGenerator.getSummaryByProjectAndTaskAndYear(selectedProject, selectedTask, Integer.parseInt(selectedYear))); } catch(Exception e) { @@ -238,103 +295,60 @@ public class ChartGUIController } } } - else + } + } + }); + + monthBox.valueProperty().addListener((ov, t, t1) -> { + String selectedProject = projectBox.getValue(); + String selectedTask = taskBox.getValue(); + String selectedYear = yearBox.getValue(); + String selectedMonth = monthBox.getValue(); + + if(selectedProject != null && selectedYear != null && selectedMonth != null) + { + if(selectedProject.equals("Alle Projekte")) + { + if(!selectedYear.equals("Alle Jahre")) { - if(selectedTask.equals("Alle Tasks")) + if(selectedMonth.equals("Alle Monate")) { - if(selectedYear.equals("Alle Jahre")) + try { - try - { - monthBox.getItems().clear(); - showPieChart(generator.getChart1000(selectedProject, selectedProject)); - } - catch(Exception e) - { - Logger.error(e); - showErrorMessage(); - } + showPieChart(generator.getChart0010(Integer.parseInt(selectedYear), "Alle Projekte - " + selectedYear)); } - else + catch(Exception e) { - try - { - months = getMonths(sql.getByProjectAndYear(selectedProject, Integer.parseInt(selectedYear))); - monthBox.getItems().clear(); - monthBox.getItems().add("Alle Monate"); - monthBox.getItems().addAll(months); - monthBox.getSelectionModel().select(0); - - showPieChart(generator.getChart1010(selectedProject, Integer.parseInt(selectedYear), selectedProject + " - " + selectedYear)); - } - catch(Exception e) - { - Logger.error(e); - showErrorMessage(); - } + Logger.error(e); + showErrorMessage(); } } else { - if(selectedYear.equals("Alle Jahre")) + try { - try - { - monthBox.getItems().clear(); - showSummary(summaryGenerator.getSummaryByProjectAndTask(selectedProject, selectedTask)); - } - catch(Exception e) - { - Logger.error(e); - showErrorMessage(); - } + showPieChart(generator.getChart0011(Integer.parseInt(selectedYear), Utils.getMonthNumber(selectedMonth), "Alle Projekte - " + selectedMonth + " " + selectedYear)); } - else + catch(Exception e) { - try - { - months = getMonths(sql.getByProjectAndTaskAndYear(selectedProject, selectedTask, Integer.parseInt(selectedYear))); - monthBox.getItems().clear(); - monthBox.getItems().add("Alle Monate"); - monthBox.getItems().addAll(months); - monthBox.getSelectionModel().select(0); - - showSummary(summaryGenerator.getSummaryByProjectAndTaskAndYear(selectedProject, selectedTask, Integer.parseInt(selectedYear))); - } - catch(Exception e) - { - Logger.error(e); - showErrorMessage(); - } + Logger.error(e); + showErrorMessage(); } } } } - } - }); - - monthBox.valueProperty().addListener(new ChangeListener<String>() - { - @Override - public void changed(ObservableValue ov, String t, String t1) - { - String selectedProject = projectBox.getValue(); - String selectedTask = taskBox.getValue(); - String selectedYear = yearBox.getValue(); - String selectedMonth = monthBox.getValue(); - - if(selectedProject != null && selectedYear != null && selectedMonth != null) + else { - if(selectedProject.equals("Alle Projekte")) + if(selectedTask.equals("Alle Tasks")) { if(!selectedYear.equals("Alle Jahre")) { if(selectedMonth.equals("Alle Monate")) { try - { - showPieChart(generator.getChart0010(Integer.parseInt(selectedYear), "Alle Projekte - " + selectedYear)); - } + { + showPieChart(generator.getChart1010(selectedProject, Integer.parseInt(selectedYear), selectedProject + " - " + selectedYear)); + } catch(Exception e) { Logger.error(e); @@ -345,7 +359,7 @@ public class ChartGUIController { try { - showPieChart(generator.getChart0011(Integer.parseInt(selectedYear), Utils.getMonthNumber(selectedMonth), "Alle Projekte - " + selectedMonth + " " + selectedYear)); + showPieChart(generator.getChart1011(selectedProject, Integer.parseInt(selectedYear), Utils.getMonthNumber(selectedMonth), selectedProject + " - " + selectedMonth + " " + selectedYear)); } catch(Exception e) { @@ -353,69 +367,36 @@ public class ChartGUIController showErrorMessage(); } } - } + } } else { - if(selectedTask.equals("Alle Tasks")) + if(!selectedYear.equals("Alle Jahre")) { - if(!selectedYear.equals("Alle Jahre")) + if(selectedMonth.equals("Alle Monate")) { - if(selectedMonth.equals("Alle Monate")) + try { - try - { - showPieChart(generator.getChart1010(selectedProject, Integer.parseInt(selectedYear), selectedProject + " - " + selectedYear)); - } - catch(Exception e) - { - Logger.error(e); - showErrorMessage(); - } + showSummary(summaryGenerator.getSummaryByProjectAndTask(selectedProject, selectedTask)); } - else + catch(Exception e) { - try - { - showPieChart(generator.getChart1011(selectedProject, Integer.parseInt(selectedYear), Utils.getMonthNumber(selectedMonth), selectedProject + " - " + selectedMonth + " " + selectedYear)); - } - catch(Exception e) - { - Logger.error(e); - showErrorMessage(); - } + showErrorMessage(); + Logger.error(e); } - } - } - else - { - if(!selectedYear.equals("Alle Jahre")) + } + else { - if(selectedMonth.equals("Alle Monate")) + try { - try - { - showSummary(summaryGenerator.getSummaryByProjectAndTask(selectedProject, selectedTask)); - } - catch(Exception e) - { - showErrorMessage(); - Logger.error(e); - } + showBarChart(barChartGenertator.getBarChart(selectedProject, selectedTask, Integer.parseInt(selectedYear), Utils.getMonthNumber(selectedMonth))); } - else + catch(Exception e) { - try - { - showBarChart(barChartGenertator.getBarChart(selectedProject, selectedTask, Integer.parseInt(selectedYear), Utils.getMonthNumber(selectedMonth))); - } - catch(Exception e) - { - showErrorMessage(); - Logger.error(e); - } + showErrorMessage(); + Logger.error(e); } - } + } } } } @@ -428,7 +409,7 @@ public class ChartGUIController showErrorMessage(); } } - + private void showErrorMessage() { Alerts.getInstance().createAlert(AlertType.ERROR, "Fehler", "Fehler beim Erstellen des Diagramms.", stage); @@ -444,9 +425,9 @@ public class ChartGUIController AnchorPane.setRightAnchor(chart, 14.0); chartPane.setMaxHeight(Double.MAX_VALUE); } - + private void showSummary(VBox vboxSummary) - { + { chartPane.getChildren().clear(); chartPane.getChildren().add(vboxSummary); AnchorPane.setBottomAnchor(vboxSummary, 14.0); @@ -466,43 +447,43 @@ public class ChartGUIController AnchorPane.setRightAnchor(chart, 14.0); chartPane.setMaxHeight(Double.MAX_VALUE); } - + private ArrayList<String> getTasks(ArrayList<LogObject> objects) { - HashSet<String> tasks = new HashSet<String>(); + HashSet<String> tasks = new HashSet<>(); for(LogObject current : objects) { tasks.add(String.valueOf(current.getTask())); } - return new ArrayList<String>(tasks); + return new ArrayList<>(tasks); } private ArrayList<String> getYears(ArrayList<LogObject> objects) { - HashSet<String> years = new HashSet<String>(); + HashSet<String> years = new HashSet<>(); for(LogObject current : objects) { years.add(String.valueOf(current.getYear())); } - return new ArrayList<String>(years); + return new ArrayList<>(years); } private ArrayList<String> getMonths(ArrayList<LogObject> objects) { - HashSet<Integer> months = new HashSet<Integer>(); + HashSet<Integer> months = new HashSet<>(); for(LogObject current : objects) { months.add(current.getMonth()); } - ArrayList<String> monthNames = new ArrayList<String>(); + ArrayList<String> monthNames = new ArrayList<>(); ArrayList<Integer> monthsNumbers = new ArrayList<>(months); - for(int k = 0; k < monthsNumbers.size(); k++) - { - monthNames.add(Utils.getMonthName(monthsNumbers.get(k)-1)); + for(Integer monthsNumber : monthsNumbers) + { + monthNames.add(Utils.getMonthName(monthsNumber - 1)); } return monthNames; - } + } } \ No newline at end of file diff --git a/src/main/java/de/deadlocker8/smarttime/charts/PieChartGenerator.java b/src/main/java/de/deadlocker8/smarttime/charts/PieChartGenerator.java index 18b723510069f221a65da3495c4a6c13181b9d36..1d7ffdb83a1a07ff3ab05ba7df6a8258ef70314e 100644 --- a/src/main/java/de/deadlocker8/smarttime/charts/PieChartGenerator.java +++ b/src/main/java/de/deadlocker8/smarttime/charts/PieChartGenerator.java @@ -1,175 +1,164 @@ package de.deadlocker8.smarttime.charts; -import java.util.ArrayList; -import java.util.HashSet; - +import de.deadlocker8.smarttime.core.ConvertTo; import de.deadlocker8.smarttime.core.LogObject; import de.deadlocker8.smarttime.core.SQL; import javafx.collections.FXCollections; import javafx.collections.ObservableList; -import javafx.event.EventHandler; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.chart.PieChart; import javafx.scene.control.Tooltip; -import javafx.scene.input.MouseEvent; -import de.deadlocker8.smarttime.core.ConvertTo; + +import java.util.ArrayList; +import java.util.HashSet; public class PieChartGenerator { private SQL sql; - + public PieChartGenerator(String path) { - sql = new SQL(path); + sql = new SQL(path); } - + private long completeTime(ArrayList<LogObject> list) - { + { long total = 0; for(LogObject current : list) { total += current.getDuration(); - } - return total; - } - + } + return total; + } + private PieChart createChart(ObservableList<PieChart.Data> data, String title) { PieChart chart = new PieChart(data); - chart.setTitle(title); - + chart.setTitle(title); + chart.getData().stream().forEach(tool -> { - Tooltip tooltip = new Tooltip(); - - double total = 0; - for (PieChart.Data d : chart.getData()) - { - total += d.getPieValue(); - } - - double pieValue = tool.getPieValue(); - double percentage = (pieValue/total) * 100; - String percent = String.valueOf(percentage); - percent = percent.substring(0, percent.indexOf(".") + 2); - String time = ConvertTo.ConvertMillisToTime((long) pieValue); - - tooltip.setText(percent + " % \n" + time); - Tooltip.install(tool.getNode(), tooltip); - Node node = tool.getNode(); - node.setOnMouseEntered(new EventHandler<MouseEvent>() { - - @Override - public void handle(MouseEvent event) { - Point2D p = node.localToScreen(event.getX()+5,event.getY()+7); - tooltip.show(node, p.getX(), p.getY()); - } - }); - node.setOnMouseExited(new EventHandler<MouseEvent>() { - - @Override - public void handle(MouseEvent event) { - tooltip.hide(); - } - }); - }); + Tooltip tooltip = new Tooltip(); + + double total = 0; + for(PieChart.Data d : chart.getData()) + { + total += d.getPieValue(); + } + + double pieValue = tool.getPieValue(); + double percentage = (pieValue / total) * 100; + String percent = String.valueOf(percentage); + percent = percent.substring(0, percent.indexOf(".") + 2); + String time = ConvertTo.ConvertMillisToTime((long) pieValue); + + tooltip.setText(percent + " % \n" + time); + Tooltip.install(tool.getNode(), tooltip); + Node node = tool.getNode(); + node.setOnMouseEntered(event -> { + Point2D p = node.localToScreen(event.getX() + 5, event.getY() + 7); + tooltip.show(node, p.getX(), p.getY()); + }); + + node.setOnMouseExited(event -> tooltip.hide()); + }); return chart; } - + private ArrayList<String> getProjectNames(ArrayList<LogObject> objects) { - HashSet<String> names = new HashSet<String>(); + HashSet<String> names = new HashSet<>(); for(LogObject current : objects) { names.add(current.getProject()); } - - return new ArrayList<String>(names); - } - + + return new ArrayList<>(names); + } + private ArrayList<String> getTasknames(ArrayList<LogObject> objects) { - HashSet<String> names = new HashSet<String>(); + HashSet<String> names = new HashSet<>(); for(LogObject current : objects) { names.add(current.getTask()); } - - return new ArrayList<String>(names); + + return new ArrayList<>(names); } - + //all Projects for all time public PieChart getChart0000(String title) throws Exception { ArrayList<String> names = sql.getProjectNames(); - ObservableList<PieChart.Data> data = FXCollections.observableArrayList(); - for(String currentName : names) - { - data.add(new PieChart.Data(currentName, completeTime(sql.getByProject(currentName)))); - } - return createChart(data, title); + ObservableList<PieChart.Data> data = FXCollections.observableArrayList(); + for(String currentName : names) + { + data.add(new PieChart.Data(currentName, completeTime(sql.getByProject(currentName)))); + } + return createChart(data, title); } - + //all Projects for one specific year public PieChart getChart0010(int year, String title) throws Exception - { + { ArrayList<String> names = getProjectNames(sql.getByYear(year)); - ObservableList<PieChart.Data> data = FXCollections.observableArrayList(); - for(String currentName : names) - { - data.add(new PieChart.Data(currentName, completeTime(sql.getByProjectAndYear(currentName, year)))); - } - return createChart(data, title); + ObservableList<PieChart.Data> data = FXCollections.observableArrayList(); + for(String currentName : names) + { + data.add(new PieChart.Data(currentName, completeTime(sql.getByProjectAndYear(currentName, year)))); + } + return createChart(data, title); } - + //all Projects for one specific year and month public PieChart getChart0011(int year, int month, String title) throws Exception - { + { ArrayList<String> names = getProjectNames(sql.getByYearAndMonth(year, month)); - ObservableList<PieChart.Data> data = FXCollections.observableArrayList(); - for(String currentName : names) - { - data.add(new PieChart.Data(currentName, completeTime(sql.getByProjectAndYearAndMonth(currentName, year, month)))); - } - return createChart(data, title); + ObservableList<PieChart.Data> data = FXCollections.observableArrayList(); + for(String currentName : names) + { + data.add(new PieChart.Data(currentName, completeTime(sql.getByProjectAndYearAndMonth(currentName, year, month)))); + } + return createChart(data, title); } - + //one specific Project for all time public PieChart getChart1000(String projectName, String title) throws Exception - { + { ArrayList<LogObject> objects = sql.getByProject(projectName); ArrayList<String> names = getTasknames(objects); - ObservableList<PieChart.Data> data = FXCollections.observableArrayList(); - for(String taskName : names) - { - data.add(new PieChart.Data(taskName, completeTime(sql.getByProjectAndTask(projectName, taskName)))); - } - return createChart(data, title); + ObservableList<PieChart.Data> data = FXCollections.observableArrayList(); + for(String taskName : names) + { + data.add(new PieChart.Data(taskName, completeTime(sql.getByProjectAndTask(projectName, taskName)))); + } + return createChart(data, title); } - + //one specific Project for one specific year public PieChart getChart1010(String projectName, int year, String title) throws Exception - { + { ArrayList<LogObject> objects = sql.getByProjectAndYear(projectName, year); ArrayList<String> names = getTasknames(objects); - ObservableList<PieChart.Data> data = FXCollections.observableArrayList(); - for(String taskName : names) - { - data.add(new PieChart.Data(taskName, completeTime(sql.getByProjectAndTaskAndYear(projectName, taskName, year)))); - } - return createChart(data, title); + ObservableList<PieChart.Data> data = FXCollections.observableArrayList(); + for(String taskName : names) + { + data.add(new PieChart.Data(taskName, completeTime(sql.getByProjectAndTaskAndYear(projectName, taskName, year)))); + } + return createChart(data, title); } - + //one specific Project for one specific year and month public PieChart getChart1011(String projectName, int year, int month, String title) throws Exception - { + { ArrayList<LogObject> objects = sql.getByProjectAndYearAndMonth(projectName, year, month); ArrayList<String> names = getTasknames(objects); - ObservableList<PieChart.Data> data = FXCollections.observableArrayList(); - for(String taskName : names) - { - data.add(new PieChart.Data(taskName, completeTime(sql.getByProjectAndTaskAndYearAndMonth(projectName, taskName, year, month)))); - } - return createChart(data, title); - } + ObservableList<PieChart.Data> data = FXCollections.observableArrayList(); + for(String taskName : names) + { + data.add(new PieChart.Data(taskName, completeTime(sql.getByProjectAndTaskAndYearAndMonth(projectName, taskName, year, month)))); + } + return createChart(data, title); + } } \ No newline at end of file diff --git a/src/main/java/de/deadlocker8/smarttime/charts/SummaryGenerator.java b/src/main/java/de/deadlocker8/smarttime/charts/SummaryGenerator.java index 944259354976baac9a24099e3c9480ddd5c616e1..f0d6f30284dfd973875aa75e1bcff159ae209d0e 100644 --- a/src/main/java/de/deadlocker8/smarttime/charts/SummaryGenerator.java +++ b/src/main/java/de/deadlocker8/smarttime/charts/SummaryGenerator.java @@ -1,8 +1,6 @@ package de.deadlocker8.smarttime.charts; -import java.util.ArrayList; -import java.util.HashSet; - +import de.deadlocker8.smarttime.core.ConvertTo; import de.deadlocker8.smarttime.core.LogObject; import de.deadlocker8.smarttime.core.SQL; import javafx.geometry.Insets; @@ -10,48 +8,50 @@ import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; -import de.deadlocker8.smarttime.core.ConvertTo; + +import java.util.ArrayList; +import java.util.HashSet; public class SummaryGenerator { private SQL sql; - + public SummaryGenerator(String path) { - sql = new SQL(path); + sql = new SQL(path); } - + private long completeTime(ArrayList<LogObject> list) - { + { long total = 0; for(LogObject current : list) { total += current.getDuration(); - } - return total; - } - + } + return total; + } + private int workingDays(ArrayList<LogObject> list) - { - HashSet<String> dates = new HashSet<String>(); + { + HashSet<String> dates = new HashSet<>(); for(LogObject current : list) { dates.add(current.getDate()); - } - return dates.size(); - } - + } + return dates.size(); + } + public VBox getSummaryByProjectAndTask(String project, String task) throws Exception { VBox vboxSummary = new VBox(); Label labelName = new Label(project + " - " + task); - labelName.setStyle("-fx-font-size: 25; -fx-font-weight: bold;"); - + labelName.setStyle("-fx-font-size: 25; -fx-font-weight: bold;"); + ArrayList<LogObject> objects = sql.getByProjectAndTask(project, task); - + Label labelTotalTime = new Label(ConvertTo.ConvertMillisToTime(completeTime(objects))); labelTotalTime.setStyle("-fx-font-size: 25;"); - + int days = workingDays(objects); Label labelDays; if(days == 1) @@ -63,32 +63,32 @@ public class SummaryGenerator labelDays = new Label(workingDays(objects) + " Arbeitstage"); } labelDays.setStyle("-fx-font-size: 25;"); - + vboxSummary.setAlignment(Pos.CENTER); vboxSummary.getChildren().add(labelName); vboxSummary.getChildren().add(labelTotalTime); vboxSummary.getChildren().add(labelDays); - VBox.setVgrow(labelName, Priority.ALWAYS); + VBox.setVgrow(labelName, Priority.ALWAYS); VBox.setVgrow(labelTotalTime, Priority.ALWAYS); VBox.setVgrow(labelDays, Priority.ALWAYS); VBox.setMargin(labelName, new Insets(0.0, 0.0, 20.0, 0.0)); VBox.setMargin(labelTotalTime, new Insets(20.0, 0.0, 20.0, 0.0)); VBox.setMargin(labelDays, new Insets(20.0, 0.0, 0.0, 0.0)); - + return vboxSummary; } - + public VBox getSummaryByProjectAndTaskAndYear(String project, String task, int year) throws Exception { VBox vboxSummary = new VBox(); Label labelName = new Label(project + " - " + task + " - " + year); - labelName.setStyle("-fx-font-size: 25; -fx-font-weight: bold;"); - + labelName.setStyle("-fx-font-size: 25; -fx-font-weight: bold;"); + ArrayList<LogObject> objects = sql.getByProjectAndTaskAndYear(project, task, year); - + Label labelTotalTime = new Label(ConvertTo.ConvertMillisToTime(completeTime(objects))); labelTotalTime.setStyle("-fx-font-size: 25;"); - + int days = workingDays(objects); Label labelDays; if(days == 1) @@ -100,18 +100,18 @@ public class SummaryGenerator labelDays = new Label(workingDays(objects) + " Arbeitstage"); } labelDays.setStyle("-fx-font-size: 25;"); - + vboxSummary.setAlignment(Pos.CENTER); vboxSummary.getChildren().add(labelName); vboxSummary.getChildren().add(labelTotalTime); vboxSummary.getChildren().add(labelDays); - VBox.setVgrow(labelName, Priority.ALWAYS); + VBox.setVgrow(labelName, Priority.ALWAYS); VBox.setVgrow(labelTotalTime, Priority.ALWAYS); VBox.setVgrow(labelDays, Priority.ALWAYS); VBox.setMargin(labelName, new Insets(0.0, 0.0, 20.0, 0.0)); VBox.setMargin(labelTotalTime, new Insets(20.0, 0.0, 20.0, 0.0)); VBox.setMargin(labelDays, new Insets(20.0, 0.0, 0.0, 0.0)); - + return vboxSummary; } } \ No newline at end of file diff --git a/src/main/java/de/deadlocker8/smarttime/controller/Controller.java b/src/main/java/de/deadlocker8/smarttime/controller/Controller.java index fa77a7f9ee76716ede314ca4d882422d285dc6ef..75503f0ad5d43a666d2480f5fd829cd735745375 100644 --- a/src/main/java/de/deadlocker8/smarttime/controller/Controller.java +++ b/src/main/java/de/deadlocker8/smarttime/controller/Controller.java @@ -1,18 +1,7 @@ package de.deadlocker8.smarttime.controller; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Locale; -import java.util.Optional; -import java.util.ResourceBundle; -import java.util.regex.Pattern; - import de.deadlocker8.smarttime.charts.ChartGUIController; +import de.deadlocker8.smarttime.core.Timer; import de.deadlocker8.smarttime.core.*; import de.thecodelabs.logger.Logger; import de.thecodelabs.utils.io.PathUtils; @@ -21,10 +10,10 @@ import de.thecodelabs.utils.util.SystemUtils; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; -import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; +import javafx.event.Event; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; @@ -33,21 +22,8 @@ import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; -import javafx.scene.control.Accordion; -import javafx.scene.control.Alert; +import javafx.scene.control.*; import javafx.scene.control.Alert.AlertType; -import javafx.scene.control.ButtonType; -import javafx.scene.control.Label; -import javafx.scene.control.ProgressIndicator; -import javafx.scene.control.ScrollPane; -import javafx.scene.control.TableColumn; -import javafx.scene.control.TableColumn.CellDataFeatures; -import javafx.scene.control.TableRow; -import javafx.scene.control.TableView; -import javafx.scene.control.TitledPane; -import javafx.scene.control.ToggleButton; -import javafx.scene.control.TreeItem; -import javafx.scene.control.TreeView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.input.MouseEvent; @@ -57,24 +33,41 @@ import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.Modality; import javafx.stage.Stage; -import javafx.stage.WindowEvent; -import javafx.util.Callback; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.*; +import java.util.regex.Pattern; public class Controller { - @FXML private Label aktuellesProjektAusgabe; - @FXML private Label aktuellerTaskAusgabe; - @FXML public Label labelTime; - @FXML private Accordion accordion; - @FXML private TitledPane Projekte; - @FXML private TitledPane gesamtesLog; - @FXML private AnchorPane MainFrame; - @FXML private ToggleButton startButton; - @FXML private TableView<LogObject> table; - @FXML private ScrollPane scrollPane; - @FXML private Label labelSeparator; - @FXML private Label labelSavePath; + @FXML + private Label aktuellesProjektAusgabe; + @FXML + private Label aktuellerTaskAusgabe; + @FXML + public Label labelTime; + @FXML + private Accordion accordion; + @FXML + private TitledPane Projekte; + @FXML + private TitledPane gesamtesLog; + @FXML + private AnchorPane MainFrame; + @FXML + private ToggleButton startButton; + @FXML + private TableView<LogObject> table; + @FXML + private ScrollPane scrollPane; + @FXML + private Label labelSeparator; + @FXML + private Label labelSavePath; private Stage stage; private Timer timer; @@ -85,7 +78,7 @@ public class Controller private long startTimestamp; private long endTimestamp; private int longestProject; - private ArrayList<LogObject> logObjects = new ArrayList<LogObject>(); + private ArrayList<LogObject> logObjects = new ArrayList<>(); private final String DEFAULT_SAVE_PATH = SystemUtils.getApplicationSupportDirectoryPath("Deadlocker", "SmartTime").toString(); private SQL sql; private Stage waitingStage = new Stage(); @@ -107,12 +100,12 @@ public class Controller loadSettings(); createLogView(); loadAll(); - + setLabelSavePath(); // verwaltet den Start/Stopp-Button startButton.setOnAction(event -> { - if(projektExistiertFlag == true) + if(projektExistiertFlag) { if(startButton.isSelected()) { @@ -164,7 +157,7 @@ public class Controller aktuellesProjektAusgabe.setText(project); aktuellerTaskAusgabe.setText(task); } - + private void setLabelSavePath() { String savePathForLabel = settings.getSavePath() + "/" + Utils.DATABASE_NAME; @@ -180,7 +173,7 @@ public class Controller try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/de/deadlocker8/smarttime/fxml/ProjectGUI.fxml")); - Parent root = (Parent)fxmlLoader.load(); + Parent root = fxmlLoader.load(); Stage newStage = new Stage(); newStage.setScene(new Scene(root, 455, 300)); newStage.setTitle("Neues Projekt"); @@ -188,8 +181,8 @@ public class Controller newStage.getIcons().add(icon); - ProjectController pfc = (ProjectController)fxmlLoader.getController(); - pfc.init(this, newStage, settings, icon); + ProjectController pfc = fxmlLoader.getController(); + pfc.init(this, newStage, settings); newStage.setResizable(false); newStage.initModality(Modality.APPLICATION_MODAL); @@ -218,7 +211,7 @@ public class Controller boxRoot.getChildren().add(labelRoot); boxRoot.getChildren().add(labelRootTime); - TreeItem<HBox> gesamt = new TreeItem<HBox>(boxRoot); + TreeItem<HBox> gesamt = new TreeItem<>(boxRoot); gesamt.setExpanded(true); try @@ -239,9 +232,9 @@ public class Controller box.getChildren().add(labelProjekt); box.getChildren().add(labelProjektTime); - item = new TreeItem<HBox>(box); + item = new TreeItem<>(box); - aktuelleTasks = new ArrayList<TreeItem<HBox>>(); + aktuelleTasks = new ArrayList<>(); ArrayList<String> taskNames = sql.getTaskNamesByProject(projectName); Collections.sort(taskNames); @@ -258,7 +251,7 @@ public class Controller // und ein neus TreeItem erzeugt, was später Kind des // übergeordneten Knoten mit dem Projektnamen sein wird - aktuelleTasks.add(new TreeItem<HBox>(box2)); + aktuelleTasks.add(new TreeItem<>(box2)); } // fügt alle TreeItems der Ansicht hinzu @@ -267,7 +260,7 @@ public class Controller } gesamt.getChildren().setAll(alleTasks); - TreeView<HBox> tree = new TreeView<HBox>(gesamt); + TreeView<HBox> tree = new TreeView<>(gesamt); Projekte.setContent(tree); } catch(Exception e) @@ -323,69 +316,54 @@ public class Controller table.getColumns().clear(); TableColumn<LogObject, String> dates = new TableColumn<>("Datum"); - dates.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<LogObject, String>, ObservableValue<String>>() - { - @Override - public ObservableValue<String> call(CellDataFeatures<LogObject, String> param) - { - StringProperty value = new SimpleStringProperty(); - value.set(param.getValue().getDate()); - return value; - } + dates.setCellValueFactory(param -> { + StringProperty value = new SimpleStringProperty(); + value.set(param.getValue().getDate()); + return value; }); dates.setStyle("-fx-alignment: CENTER;"); - dates.setComparator(new Comparator<String>() - { - @Override - public int compare(String input1, String input2) - { - // 0 --> input1 == input2 - // 1 --> input1 > input2 - // -1 --> input1 < input2 + dates.setComparator((input1, input2) -> { + // 0 --> input1 == input2 + // 1 --> input1 > input2 + // -1 --> input1 < input2 - if(input1.equals(input2)) - { - return 0; - } - else - { - String[] date1 = input1.split(Pattern.quote(".")); - String[] date2 = input2.split(Pattern.quote(".")); + if(input1.equals(input2)) + { + return 0; + } + else + { + String[] date1 = input1.split(Pattern.quote(".")); + String[] date2 = input2.split(Pattern.quote(".")); - String newDate1 = date1[2] + "." + date1[1] + "." + date1[0]; - String newDate2 = date2[2] + "." + date2[1] + "." + date2[0]; + String newDate1 = date1[2] + "." + date1[1] + "." + date1[0]; + String newDate2 = date2[2] + "." + date2[1] + "." + date2[0]; - return newDate1.compareTo(newDate2); - } + return newDate1.compareTo(newDate2); } }); TableColumn<LogObject, String> startTimes = new TableColumn<>("Startzeit"); - startTimes.setCellValueFactory(new PropertyValueFactory<LogObject, String>("startTime")); + startTimes.setCellValueFactory(new PropertyValueFactory<>("startTime")); startTimes.setStyle("-fx-alignment: CENTER;"); TableColumn<LogObject, String> endTimes = new TableColumn<>("Endzeit"); - endTimes.setCellValueFactory(new PropertyValueFactory<LogObject, String>("endTime")); + endTimes.setCellValueFactory(new PropertyValueFactory<>("endTime")); endTimes.setStyle("-fx-alignment: CENTER;"); TableColumn<LogObject, String> projects = new TableColumn<>("Projekt"); - projects.setCellValueFactory(new PropertyValueFactory<LogObject, String>("project")); + projects.setCellValueFactory(new PropertyValueFactory<>("project")); projects.setStyle("-fx-alignment: CENTER;"); TableColumn<LogObject, String> tasks = new TableColumn<>("Task"); - tasks.setCellValueFactory(new PropertyValueFactory<LogObject, String>("task")); + tasks.setCellValueFactory(new PropertyValueFactory<>("task")); tasks.setStyle("-fx-alignment: CENTER;"); TableColumn<LogObject, String> durations = new TableColumn<>("Dauer"); - durations.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<LogObject, String>, ObservableValue<String>>() - { - @Override - public ObservableValue<String> call(CellDataFeatures<LogObject, String> param) - { - StringProperty value = new SimpleStringProperty(); - value.set(ConvertTo.ConvertMillisToTime(param.getValue().getDuration())); - return value; - } + durations.setCellValueFactory(param -> { + StringProperty value = new SimpleStringProperty(); + value.set(ConvertTo.ConvertMillisToTime(param.getValue().getDuration())); + return value; }); durations.setStyle("-fx-alignment: CENTER;"); @@ -407,16 +385,16 @@ public class Controller { if(event.isPrimaryButtonDown() && event.getClickCount() == 2) { - Node node = ((Node)event.getTarget()).getParent(); + Node node = ((Node) event.getTarget()).getParent(); TableRow<LogObject> row; if(node instanceof TableRow) { - row = (TableRow<LogObject>)node; + row = (TableRow<LogObject>) node; } else { // clicking on text part - row = (TableRow<LogObject>)node.getParent(); + row = (TableRow<LogObject>) node.getParent(); } editEntry(row.getItem()); @@ -434,14 +412,14 @@ public class Controller try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/de/deadlocker8/smarttime/fxml/ChartGUI.fxml")); - Parent root = (Parent)fxmlLoader.load(); + Parent root = (Parent) fxmlLoader.load(); Scene scene = new Scene(root, 800, 600); scene.getStylesheets().add("/de/deadlocker8/smarttime/css/Chart.css"); Stage newStage = new Stage(); newStage.setScene(scene); newStage.setTitle("Diagramme"); - ChartGUIController controller = (ChartGUIController)fxmlLoader.getController(); - controller.init(settings, newStage, icon); + ChartGUIController controller = fxmlLoader.getController(); + controller.init(settings, newStage); newStage.getIcons().add(icon); newStage.initOwner(stage); @@ -516,13 +494,13 @@ public class Controller try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/de/deadlocker8/smarttime/fxml/InsertTimeGUI.fxml")); - Parent root = (Parent)fxmlLoader.load(); + Parent root = fxmlLoader.load(); Scene scene = new Scene(root, 540, 400); Stage newStage = new Stage(); newStage.setScene(scene); newStage.setTitle("Zeit nachträglich einfügen"); - InsertTimeController controller = (InsertTimeController)fxmlLoader.getController(); + InsertTimeController controller = fxmlLoader.getController(); controller.init(newStage, this, settings, icon); newStage.getIcons().add(icon); newStage.initOwner(stage); @@ -546,21 +524,17 @@ public class Controller File file = fileChooser.showOpenDialog(stage); if(file != null) { - Thread importThread = new Thread() - { - public void run() - { - Platform.runLater(() -> { - showWaitingDialog("Importiere...", "Bitte warten..."); - }); - Importer importer = new Importer(settings.getSavePath() + "/" + Utils.DATABASE_NAME, stage, icon); - importer.importFromSmartTime(file); - Platform.runLater(() -> { - closeWaitingDialog(); - loadAll(); - }); - } - }; + Thread importThread = new Thread(() -> { + Platform.runLater(() -> { + showWaitingDialog("Importiere...", "Bitte warten..."); + }); + Importer importer = new Importer(settings.getSavePath() + "/" + Utils.DATABASE_NAME, stage); + importer.importFromSmartTime(file); + Platform.runLater(() -> { + closeWaitingDialog(); + loadAll(); + }); + }); importThread.start(); } } @@ -574,21 +548,15 @@ public class Controller File file = fileChooser.showOpenDialog(stage); if(file != null) { - Thread importThread = new Thread() - { - public void run() - { - Platform.runLater(() -> { - showWaitingDialog("Importiere...", "Bitte warten..."); - }); - Importer importer = new Importer(settings.getSavePath() + "/" + Utils.DATABASE_NAME, stage, icon); - importer.importFromDB(file); - Platform.runLater(() -> { - closeWaitingDialog(); - loadAll(); - }); - } - }; + Thread importThread = new Thread(() -> { + Platform.runLater(() -> showWaitingDialog("Importiere...", "Bitte warten...")); + Importer importer = new Importer(settings.getSavePath() + "/" + Utils.DATABASE_NAME, stage); + importer.importFromDB(file); + Platform.runLater(() -> { + closeWaitingDialog(); + loadAll(); + }); + }); importThread.start(); } } @@ -602,21 +570,15 @@ public class Controller File file = fileChooser.showOpenDialog(stage); if(file != null) { - Thread importThread = new Thread() - { - public void run() - { - Platform.runLater(() -> { - showWaitingDialog("Importiere...", "Bitte warten..."); - }); - Importer importer = new Importer(settings.getSavePath() + "/" + Utils.DATABASE_NAME, stage, icon); - importer.importFromJSON(file); - Platform.runLater(() -> { - closeWaitingDialog(); - loadAll(); - }); - } - }; + Thread importThread = new Thread(() -> { + Platform.runLater(() -> showWaitingDialog("Importiere...", "Bitte warten...")); + Importer importer = new Importer(settings.getSavePath() + "/" + Utils.DATABASE_NAME, stage); + importer.importFromJSON(file); + Platform.runLater(() -> { + closeWaitingDialog(); + loadAll(); + }); + }); importThread.start(); } } @@ -653,20 +615,12 @@ public class Controller File file = fileChooser.showSaveDialog(stage); if(file != null) { - Thread exportThread = new Thread() - { - public void run() - { - Platform.runLater(() -> { - showWaitingDialog("Exportiere...", "Bitte warten..."); - }); - Exporter exporter = new Exporter(settings.getSavePath() + "/" + Utils.DATABASE_NAME, stage, icon); - exporter.exportAsJSON(file); - Platform.runLater(() -> { - closeWaitingDialog(); - }); - } - }; + Thread exportThread = new Thread(() -> { + Platform.runLater(() -> showWaitingDialog("Exportiere...", "Bitte warten...")); + Exporter exporter = new Exporter(settings.getSavePath() + "/" + Utils.DATABASE_NAME, stage); + exporter.exportAsJSON(file); + Platform.runLater(this::closeWaitingDialog); + }); exportThread.start(); } } @@ -691,14 +645,7 @@ public class Controller waitingStage.initOwner(stage); waitingStage.setResizable(false); waitingStage.initModality(Modality.APPLICATION_MODAL); - waitingStage.setOnCloseRequest(new EventHandler<WindowEvent>() - { - @Override - public void handle(WindowEvent event) - { - event.consume(); - } - }); + waitingStage.setOnCloseRequest(Event::consume); waitingStage.show(); } @@ -715,14 +662,14 @@ public class Controller try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/de/deadlocker8/smarttime/fxml/EditGUI.fxml")); - Parent root = (Parent)fxmlLoader.load(); + Parent root = fxmlLoader.load(); Stage newStage = new Stage(); newStage.setScene(new Scene(root, 455, 280)); newStage.setTitle("Eintrag bearbeiten"); newStage.getIcons().add(icon); newStage.initOwner(stage); - EditController pfc = (EditController)fxmlLoader.getController(); + EditController pfc = fxmlLoader.getController(); pfc.init(this, newStage, settings, icon, object); newStage.setResizable(false); @@ -805,7 +752,7 @@ public class Controller alert.setTitle("Löschen"); alert.setHeaderText(""); alert.setContentText("Möchten Sie die gesamte Datenbank wirklich unwiederruflich löschen?"); - Stage dialogStage = (Stage)alert.getDialogPane().getScene().getWindow(); + Stage dialogStage = (Stage) alert.getDialogPane().getScene().getWindow(); dialogStage.getIcons().add(icon); Optional<ButtonType> result = alert.showAndWait(); @@ -841,7 +788,7 @@ public class Controller { settings = Utils.loadSettings(); if(settings != null) - { + { setLabels(settings.getLastProject(), settings.getLastTask()); projektExistiertFlag = true; newProject(settings.getLastProject(), settings.getLastTask()); @@ -856,14 +803,14 @@ public class Controller settings.setSavePath(DEFAULT_SAVE_PATH); } } - + @FXML public void createReport() { try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/de/deadlocker8/smarttime/fxml/ReportGUI.fxml")); - Parent root = (Parent)fxmlLoader.load(); + Parent root = (Parent) fxmlLoader.load(); Stage newStage = new Stage(); newStage.setScene(new Scene(root, 500, 500)); newStage.setMinWidth(300); @@ -872,7 +819,7 @@ public class Controller newStage.getIcons().add(icon); newStage.initOwner(stage); - ReportController reportController = (ReportController)fxmlLoader.getController(); + ReportController reportController = (ReportController) fxmlLoader.getController(); reportController.init(this, newStage, settings, icon); newStage.setResizable(true); diff --git a/src/main/java/de/deadlocker8/smarttime/controller/EditController.java b/src/main/java/de/deadlocker8/smarttime/controller/EditController.java index 8319231261adc3b2f8cf5d6e6777fc0f7be35f93..ab850c5eba63d1f7a40db8e6f7aa9dc6d863f1e4 100644 --- a/src/main/java/de/deadlocker8/smarttime/controller/EditController.java +++ b/src/main/java/de/deadlocker8/smarttime/controller/EditController.java @@ -39,7 +39,7 @@ public class EditController this.icon = icon; this.object = object; - ArrayList<String> objects = new ArrayList<String>(); + ArrayList<String> objects = new ArrayList<>(); SQL sql = new SQL(settings.getSavePath() + "/" + Utils.DATABASE_NAME); try @@ -55,24 +55,19 @@ public class EditController dropdown.setStyle("-fx-font-family: \"Arial\";-fx-font-size: 18px;"); dropdownTasks.setStyle("-fx-font-family: \"Arial\";-fx-font-size: 18px;"); - dropdown.valueProperty().addListener(new ChangeListener<String>() - { - @Override - public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) - { - dropdownTasks.getItems().clear(); + dropdown.valueProperty().addListener((observable, oldValue, newValue) -> { + dropdownTasks.getItems().clear(); - if(newValue != null && ! newValue.equals("")) + if(newValue != null && ! newValue.equals("")) + { + try + { + ArrayList<String> tasks = sql.getTaskNamesByProject(newValue); + Collections.sort(tasks); + dropdownTasks.getItems().addAll(tasks); + } + catch(Exception e) { - try - { - ArrayList<String> tasks = sql.getTaskNamesByProject(newValue); - Collections.sort(tasks); - dropdownTasks.getItems().addAll(tasks); - } - catch(Exception e) - { - } } } }); diff --git a/src/main/java/de/deadlocker8/smarttime/controller/InsertTimeController.java b/src/main/java/de/deadlocker8/smarttime/controller/InsertTimeController.java index dd22f128af09ce0f79e1d639035e011d21ddcaf0..ce492866e60bb1c663625c97e8df0ddaec5f8084 100644 --- a/src/main/java/de/deadlocker8/smarttime/controller/InsertTimeController.java +++ b/src/main/java/de/deadlocker8/smarttime/controller/InsertTimeController.java @@ -5,8 +5,6 @@ import de.thecodelabs.logger.Logger; import de.thecodelabs.utils.ui.Alerts; import de.thecodelabs.utils.ui.icon.FontAwesomeType; import de.thecodelabs.utils.ui.icon.FontIcon; -import javafx.beans.value.ChangeListener; -import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.Parent; import javafx.scene.control.Alert.AlertType; @@ -28,82 +26,89 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Date; -public class InsertTimeController +public class InsertTimeController { - @FXML private DatePicker datePicker1; - @FXML private DatePicker datePicker2; - @FXML private Parent timePicker1; - @FXML private TimePickerController timePicker1Controller; - @FXML private Parent timePicker2; - @FXML private TimePickerController timePicker2Controller; - @FXML private Button buttonUseCurrentTime; - @FXML private Button buttonAdd; - @FXML private Button buttonCancel; - @FXML private Label labelDuration; - @FXML private ComboBox<String> comboBoxProject; - @FXML private ComboBox<String> comboBoxTask; - + @FXML + private DatePicker datePicker1; + @FXML + private DatePicker datePicker2; + @FXML + private Parent timePicker1; + @FXML + private TimePickerController timePicker1Controller; + @FXML + private Parent timePicker2; + @FXML + private TimePickerController timePicker2Controller; + @FXML + private Button buttonUseCurrentTime; + @FXML + private Button buttonAdd; + @FXML + private Button buttonCancel; + @FXML + private Label labelDuration; + @FXML + private ComboBox<String> comboBoxProject; + @FXML + private ComboBox<String> comboBoxTask; + private Stage stage; private Controller controller; private String savePath; private Image icon; - + public void init(Stage stage, Controller controller, Settings settings, Image icon) - { + { this.savePath = settings.getSavePath() + "/" + Utils.DATABASE_NAME; this.stage = stage; - this.controller = controller; + this.controller = controller; this.icon = icon; final FontIcon fontIconClock = new FontIcon(FontAwesomeType.CLOCK_ALT); fontIconClock.setSize(14); fontIconClock.setColor(Color.BLACK); buttonUseCurrentTime.setGraphic(fontIconClock); - - ArrayList<String> objects = new ArrayList<String>(); - + + ArrayList<String> objects = new ArrayList<>(); + SQL sql = new SQL(savePath); try - { - objects = sql.getProjectNames(); + { + objects = sql.getProjectNames(); Collections.sort(objects); } catch(Exception e) - { - } - - comboBoxProject.getItems().addAll(objects); - comboBoxProject.setStyle("-fx-font-family: \"Arial\";-fx-font-size: 15px;"); - comboBoxTask.setStyle("-fx-font-family: \"Arial\";-fx-font-size: 15px;"); - - comboBoxProject.valueProperty().addListener(new ChangeListener<String>() { - @Override - public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) + } + + comboBoxProject.getItems().addAll(objects); + comboBoxProject.setStyle("-fx-font-family: \"Arial\";-fx-font-size: 15px;"); + comboBoxTask.setStyle("-fx-font-family: \"Arial\";-fx-font-size: 15px;"); + + comboBoxProject.valueProperty().addListener((observable, oldValue, newValue) -> { + comboBoxTask.getItems().clear(); + + if(newValue != null && !newValue.equals("")) { - comboBoxTask.getItems().clear(); - - if(newValue != null && !newValue.equals("")) + try + { + ArrayList<String> tasks = sql.getTaskNamesByProject(newValue); + Collections.sort(tasks); + comboBoxTask.getItems().addAll(tasks); + } + catch(Exception e) { - try - { - ArrayList<String> tasks = sql.getTaskNamesByProject(newValue); - Collections.sort(tasks); - comboBoxTask.getItems().addAll(tasks); - } - catch(Exception e) - { - } } } - }); - + }); + timePicker1Controller.setController(this); - timePicker2Controller.setController(this); - + timePicker2Controller.setController(this); + datePicker1.setValue(LocalDate.now()); - datePicker2.setValue(LocalDate.now()); - + datePicker2.setValue(LocalDate.now()); + final Callback<DatePicker, DateCell> dayCellFactory = new Callback<DatePicker, DateCell>() { @Override @@ -126,91 +131,81 @@ public class InsertTimeController } }; datePicker2.setDayCellFactory(dayCellFactory); - - datePicker1.valueProperty().addListener(new ChangeListener<LocalDate>() - { - @Override - public void changed(ObservableValue<? extends LocalDate> observable, LocalDate oldValue, LocalDate newValue) + + datePicker1.valueProperty().addListener((observable, oldValue, newValue) -> { + if(isEndDateAfterStartDate()) { - if(isEndDateAfterStartDate()) - { - setLabelDuration(); - } - else - { - labelDuration.setText("Endzeit liegt vor Startzeit"); - } + setLabelDuration(); + } + else + { + labelDuration.setText("Endzeit liegt vor Startzeit"); } }); - - datePicker2.valueProperty().addListener(new ChangeListener<LocalDate>() - { - @Override - public void changed(ObservableValue<? extends LocalDate> observable, LocalDate oldValue, LocalDate newValue) + + datePicker2.valueProperty().addListener((observable, oldValue, newValue) -> { + if(isEndDateAfterStartDate()) { - if(isEndDateAfterStartDate()) - { - setLabelDuration(); - } - else - { - labelDuration.setText("Endzeit liegt vor Startzeit"); - } + setLabelDuration(); + } + else + { + labelDuration.setText("Endzeit liegt vor Startzeit"); } }); - - comboBoxProject.requestFocus(); + + comboBoxProject.requestFocus(); } - + @FXML public void buttonAdd() { - String project = comboBoxProject.getValue(); - String task = comboBoxTask.getValue(); - + String project = comboBoxProject.getValue(); + String task = comboBoxTask.getValue(); + if(project != null && !project.equals("") && task != null && !task.equals("")) - { + { if(isEndDateAfterStartDate()) { int hours1 = timePicker1Controller.getHours(); int minutes1 = timePicker1Controller.getMinutes(); int seconds1 = timePicker1Controller.getSeconds(); - + int hours2 = timePicker2Controller.getHours(); int minutes2 = timePicker2Controller.getMinutes(); int seconds2 = timePicker2Controller.getSeconds(); - + LocalDate dateOne = datePicker1.getValue(); - LocalDate dateTwo = datePicker2.getValue(); - - Timestamp timestampStart = Timestamp.valueOf(dateOne.toString() + " " + hours1 + ":" + minutes1 +":" + seconds1 + ".000"); - Timestamp timestampEnd = Timestamp.valueOf(dateTwo.toString() + " " + hours2 + ":" + minutes2 +":" + seconds2 + ".000"); - + LocalDate dateTwo = datePicker2.getValue(); + + Timestamp timestampStart = Timestamp.valueOf(dateOne.toString() + " " + hours1 + ":" + minutes1 + ":" + seconds1 + ".000"); + Timestamp timestampEnd = Timestamp.valueOf(dateTwo.toString() + " " + hours2 + ":" + minutes2 + ":" + seconds2 + ".000"); + LogObject log = new LogObject( dateOne.getYear(), dateOne.getMonthValue(), - dateOne.getDayOfMonth(), - getCorrectedString(hours1) + ":" + getCorrectedString(minutes1) +":" + getCorrectedString(seconds1), - getCorrectedString(hours2) + ":" + getCorrectedString(minutes2) +":" + getCorrectedString(seconds2), - timestampEnd.getTime()-timestampStart.getTime(), - project, + dateOne.getDayOfMonth(), + getCorrectedString(hours1) + ":" + getCorrectedString(minutes1) + ":" + getCorrectedString(seconds1), + getCorrectedString(hours2) + ":" + getCorrectedString(minutes2) + ":" + getCorrectedString(seconds2), + timestampEnd.getTime() - timestampStart.getTime(), + project, task - ); - - SQL sql = new SQL(savePath); + ); + + SQL sql = new SQL(savePath); try - { - sql.insert(log); + { + sql.insert(log); } catch(Exception e) - { + { Logger.error(e); Alerts.getInstance().createAlert(AlertType.ERROR, "Fehler", "Fehler beim Speichern des Eintrags.", stage); } Alerts.getInstance().createAlert(AlertType.INFORMATION, "Gespeichert", "Der Eintrag wurde erfolgreich gespeichert.", stage); stage.close(); - controller.loadAll(); + controller.loadAll(); } else { @@ -222,22 +217,22 @@ public class InsertTimeController Alerts.getInstance().createAlert(AlertType.WARNING, "Warnung", "Die Felder für Projekt und Task dürfen nicht leer sein.", stage); } } - + @FXML public void buttonCancel() { stage.close(); } - + @FXML public void useCurrentTime() { LocalDateTime now = LocalDateTime.now(); - timePicker2Controller.setTime(now.getHour(), now.getMinute(), now.getSecond()); + timePicker2Controller.setTime(now.getHour(), now.getMinute(), now.getSecond()); timePicker2Controller.init(); setLabelDuration(); } - + public void refresh(TimePickerController controller, int hours, int minutes, int seconds, String item, String direction) { if(controller == timePicker1Controller) @@ -246,16 +241,16 @@ public class InsertTimeController { if(direction.equals("up")) { - hours++; + hours++; if(hours == 24) { hours = 0; } } else - { + { hours--; - if(hours == -1 ) + if(hours == -1) { hours = 23; } @@ -265,15 +260,15 @@ public class InsertTimeController { if(direction.equals("up")) { - minutes++; + minutes++; if(minutes == 60) { minutes = 0; } } else - { - minutes--; + { + minutes--; if(minutes == -1) { minutes = 59; @@ -291,16 +286,16 @@ public class InsertTimeController } } else - { + { seconds--; if(seconds == -1) { seconds = 59; } } - } + } timePicker1Controller.setTime(hours, minutes, seconds); - timePicker1Controller.init(); + timePicker1Controller.init(); } else { @@ -308,16 +303,16 @@ public class InsertTimeController { if(direction.equals("up")) { - hours++; + hours++; if(hours == 24) { hours = 0; } } else - { + { hours--; - if(hours == -1 ) + if(hours == -1) { hours = 23; } @@ -327,15 +322,15 @@ public class InsertTimeController { if(direction.equals("up")) { - minutes++; + minutes++; if(minutes == 60) { minutes = 0; } } else - { - minutes--; + { + minutes--; if(minutes == -1) { minutes = 59; @@ -353,18 +348,18 @@ public class InsertTimeController } } else - { + { seconds--; if(seconds == -1) { seconds = 59; } } - } + } timePicker2Controller.setTime(hours, minutes, seconds); - timePicker2Controller.init(); + timePicker2Controller.init(); } - + if(isEndDateAfterStartDate()) { setLabelDuration(); @@ -374,68 +369,61 @@ public class InsertTimeController labelDuration.setText("Endzeit liegt vor Startzeit"); } } - + public void setLabelDuration() { int hours1 = timePicker1Controller.getHours(); int minutes1 = timePicker1Controller.getMinutes(); int seconds1 = timePicker1Controller.getSeconds(); - + int hours2 = timePicker2Controller.getHours(); int minutes2 = timePicker2Controller.getMinutes(); - int seconds2 = timePicker2Controller.getSeconds(); - + int seconds2 = timePicker2Controller.getSeconds(); + String dateString = datePicker1.getValue().getYear() + "-" + getCorrectedString(datePicker1.getValue().getMonthValue()) + "-" + getCorrectedString(datePicker1.getValue().getDayOfMonth()) + "-" + getCorrectedString(hours1) + ":" + getCorrectedString(minutes1) + ":" + getCorrectedString(seconds1); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH:mm:ss"); LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter); - + dateString = datePicker2.getValue().getYear() + "-" + getCorrectedString(datePicker2.getValue().getMonthValue()) + "-" + getCorrectedString(datePicker2.getValue().getDayOfMonth()) + "-" + getCorrectedString(hours2) + ":" + getCorrectedString(minutes2) + ":" + getCorrectedString(seconds2); LocalDateTime dateTime2 = LocalDateTime.parse(dateString, formatter); - - Duration d= Duration.between(dateTime, dateTime2); - + + Duration d = Duration.between(dateTime, dateTime2); + labelDuration.setText(ConvertTo.ConvertSecondsToTime(d.getSeconds())); } - + public boolean isEndDateAfterStartDate() { int hours1 = timePicker1Controller.getHours(); int minutes1 = timePicker1Controller.getMinutes(); int seconds1 = timePicker1Controller.getSeconds(); - + int hours2 = timePicker2Controller.getHours(); int minutes2 = timePicker2Controller.getMinutes(); int seconds2 = timePicker2Controller.getSeconds(); - + String dateOne = java.sql.Date.valueOf(datePicker1.getValue()).toString(); - String dateTwo = java.sql.Date.valueOf(datePicker2.getValue()).toString(); - + String dateTwo = java.sql.Date.valueOf(datePicker2.getValue()).toString(); + DateFormat format = new SimpleDateFormat("yy-MM-dd - HH:mm:ss"); - - dateOne = dateOne + " - " + getCorrectedString(hours1) + ":"+ getCorrectedString(minutes1) + ":" + getCorrectedString(seconds1); - dateTwo = dateTwo + " - " + getCorrectedString(hours2) + ":"+ getCorrectedString(minutes2) + ":" + getCorrectedString(seconds2); - + + dateOne = dateOne + " - " + getCorrectedString(hours1) + ":" + getCorrectedString(minutes1) + ":" + getCorrectedString(seconds1); + dateTwo = dateTwo + " - " + getCorrectedString(hours2) + ":" + getCorrectedString(minutes2) + ":" + getCorrectedString(seconds2); + try { Date startDate = format.parse(dateOne); - Date endDate = format.parse(dateTwo); - - if(startDate.before(endDate)) - { - return true; - } - else - { - return false; - } + Date endDate = format.parse(dateTwo); + + return startDate.before(endDate); } catch(ParseException e) - { + { Logger.error(e); - } - return false; + } + return false; } - + private String getCorrectedString(int number) { if(number < 10) @@ -445,6 +433,6 @@ public class InsertTimeController else { return "" + number; - } - } + } + } } \ No newline at end of file diff --git a/src/main/java/de/deadlocker8/smarttime/controller/ProjectController.java b/src/main/java/de/deadlocker8/smarttime/controller/ProjectController.java index f20820fcd502e004bbab8733e48bdaadead101e3..857bb96869b0c01e838cb0d51df12b2a9f57d903 100644 --- a/src/main/java/de/deadlocker8/smarttime/controller/ProjectController.java +++ b/src/main/java/de/deadlocker8/smarttime/controller/ProjectController.java @@ -4,8 +4,6 @@ import de.deadlocker8.smarttime.core.SQL; import de.deadlocker8.smarttime.core.Settings; import de.deadlocker8.smarttime.core.Utils; import de.thecodelabs.utils.ui.Alerts; -import javafx.beans.value.ChangeListener; -import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Alert.AlertType; @@ -19,29 +17,29 @@ import java.util.Collections; /** * Controllerklasse für das Projektfenster - * - * @author Robert * + * @author Robert */ public class ProjectController { - @FXML private Button abbrechenButton; - @FXML private ComboBox<String> dropdown; - @FXML private ComboBox<String> dropdownTasks; + @FXML + private Button abbrechenButton; + @FXML + private ComboBox<String> dropdown; + @FXML + private ComboBox<String> dropdownTasks; private Stage stage; private Controller controller; - private Image icon; - public void init(Controller controller, Stage stage, Settings settings, Image icon) + public void init(Controller controller, Stage stage, Settings settings) { this.controller = controller; this.stage = stage; - this.stage.setOnCloseRequest((handle)-> { + this.stage.setOnCloseRequest((handle) -> { controller.projektExistiertFlag = false; - stage.close(); - }); - this.icon = icon; + stage.close(); + }); ArrayList<String> objects = new ArrayList<String>(); @@ -59,24 +57,19 @@ public class ProjectController dropdown.setStyle("-fx-font-family: \"Arial\";-fx-font-size: 18px;"); dropdownTasks.setStyle("-fx-font-family: \"Arial\";-fx-font-size: 18px;"); - dropdown.valueProperty().addListener(new ChangeListener<String>() - { - @Override - public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) - { - dropdownTasks.getItems().clear(); + dropdown.valueProperty().addListener((observable, oldValue, newValue) -> { + dropdownTasks.getItems().clear(); - if(newValue != null && ! newValue.equals("")) + if(newValue != null && !newValue.equals("")) + { + try + { + ArrayList<String> tasks = sql.getTaskNamesByProject(newValue); + Collections.sort(tasks); + dropdownTasks.getItems().addAll(tasks); + } + catch(Exception e) { - try - { - ArrayList<String> tasks = sql.getTaskNamesByProject(newValue); - Collections.sort(tasks); - dropdownTasks.getItems().addAll(tasks); - } - catch(Exception e) - { - } } } }); diff --git a/src/main/java/de/deadlocker8/smarttime/controller/ReportController.java b/src/main/java/de/deadlocker8/smarttime/controller/ReportController.java index fea78e84ad0ec676228deb46f6b340ec43947cfa..16cb6546ee72ac707764b514da6eecc3c3d7d826 100644 --- a/src/main/java/de/deadlocker8/smarttime/controller/ReportController.java +++ b/src/main/java/de/deadlocker8/smarttime/controller/ReportController.java @@ -1,8 +1,5 @@ package de.deadlocker8.smarttime.controller; -import java.util.ArrayList; -import java.util.Collections; - import de.deadlocker8.smarttime.core.SQL; import de.deadlocker8.smarttime.core.Settings; import de.deadlocker8.smarttime.core.Utils; @@ -10,28 +7,32 @@ import de.thecodelabs.logger.Logger; import de.thecodelabs.utils.ui.Alerts; import javafx.fxml.FXML; import javafx.scene.control.Alert.AlertType; -import javafx.scene.control.CheckBox; -import javafx.scene.control.ComboBox; -import javafx.scene.control.ListView; -import javafx.scene.control.RadioButton; -import javafx.scene.control.ToggleGroup; +import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.stage.Stage; +import java.util.ArrayList; +import java.util.Collections; + public class ReportController { - @FXML private ComboBox<String> comboBoxProject; - @FXML private ListView<CheckBox> listViewTasks; - @FXML private RadioButton radioButtonList; - @FXML private RadioButton radioButtonGroupByTasks; - @FXML private RadioButton radioButtonGroupByDate; - + @FXML + private ComboBox<String> comboBoxProject; + @FXML + private ListView<CheckBox> listViewTasks; + @FXML + private RadioButton radioButtonList; + @FXML + private RadioButton radioButtonGroupByTasks; + @FXML + private RadioButton radioButtonGroupByDate; + private Controller controller; private Stage stage; private Image icon; private Settings settings; private SQL sql; - private final String ALL_PROJECTS = "Alle"; + private static final String ALL_PROJECTS = "Alle"; public void init(Controller controller, Stage stage, Settings settings, Image icon) { @@ -39,20 +40,20 @@ public class ReportController this.stage = stage; this.settings = settings; this.icon = icon; - + sql = new SQL(settings.getSavePath() + "/" + Utils.DATABASE_NAME); prefill(); } - + private void prefill() { ToggleGroup toggleGroup = new ToggleGroup(); radioButtonList.setToggleGroup(toggleGroup); radioButtonGroupByTasks.setToggleGroup(toggleGroup); radioButtonGroupByDate.setToggleGroup(toggleGroup); - - radioButtonList.setSelected(true); - + + radioButtonList.setSelected(true); + try { ArrayList<String> projectNames = sql.getProjectNames(); @@ -64,15 +65,15 @@ public class ReportController { Logger.error(e); } - - comboBoxProject.valueProperty().addListener((observable, oldValue, newValue)->{ + + comboBoxProject.valueProperty().addListener((observable, oldValue, newValue) -> { if(newValue.equals(ALL_PROJECTS)) { radioButtonGroupByTasks.setDisable(true); listViewTasks.getItems().clear(); return; } - + try { ArrayList<String> tasks = sql.getTaskNamesByProject(newValue); @@ -82,25 +83,25 @@ public class ReportController { CheckBox currentCheckBox = new CheckBox(currentTask); currentCheckBox.setSelected(true); - currentCheckBox.selectedProperty().addListener((obs, oldVal, newVal)->{ + currentCheckBox.selectedProperty().addListener((obs, oldVal, newVal) -> { checkTasks(); }); listViewTasks.getItems().add(currentCheckBox); } - + radioButtonGroupByTasks.setDisable(false); } catch(Exception e) { Logger.error(e); } - + checkTasks(); }); - + comboBoxProject.setValue(ALL_PROJECTS); } - + private int getNumberOfActivatedTasks() { int numberOfActivatedTasks = 0; @@ -111,22 +112,15 @@ public class ReportController numberOfActivatedTasks++; } } - + return numberOfActivatedTasks; } - + private void checkTasks() - { - if(getNumberOfActivatedTasks() > 1) - { - radioButtonGroupByTasks.setDisable(false); - } - else - { - radioButtonGroupByTasks.setDisable(true); - } + { + radioButtonGroupByTasks.setDisable(getNumberOfActivatedTasks() <= 1); } - + @FXML public void generateReport() { @@ -136,13 +130,13 @@ public class ReportController Alerts.getInstance().createAlert(AlertType.WARNING, "Warnung", "Bitte wähle ein Projekt aus", stage); return; } - + if(!project.equals(ALL_PROJECTS) && getNumberOfActivatedTasks() == 0) { Alerts.getInstance().createAlert(AlertType.WARNING, "Warnung", "Bitte wähle mindestens einen Task aus", stage); return; } - + //TODO file chooser //TODO generate report } diff --git a/src/main/java/de/deadlocker8/smarttime/controller/TimePickerController.java b/src/main/java/de/deadlocker8/smarttime/controller/TimePickerController.java index 37e8e86781cde9205d8544bee63ef577c65d0be4..9a7e7b525dd9e0ba327c7c6184eeef36f9a2c685 100644 --- a/src/main/java/de/deadlocker8/smarttime/controller/TimePickerController.java +++ b/src/main/java/de/deadlocker8/smarttime/controller/TimePickerController.java @@ -2,8 +2,6 @@ package de.deadlocker8.smarttime.controller; import de.thecodelabs.utils.ui.icon.FontAwesomeType; import de.thecodelabs.utils.ui.icon.FontIcon; -import javafx.event.ActionEvent; -import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Pos; @@ -18,8 +16,9 @@ import java.util.ResourceBundle; public class TimePickerController implements Initializable { - @FXML private HBox hbox; - + @FXML + private HBox hbox; + private Label labelHours; private Label labelMinutes; private Label labelSeconds; @@ -32,18 +31,18 @@ public class TimePickerController implements Initializable private Button buttonSecondsUp; private Button buttonSecondsDown; - + private int hours = 0; private int minutes = 0; private int seconds = 0; private InsertTimeController controller; - + public void setController(InsertTimeController controller) { this.controller = controller; } - + public int getHours() { return hours; @@ -58,19 +57,19 @@ public class TimePickerController implements Initializable { return seconds; } - + public void setTime(int hours, int minutes, int seconds) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; - } - + } + public void refresh(String item, String direction) { controller.refresh(this, hours, minutes, seconds, item, direction); } - + private String getCorrectedString(int number) { if(number < 10) @@ -80,9 +79,9 @@ public class TimePickerController implements Initializable else { return "" + number; - } + } } - + public void init() { labelHours.setText(getCorrectedString(hours)); @@ -96,128 +95,86 @@ public class TimePickerController implements Initializable FontIcon arrowUp = new FontIcon(FontAwesomeType.ARROW_UP); arrowUp.setSize(10); arrowUp.setColor(Color.web("#000000")); - + FontIcon arrowDown = new FontIcon(FontAwesomeType.ARROW_DOWN); arrowDown.setSize(10); arrowDown.setColor(Color.web("#000000")); - - //VBoxHours - buttonHoursUp = new Button("", arrowUp); - buttonHoursUp.setOnAction(new EventHandler<ActionEvent>() - { - @Override - public void handle(ActionEvent event) - { - refresh("hours", "up"); - } - }); - + + //VBoxHours + buttonHoursUp = new Button("", arrowUp); + buttonHoursUp.setOnAction(event -> refresh("hours", "up")); + labelHours = new Label("00"); labelHours.setStyle("-fx-font-size: 18; "); - - buttonHoursDown = new Button("", arrowDown); - buttonHoursDown.setOnAction(new EventHandler<ActionEvent>() - { - @Override - public void handle(ActionEvent event) - { - refresh("hours", "down"); - } - }); - + + buttonHoursDown = new Button("", arrowDown); + buttonHoursDown.setOnAction(event -> refresh("hours", "down")); + VBox vboxHours = new VBox(); vboxHours.getChildren().add(buttonHoursUp); vboxHours.getChildren().add(labelHours); vboxHours.getChildren().add(buttonHoursDown); vboxHours.setAlignment(Pos.CENTER); - - //VBoxMinutes - + + //VBoxMinutes + arrowUp = new FontIcon(FontAwesomeType.ARROW_UP); arrowUp.setSize(10); arrowUp.setColor(Color.web("#000000")); - + arrowDown = new FontIcon(FontAwesomeType.ARROW_DOWN); arrowDown.setSize(10); arrowDown.setColor(Color.web("#000000")); - - buttonMinutesUp = new Button("", arrowUp); - buttonMinutesUp.setOnAction(new EventHandler<ActionEvent>() - { - @Override - public void handle(ActionEvent event) - { - refresh("minutes", "up"); - } - }); - + + buttonMinutesUp = new Button("", arrowUp); + buttonMinutesUp.setOnAction(event -> refresh("minutes", "up")); + labelMinutes = new Label("00"); labelMinutes.setStyle("-fx-font-size: 18;"); - - buttonMinutesDown = new Button("", arrowDown); - buttonMinutesDown.setOnAction(new EventHandler<ActionEvent>() - { - @Override - public void handle(ActionEvent event) - { - refresh("minutes", "down"); - } - }); - + + buttonMinutesDown = new Button("", arrowDown); + buttonMinutesDown.setOnAction(event -> refresh("minutes", "down")); + VBox vboxMinutes = new VBox(); vboxMinutes.getChildren().add(buttonMinutesUp); vboxMinutes.getChildren().add(labelMinutes); vboxMinutes.getChildren().add(buttonMinutesDown); vboxMinutes.setAlignment(Pos.CENTER); - - //VBoxSeconds + + //VBoxSeconds arrowUp = new FontIcon(FontAwesomeType.ARROW_UP); arrowUp.setSize(10); arrowUp.setColor(Color.web("#000000")); - + arrowDown = new FontIcon(FontAwesomeType.ARROW_DOWN); arrowDown.setSize(10); arrowDown.setColor(Color.web("#000000")); - - buttonSecondsUp = new Button("", arrowUp); - buttonSecondsUp.setOnAction(new EventHandler<ActionEvent>() - { - @Override - public void handle(ActionEvent event) - { - refresh("seconds", "up"); - } - }); - + + buttonSecondsUp = new Button("", arrowUp); + buttonSecondsUp.setOnAction(event -> refresh("seconds", "up")); + labelSeconds = new Label("00"); labelSeconds.setStyle("-fx-font-size: 18; "); - - buttonSecondsDown = new Button("", arrowDown); - buttonSecondsDown.setOnAction(new EventHandler<ActionEvent>() - { - @Override - public void handle(ActionEvent event) - { - refresh("seconds", "down"); - } - }); - + + buttonSecondsDown = new Button("", arrowDown); + buttonSecondsDown.setOnAction(event -> refresh("seconds", "down")); + VBox vboxSeconds = new VBox(); vboxSeconds.getChildren().add(buttonSecondsUp); vboxSeconds.getChildren().add(labelSeconds); vboxSeconds.getChildren().add(buttonSecondsDown); vboxSeconds.setAlignment(Pos.CENTER); - //Hinzufügen zur HBox + //Hinzufügen zur HBox Label separator = new Label(" : "); separator.setStyle("-fx-font-size: 18; -fx-font-weight: bold;"); Label separator2 = new Label(" : "); separator2.setStyle("-fx-font-size: 18; -fx-font-weight: bold;"); - + hbox.getChildren().add(vboxHours); hbox.getChildren().add(separator); hbox.getChildren().add(vboxMinutes); hbox.getChildren().add(separator2); - hbox.getChildren().add(vboxSeconds); + hbox.getChildren().add(vboxSeconds); } } \ No newline at end of file diff --git a/src/main/java/de/deadlocker8/smarttime/core/ConvertTo.java b/src/main/java/de/deadlocker8/smarttime/core/ConvertTo.java index 73fa03bc2126082d1b9f2a00f5d28324758ecf94..a507feb9063662c7044c22ed7c21690e4a019372 100644 --- a/src/main/java/de/deadlocker8/smarttime/core/ConvertTo.java +++ b/src/main/java/de/deadlocker8/smarttime/core/ConvertTo.java @@ -1,25 +1,20 @@ package de.deadlocker8.smarttime.core; -import java.sql.Timestamp; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - -import javafx.scene.paint.Color; - /** * stellt Methoden zur Konvertierung von Einheiten zur Verfügung * * @author Robert - * */ public class ConvertTo { + private ConvertTo() + { + } + /** * Konvertiert Millisekunden in Stunden, Minuten und Sekunden * - * @param millis - * long - Millisekunden + * @param millis long - Millisekunden * @return String - Stunden + Minuten + Sekunden */ public static String ConvertMillisToTime(long millis) @@ -34,8 +29,7 @@ public class ConvertTo /** * Konvertiert Sekunden in Stunden, Minuten und Sekunden * - * @param seconds - * long - Sekunden + * @param seconds long - Sekunden * @return String - Stunden + Minuten + Sekunden */ public static String ConvertSecondsToTime(long seconds) @@ -46,117 +40,4 @@ public class ConvertTo return hour + " h " + min + " min " + sek + " sek"; } - - /** - * Konvertiert Sekunden in Minuten und Sekunden - * - * @param seconds - * long - Sekunden - * @return String - Minuten + Sekunden - */ - public static String ConvertMillisToMinutesAndSeconds(long millis) - { - long sek = (millis / 1000) % 60; - long min = (millis / 1000) / 60; - - return min + ":" + String.format("%02d", sek); - } - - /** - * Konvertiert Millisekunden in Datum und Uhrzeit - * - * @param millis - * long - Millisekunden - * @return String - dd.MM.yyyy-hh:mm:ss.SSS - */ - public static String ConvertMillisToDateAndTime(long millis) - { - Date date = new Date(millis); - - DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS"); - return formatter.format(date); - } - - /** - * Konvertiert einen Timestamp zurück in Millisekunden - * - * @param time - * String - Timestamp - * @return long - Millisekunden - */ - public static long ConvertTimestampToMillis(String time) - { - try - { - Timestamp timestamp = Timestamp.valueOf(time); - return timestamp.getTime(); - } - catch(IllegalArgumentException e) - { - System.err.println("Falsches Eingabeformat \nString muss folgende Struktur haben: yyyy-mm-dd hh:mm:ss[.SSSSSSSSS]"); - } - return 0; - } - - /** - * Konvertiert Bytes zu MB, KB und Bytes - * - * @param bytes - * long - Bytes - * @return String - Megabyte + Kilobyte + Byte; - */ - public static String ConvertBytesToDecimalSize(long bytes) - { - long normal = bytes % 1000; - long kilo = (bytes / 1000) % 1000; - long mega = (bytes / 1000000) % 1000000; - - return mega + " MB " + kilo + " KB " + normal; - } - - /** - * Konvertiert Bytes zu MB, KB und Bytes - * - * @param bytes - * long - Bytes - * @return String - Megabyte + Kilobyte + Byte; - */ - public static String ConvertBytesToBinarySize(long bytes) - { - long normal = bytes % 1024; - long kilo = (bytes / 1024) % 1024; - long mega = (bytes / 1048576) % 1048576; - - return mega + " MB " + kilo + " KB " + normal; - } - - public static String toRGBHex(Color color) - { - return String.format("#%02X%02X%02X%02X", (int)(color.getRed() * 255), (int)(color.getGreen() * 255), (int)(color.getBlue() * 255), (int)(color.getOpacity() * 255)); - } - - public static String toRGBHexWithoutOpacity(Color color) - { - return String.format("#%02X%02X%02X", (int)(color.getRed() * 255), (int)(color.getGreen() * 255), (int)(color.getBlue() * 255)); - } - - /** - * get an appropriate readable text color for given background color - * @param color - background color - * @return Color - text color - */ - public static Color getAppropriateTextColor(Color color) - { - // Counting the perceptive luminance - human eye favors green color... - double a = 1 - (0.299 * (int)(color.getRed()*255) + 0.587 * (int)(color.getGreen()*255) + 0.114 * (int)(color.getBlue()*255)) / 255; - - if(a < 0.5) - { - return Color.BLACK; - } - else - { - return Color.WHITE; - } - } } \ No newline at end of file diff --git a/src/main/java/de/deadlocker8/smarttime/core/Exporter.java b/src/main/java/de/deadlocker8/smarttime/core/Exporter.java index f5f11bb43b3e2cee0a7ae68408a274d1d443f90a..678a914aa167bf33f9ac9672e63a8b647211806b 100644 --- a/src/main/java/de/deadlocker8/smarttime/core/Exporter.java +++ b/src/main/java/de/deadlocker8/smarttime/core/Exporter.java @@ -6,7 +6,6 @@ import de.thecodelabs.logger.Logger; import de.thecodelabs.utils.ui.Alerts; import javafx.application.Platform; import javafx.scene.control.Alert.AlertType; -import javafx.scene.image.Image; import javafx.stage.Stage; import java.io.BufferedWriter; @@ -17,57 +16,51 @@ import java.util.Date; public class Exporter { - private String path; - private Stage stage; - private Image icon; - - public Exporter(String path, Stage stage, Image icon) + private final String path; + private final Stage stage; + + public Exporter(String path, Stage stage) { this.path = path; this.stage = stage; - this.icon = icon; } - + public void exportAsJSON(File file) { try - { - SQL sql = new SQL(path); + { + SQL sql = new SQL(path); ArrayList<LogObject> objects = sql.getLogObjects(); - - JsonObject allItems = new JsonObject(); + + JsonObject allItems = new JsonObject(); allItems.addProperty("SmartTime", new Date().toString()); - - JsonArray allLogObjects = new JsonArray(); - + + JsonArray allLogObjects = new JsonArray(); + for(LogObject current : objects) { - JsonObject item = new JsonObject(); + JsonObject item = new JsonObject(); item.addProperty("date", current.getDate()); item.addProperty("startTime", current.getStartTime()); item.addProperty("endTime", current.getEndTime()); - item.addProperty("duration", current.getDuration()); + item.addProperty("duration", current.getDuration()); item.addProperty("project", current.getProject()); item.addProperty("task", current.getTask()); allLogObjects.add(item); - } - + } + allItems.add("logObjects", allLogObjects); - - BufferedWriter out = new BufferedWriter(new FileWriter(file)); - out.write(allItems.toString()); - out.close(); - - Platform.runLater(()->{ - Alerts.getInstance().createAlert(AlertType.INFORMATION, "Erfolgreich exportiert", "Der Exportvorgang wurde erfolgreich abgeschlossen.", stage); - }); + + BufferedWriter out = new BufferedWriter(new FileWriter(file)); + out.write(allItems.toString()); + out.close(); + + Platform.runLater(() -> Alerts.getInstance().createAlert(AlertType.INFORMATION, "Erfolgreich exportiert", "Der Exportvorgang wurde erfolgreich abgeschlossen.", stage)); } catch(Exception e) - { + { Logger.error(e); - Platform.runLater(()->{ - Alerts.getInstance().createAlert(AlertType.ERROR, "Fehler", "Beim Exportieren der Daten ist ein Fehler aufgetreten.", stage); - }); - } - } + Platform.runLater(() -> Alerts.getInstance().createAlert(AlertType.ERROR, "Fehler", "Beim Exportieren der Daten ist ein Fehler aufgetreten.", stage)); + } + } } \ No newline at end of file diff --git a/src/main/java/de/deadlocker8/smarttime/core/Importer.java b/src/main/java/de/deadlocker8/smarttime/core/Importer.java index 3c25f26c02dc59a7e6e89c60de69bfc54b53e417..a6a1c38d459563cacf730d4c8252d06e6e77ea03 100644 --- a/src/main/java/de/deadlocker8/smarttime/core/Importer.java +++ b/src/main/java/de/deadlocker8/smarttime/core/Importer.java @@ -7,7 +7,6 @@ import de.thecodelabs.logger.Logger; import de.thecodelabs.utils.ui.Alerts; import javafx.application.Platform; import javafx.scene.control.Alert.AlertType; -import javafx.scene.image.Image; import javafx.stage.Stage; import java.io.BufferedReader; @@ -19,56 +18,50 @@ import java.util.regex.Pattern; public class Importer { - private String path; - private Stage stage; - private Image icon; - - public Importer(String path, Stage stage, Image icon) + private final String path; + private final Stage stage; + + public Importer(String path, Stage stage) { this.path = path; this.stage = stage; - this.icon = icon; } - + public void importFromSmartTime(File file) { try { - ArrayList<String > lines = readFile(file); - ArrayList<LogObject> objects = new ArrayList<LogObject>(); + ArrayList<String> lines = readFile(file); + ArrayList<LogObject> objects = new ArrayList<>(); for(String item : lines) { String[] parts = item.split("\t"); - + String date = parts[0]; String[] dateParts = date.split("-"); - + LogObject current = new LogObject(Integer.parseInt(dateParts[2]), Integer.parseInt(dateParts[1]), Integer.parseInt(dateParts[0]), parts[3], parts[4], Long.parseLong(parts[7]), parts[5], parts[6]); - objects.add(current); + objects.add(current); } - - SQL sql = new SQL(path); + + SQL sql = new SQL(path); for(LogObject o : objects) { sql.insert(o); } - - Platform.runLater(()->{ - Alerts.getInstance().createAlert(AlertType.INFORMATION, "Erfolgreich importiert", "Der Importvorgang wurde erfolgreich abgeschlossen.", stage); - }); + + Platform.runLater(() -> Alerts.getInstance().createAlert(AlertType.INFORMATION, "Erfolgreich importiert", "Der Importvorgang wurde erfolgreich abgeschlossen.", stage)); } catch(Exception e) - { + { Logger.error(e); - Platform.runLater(()->{ - Alerts.getInstance().createAlert(AlertType.ERROR, "Fehler", "Beim Importieren der Daten ist ein Fehler aufgetreten.", stage); - }); - } - } - + Platform.runLater(() -> Alerts.getInstance().createAlert(AlertType.ERROR, "Fehler", "Beim Importieren der Daten ist ein Fehler aufgetreten.", stage)); + } + } + public void importFromDB(File file) - { - SQL sql = new SQL(file.getAbsolutePath()); + { + SQL sql = new SQL(file.getAbsolutePath()); try { ArrayList<LogObject> objects = sql.getLogObjects(); @@ -77,38 +70,34 @@ public class Importer { currentDB.insert(item); } - - Platform.runLater(()->{ - Alerts.getInstance().createAlert(AlertType.INFORMATION, "Erfolgreich importiert", "Der Importvorgang wurde erfolgreich abgeschlossen.", stage); - }); + + Platform.runLater(() -> Alerts.getInstance().createAlert(AlertType.INFORMATION, "Erfolgreich importiert", "Der Importvorgang wurde erfolgreich abgeschlossen.", stage)); } catch(Exception e) - { + { Logger.error(e); - Platform.runLater(()->{ - Alerts.getInstance().createAlert(AlertType.ERROR, "Fehler", "Beim Importieren der Daten ist ein Fehler aufgetreten.", stage); - }); - } + Platform.runLater(() -> Alerts.getInstance().createAlert(AlertType.ERROR, "Fehler", "Beim Importieren der Daten ist ein Fehler aufgetreten.", stage)); + } } - + public void importFromJSON(File file) - { - try - { - FileInputStream fis = new FileInputStream(file); - BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); - String text = ""; - String line; - while ((line = reader.readLine()) != null) + { + try + { + FileInputStream fis = new FileInputStream(file); + BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); + StringBuilder text = new StringBuilder(); + String line; + while((line = reader.readLine()) != null) { - text = text + line; - } - reader.close(); - - JsonObject allItems = new JsonParser().parse(text).getAsJsonObject(); - + text.append(line); + } + reader.close(); + + JsonObject allItems = new JsonParser().parse(text.toString()).getAsJsonObject(); + SQL sql = new SQL(path); - JsonArray loadedItems = (JsonArray)allItems.get("logObjects"); + JsonArray loadedItems = (JsonArray) allItems.get("logObjects"); for(int i = 0; i < loadedItems.size(); i++) { JsonObject item = (JsonObject) loadedItems.get(i); @@ -118,35 +107,33 @@ public class Importer long duration = item.get("duration").getAsLong(); String project = item.get("project").getAsString(); String task = item.get("task").getAsString(); - + String[] dateParts = date.split(Pattern.quote(".")); - - LogObject loadedObject = new LogObject(Integer.parseInt(dateParts[2]), Integer.parseInt(dateParts[1]), Integer.parseInt(dateParts[0]), startTime, endTime, duration, project, task); + + LogObject loadedObject = new LogObject(Integer.parseInt(dateParts[2]), Integer.parseInt(dateParts[1]), Integer.parseInt(dateParts[0]), startTime, endTime, duration, project, task); sql.insert(loadedObject); } } catch(Exception e) - { + { Logger.error(e); - Platform.runLater(()->{ - Alerts.getInstance().createAlert(AlertType.ERROR, "Fehler", "Beim Importieren der Daten ist ein Fehler aufgetreten.", stage); - }); - } + Platform.runLater(() -> Alerts.getInstance().createAlert(AlertType.ERROR, "Fehler", "Beim Importieren der Daten ist ein Fehler aufgetreten.", stage)); + } } - + private ArrayList<String> readFile(File file) throws Exception { FileInputStream fis = new FileInputStream(file); - BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); + BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); ArrayList<String> list = new ArrayList<>(); - String line; + String line; while((line = reader.readLine()) != null) { list.add(line); } - - reader.close(); + + reader.close(); return list; } } diff --git a/src/main/java/de/deadlocker8/smarttime/core/LogObject.java b/src/main/java/de/deadlocker8/smarttime/core/LogObject.java index d1aab6e5471033847474bf0a040c64a5c953b135..c099f1d3c3d1b12ba98e59de5305807d1e4a59cd 100644 --- a/src/main/java/de/deadlocker8/smarttime/core/LogObject.java +++ b/src/main/java/de/deadlocker8/smarttime/core/LogObject.java @@ -3,27 +3,25 @@ package de.deadlocker8.smarttime.core; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import de.deadlocker8.smarttime.core.ConvertTo; - /** * Klasse "Logobject" - generiert Objekte, die alle wichtigen Eigenschaften für das Logfile enthalten - * @author Robert * + * @author Robert */ public class LogObject { private int year; private int month; private int day; - private String startTime; + private String startTime; private String endTime; private long duration; private String project; - private String task; - - + private String task; + + public LogObject(int year, int month, int day, String startTime, String endTime, long duration, String project, String task) - { + { this.year = year; this.month = month; this.day = day; @@ -33,38 +31,38 @@ public class LogObject this.project = project; this.task = task; } - + public LogObject() - { + { } - + public String toString() { - return day + "." + month + "." + year + " " + startTime + " bis " + endTime + "\t" + project + "\t" + task +"\t" + duration + " (" + ConvertTo.ConvertMillisToTime(duration)+ ")"; + return day + "." + month + "." + year + " " + startTime + " bis " + endTime + "\t" + project + "\t" + task + "\t" + duration + " (" + ConvertTo.ConvertMillisToTime(duration) + ")"; } - + public void createStartTime() { LocalDateTime date = LocalDateTime.now(); year = date.getYear(); month = date.getMonthValue(); - day = date.getDayOfMonth(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); - startTime = date.format(formatter); + day = date.getDayOfMonth(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); + startTime = date.format(formatter); } - + public void createEndTime() { - LocalDateTime date = LocalDateTime.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); - endTime = date.format(formatter); + LocalDateTime date = LocalDateTime.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); + endTime = date.format(formatter); } - + public void setDuration(long duration) { this.duration = duration; } - + public void setProject(String p) { project = p; @@ -74,29 +72,29 @@ public class LogObject { task = t; } - + public String getDate() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy"); - LocalDateTime dateTime = LocalDateTime.of(year, month, day, 12, 00); + LocalDateTime dateTime = LocalDateTime.of(year, month, day, 12, 0); return dateTime.format(formatter); - } - + } + public String getStartTime() { return startTime; } - + public String getEndTime() { return endTime; - } - + } + public long getDuration() { return duration; } - + public String getProject() { return project; @@ -120,5 +118,5 @@ public class LogObject public int getDay() { return day; - } + } } \ No newline at end of file diff --git a/src/main/java/de/deadlocker8/smarttime/core/Settings.java b/src/main/java/de/deadlocker8/smarttime/core/Settings.java index 68113c6654c5c84c2990c4d007b76b3454934d14..b509938fba365fdcabad9e893635791f7d2fb061 100644 --- a/src/main/java/de/deadlocker8/smarttime/core/Settings.java +++ b/src/main/java/de/deadlocker8/smarttime/core/Settings.java @@ -8,7 +8,6 @@ public class Settings public Settings() { - } public Settings(String savePath, String lastProject, String lastTask) diff --git a/src/main/java/de/deadlocker8/smarttime/core/Timer.java b/src/main/java/de/deadlocker8/smarttime/core/Timer.java index 9c0c4c31295eec025ab2a266f3ec109679eca385..1d864c1330bf58dcc21e343d6d96465bf46ee710 100644 --- a/src/main/java/de/deadlocker8/smarttime/core/Timer.java +++ b/src/main/java/de/deadlocker8/smarttime/core/Timer.java @@ -1,37 +1,34 @@ package de.deadlocker8.smarttime.core; +import javafx.animation.Animation.Status; import javafx.animation.KeyFrame; import javafx.animation.Timeline; -import javafx.animation.Animation.Status; import javafx.scene.control.Label; import javafx.util.Duration; -import de.deadlocker8.smarttime.core.ConvertTo; public class Timer { Timeline timeline; long startTime; - + public Timer(Label label) { timeline = new Timeline(); timeline.setCycleCount(Timeline.INDEFINITE); - timeline.getKeyFrames().add(new KeyFrame(Duration.millis(500), (event) -> { - label.setText(ConvertTo.ConvertMillisToTime(System.currentTimeMillis()-startTime)); - })); + timeline.getKeyFrames().add(new KeyFrame(Duration.millis(500), event -> label.setText(ConvertTo.ConvertMillisToTime(System.currentTimeMillis() - startTime)))); } - + public void start() { startTime = System.currentTimeMillis(); timeline.playFromStart(); } - + public void stop() { timeline.stop(); } - + public boolean isRunning() { return timeline.getStatus().equals(Status.RUNNING); diff --git a/src/main/java/de/deadlocker8/smarttime/core/Utils.java b/src/main/java/de/deadlocker8/smarttime/core/Utils.java index 258b28f2935e616f119a639850dd6fe97f404ac9..7145d9419df0f65654bf576b072998911b777abf 100644 --- a/src/main/java/de/deadlocker8/smarttime/core/Utils.java +++ b/src/main/java/de/deadlocker8/smarttime/core/Utils.java @@ -1,49 +1,51 @@ package de.deadlocker8.smarttime.core; -import java.io.File; +import com.google.gson.Gson; +import de.thecodelabs.utils.io.PathUtils; +import de.thecodelabs.utils.util.SystemUtils; + import java.io.IOException; import java.io.Reader; import java.io.Writer; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Arrays; import java.util.Locale; import java.util.ResourceBundle; -import com.google.gson.Gson; -import de.thecodelabs.utils.io.PathUtils; -import de.thecodelabs.utils.util.SystemUtils; +public class Utils +{ + private Utils() + { + } -public class Utils -{ private static final ResourceBundle bundle = ResourceBundle.getBundle("de/deadlocker8/smarttime/", Locale.GERMANY); - - private static final String[] AVAILABLE_MONTH_NAMES = {"Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"}; - - public static final String DATABASE_NAME = "SmartTime.db"; - public static String getMonthName(int monthNumberOneIndexed) - { - return AVAILABLE_MONTH_NAMES[monthNumberOneIndexed]; - } - - public static int getMonthNumber(String monthName) - { - return Arrays.asList(AVAILABLE_MONTH_NAMES).indexOf(monthName) + 1; - } - - public static Settings loadSettings() + private static final String[] AVAILABLE_MONTH_NAMES = {"Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"}; + + public static final String DATABASE_NAME = "SmartTime.db"; + + public static String getMonthName(int monthNumberOneIndexed) + { + return AVAILABLE_MONTH_NAMES[monthNumberOneIndexed]; + } + + public static int getMonthNumber(String monthName) + { + return Arrays.asList(AVAILABLE_MONTH_NAMES).indexOf(monthName) + 1; + } + + public static Settings loadSettings() { Settings settings; try { Gson gson = new Gson(); Path configDir = SystemUtils.getApplicationSupportDirectoryPath(bundle.getString("folder")); - Reader reader = Files.newBufferedReader(configDir.resolve("settings.json"), Charset.forName("UTF-8")); - settings = gson.fromJson(reader, Settings.class); + Reader reader = Files.newBufferedReader(configDir.resolve("settings.json"), StandardCharsets.UTF_8); + settings = gson.fromJson(reader, Settings.class); reader.close(); return settings; } @@ -52,15 +54,15 @@ public class Utils return null; } } - + public static void saveSettings(Settings settings) throws IOException - { + { Gson gson = new Gson(); String jsonString = gson.toJson(settings); Path configDir = SystemUtils.getApplicationSupportDirectoryPath(bundle.getString("folder")); PathUtils.createDirectoriesIfNotExists(configDir); - Writer writer = Files.newBufferedWriter(configDir.resolve("settings.json"), Charset.forName("UTF-8")); + Writer writer = Files.newBufferedWriter(configDir.resolve("settings.json"), StandardCharsets.UTF_8); writer.write(jsonString); writer.close(); } diff --git a/src/main/java/de/deadlocker8/smarttime/main/Main.java b/src/main/java/de/deadlocker8/smarttime/main/Main.java index 1ce0c54b1ba4ea551644573573398a330f6d5eb9..b76ea1c7ac89bb755d77f26af6f720484796c54a 100644 --- a/src/main/java/de/deadlocker8/smarttime/main/Main.java +++ b/src/main/java/de/deadlocker8/smarttime/main/Main.java @@ -4,21 +4,16 @@ import de.deadlocker8.smarttime.controller.Controller; import de.thecodelabs.logger.FileOutputOption; import de.thecodelabs.logger.LogLevelFilter; import de.thecodelabs.logger.Logger; -import de.thecodelabs.utils.application.ApplicationUtils; -import de.thecodelabs.utils.application.container.PathType; -import de.thecodelabs.utils.io.PathUtils; import de.thecodelabs.utils.ui.Alerts; import de.thecodelabs.utils.ui.NVCStage; import de.thecodelabs.utils.util.SystemUtils; import javafx.application.Application; -import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert.AlertType; import javafx.scene.image.Image; import javafx.stage.Stage; -import javafx.stage.WindowEvent; import java.util.Locale; import java.util.Optional; @@ -33,7 +28,7 @@ public class Main extends Application try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/de/deadlocker8/smarttime/fxml/MainGUI.fxml")); - Parent root = (Parent) loader.load(); + Parent root = loader.load(); Scene scene = new Scene(root, 800, 800); scene.getStylesheets().add("/de/deadlocker8/smarttime/css/application.css"); @@ -43,7 +38,7 @@ public class Main extends Application stage.setTitle("SmartTime"); stage.setScene(scene); - Controller controller = (Controller) loader.getController(); + Controller controller = loader.getController(); controller.init(stage); stage.getIcons().add(new Image("/de/deadlocker8/smarttime/icon.png")); @@ -51,22 +46,18 @@ public class Main extends Application // fängt die Aufforderung das Fenster zu schließen ab, um vorher // noch eine Prüfung duchzuführen - stage.setOnCloseRequest(new EventHandler<WindowEvent>() - { - public void handle(WindowEvent we) + stage.setOnCloseRequest(we -> { + if(controller.isTimerRunning()) { - if(controller.isTimerRunning()) - { - Alerts.getInstance().createAlert(AlertType.WARNING, "Warnung", "Die Stoppuhr läuft noch!", stage); + Alerts.getInstance().createAlert(AlertType.WARNING, "Warnung", "Die Stoppuhr läuft noch!", stage); - // "schluckt" die Aufforderung das Fenster zu schließen - // (Fenster wird dadurch nicht geschlossen) - we.consume(); - } - else - { - stage.close(); - } + // "schluckt" die Aufforderung das Fenster zu schließen + // (Fenster wird dadurch nicht geschlossen) + we.consume(); + } + else + { + stage.close(); } }); }