Ejemplo n.º 1
1
 @FXML
 void loadSelectedPlaylist() {
   Playlist p = (Playlist) playlistsView.getSelectionModel().getSelectedItem();
   if (p == null) return;
   tracksView.setPlaceholder(offlinePlaceHolder);
   Platform.runLater(
       () -> {
         List<Track> tracks = p.getTracks();
         tracksView.getItems().clear();
         for (int i = tracks.size() - 1; i >= 0; i--) {
           tracksView.getItems().add(tracks.get(i));
         }
         if (findTrack) {
           Platform.runLater(
               () -> {
                 tracksView.getSelectionModel().select(currentTrack);
                 tracksView.scrollTo(currentTrack);
                 tracksView.requestFocus();
                 findTrack = false;
               });
         } else {
           if (tracksView.getItems().size() > 0) {
             tracksView.scrollTo(0);
           }
         }
       });
 }
Ejemplo n.º 2
0
  public static EventHandler<ActionEvent> getBrowseHandler(
      FXController controller, TextField filePath) {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Select a file to upload...");

    return e -> {
      if (AESCTR.secretKey == null) {
        new Alert(Alert.AlertType.INFORMATION, "Please generate or choose a key", ButtonType.OK)
            .showAndWait();
        return;
      }

      selectedFiles = fileChooser.showOpenMultipleDialog(null);
      if (selectedFiles != null) {
        controller.writeLog("Selected files: ");
        StringBuilder sb = new StringBuilder(1024);

        for (int i = 0; i < selectedFiles.size(); i++) {
          if (i == selectedFiles.size() - 1) {
            sb.append(selectedFiles.get(i).getAbsolutePath());
          } else {
            sb.append(selectedFiles.get(i).getAbsolutePath() + ", ");
          }
          controller.writeLog(selectedFiles.get(i).getName());
        }
        filePath.setText(sb.toString());
      }
    };
  }
Ejemplo n.º 3
0
 void playRandom() {
   List<Track> tracks = tracksView.getItems();
   Random random = new Random();
   int size = tracks.size();
   int r = random.nextInt(size - 1);
   tracksView.getSelectionModel().select(r);
   tracksView.scrollTo(tracksView.getSelectionModel().getSelectedIndex());
   Track nextTrack = (Track) tracksView.getSelectionModel().getSelectedItem();
   playTrack(nextTrack);
 }
Ejemplo n.º 4
0
 void playNext() {
   List<Track> tracks = tracksView.getItems();
   int selected = tracksView.getSelectionModel().getSelectedIndex();
   int next = selected + 1;
   if (next >= tracks.size()) {
     next = 0;
   }
   tracksView.getSelectionModel().select(next);
   tracksView.scrollTo(tracksView.getSelectionModel().getSelectedIndex());
   Track nextTrack = (Track) tracksView.getSelectionModel().getSelectedItem();
   playTrack(nextTrack);
 }
Ejemplo n.º 5
0
 private void hideTablesHeaders() {
   List<Pane> headers =
       Arrays.asList(
           (Pane) tracksView.lookup("TableHeaderRow"),
           (Pane) playlistsView.lookup("TableHeaderRow"));
   headers.forEach(
       header -> {
         header.setMaxHeight(0);
         header.setMinHeight(0);
         header.setPrefHeight(0);
         header.setVisible(false);
       });
 }
Ejemplo n.º 6
0
  @Autowired
  public TabService(
      final ApplicationController controller,
      final WebviewService webviewService,
      final EditorService editorService,
      final PathResolverService pathResolver,
      final ThreadService threadService,
      final Current current,
      final DirectoryService directoryService) {
    this.controller = controller;
    this.webviewService = webviewService;
    this.editorService = editorService;
    this.pathResolver = pathResolver;
    this.threadService = threadService;
    this.current = current;
    this.directoryService = directoryService;

    final Consumer<Path> openFileConsumer =
        path -> {
          if (Files.isDirectory(path)) {
            directoryService.changeWorkigDir(
                path.equals(directoryService.workingDirectory()) ? path.getParent() : path);
          } else if (pathResolver.isImage(path)) {
            addImageTab(path);
          } else if (pathResolver.isHTML(path)
              || pathResolver.isAsciidoc(path)
              || pathResolver.isMarkdown(path)) {
            addTab(path);
          } else if (pathResolver.isEpub(path)) {
            controller
                .getHostServices()
                .showDocument(
                    String.format(
                        "http://localhost:%d/epub/viewer?path=%s",
                        controller.getPort(), path.toString()));
          } else {
            List<String> supportedModes = controller.getSupportedModes();
            String extension = FilenameUtils.getExtension(path.toString());

            if ("".equals(extension) || supportedModes.contains(extension)) {
              addTab(path);
              controller.hidePreviewPanel();
            } else {
              controller.getHostServices().showDocument(path.toUri().toString());
            }
          }
        };
    directoryService.setOpenFileConsumer(openFileConsumer);
  }
Ejemplo n.º 7
0
 void addToPlaylist(List<File> files, Playlist p) {
   if (interfaceDisabled) return;
   new Thread(
           () -> {
             setInterfaceDisabled(true);
             int total = files.size();
             AtomicInteger current = new AtomicInteger(0);
             Cache.pushToPlaylist(
                 files,
                 p,
                 (Track t) -> {
                   Platform.runLater(
                       () -> {
                         infoLabel.setText(
                             String.format(
                                 res.getString("processed"),
                                 current.incrementAndGet(),
                                 total,
                                 t.getTitle()));
                         if (p == getSelectedPlaylist()) {
                           tracksView.getItems().remove(t);
                           tracksView.getItems().add(0, t);
                         }
                       });
                 });
             setInterfaceDisabled(false);
           })
       .start();
   if (p == getSelectedPlaylist()) {
     Platform.runLater(
         () -> {
           loadSelectedPlaylist();
         });
   }
 }
  private void processWithoutGrouping(List<TaskWithWorklogs> tasks, DisplayData displayData) {
    LOGGER.debug("Processing without grouping");
    tasks
        .stream()
        .sorted((o1, o2) -> COLLATOR.compare(o1.getIssue(), o2.getIssue()))
        .forEach(
            taskWithWorklogs -> {
              DisplayRow row = new DisplayRow();
              row.setIssueId(taskWithWorklogs.getIssue());
              row.setLabel(taskWithWorklogs.getSummary());
              row.setResolvedDate(taskWithWorklogs.getResolved());

              taskWithWorklogs
                  .getWorklogItemList()
                  .forEach(
                      worklogItem -> {
                        LocalDate date = worklogItem.getDate();
                        DisplayDayEntry workdayEntry =
                            row.getWorkdayEntry(date)
                                .orElseGet(
                                    () -> {
                                      DisplayDayEntry newWorkdayEntry = new DisplayDayEntry();
                                      newWorkdayEntry.setDate(date);
                                      row.addDisplayDayEntry(newWorkdayEntry);
                                      return newWorkdayEntry;
                                    });

                        workdayEntry.getSpentTime().addAndGet(worklogItem.getDurationInMinutes());
                      });

              displayData.addRow(new TreeItem<>(row));
            });
  }
Ejemplo n.º 9
0
  public void initProviders() throws DataBaseException {
    providers = dao.getProviders();
    selectProviderCb.getItems().clear();

    for (Provider provider : providers) {
      selectProviderCb.getItems().add(provider.getName());
    }
    selectProviderCb.setValue(providers.get(0).getName());
  }
Ejemplo n.º 10
0
 @FXML
 void search() {
   searching = true;
   new Thread(
           () -> {
             List<Track> tracks = Cache.search(searchText.getText());
             tracksView.setPlaceholder(searchPlaceholder);
             Platform.runLater(
                 () -> {
                   if (tracksView.getItems().size() > 0) {
                     tracksView.scrollTo(0);
                   }
                   tracksView.getItems().clear();
                   tracksView.getItems().addAll(tracks.toArray());
                 });
           })
       .start();
 }
Ejemplo n.º 11
0
  public void initGrains() {
    grains = new ArrayList<>();
    grains.add(new Wheat());
    grains.add(new Rice());
    for (Grain grain : grains) {
      selectGrainCb.getItems().add(grain.getDescription());
    }

    selectGrainCb
        .valueProperty()
        .addListener(
            new ChangeListener<String>() {
              @Override
              public void changed(ObservableValue ov, String t, String t1) {
                grain = getGrain(t1);
                initProperties(grain);
              }
            });

    selectGrainCb.setValue(grains.get(0).getDescription());
  }
Ejemplo n.º 12
0
  public void newFile() {
    infoTa.setText("");
    selectProviderCb.setValue(providers.get(0).getName());
    weightTf.setText("0.0");

    for (Entry<String, TextField> entry : propertiesTf.entrySet()) {
      String propertyName = entry.getKey();
      TextField tf = entry.getValue();
      CheckBox cb = propertiesCb.get(propertyName);

      tf.setText("0.0");
      tf.setDisable(true);
      cb.setSelected(false);
    }

    file = null;
    mainStage.setTitle("unknown");
  }
  public void writeDataToExcel(Sheet sheet) {
    LOGGER.debug("[{}] Exporting data to excel", getText());

    List<ExcelColumnRenderer> columnRendererList = new ArrayList<>();
    columnRendererList.add(new TaskStatusExcelColumn());
    columnRendererList.add(new TaskDescriptionExcelColumn());

    TimerangeProvider timerangeProvider = fetchTimereportContext.get().getTimerangeProvider();
    LocalDate startDate = timerangeProvider.getStartDate();
    LocalDate endDate = timerangeProvider.getEndDate();

    long amountOfDaysToDisplay = ChronoUnit.DAYS.between(startDate, endDate);
    for (int days = 0; days <= amountOfDaysToDisplay; days++) {
      LocalDate currentColumnDate = timerangeProvider.getStartDate().plus(days, ChronoUnit.DAYS);
      String displayDate = FormattingUtil.formatDate(currentColumnDate);
      columnRendererList.add(new WorklogExcelColumn(displayDate, currentColumnDate));
    }

    columnRendererList.add(new TaskWorklogSummaryExcelColumn());

    TreeItem<DisplayRow> root = taskTableView.getRoot();
    ObservableList<TreeItem<DisplayRow>> children = root.getChildren();

    for (int columnIndex = 0; columnIndex < columnRendererList.size(); columnIndex++) {
      ExcelColumnRenderer excelColumnRenderer = columnRendererList.get(columnIndex);
      excelColumnRenderer.renderCells(
          columnIndex,
          sheet,
          children,
          fetchTimereportContext.get().getGroupByCategory().isPresent());
    }

    // autosize column widths
    for (int i = 0; i < columnRendererList.size(); i++) {
      sheet.autoSizeColumn(i);
    }
  }
Ejemplo n.º 14
0
  void setupTracksContextMenu() {
    ContextMenu cm = tracksContextMenu;
    List<MenuItem> items = cm.getItems();
    items.clear();

    Playlist pl = getSelectedPlaylist();
    if (pl == null) {
      items.add(
          menuItem(
              "-> " + res.getString("add_to"),
              () -> {
                menuAddToPlaylist();
              }));
      if (rememberedPlaylist != null) {
        items.add(
            menuItem(
                "-> "
                    + String.format(
                        res.getString("add_to_featured"), rememberedPlaylist.getTitle()),
                () -> {
                  Track t = getSelectedTrack();
                  if (t != null) {
                    addToPlaylist(t, rememberedPlaylist);
                  }
                }));
      }
    } else {
      items.add(
          menuItem(
              "(+) " + res.getString("add_files"),
              () -> {
                FileChooser fileChooser = new FileChooser();
                fileChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
                fileChooser.setTitle(String.format(res.getString("add_files_to"), pl.getTitle()));
                fileChooser
                    .getExtensionFilters()
                    .addAll(new FileChooser.ExtensionFilter("MP3", "*.mp3"));
                List<File> files = fileChooser.showOpenMultipleDialog(null);
                if (files != null) {
                  addToPlaylist(files, pl);
                }
              }));
      items.add(
          menuItem(
              "(+) " + res.getString("add_folder_recursively"),
              () -> {
                DirectoryChooser dirChooser = new DirectoryChooser();
                dirChooser.setTitle(String.format(res.getString("add_folder_to"), pl.getTitle()));
                dirChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
                File dir = dirChooser.showDialog(null);
                if (dir == null) return;
                Collection<File> files = FileUtils.listFiles(dir, new String[] {"mp3"}, true);
                addToPlaylist(new ArrayList(files), pl);
              }));
      items.add(new SeparatorMenuItem());
      if (rememberedPlaylist != null)
        items.add(
            menuItem(
                "-> "
                    + String.format(
                        res.getString("add_to_featured"), rememberedPlaylist.getTitle()),
                () -> {
                  Track t = getSelectedTrack();
                  if (t != null) addToPlaylist(t, rememberedPlaylist);
                }));
      items.add(
          menuItem(
              "-> " + res.getString("add_to"),
              () -> {
                menuAddToPlaylist();
              }));
      items.add(new SeparatorMenuItem());
      items.add(
          menuItem(
              "(...) " + res.getString("rename_track"),
              () -> {
                renameTrack();
              }));
      items.add(new SeparatorMenuItem());
      items.add(
          menuItem(
              "(-) " + res.getString("delete_track") + pl.getTitle(),
              () -> {
                deleteTrackFromPlaylist();
              }));
      items.add(
          menuItem(
              "(-) " + res.getString("delete_dead_items"),
              () -> {
                Track t = getSelectedTrack();
                if (t == null) {
                  return;
                }
                deleteDeadFromOfflinePlaylist(pl);
              }));
    }
  }
Ejemplo n.º 15
0
  public static EventHandler<ActionEvent> getUploadHandler(
      FXController controller, ProgressBar progressBar, CheckBox stem) {
    return e -> {
      Alert a;
      if (selectedFiles != null) {
        controller.selectedFiles = new File[selectedFiles.size()];
        for (int i = 0; i < selectedFiles.size(); i++) {
          String filepath = selectedFiles.get(i).getAbsolutePath();
          if (lastUpload.contains(filepath)) {
            a = new Alert(Alert.AlertType.CONFIRMATION);
            a.setTitle("Are you sure?");
            a.setContentText(
                "You just uploaded " + filepath + ", are you sure you want to upload it again?");
            Optional<ButtonType> result = a.showAndWait();
            if (result.get() != ButtonType.OK) {
              return;
            }
          }
          if (selectedFiles.get(i).isAbsolute() && selectedFiles.get(i).exists()) {
            controller.selectedFiles[i] = selectedFiles.get(i);
          } else {
            a = new Alert(Alert.AlertType.INFORMATION, "Invalid path to file.", ButtonType.OK);
            a.setTitle("Information");
            a.showAndWait();
            return;
          }
        }
      } else {
        a = new Alert(Alert.AlertType.INFORMATION, "Please select a file.", ButtonType.OK);
        a.initStyle(StageStyle.UTILITY);
        a.setTitle("Information");
        a.showAndWait();
        return;
      }

      progressBar.setProgress(0);
      controller.writeLog("Uploading file(s)...");
      Button source = (Button) e.getSource();
      source.setDisable(true);

      SwingWorker<Boolean, Double> worker =
          new SwingWorker<Boolean, Double>() {
            @Override
            protected Boolean doInBackground() throws Exception {
              String[] key = new String[FXController.selectedFiles.length];
              publish(0.05);

              for (int i = 0; i < FXController.selectedFiles.length; i++) {
                key[i] = UUID.randomUUID().toString();
                FileUtils.uploadFile(FXController.selectedFiles[i], key[i], AESCTR.secretKey);
              }
              publish(0.4);

              Map<String, ArrayList<StringPair>> map =
                  SSE.EDBSetup(
                      FXController.selectedFiles, AESCTR.secretKey, key, stem.isSelected());
              publish(0.6);

              ObjectMapper mapper = new ObjectMapper();
              try {
                String json = mapper.writeValueAsString(map);
                publish(0.8);
                HttpUtil.HttpPost(json);
              } catch (JsonProcessingException e1) {
                e1.printStackTrace();
                return false;
              }

              publish(1.0);
              return true;
            }

            @Override
            protected void done() {
              Platform.runLater(
                  new TimerTask() {
                    @Override
                    public void run() {
                      Alert a;
                      try {
                        if (get()) {
                          controller.writeLog("Upload successful!");
                          a =
                              new Alert(
                                  Alert.AlertType.INFORMATION, "Upload successful!", ButtonType.OK);
                          a.setTitle("Success!");
                          a.showAndWait();
                          lastUpload.clear();
                          for (File f : FXController.selectedFiles) {
                            lastUpload.add(f.getAbsolutePath());
                          }
                        } else {
                          controller.writeLog("Upload failed!");
                          a = new Alert(Alert.AlertType.ERROR, "Upload failed!", ButtonType.OK);
                          a.setTitle("Error!");
                          a.showAndWait();
                        }
                      } catch (Exception ex) {
                        a = new Alert(Alert.AlertType.ERROR, "Upload error!", ButtonType.OK);
                        a.setTitle("Error!");
                        a.showAndWait();
                        ex.printStackTrace();
                      }
                      source.setDisable(false);
                    }
                  });
            }

            @Override
            protected void process(List<Double> n) {
              progressBar.setProgress(n.get(n.size() - 1));
            }
          };

      worker.execute();
    };
  }
  @FXML
  private void OK_click(ActionEvent event) {
    logger.entry();
    FederateHandle federateHandle;
    LogEntry log = new LogEntry("4.9", "Join Federation Execution service");
    try {
      if (!FederateName.getText().isEmpty()) {
        log.getSuppliedArguments()
            .add(new ClassValuePair("Federate Name", String.class, FederateName.getText()));
      }
      log.getSuppliedArguments()
          .add(new ClassValuePair("Federate Type", String.class, FederateType.getText()));
      log.getSuppliedArguments()
          .add(
              new ClassValuePair(
                  "Federation Execution Name", String.class, FederationExecutionName.getText()));
      List<URL> foms = new ArrayList<>();
      int i = 1;
      for (File file : FomModuleDesignators.getFiles()) {
        foms.add(file.toURI().toURL());
        log.getSuppliedArguments()
            .add(
                new ClassValuePair(
                    "FOM Module Deisgnator " + i++, URL.class, file.toURI().toURL().toString()));
      }
      if (FederateName.getText().isEmpty() && FomModuleDesignators.getFileNames().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateType.getText(), FederationExecutionName.getText());
      } else if (FomModuleDesignators.getFileNames().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateName.getText(), FederateType.getText(), FederationExecutionName.getText());
      } else if (FederateName.getText().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateType.getText(),
                FederationExecutionName.getText(),
                foms.toArray(new URL[foms.size()]));
      } else {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateName.getText(),
                FederateType.getText(),
                FederationExecutionName.getText(),
                foms.toArray(new URL[foms.size()]));
      }
      log.getReturnedArguments()
          .add(
              new ClassValuePair(
                  "Federate Handle", FederateHandle.class, federateHandle.toString()));
      log.setDescription("Federate joined federation execution successfully");
      log.setLogType(LogEntryType.REQUEST);
      logicalTimeFactory = rtiAmb.getTimeFactory();
      currentLogicalTime = logicalTimeFactory.makeInitial();

      // subscribe to HLAcurrentFDD to retrieve FDD
      ObjectClassHandle FederationHandle =
          rtiAmb.getObjectClassHandle("HLAobjectRoot.HLAmanager.HLAfederation");
      currentFDDHandle = rtiAmb.getAttributeHandle(FederationHandle, "HLAcurrentFDD");
      AttributeHandleSet set = rtiAmb.getAttributeHandleSetFactory().create();
      set.add(currentFDDHandle);
      rtiAmb.subscribeObjectClassAttributes(FederationHandle, set);
      rtiAmb.requestAttributeValueUpdate(FederationHandle, set, null);
      // In case of HLA_EVOKED we require this line to receive the FDD
      rtiAmb.evokeMultipleCallbacks(
          .05,
          1); // evoke one callback will not be enough because the reflect attribute is the second
              // one
    } catch (CouldNotCreateLogicalTimeFactory
        | CallNotAllowedFromWithinCallback
        | CouldNotOpenFDD
        | ErrorReadingFDD
        | InconsistentFDD
        | FederateNameAlreadyInUse
        | FederateAlreadyExecutionMember
        | FederationExecutionDoesNotExist
        | SaveInProgress
        | RestoreInProgress
        | NotConnected
        | RTIinternalError ex) {
      log.setException(ex);
      log.setLogType(LogEntryType.ERROR);
      logger.log(Level.ERROR, ex.getMessage(), ex);
    } catch (Exception ex) {
      log.setException(ex);
      log.setLogType(LogEntryType.FATAL);
      logger.log(Level.FATAL, ex.getMessage(), ex);
    }
    logEntries.add(log);
    ((Stage) FederationExecutionName.getScene().getWindow()).close();
    logger.exit();
  }
  private void updateStatisticsData(List<TaskWithWorklogs> displayResult) {

    if (!SettingsUtil.loadSettings().isShowStatistics()) {
      return;
    }

    statisticsView.getChildren().clear();

    WorklogStatistics statistics = new WorklogStatistics();

    // generic statistics
    displayResult.forEach(
        taskWithWorklogs -> {
          statistics.getTotalTimeSpent().addAndGet(taskWithWorklogs.getTotalInMinutes());

          for (WorklogItem worklogItem : taskWithWorklogs.getWorklogItemList()) {
            String employee = worklogItem.getUserDisplayname();

            // employee total time spent
            AtomicLong totalTimeSpent = statistics.getEmployeeToTotaltimeSpent().get(employee);
            if (totalTimeSpent == null) {
              totalTimeSpent = new AtomicLong(0);
              statistics.getEmployeeToTotaltimeSpent().put(employee, totalTimeSpent);
            }
            totalTimeSpent.addAndGet(worklogItem.getDurationInMinutes());

            // distinct tasks per employee
            Set<String> totalDistinctTasks =
                statistics.getEmployeeToTotalDistinctTasks().get(employee);
            if (totalDistinctTasks == null) {
              totalDistinctTasks = new HashSet<>();
              statistics.getEmployeeToTotalDistinctTasks().put(employee, totalDistinctTasks);
            }
            totalDistinctTasks.add(taskWithWorklogs.getIssue());

            // distinct tasks per employee per project
            Map<String, Set<String>> projectToDistinctTasks =
                statistics.getEmployeeToProjectToDistinctTasks().get(employee);
            if (projectToDistinctTasks == null) {
              projectToDistinctTasks = new HashMap<>();
              statistics
                  .getEmployeeToProjectToDistinctTasks()
                  .put(employee, projectToDistinctTasks);
            }

            Set<String> distinctTasks = projectToDistinctTasks.get(taskWithWorklogs.getProject());
            if (distinctTasks == null) {
              distinctTasks = new HashSet<>();
              projectToDistinctTasks.put(taskWithWorklogs.getProject(), distinctTasks);
            }

            distinctTasks.add(taskWithWorklogs.getIssue());

            // time spent per project
            Map<String, AtomicLong> projectToTimespent =
                statistics.getEmployeeToProjectToWorktime().get(employee);
            if (projectToTimespent == null) {
              projectToTimespent = new HashMap<>();
              statistics.getEmployeeToProjectToWorktime().put(employee, projectToTimespent);
            }

            AtomicLong timespentOnProject = projectToTimespent.get(taskWithWorklogs.getProject());
            if (timespentOnProject == null) {
              timespentOnProject = new AtomicLong(0);
              projectToTimespent.put(taskWithWorklogs.getProject(), timespentOnProject);
            }

            timespentOnProject.addAndGet(worklogItem.getDurationInMinutes());
          }
        });

    // render grid and bar graph
    final AtomicInteger currentGridRow = new AtomicInteger(0);

    GridPane employeeProjectSummaryGrid = new GridPane();
    employeeProjectSummaryGrid.setHgap(5);
    employeeProjectSummaryGrid.setVgap(5);

    NumberAxis projectEmployeeXAxis = new NumberAxis();
    projectEmployeeXAxis.setLabel(FormattingUtil.getFormatted("view.statistics.timespentinhours"));
    projectEmployeeXAxis.setTickLabelRotation(90);

    NumberAxis employeeProjectXAxis = new NumberAxis();
    employeeProjectXAxis.setLabel(FormattingUtil.getFormatted("view.statistics.timespentinhours"));
    employeeProjectXAxis.setTickLabelRotation(90);

    CategoryAxis projectEmployeeYAxis = new CategoryAxis();
    CategoryAxis employeeProjectYAxis = new CategoryAxis();

    StackedBarChart<Number, String> projectEmployeeBargraph =
        new StackedBarChart<>(projectEmployeeXAxis, projectEmployeeYAxis);
    StackedBarChart<Number, String> employeeProjectBargraph =
        new StackedBarChart<>(employeeProjectXAxis, employeeProjectYAxis);

    projectEmployeeBargraph.setTitle(
        FormattingUtil.getFormatted("view.statistics.byprojectandemployee"));
    employeeProjectBargraph.setTitle(
        FormattingUtil.getFormatted("view.statistics.byemployeeandproject"));

    Set<String> projectsToDisplay = new HashSet<>();
    displayResult.forEach(
        taskWithWorklogs -> {
          projectsToDisplay.add(taskWithWorklogs.getProject());
        });
    int projectEmployeeBargraphPreferedHeight =
        HEIGHT_PER_Y_AXIS_ELEMENT * projectsToDisplay.size()
            + HEIGHT_PER_X_AXIS_ELEMENT * statistics.getEmployeeToTotaltimeSpent().keySet().size()
            + ADDITIONAL_HEIGHT;
    projectEmployeeBargraph.setPrefHeight(projectEmployeeBargraphPreferedHeight);
    VBox.setVgrow(projectEmployeeBargraph, Priority.ALWAYS);

    int employeeProjectBargraphPreferedHeight =
        HEIGHT_PER_Y_AXIS_ELEMENT * statistics.getEmployeeToProjectToWorktime().keySet().size()
            + HEIGHT_PER_X_AXIS_ELEMENT * projectsToDisplay.size()
            + ADDITIONAL_HEIGHT;
    employeeProjectBargraph.setPrefHeight(employeeProjectBargraphPreferedHeight);
    VBox.setVgrow(employeeProjectBargraph, Priority.ALWAYS);

    Map<String, XYChart.Series<Number, String>> projectNameToSeries = Maps.newHashMap();

    statistics
        .getEmployeeToProjectToWorktime()
        .keySet()
        .stream()
        .sorted(COLLATOR::compare)
        .forEach(
            employee -> {

              // employee headline label
              Set<String> totalDistinctTasksOfEmployee =
                  statistics.getEmployeeToTotalDistinctTasks().get(employee);
              Label employeeLabel =
                  getBoldLabel(
                      FormattingUtil.getFormatted(
                          "view.statistics.somethingtoamountoftickets",
                          employee,
                          totalDistinctTasksOfEmployee.size()));
              employeeLabel.setPadding(new Insets(20, 0, 0, 0));
              GridPane.setConstraints(employeeLabel, 0, currentGridRow.getAndIncrement());
              GridPane.setColumnSpan(employeeLabel, 4);
              employeeProjectSummaryGrid.getChildren().addAll(employeeLabel);

              // bar graph data container
              XYChart.Series<Number, String> projectEmployeeSeries = new XYChart.Series<>();
              projectEmployeeSeries.setName(employee);
              projectEmployeeBargraph.getData().add(projectEmployeeSeries);

              // time spent per project
              Map<String, AtomicLong> projectToWorktime =
                  statistics.getEmployeeToProjectToWorktime().get(employee);
              Map<String, Label> projectToPercentageLabel = Maps.newHashMap();

              projectToWorktime
                  .keySet()
                  .stream()
                  .sorted(COLLATOR::compare)
                  .forEach(
                      projectName -> {
                        XYChart.Series<Number, String> employeeProjectSeries =
                            projectNameToSeries.get(projectName);
                        if (employeeProjectSeries == null) {
                          employeeProjectSeries = new XYChart.Series<>();
                          employeeProjectSeries.setName(projectName);
                          employeeProjectBargraph.getData().add(employeeProjectSeries);
                          projectNameToSeries.put(projectName, employeeProjectSeries);
                        }

                        // percentage label
                        Label percentageLabel = getBoldLabel("PLACEHOLDER");
                        percentageLabel.setAlignment(Pos.CENTER_RIGHT);
                        percentageLabel.setPadding(new Insets(0, 0, 0, 20));
                        GridPane.setConstraints(percentageLabel, 1, currentGridRow.get());
                        GridPane.setHalignment(percentageLabel, HPos.RIGHT);
                        projectToPercentageLabel.put(projectName, percentageLabel);

                        // project label
                        Set<String> distinctTasksPerProject =
                            statistics
                                .getEmployeeToProjectToDistinctTasks()
                                .get(employee)
                                .get(projectName);
                        Label projectLabel =
                            getBoldLabel(
                                FormattingUtil.getFormatted(
                                    "view.statistics.somethingtoamountoftickets",
                                    projectName,
                                    distinctTasksPerProject.size()));
                        GridPane.setConstraints(projectLabel, 2, currentGridRow.get());

                        // time spent for project label
                        long timespentInMinutes = projectToWorktime.get(projectName).longValue();
                        Label timespentLabel =
                            new Label(FormattingUtil.formatMinutes(timespentInMinutes, true));
                        GridPane.setConstraints(timespentLabel, 3, currentGridRow.get());
                        GridPane.setHgrow(timespentLabel, Priority.ALWAYS);
                        GridPane.setHalignment(timespentLabel, HPos.RIGHT);

                        employeeProjectSummaryGrid
                            .getChildren()
                            .addAll(percentageLabel, projectLabel, timespentLabel);
                        currentGridRow.incrementAndGet();

                        // bargraph data
                        projectEmployeeSeries
                            .getData()
                            .add(new XYChart.Data<>(timespentInMinutes / 60d, projectName));
                        employeeProjectSeries
                            .getData()
                            .addAll(new XYChart.Data<>(timespentInMinutes / 60d, employee));
                      });

              // total time spent
              Label totalLabel =
                  getBoldLabel(FormattingUtil.getFormatted("view.statistics.totaltimespent"));
              GridPane.setConstraints(totalLabel, 0, currentGridRow.get());
              GridPane.setColumnSpan(totalLabel, 4);

              Label timespentLabel =
                  new Label(
                      FormattingUtil.formatMinutes(
                          statistics.getEmployeeToTotaltimeSpent().get(employee).get(), true));
              GridPane.setConstraints(timespentLabel, 3, currentGridRow.get());
              GridPane.setHgrow(timespentLabel, Priority.ALWAYS);
              GridPane.setHalignment(timespentLabel, HPos.RIGHT);
              employeeProjectSummaryGrid.getChildren().addAll(totalLabel, timespentLabel);

              // set label now that we can calculate the percentage
              projectToWorktime
                  .keySet()
                  .forEach(
                      projectName -> {
                        Label percentageLabel = projectToPercentageLabel.get(projectName);

                        double totalSpentTime =
                            statistics.getEmployeeToTotaltimeSpent().get(employee).doubleValue();
                        double spentTimeOnProject =
                            projectToWorktime.get(projectName).doubleValue();

                        double percentage = spentTimeOnProject / totalSpentTime;
                        String percentageFormatted = FormattingUtil.formatPercentage(percentage);
                        percentageLabel.setText(percentageFormatted);
                      });

              currentGridRow.incrementAndGet();
            });

    // employeeProjectBargraph

    statisticsView
        .getChildren()
        .addAll(employeeProjectSummaryGrid, projectEmployeeBargraph, employeeProjectBargraph);

    // custom view statistics
    addAdditionalStatistics(statisticsView, statistics, displayResult);
  }
  private DisplayData getDisplayData(
      FetchTimereportContext reportContext, boolean changedSinceLastRender) {

    if (changedSinceLastRender) {
      LOGGER.debug("Refreshing display data");
      DisplayData displayData = new DisplayData();

      WorklogReport result = reportContext.getResult().get();
      ImmutableList<TaskWithWorklogs> originalTasks = result.getTasks();

      // create a copy of the original task list
      // and pass it on to the getFilteredList method
      // which then may freely modify the list and its items
      List<TaskWithWorklogs> deepCopiedList = Lists.newArrayList();
      originalTasks.forEach(
          taskWithWorklogs -> deepCopiedList.add(taskWithWorklogs.createDeepCopy()));
      List<TaskWithWorklogs> filteredList = getFilteredList(deepCopiedList);

      // render the treetabledata
      if (reportContext.getGroupByCategory().isPresent()) {
        // grouping present
        processWithGrouping(filteredList, displayData);
      } else {
        // no grouping
        processWithoutGrouping(filteredList, displayData);
      }

      // add grandtotal column
      DisplayRow grandTotal = new DisplayRow();
      grandTotal.setIsGrandTotalSummary(true);
      displayData.addRow(new TreeItem<>(grandTotal));

      filteredList
          .stream()
          .map(TaskWithWorklogs::getWorklogItemList)
          .flatMap(Collection::stream)
          .forEach(
              worklogItem -> {
                LocalDate date = worklogItem.getDate();

                DisplayDayEntry workdayEntry =
                    grandTotal
                        .getWorkdayEntry(date)
                        .orElseGet(
                            () -> {
                              DisplayDayEntry displayDayEntry = new DisplayDayEntry();
                              displayDayEntry.setDate(date);

                              grandTotal.addDisplayDayEntry(displayDayEntry);

                              return displayDayEntry;
                            });

                workdayEntry.getSpentTime().addAndGet(worklogItem.getDurationInMinutes());
              });

      // call statistics update
      updateStatisticsData(filteredList);

      resultItemsToDisplay = Optional.of(displayData);
    }

    return resultItemsToDisplay.get();
  }
Ejemplo n.º 19
0
  public static void setJar(final Tile node) {
    node.data.put("type", "Jar");
    List<Node> toRemove = new ArrayList<>();
    for (Node n : node.node.getChildren()) {
      if (!n.getId().equals("delete")) {
        if (n.getId().equals("typeLabel")) {
          Label l = (Label) n;
          l.setText("jar");
          l.setTranslateY(l.getTranslateY() - 1);
        } else {
          toRemove.add(n);
        }
      }
    }

    VBox leftPadding = new VBox();
    leftPadding.setPrefWidth(14);
    VBox buttons = new VBox();
    VBox textBoxes = new VBox();
    VBox extra = new VBox();

    buttons.setSpacing(5);
    textBoxes.setSpacing(5);
    extra.setSpacing(5);

    buttons.setPadding(new Insets(7, 0, 0, 0));
    textBoxes.setPadding(new Insets(7, 0, 0, 0));
    extra.setPadding(new Insets(7, 0, 0, 0));

    textBoxes.setTranslateX(17);
    extra.setTranslateX(32);

    node.node.getChildren().removeAll(toRemove);

    final String name = "Package Name";
    final String name2 = "Jar Name";

    Button findPkg = new Button();
    final TextField pkgText = new TextField();
    final TextField jarName = new TextField();

    findPkg.getStyleClass().add("defaultButton");
    findPkg.setText("Find Package Name");
    findPkg.setPrefHeight(25);
    findPkg.setTranslateX(12);

    findPkg.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            String mainClassName = Util.packageNameFromTile();
            if (mainClassName != null) {
              pkgText.setText(mainClassName);
            }
          }
        });

    pkgText.setText(name);
    pkgText.setPrefSize(150, 27);
    pkgText.setFont(Font.font("Segoe UI"));
    pkgText.setId("textBox");
    pkgText
        .textProperty()
        .addListener(
            new ChangeListener<String>() {
              @Override
              public void changed(
                  ObservableValue<? extends String> observable, String oldValue, String newValue) {
                node.data.put("package", pkgText.getText().trim());
              }
            });
    pkgText
        .focusedProperty()
        .addListener(
            new ChangeListener<Boolean>() {
              @Override
              public void changed(
                  ObservableValue<? extends Boolean> observable,
                  Boolean oldValue,
                  Boolean newValue) {
                if (newValue == true && pkgText.getText().equals(name)) {
                  pkgText.setText("");
                } else if (newValue == false && pkgText.getText().trim().equals("")) {
                  pkgText.setText(name);
                }
              }
            });

    jarName.setText(name2);
    jarName.setPrefSize(150, 27);
    jarName.setFont(Font.font("Segoe UI"));
    jarName.setId("textBox");
    jarName
        .textProperty()
        .addListener(
            new ChangeListener<String>() {
              @Override
              public void changed(
                  ObservableValue<? extends String> observable, String oldValue, String newValue) {
                node.data.put("jarname", jarName.getText().trim());
              }
            });
    jarName
        .focusedProperty()
        .addListener(
            new ChangeListener<Boolean>() {
              @Override
              public void changed(
                  ObservableValue<? extends Boolean> observable,
                  Boolean oldValue,
                  Boolean newValue) {
                if (newValue == true && jarName.getText().equals(name2)) {
                  jarName.setText("");
                } else if (newValue == false && jarName.getText().trim().equals("")) {
                  jarName.setText(name2);
                }
              }
            });

    final String defTxt = "Additional Flags";
    final TextField flags = new TextField();
    flags.setText(defTxt);
    flags.setPrefSize(150, 27);
    flags.setFont(Font.font("Segoe UI"));
    flags.setId("textBox");

    flags
        .focusedProperty()
        .addListener(
            new ChangeListener<Boolean>() {
              @Override
              public void changed(
                  ObservableValue<? extends Boolean> observable,
                  Boolean oldValue,
                  Boolean newValue) {
                if (newValue == true && flags.getText().equals(defTxt)) {
                  flags.setText("");
                } else if (newValue == false && flags.getText().trim().equals("")) {
                  flags.setText(defTxt);
                }
              }
            });
    flags
        .textProperty()
        .addListener(
            new ChangeListener<String>() {
              @Override
              public void changed(
                  ObservableValue<? extends String> observable, String oldValue, String newValue) {
                node.data.put("flags", flags.getText().trim());
              }
            });

    final String defTxt2 = "Output Directory";
    final TextField outputDir = new TextField();
    outputDir.setText(defTxt2);
    outputDir.setPrefSize(150, 27);
    outputDir.setFont(Font.font("Segoe UI"));
    outputDir.setId("textBox");

    outputDir
        .focusedProperty()
        .addListener(
            new ChangeListener<Boolean>() {
              @Override
              public void changed(
                  ObservableValue<? extends Boolean> observable,
                  Boolean oldValue,
                  Boolean newValue) {
                if (newValue == true && outputDir.getText().equals(defTxt2)) {
                  outputDir.setText("");
                } else if (newValue == false && outputDir.getText().trim().equals("")) {
                  outputDir.setText(defTxt2);
                }
              }
            });
    outputDir
        .textProperty()
        .addListener(
            new ChangeListener<String>() {
              @Override
              public void changed(
                  ObservableValue<? extends String> observable, String oldValue, String newValue) {
                node.data.put("output", outputDir.getText().trim());
              }
            });

    buttons.getChildren().addAll(findPkg);
    textBoxes.getChildren().addAll(pkgText, jarName);
    extra.getChildren().addAll(flags, outputDir);
    node.node.getChildren().addAll(leftPadding, buttons, textBoxes, extra);
  }
  private void processWithGrouping(List<TaskWithWorklogs> tasks, DisplayData displayData) {
    LOGGER.debug("Processing with grouping");
    List<String> distinctGroupByCriteria =
        tasks
            .stream()
            .map(TaskWithWorklogs::getDistinctGroupByCriteriaValues)
            .flatMap(Collection::stream)
            .distinct()
            .sorted(COLLATOR)
            .collect(Collectors.toList());

    distinctGroupByCriteria.forEach(
        groupByCriteria -> {
          LOGGER.debug("Gathering data for group criteria value {}", groupByCriteria);
          DisplayRow groupCaptionRow = new DisplayRow();
          groupCaptionRow.setIsGroupContainer(true);
          groupCaptionRow.setLabel(groupByCriteria);

          TreeItem<DisplayRow> groupRow = new TreeItem<>(groupCaptionRow);
          groupRow.setExpanded(true);
          Map<String, DisplayRow> ticketIdToDisplayRow = Maps.newHashMap();

          // add sub rows to groupRow
          tasks
              .stream()
              .filter(
                  taskWithWorklogs ->
                      taskWithWorklogs.getDistinctGroupByCriteriaValues().contains(groupByCriteria))
              .sorted((o1, o2) -> COLLATOR.compare(o1.getIssue(), o2.getIssue()))
              .forEach(
                  taskWithWorklogs -> {
                    // this task with worklogs contains at least one workitem
                    // having the group by criteria

                    DisplayRow ticketRowWithinThisGroup =
                        ticketIdToDisplayRow.get(taskWithWorklogs.getIssue());
                    if (ticketRowWithinThisGroup == null) {
                      ticketRowWithinThisGroup = new DisplayRow();
                      ticketRowWithinThisGroup.setLabel(taskWithWorklogs.getSummary());
                      ticketRowWithinThisGroup.setIssueId(taskWithWorklogs.getIssue());
                      ticketRowWithinThisGroup.setResolvedDate(taskWithWorklogs.getResolved());
                      groupRow.getChildren().add(new TreeItem<>(ticketRowWithinThisGroup));
                      ticketIdToDisplayRow.put(
                          taskWithWorklogs.getIssue(), ticketRowWithinThisGroup);
                    }

                    DisplayRow ticketRowWithinThisGroupAsFinal = ticketRowWithinThisGroup;

                    taskWithWorklogs
                        .getWorklogItemList()
                        .stream()
                        .filter(
                            worklogItem ->
                                StringUtils.equals(worklogItem.getGroup(), groupByCriteria))
                        .sorted((o1, o2) -> o1.getDate().compareTo(o2.getDate()))
                        .forEach(
                            worklogItem -> {
                              // this worklog item matches the critera
                              // add workday entry to current row
                              LocalDate date = worklogItem.getDate();

                              DisplayDayEntry workdayEntry =
                                  ticketRowWithinThisGroupAsFinal
                                      .getWorkdayEntry(date)
                                      .orElseGet(
                                          () -> {
                                            DisplayDayEntry displayDayEntry = new DisplayDayEntry();
                                            displayDayEntry.setDate(date);
                                            ticketRowWithinThisGroupAsFinal.addDisplayDayEntry(
                                                displayDayEntry);

                                            return displayDayEntry;
                                          });

                              workdayEntry
                                  .getSpentTime()
                                  .addAndGet(worklogItem.getDurationInMinutes());

                              // also add up the spent time in the group header per group
                              workdayEntry =
                                  groupCaptionRow
                                      .getWorkdayEntry(date)
                                      .orElseGet(
                                          () -> {
                                            DisplayDayEntry newWorkdayEntry = new DisplayDayEntry();
                                            newWorkdayEntry.setDate(date);
                                            groupCaptionRow.addDisplayDayEntry(newWorkdayEntry);
                                            return newWorkdayEntry;
                                          });
                              workdayEntry
                                  .getSpentTime()
                                  .addAndGet(worklogItem.getDurationInMinutes());
                            });
                  });

          // add groupRow to result
          displayData.addRow(groupRow);
        });
  }