ReportCSVHelper.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.ReportLine;

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

  17. public class ReportCSVHelper {

  18.   private ReportCSVHelper() {}

  19.   /**
  20.    * This method is a hack to avoid a jacoco issue; it isn't possible to
  21.    * exclude an individual method call from jacoco coverage, but we can
  22.    * exclude the entire method.  
  23.    * @param out
  24.    */

  25.   public static void flush_and_close_noPitest(ByteArrayOutputStream out, CSVPrinter csvPrinter) throws IOException {
  26.     csvPrinter.flush();
  27.     csvPrinter.close();
  28.     out.flush();
  29.     out.close();
  30.   }
  31.  
  32.   public static ByteArrayInputStream toCSV(Iterable<ReportLine> lines) throws IOException {
  33.     final CSVFormat format = CSVFormat.DEFAULT;

  34.     List<String> headers = Arrays.asList(
  35.         "id",
  36.         "reportId",
  37.         "userId",
  38.         "username",
  39.         "totalWealth",
  40.         "numOfCows",
  41.         "avgCowHealth",
  42.         "cowsBought",
  43.         "cowsSold",
  44.         "cowDeaths",
  45.         "reportDate");

  46.     ByteArrayOutputStream out = new ByteArrayOutputStream();
  47.     CSVPrinter csvPrinter = new CSVPrinter(new PrintWriter(out), format);

  48.     csvPrinter.printRecord(headers);

  49.     for (ReportLine line : lines) {
  50.       List<String> data = Arrays.asList(
  51.           String.valueOf(line.getId()),
  52.           String.valueOf(line.getReportId()),
  53.           String.valueOf(line.getUserId()),
  54.           line.getUsername(),
  55.           String.valueOf(line.getTotalWealth()),
  56.           String.valueOf(line.getNumOfCows()),
  57.           String.valueOf(line.getAvgCowHealth()),
  58.           String.valueOf(line.getCowsBought()),
  59.           String.valueOf(line.getCowsSold()),
  60.           String.valueOf(line.getCowDeaths()),
  61.           String.valueOf(line.getCreateDate()));
  62.       csvPrinter.printRecord(data);
  63.     }

  64.     flush_and_close_noPitest(out, csvPrinter);
  65.     return new ByteArrayInputStream(out.toByteArray());
  66.   }
  67. }