CSVDownloadsController.java

1
package edu.ucsb.cs156.frontiers.controllers;
2
3
import com.opencsv.bean.StatefulBeanToCsv;
4
import com.opencsv.exceptions.CsvDataTypeMismatchException;
5
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
6
import edu.ucsb.cs156.frontiers.entities.Course;
7
import edu.ucsb.cs156.frontiers.entities.RosterStudent;
8
import edu.ucsb.cs156.frontiers.enums.RosterStatus;
9
import edu.ucsb.cs156.frontiers.errors.EntityNotFoundException;
10
import edu.ucsb.cs156.frontiers.models.NameAndTeam;
11
import edu.ucsb.cs156.frontiers.models.RosterStudentDTO;
12
import edu.ucsb.cs156.frontiers.repositories.CourseRepository;
13
import edu.ucsb.cs156.frontiers.repositories.RosterStudentRepository;
14
import edu.ucsb.cs156.frontiers.services.RosterStudentDTOService;
15
import edu.ucsb.cs156.frontiers.services.SectionTranslationService;
16
import edu.ucsb.cs156.frontiers.services.TeamCsvService;
17
import io.swagger.v3.oas.annotations.Operation;
18
import io.swagger.v3.oas.annotations.Parameter;
19
import io.swagger.v3.oas.annotations.media.Content;
20
import io.swagger.v3.oas.annotations.media.Schema;
21
import io.swagger.v3.oas.annotations.responses.ApiResponse;
22
import io.swagger.v3.oas.annotations.tags.Tag;
23
import java.io.IOException;
24
import java.io.OutputStreamWriter;
25
import java.io.Writer;
26
import java.nio.charset.StandardCharsets;
27
import java.util.List;
28
import java.util.Map;
29
import lombok.extern.slf4j.Slf4j;
30
import org.apache.commons.csv.CSVFormat;
31
import org.apache.commons.csv.CSVPrinter;
32
import org.springframework.beans.factory.annotation.Autowired;
33
import org.springframework.http.HttpHeaders;
34
import org.springframework.http.MediaType;
35
import org.springframework.http.ResponseEntity;
36
import org.springframework.security.access.prepost.PreAuthorize;
37
import org.springframework.web.bind.annotation.GetMapping;
38
import org.springframework.web.bind.annotation.RequestMapping;
39
import org.springframework.web.bind.annotation.RequestParam;
40
import org.springframework.web.bind.annotation.RestController;
41
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
42
43
@Tag(name = "CSV Downloads")
44
@RequestMapping("/api/csv")
45
@RestController
46
@Slf4j
47
public class CSVDownloadsController extends ApiController {
48
49
  @Autowired private CourseRepository courseRepository;
50
51
  @Autowired private RosterStudentDTOService rosterStudentDTOService;
52
53
  @Autowired private RosterStudentRepository rosterStudentRepository;
54
55
  @Autowired private SectionTranslationService sectionTranslationService;
56
57
  @Autowired private TeamCsvService teamCsvService;
58
59
  @Operation(
60
      summary = "Download CSV File of Roster Students",
61
      description = "Returns a CSV file as a response",
62
      responses = {
63
        @ApiResponse(
64
            responseCode = "200",
65
            description = "CSV file",
66
            content =
67
                @Content(
68
                    mediaType = "text/csv",
69
                    schema = @Schema(type = "string", format = "binary"))),
70
        @ApiResponse(responseCode = "500", description = "Internal Server Error")
71
      })
72
  @GetMapping(value = "/rosterstudents", produces = "text/csv")
73
  @PreAuthorize("@CourseSecurity.hasManagePermissions(#root, #courseId)")
74
  public ResponseEntity<StreamingResponseBody> csvForQuarter(
75
      @Parameter(name = "courseId", description = "course id", example = "1") @RequestParam
76
          Long courseId)
77
      throws EntityNotFoundException, Exception, IOException {
78
    Course course =
79
        courseRepository
80
            .findById(courseId)
81 1 1. lambda$csvForQuarter$0 : replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::lambda$csvForQuarter$0 → KILLED
            .orElseThrow(() -> new EntityNotFoundException(Course.class, courseId));
82
    StreamingResponseBody stream =
83
        (outputStream) -> {
84
          List<RosterStudentDTO> list = rosterStudentDTOService.getRosterStudentDTOs(courseId);
85
          try (Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
86
            try {
87
              StatefulBeanToCsv<RosterStudentDTO> beanToCsvWriter =
88
                  rosterStudentDTOService.getStatefulBeanToCSV(writer);
89 1 1. lambda$csvForQuarter$1 : removed call to com/opencsv/bean/StatefulBeanToCsv::write → KILLED
              beanToCsvWriter.write(list);
90
            } catch (CsvDataTypeMismatchException | CsvRequiredFieldEmptyException e) {
91
              log.error("Error writing CSV file", e);
92
              throw new IOException("Error writing CSV file: " + e.getMessage());
93
            }
94
          }
95
        };
96
97 1 1. csvForQuarter : replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::csvForQuarter → KILLED
    return ResponseEntity.ok()
98
        .contentType(MediaType.parseMediaType("text/csv; charset=UTF-8"))
99
        .header(
100
            HttpHeaders.CONTENT_DISPOSITION,
101
            String.format("attachment;filename=%s_roster.csv", course.getCourseName()))
102
        .header(HttpHeaders.CONTENT_TYPE, "text/csv; charset=UTF-8")
103
        .header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION)
104
        .body(stream);
105
  }
106
107
  @Operation(
108
      summary = "Download CATME CSV File of Roster Students",
109
      description = "Returns a CSV file as a response",
110
      responses = {
111
        @ApiResponse(
112
            responseCode = "200",
113
            description = "CSV file",
114
            content =
115
                @Content(
116
                    mediaType = "text/csv",
117
                    schema = @Schema(type = "string", format = "binary"))),
118
        @ApiResponse(responseCode = "500", description = "Internal Server Error")
119
      })
120
  @GetMapping(value = "/catme", produces = "text/csv")
121
  @PreAuthorize("@CourseSecurity.hasManagePermissions(#root, #courseId)")
122
  public ResponseEntity<StreamingResponseBody> catmeCsv(
123
      @Parameter(name = "courseId", description = "course id", example = "1") @RequestParam
124
          Long courseId)
125
      throws EntityNotFoundException {
126
    Course course =
127
        courseRepository
128
            .findById(courseId)
129 1 1. lambda$catmeCsv$0 : replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::lambda$catmeCsv$0 → KILLED
            .orElseThrow(() -> new EntityNotFoundException(Course.class, courseId));
130
    StreamingResponseBody stream =
131
        (outputStream) -> {
132
          List<RosterStudent> rosterStudents =
133
              rosterStudentRepository
134
                  .findByCourseIdAndRosterStatusInOrderByFirstNameAscLastNameAscIgnoreCase(
135
                      courseId, List.of(RosterStatus.ROSTER, RosterStatus.MANUAL));
136
          Map<String, String> sectionTranslations =
137
              sectionTranslationService.getSectionTranslations(courseId);
138
          try (Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
139
              CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT)) {
140 1 1. lambda$catmeCsv$1 : removed call to org/apache/commons/csv/CSVPrinter::printRecord → KILLED
            csvPrinter.printRecord("first", "last", "email", "id", "section", "team");
141
            for (RosterStudent student : rosterStudents) {
142
              List<String> teams = student.getTeams();
143 2 1. lambda$catmeCsv$1 : negated conditional → KILLED
2. lambda$catmeCsv$1 : negated conditional → KILLED
              String team = teams != null && !teams.isEmpty() ? teams.get(0) : "";
144 1 1. lambda$catmeCsv$1 : removed call to org/apache/commons/csv/CSVPrinter::printRecord → KILLED
              csvPrinter.printRecord(
145
                  student.getFirstName(),
146
                  student.getLastName(),
147
                  student.getEmail(),
148
                  student.getStudentId(),
149
                  SectionTranslationService.translateSection(
150
                      student.getSection(), sectionTranslations),
151
                  team);
152
            }
153
          }
154
        };
155
156 1 1. catmeCsv : replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::catmeCsv → KILLED
    return ResponseEntity.ok()
157
        .contentType(MediaType.parseMediaType("text/csv; charset=UTF-8"))
158
        .header(
159
            HttpHeaders.CONTENT_DISPOSITION,
160
            String.format("attachment;filename=%s_catme.csv", course.getCourseName()))
161
        .header(HttpHeaders.CONTENT_TYPE, "text/csv; charset=UTF-8")
162
        .header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION)
163
        .body(stream);
164
  }
165
166
  @Operation(
167
      summary = "Download compact Name to Team CSV File",
168
      description =
169
          "Returns a CSV file with the roster laid out in several side-by-side Name,Team column"
170
              + " pairs. Names are sorted by first name and abbreviated as far as possible while"
171
              + " remaining unique (first name; first name plus last initial; first name plus last"
172
              + " name). Exact duplicate names are marked with an asterisk.",
173
      responses = {
174
        @ApiResponse(
175
            responseCode = "200",
176
            description = "CSV file",
177
            content =
178
                @Content(
179
                    mediaType = "text/csv",
180
                    schema = @Schema(type = "string", format = "binary"))),
181
        @ApiResponse(responseCode = "400", description = "columns is less than 1"),
182
        @ApiResponse(responseCode = "404", description = "Course not found"),
183
        @ApiResponse(responseCode = "500", description = "Internal Server Error")
184
      })
185
  @GetMapping(value = "/name2team", produces = "text/csv")
186
  @PreAuthorize("@CourseSecurity.hasManagePermissions(#root, #courseId)")
187
  public ResponseEntity<StreamingResponseBody> name2TeamCsv(
188
      @Parameter(name = "courseId", description = "course id", example = "1") @RequestParam
189
          Long courseId,
190
      @Parameter(
191
              name = "columns",
192
              description = "number of Name,Team column pairs (default 4)",
193
              example = "4")
194
          @RequestParam(defaultValue = "4")
195
          int columns)
196
      throws EntityNotFoundException {
197 1 1. name2TeamCsv : replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::name2TeamCsv → KILLED
    return teamCsvResponse(courseId, columns, "name2team", teamCsvService::writeName2TeamCsv);
198
  }
199
200
  @Operation(
201
      summary = "Download compact Team Table CSV File",
202
      description =
203
          "Returns a CSV file with the teams laid out in several side-by-side Team,Name column"
204
              + " pairs, one row per student, teams sorted by name and balanced across the columns"
205
              + " so that no team is split. Names are sorted by first name and abbreviated as far"
206
              + " as possible while remaining unique (first name; first name plus last initial;"
207
              + " first name plus last name). Exact duplicate names are marked with an asterisk."
208
              + " Students with no team are listed last with a blank team.",
209
      responses = {
210
        @ApiResponse(
211
            responseCode = "200",
212
            description = "CSV file",
213
            content =
214
                @Content(
215
                    mediaType = "text/csv",
216
                    schema = @Schema(type = "string", format = "binary"))),
217
        @ApiResponse(responseCode = "400", description = "columns is less than 1"),
218
        @ApiResponse(responseCode = "404", description = "Course not found"),
219
        @ApiResponse(responseCode = "500", description = "Internal Server Error")
220
      })
221
  @GetMapping(value = "/teamtable", produces = "text/csv")
222
  @PreAuthorize("@CourseSecurity.hasManagePermissions(#root, #courseId)")
223
  public ResponseEntity<StreamingResponseBody> teamTableCsv(
224
      @Parameter(name = "courseId", description = "course id", example = "1") @RequestParam
225
          Long courseId,
226
      @Parameter(
227
              name = "columns",
228
              description = "number of Team,Name column pairs (default 4)",
229
              example = "4")
230
          @RequestParam(defaultValue = "4")
231
          int columns)
232
      throws EntityNotFoundException {
233 1 1. teamTableCsv : replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::teamTableCsv → KILLED
    return teamCsvResponse(courseId, columns, "teamtable", teamCsvService::writeTeamTableCsv);
234
  }
235
236
  /** Writes one of the compact team CSV tables from a list of abbreviated names and teams. */
237
  @FunctionalInterface
238
  interface TeamCsvWriter {
239
    void write(Writer writer, List<NameAndTeam> entries, int columns) throws IOException;
240
  }
241
242
  /**
243
   * Shared response for the compact team CSV downloads: looks up the course, validates the column
244
   * count, loads the ROSTER and MANUAL students sorted by first name, abbreviates their names and
245
   * streams the table written by the given writer.
246
   *
247
   * @param courseId the course id
248
   * @param columns the number of column pairs, at least 1
249
   * @param suffix the file name suffix, e.g. "name2team" gives "&lt;courseName&gt;_name2team.csv"
250
   * @param csvWriter writes the table
251
   * @return the streaming CSV response
252
   * @throws EntityNotFoundException if the course does not exist
253
   * @throws IllegalArgumentException if columns is less than 1
254
   */
255
  private ResponseEntity<StreamingResponseBody> teamCsvResponse(
256
      Long courseId, int columns, String suffix, TeamCsvWriter csvWriter)
257
      throws EntityNotFoundException {
258
    Course course =
259
        courseRepository
260
            .findById(courseId)
261 1 1. lambda$teamCsvResponse$0 : replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::lambda$teamCsvResponse$0 → KILLED
            .orElseThrow(() -> new EntityNotFoundException(Course.class, courseId));
262 2 1. teamCsvResponse : negated conditional → KILLED
2. teamCsvResponse : changed conditional boundary → KILLED
    if (columns < 1) {
263
      throw new IllegalArgumentException("columns must be at least 1");
264
    }
265
    StreamingResponseBody stream =
266
        (outputStream) -> {
267
          List<RosterStudent> rosterStudents =
268
              rosterStudentRepository
269
                  .findByCourseIdAndRosterStatusInOrderByFirstNameAscLastNameAscIgnoreCase(
270
                      courseId, List.of(RosterStatus.ROSTER, RosterStatus.MANUAL));
271
          List<NameAndTeam> entries = teamCsvService.nameAndTeams(rosterStudents);
272
          try (Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
273 1 1. lambda$teamCsvResponse$1 : removed call to edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController$TeamCsvWriter::write → KILLED
            csvWriter.write(writer, entries, columns);
274
          }
275
        };
276
277 1 1. teamCsvResponse : replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::teamCsvResponse → KILLED
    return ResponseEntity.ok()
278
        .contentType(MediaType.parseMediaType("text/csv; charset=UTF-8"))
279
        .header(
280
            HttpHeaders.CONTENT_DISPOSITION,
281
            String.format("attachment;filename=%s_%s.csv", course.getCourseName(), suffix))
282
        .header(HttpHeaders.CONTENT_TYPE, "text/csv; charset=UTF-8")
283
        .header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION)
284
        .body(stream);
285
  }
286
}

Mutations

81

1.1
Location : lambda$csvForQuarter$0
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_no_such_course()]
replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::lambda$csvForQuarter$0 → KILLED

89

1.1
Location : lambda$csvForQuarter$1
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:mockMvcSRBTest()]
removed call to com/opencsv/bean/StatefulBeanToCsv::write → KILLED

97

1.1
Location : csvForQuarter
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_csv_exception()]
replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::csvForQuarter → KILLED

129

1.1
Location : lambda$catmeCsv$0
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_catme_no_such_course()]
replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::lambda$catmeCsv$0 → KILLED

140

1.1
Location : lambda$catmeCsv$1
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_catme_csv_uses_raw_sections_when_option_explicitly_disabled()]
removed call to org/apache/commons/csv/CSVPrinter::printRecord → KILLED

143

1.1
Location : lambda$catmeCsv$1
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_catme_csv_uses_raw_sections_when_option_explicitly_disabled()]
negated conditional → KILLED

2.2
Location : lambda$catmeCsv$1
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_catme_csv_filters_to_roster_and_manual()]
negated conditional → KILLED

144

1.1
Location : lambda$catmeCsv$1
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_catme_csv_uses_raw_sections_when_option_explicitly_disabled()]
removed call to org/apache/commons/csv/CSVPrinter::printRecord → KILLED

156

1.1
Location : catmeCsv
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_catme_csv_uses_raw_sections_when_option_explicitly_disabled()]
replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::catmeCsv → KILLED

197

1.1
Location : name2TeamCsv
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_name2team_csv_with_one_column()]
replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::name2TeamCsv → KILLED

233

1.1
Location : teamTableCsv
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_teamtable_csv_with_one_column()]
replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::teamTableCsv → KILLED

261

1.1
Location : lambda$teamCsvResponse$0
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_teamtable_no_such_course()]
replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::lambda$teamCsvResponse$0 → KILLED

262

1.1
Location : teamCsvResponse
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_name2team_rejects_columns_less_than_one()]
negated conditional → KILLED

2.2
Location : teamCsvResponse
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_name2team_csv_with_one_column()]
changed conditional boundary → KILLED

273

1.1
Location : lambda$teamCsvResponse$1
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_name2team_csv_with_one_column()]
removed call to edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController$TeamCsvWriter::write → KILLED

277

1.1
Location : teamCsvResponse
Killed by : edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.frontiers.controllers.CSVDownloadsControllerTests]/[method:test_name2team_csv_with_one_column()]
replaced return value with null for edu/ucsb/cs156/frontiers/controllers/CSVDownloadsController::teamCsvResponse → KILLED

Active mutators

Tests examined


Report generated by PIT 1.30.0 support