CsvConverter implements Converter { @SuppressFBWarnings(value = "UC_USELESS_OBJECT", justification = "False positive with List.forEach") public String convertToCsv(Recording recording) { List<String> header = makeHeader(recording); int headerSize = header.size(); CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(header.toArray(new String[headerSize])); try (var writer = new StringWriter(); var csvPrinter = new CSVPrinter(writer, csvFormat)) { var flattenedData = Converter.flatten(recording, not(Converter::isMetadata), windowSize.get()); var rows = flattenedData.entrySet() .stream() .sorted(Comparator.comparingLong(Map.Entry::getKey)) .map(e -> toRow(header, headerSize, e)) .filter(Objects::nonNull) .collect(Collectors.toList()); if (fillEmpty.get()) { fillEmptyCells(rows); } for (Object[] row : rows) { csvPrinter.printRecord(row); } return writer.toString(); } catch (IOException e) { throw new IllegalStateException("Could not convert recording to CSV", e); } } @VisibleForTesting  CsvConverter(Preferences prefs); @Override String formatName(); @Override String fileExtension(); @Override void export(Recording recording, Path destination); @Override List<Group> getSettings(); @SuppressFBWarnings(value = "UC_USELESS_OBJECT", justification = "False positive with List.forEach") String convertToCsv(Recording recording); static final CsvConverter Instance; }
@Test public void testDataAndMarkerInSameWindow() { recording.append(new TimestampedData("foo", DataTypes.String, "bar", 0)); recording.addMarker(new Marker("Name", "Description", MarkerImportance.CRITICAL, 4L)); String csv = converter.convertToCsv(recording); var lines = csv.lines().collect(Collectors.toList()); assertAll( () -> assertEquals(EMPTY_HEADER + ",foo", lines.get(0)), () -> assertEquals("0,Name,Description,CRITICAL,bar", lines.get(1)) ); }
@Test public void testMultipleMarkersInSameWindow() { recording.addMarker(new Marker("First", "", MarkerImportance.LOW, 0L)); recording.addMarker(new Marker("Second", "", MarkerImportance.CRITICAL, 0L)); recording.addMarker(new Marker("Third", "", MarkerImportance.NORMAL, 255)); String csv = converter.convertToCsv(recording); var lines = csv.lines().collect(Collectors.toList()); assertAll( () -> assertEquals(EMPTY_HEADER, lines.get(0), "First line should be the header"), () -> assertEquals("0,First,,LOW", lines.get(1), "Second line should be the first marker"), () -> assertEquals("255,Third,,NORMAL", lines.get(2), "Third line should be the third marker") ); }