CommonStatsCSVHelper.java

  1. package edu.ucsb.cs156.happiercows.helpers;

  2. import java.io.ByteArrayInputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.IOException;
  5. import java.io.PrintWriter;
  6. import java.util.Arrays;
  7. import java.util.List;
  8. import org.apache.commons.csv.CSVFormat;
  9. import org.apache.commons.csv.CSVPrinter;
  10. import edu.ucsb.cs156.happiercows.entities.CommonStats;
  11. import lombok.AccessLevel;
  12. import lombok.NoArgsConstructor;

  13. /*
  14.  * This code is based on
  15.  * <a href="https://bezkoder.com/spring-boot-download-csv-file/">https://bezkoder.com/spring-boot-download-csv-file/</a>
  16.  * and provides a way to serve up a CSV file containing information associated
  17.  * with an instructor report.
  18.  */

  19. public class CommonStatsCSVHelper {

  20.   private CommonStatsCSVHelper() {}

  21.   /**
  22.    * This method is a hack to avoid a pitest issue; it isn't possible to
  23.    * exclude an individual method call from pitest coverage, but we can
  24.    * exclude the entire method by name in the pitest settings in pom.xml
  25.    * @param out stream to close
  26.    * @param csvPrinter printer to close
  27.    */

  28.   public static void flush_and_close_noPitest(ByteArrayOutputStream out, CSVPrinter csvPrinter) throws IOException {
  29.     csvPrinter.flush();
  30.     csvPrinter.close();
  31.     out.flush();
  32.     out.close();
  33.   }

  34.   public static ByteArrayInputStream toCSV(Iterable<CommonStats> lines) throws IOException {
  35.     final CSVFormat format = CSVFormat.DEFAULT;

  36.     List<String> headers = Arrays.asList(
  37.         "id",
  38.         "commonsId",
  39.         "numCows",
  40.         "avgHealth",
  41.         "timestamp");

  42.     ByteArrayOutputStream out = new ByteArrayOutputStream();
  43.     CSVPrinter csvPrinter = new CSVPrinter(new PrintWriter(out), format);

  44.     csvPrinter.printRecord(headers);

  45.     for (CommonStats stats : lines) {
  46.       List<String> data = Arrays.asList(
  47.           String.valueOf(stats.getId()),
  48.           String.valueOf(stats.getCommonsId()),
  49.           String.valueOf(stats.getNumCows()),
  50.           String.valueOf(stats.getAvgHealth()),
  51.           String.valueOf(stats.getTimestamp()));
  52.       csvPrinter.printRecord(data);
  53.     }

  54.     flush_and_close_noPitest(out, csvPrinter);
  55.     return new ByteArrayInputStream(out.toByteArray());
  56.   }
  57. }