StudentController.java

1
package edu.ucsb.cs156.happiercows.controllers;
2
3
import edu.ucsb.cs156.happiercows.entities.Student;
4
import edu.ucsb.cs156.happiercows.entities.User;
5
import edu.ucsb.cs156.happiercows.errors.EntityNotFoundException;
6
import edu.ucsb.cs156.happiercows.helpers.StudentCsvFormat;
7
import edu.ucsb.cs156.happiercows.models.CsvUploadResult;
8
import edu.ucsb.cs156.happiercows.models.StudentDTO;
9
import edu.ucsb.cs156.happiercows.models.StudentWithLastLogin;
10
import edu.ucsb.cs156.happiercows.repositories.StudentRepository;
11
import edu.ucsb.cs156.happiercows.repositories.UserRepository;
12
import edu.ucsb.cs156.happiercows.utilities.CanonicalFormConverter;
13
import edu.ucsb.cs156.happiercows.utilities.PacificTimeUtils;
14
import io.swagger.v3.oas.annotations.tags.Tag;
15
import io.swagger.v3.oas.annotations.Operation;
16
import io.swagger.v3.oas.annotations.Parameter;
17
import lombok.extern.slf4j.Slf4j;
18
import org.apache.commons.csv.CSVFormat;
19
import org.apache.commons.csv.CSVParser;
20
import org.apache.commons.csv.CSVRecord;
21
import org.springframework.beans.factory.annotation.Autowired;
22
import org.springframework.http.MediaType;
23
import org.springframework.security.access.prepost.PreAuthorize;
24
import org.springframework.web.bind.annotation.*;
25
import org.springframework.web.multipart.MultipartFile;
26
27
import java.io.IOException;
28
import java.io.InputStreamReader;
29
import java.nio.charset.StandardCharsets;
30
import java.time.LocalDateTime;
31
import java.util.ArrayList;
32
import java.util.Iterator;
33
import java.util.List;
34
import java.util.Optional;
35
36
@Slf4j
37
@Tag(name = "Student")
38
@RequestMapping("/api/student")
39
@RestController
40
public class StudentController extends ApiController {
41
    @Autowired
42
    private StudentRepository studentRepository;
43
44
    @Autowired
45
    private UserRepository userRepository;
46
47
    @Operation(summary = "List all roster students")
48
    @PreAuthorize("hasRole('ROLE_ADMIN')")
49
    @GetMapping("/all")
50
    public Iterable<Student> allStudents() {
51 1 1. allStudents : replaced return value with Collections.emptyList for edu/ucsb/cs156/happiercows/controllers/StudentController::allStudents → KILLED
        return studentRepository.findAll();
52
    }
53
54
    @Operation(summary = "List the roster students for a single course, including each student's last login (null if the student has never logged in)")
55
    @PreAuthorize("hasRole('ROLE_ADMIN')")
56
    @GetMapping("/course/{courseId}")
57
    public Iterable<StudentWithLastLogin> studentsForCourse(
58
            @Parameter(name = "courseId") @PathVariable Long courseId) {
59
        List<StudentWithLastLogin> result = new ArrayList<>();
60
        for (Student student : studentRepository.findByCourseId(courseId)) {
61
            Optional<User> user = userRepository.findByEmail(student.getEmail());
62
            LocalDateTime lastLoginDateTime = user
63 1 1. lambda$studentsForCourse$0 : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::lambda$studentsForCourse$0 → KILLED
                    .map(u -> LocalDateTime.ofInstant(u.getLastOnline(), PacificTimeUtils.ZONE))
64
                    .orElse(null);
65
66
            result.add(StudentWithLastLogin.builder()
67
                    .id(student.getId())
68
                    .lastName(student.getLastName())
69
                    .firstMiddleName(student.getFirstMiddleName())
70
                    .email(student.getEmail())
71
                    .perm(student.getPerm())
72
                    .courseId(student.getCourseId())
73
                    .lastLoginDateTime(lastLoginDateTime)
74
                    .build());
75
        }
76 1 1. studentsForCourse : replaced return value with Collections.emptyList for edu/ucsb/cs156/happiercows/controllers/StudentController::studentsForCourse → KILLED
        return result;
77
    }
78
79
    @Operation(summary = "Get a roster student by id")
80
    @PreAuthorize("hasRole('ROLE_ADMIN')")
81
    @GetMapping("/{id}")
82
    public Student getStudentById(
83
            @Parameter(name = "id") @PathVariable Long id) {
84 1 1. getStudentById : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::getStudentById → KILLED
        return studentRepository.findById(id)
85 1 1. lambda$getStudentById$0 : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::lambda$getStudentById$0 → KILLED
                .orElseThrow(() -> new EntityNotFoundException(Student.class, id));
86
    }
87
88
    @Operation(summary = "Add a roster student to a course")
89
    @PreAuthorize("hasRole('ROLE_ADMIN')")
90
    @PostMapping("")
91
    public Student postStudent(
92
            @Parameter(name = "student") @RequestBody StudentDTO studentDTO) {
93 1 1. postStudent : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::postStudent → KILLED
        return studentRepository.save(studentDTO.toStudent());
94
    }
95
96
    @Operation(summary = "Update a single roster student")
97
    @PreAuthorize("hasRole('ROLE_ADMIN')")
98
    @PutMapping("/{id}")
99
    public Student updateStudent(
100
            @Parameter(name = "id") @PathVariable Long id, @RequestBody StudentDTO studentDTO) {
101
        Student student = studentRepository.findById(id)
102 1 1. lambda$updateStudent$0 : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::lambda$updateStudent$0 → KILLED
                .orElseThrow(() -> new EntityNotFoundException(Student.class, id));
103
104 1 1. updateStudent : removed call to edu/ucsb/cs156/happiercows/entities/Student::setLastName → KILLED
        student.setLastName(studentDTO.getLastName());
105 1 1. updateStudent : removed call to edu/ucsb/cs156/happiercows/entities/Student::setFirstMiddleName → KILLED
        student.setFirstMiddleName(studentDTO.getFirstMiddleName());
106 1 1. updateStudent : removed call to edu/ucsb/cs156/happiercows/entities/Student::setEmail → KILLED
        student.setEmail(CanonicalFormConverter.convertToValidEmail(studentDTO.getEmail()));
107 1 1. updateStudent : removed call to edu/ucsb/cs156/happiercows/entities/Student::setPerm → KILLED
        student.setPerm(studentDTO.getPerm());
108 1 1. updateStudent : removed call to edu/ucsb/cs156/happiercows/entities/Student::setCourseId → KILLED
        student.setCourseId(studentDTO.getCourseId());
109
110
        studentRepository.save(student);
111
112 1 1. updateStudent : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::updateStudent → KILLED
        return student;
113
    }
114
115
    @Operation(summary = "Remove a roster student from a course")
116
    @PreAuthorize("hasRole('ROLE_ADMIN')")
117
    @DeleteMapping("/{id}")
118
    public Object deleteStudent(
119
            @Parameter(name = "id") @PathVariable Long id) {
120
        Student student = studentRepository.findById(id)
121 1 1. lambda$deleteStudent$0 : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::lambda$deleteStudent$0 → KILLED
                .orElseThrow(() -> new EntityNotFoundException(Student.class, id));
122
123 1 1. deleteStudent : removed call to edu/ucsb/cs156/happiercows/repositories/StudentRepository::delete → KILLED
        studentRepository.delete(student);
124 1 1. deleteStudent : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::deleteStudent → KILLED
        return genericMessage("Student with id %s deleted".formatted(id));
125
    }
126
127
    /**
128
     * Bulk-adds roster students to a course from an uploaded CSV file. The
129
     * CSV's header row is used to auto-detect which school's roster export
130
     * format it is (see {@link StudentCsvFormat}); rows whose email is
131
     * already on the course roster are skipped rather than duplicated.
132
     *
133
     * @param courseId the course to add the students to
134
     * @param file the uploaded CSV file
135
     * @return a summary of how many students were created, and which emails
136
     *         were skipped as already-on-roster
137
     */
138
    @Operation(summary = "Upload a CSV file of roster students for a course")
139
    @PreAuthorize("hasRole('ROLE_ADMIN')")
140
    @PostMapping(value = "/upload/csv", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
141
    public CsvUploadResult uploadStudentsCsv(
142
            @Parameter(name = "courseId") @RequestParam Long courseId,
143
            @Parameter(name = "file") @RequestParam("file") MultipartFile file) throws IOException {
144
145
        List<CSVRecord> records;
146
        try (CSVParser parser = CSVFormat.DEFAULT.parse(
147
                new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
148
            records = parser.getRecords();
149
        }
150
151 1 1. uploadStudentsCsv : negated conditional → KILLED
        if (records.isEmpty()) {
152
            throw new IllegalArgumentException("CSV file is empty");
153
        }
154
155
        Iterator<CSVRecord> rows = records.iterator();
156
157
        List<String> headerValues = new ArrayList<>();
158
        for (String value : rows.next()) {
159
            headerValues.add(value);
160
        }
161
162
        StudentCsvFormat format = StudentCsvFormat.detect(headerValues);
163 1 1. uploadStudentsCsv : negated conditional → KILLED
        if (format == null) {
164
            throw new IllegalArgumentException("Unrecognized CSV header format");
165
        }
166
167
        int created = 0;
168
        List<String> skippedEmails = new ArrayList<>();
169
170 1 1. uploadStudentsCsv : negated conditional → KILLED
        while (rows.hasNext()) {
171
            CSVRecord row = rows.next();
172 1 1. uploadStudentsCsv : negated conditional → KILLED
            if (row.size() != format.getHeaders().size()) {
173
                throw new IllegalArgumentException(
174
                        "Row %d does not have the expected number of columns".formatted(row.getRecordNumber()));
175
            }
176
177
            Student student = format.toStudent(row, courseId);
178
179 1 1. uploadStudentsCsv : negated conditional → KILLED
            if (studentRepository.findByCourseIdAndEmail(courseId, student.getEmail()).iterator().hasNext()) {
180
                skippedEmails.add(student.getEmail());
181
                continue;
182
            }
183
184
            studentRepository.save(student);
185 1 1. uploadStudentsCsv : Changed increment from 1 to -1 → KILLED
            created++;
186
        }
187
188 1 1. uploadStudentsCsv : replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::uploadStudentsCsv → KILLED
        return CsvUploadResult.builder()
189
                .created(created)
190
                .skippedEmails(skippedEmails)
191
                .build();
192
    }
193
}

Mutations

51

1.1
Location : allStudents
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_get_all_students()]
replaced return value with Collections.emptyList for edu/ucsb/cs156/happiercows/controllers/StudentController::allStudents → KILLED

63

1.1
Location : lambda$studentsForCourse$0
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_get_students_for_a_course()]
replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::lambda$studentsForCourse$0 → KILLED

76

1.1
Location : studentsForCourse
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_get_students_for_a_course()]
replaced return value with Collections.emptyList for edu/ucsb/cs156/happiercows/controllers/StudentController::studentsForCourse → KILLED

84

1.1
Location : getStudentById
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_get_student_by_id()]
replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::getStudentById → KILLED

85

1.1
Location : lambda$getStudentById$0
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_cannot_get_student_when_it_does_not_exist()]
replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::lambda$getStudentById$0 → KILLED

93

1.1
Location : postStudent
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_post_new_student()]
replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::postStudent → KILLED

102

1.1
Location : lambda$updateStudent$0
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_cannot_edit_student_that_does_not_exist()]
replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::lambda$updateStudent$0 → KILLED

104

1.1
Location : updateStudent
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_edit_an_existing_student()]
removed call to edu/ucsb/cs156/happiercows/entities/Student::setLastName → KILLED

105

1.1
Location : updateStudent
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_edit_an_existing_student()]
removed call to edu/ucsb/cs156/happiercows/entities/Student::setFirstMiddleName → KILLED

106

1.1
Location : updateStudent
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_edit_an_existing_student()]
removed call to edu/ucsb/cs156/happiercows/entities/Student::setEmail → KILLED

107

1.1
Location : updateStudent
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_edit_an_existing_student()]
removed call to edu/ucsb/cs156/happiercows/entities/Student::setPerm → KILLED

108

1.1
Location : updateStudent
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_edit_an_existing_student()]
removed call to edu/ucsb/cs156/happiercows/entities/Student::setCourseId → KILLED

112

1.1
Location : updateStudent
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_edit_an_existing_student()]
replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::updateStudent → KILLED

121

1.1
Location : lambda$deleteStudent$0
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_tries_to_delete_non_existant_student_and_gets_right_error_message()]
replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::lambda$deleteStudent$0 → KILLED

123

1.1
Location : deleteStudent
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_delete_a_student()]
removed call to edu/ucsb/cs156/happiercows/repositories/StudentRepository::delete → KILLED

124

1.1
Location : deleteStudent
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_delete_a_student()]
replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::deleteStudent → KILLED

151

1.1
Location : uploadStudentsCsv
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:empty_csv_file_is_rejected()]
negated conditional → KILLED

163

1.1
Location : uploadStudentsCsv
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:unrecognized_header_format_is_rejected()]
negated conditional → KILLED

170

1.1
Location : uploadStudentsCsv
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:malformed_row_with_too_few_columns_is_rejected()]
negated conditional → KILLED

172

1.1
Location : uploadStudentsCsv
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:malformed_row_with_too_few_columns_is_rejected()]
negated conditional → KILLED

179

1.1
Location : uploadStudentsCsv
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_upload_generic_format_csv()]
negated conditional → KILLED

185

1.1
Location : uploadStudentsCsv
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_upload_generic_format_csv()]
Changed increment from 1 to -1 → KILLED

188

1.1
Location : uploadStudentsCsv
Killed by : edu.ucsb.cs156.happiercows.controllers.StudentControllerTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.happiercows.controllers.StudentControllerTests]/[method:admin_can_upload_generic_format_csv()]
replaced return value with null for edu/ucsb/cs156/happiercows/controllers/StudentController::uploadStudentsCsv → KILLED

Active mutators

Tests examined


Report generated by PIT 1.22.1