Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,17 @@ public StudentAttendanceMovement toRestMovement(school.hei.haapi.model.StudentAt
}

public StudentAttendance toDomain(CreateAttendanceMovement toCreate) {
if (userRepository.findById(toCreate.getStudentId()).isEmpty()) {
throw new NotFoundException(
"the student with #" + toCreate.getStudentId() + " doesn't exist");
}
return StudentAttendance.builder()
.attendanceMovementType(toCreate.getAttendanceMovementType())
.place(toCreate.getPlace())
.createdAt(toCreate.getCreatedAt())
.student(userRepository.findById(toCreate.getStudentId()).get())
.student(
userRepository
.findById(toCreate.getStudentId())
.orElseThrow(
() ->
new NotFoundException(
"the student with #" + toCreate.getStudentId() + " doesn't exist")))
Comment on lines +50 to +55

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can't you use UserService's method?

.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@ public class EventMapper {
public school.hei.haapi.model.Event toDomain(CreateEvent createEvent) {
List<GroupIdentifier> groupIdentifiers = Objects.requireNonNull(createEvent.getGroups());
List<Group> groups =
groupService.getAllById(groupIdentifiers.stream().map(GroupIdentifier::getId).toList());
groups.stream()
.map(group -> mapGroupColorFromGroupIdentifiers(group, groupIdentifiers))
.toList();
groupService
.getAllById(groupIdentifiers.stream().map(GroupIdentifier::getId).toList())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need to collect toList if you're going to stream it again man

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also, to ensure that you really get all given groups, you might need to check if getAllById throws NotFound if ID is not found in DB, otherwise, you'll need to check for the size, like given group list size must equal retrieved group size from db

.stream()
.map(group -> mapGroupColorFromGroupIdentifiers(group, groupIdentifiers))
.toList();
List<Group> mappedGroup = groupService.saveDomainGroup(groups);

return Event.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package school.hei.haapi.endpoint.rest.mapper;

import java.util.List;
import java.util.Optional;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import school.hei.haapi.endpoint.rest.model.CrupdateGrade;
Expand All @@ -10,6 +9,7 @@
import school.hei.haapi.endpoint.rest.validator.GradeValidator;
import school.hei.haapi.model.Exam;
import school.hei.haapi.model.User;
import school.hei.haapi.model.exception.NotFoundException;
import school.hei.haapi.repository.GradeRepository;
import school.hei.haapi.service.ExamService;
import school.hei.haapi.service.GradeService;
Expand All @@ -25,63 +25,41 @@ public class GradeMapper {
private final GradeValidator validator;
private final GradeRepository gradeRepository;

// todo: to review all class
public school.hei.haapi.model.Grade toDomain(Grade grade) {
return school.hei.haapi.model.Grade.builder()
.score(grade.getScore())
.creationDatetime(grade.getCreatedAt())
.build();
}

public Grade toRest(school.hei.haapi.model.Grade grade) {
return new Grade()
.id(grade.getId())
.createdAt(grade.getCreationDatetime())
.score(grade.getScore().doubleValue())
.score(grade.getScore())
.updateDate(grade.getCreationDatetime());
}

public StudentGrade toRestStudentGrade(school.hei.haapi.model.Grade grade) {
if (grade == null) {
return null;
}
var getStudentGrade = new StudentGrade().grade(toRest(grade));
getStudentGrade.setStudent(userMapper.toRestStudent(grade.getStudent()));

return getStudentGrade;
}

public StudentGrade toRestStudentExamGrade(User student, Exam exam) {
Optional<school.hei.haapi.model.Grade> optionalGrade =
exam.getGrades().stream()
.filter(grade -> grade.getStudent().getId().equals(student.getId()))
.findFirst();
school.hei.haapi.model.Grade grade = optionalGrade.get();
var getStudentGrade = new StudentGrade().grade(toRest(grade));
getStudentGrade.setStudent(userMapper.toRestStudent(student));
return getStudentGrade;
return new StudentGrade()
.grade(
toRest(
exam.getGrades().stream()
.filter(grade -> grade.getStudent().getId().equals(student.getId()))
.findFirst()
.orElseThrow(
() ->
new NotFoundException(
"Student %s have no grade for the exam %s"
.formatted(student.getId(), exam.getId())))))
Comment on lines +47 to +54

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmmm, this looks like it could be done with way more ease,
like a db call to get student grade from an exam instead of loading all grades then finding the right one,
also, if you're doing this, for a List for a single exam, you could opt for a basic use of Map<String, StudentGrade>

.student(userMapper.toRestStudent(student));
}

// public ExamDetail toRestExamDetail(Exam exam, List<school.hei.haapi.model.Grade> grades) {
// return new ExamDetail()
// .id(exam.getId())
// .coefficient(exam.getCoefficient())
// .title(exam.getTitle())
// .examinationDate(exam.getExaminationDate().atZone(ZoneId.systemDefault()).toInstant())
// .participants(
// grades.stream().map(grade -> this.toRestStudentGrade(grade)).collect(toList()));
// }

public school.hei.haapi.model.Grade toDomain(
CrupdateGrade grade, String examId, String studentRef) {
validator.accept(grade);

Exam exam = examService.getExamById(examId);
double scoreFinal = 0.0;

if (exam.getCoefficient() > 0 && grade.getScore() != null && grade.getScore() >= 0) {
scoreFinal = grade.getScore() * exam.getCoefficient();
}

school.hei.haapi.model.Grade resultGrade =
gradeRepository
Expand All @@ -94,7 +72,7 @@ public school.hei.haapi.model.Grade toDomain(
exam, userService.findByRef(studentRef))))
.getFirst());

resultGrade.setScore(scoreFinal);
resultGrade.setScore(grade.getScore() * exam.getCoefficient());
return resultGrade;
}
}
21 changes: 9 additions & 12 deletions src/main/java/school/hei/haapi/service/aws/FileService.java
Original file line number Diff line number Diff line change
Expand Up @@ -95,25 +95,22 @@ public static String getFormattedBucketKey(User user, FileType fileType, String
}

/* Use the JDK HttpClient (since v11) class to do the download. */

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why did you choose HttpClient ?
don't you guys have a RestTemplate bean somewhere ?

public byte[] useHttpClientToGet(String presignedUrlString) {
public byte[] useHttpClientToGet(String presignedUrlString)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

method name leaks implementation details,

className should be enough to guess that this class handles HTTP or in a more abstract way, Networking things,

and method name could be httpGet

throws URISyntaxException, IOException, InterruptedException {
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(); // Capture the response body to a byte array.

HttpRequest.Builder requestBuilder = HttpRequest.newBuilder();
HttpClient httpClient = HttpClient.newHttpClient();
try {
URL presignedUrl = new URL(presignedUrlString);
HttpResponse<InputStream> response =
httpClient.send(
requestBuilder.uri(presignedUrl.toURI()).GET().build(),
HttpResponse.BodyHandlers.ofInputStream());
URL presignedUrl = new URL(presignedUrlString);
HttpResponse<InputStream> response =
httpClient.send(
requestBuilder.uri(presignedUrl.toURI()).GET().build(),
HttpResponse.BodyHandlers.ofInputStream());

IoUtils.copy(response.body(), byteArrayOutputStream);
IoUtils.copy(response.body(), byteArrayOutputStream);

logger.info("HTTP response code is " + response.statusCode());
} catch (URISyntaxException | InterruptedException | IOException e) {
logger.error(e.getMessage(), e);
}
logger.info("HTTP response code is " + response.statusCode());
return byteArrayOutputStream.toByteArray();
}
}
4 changes: 4 additions & 0 deletions src/test/java/school/hei/haapi/integration/GradeIT.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,14 @@
import school.hei.haapi.endpoint.rest.api.TeachingApi;
import school.hei.haapi.endpoint.rest.client.ApiClient;
import school.hei.haapi.endpoint.rest.client.ApiException;
import school.hei.haapi.endpoint.rest.mapper.GradeMapper;
import school.hei.haapi.endpoint.rest.model.AwardedCourseExam;
import school.hei.haapi.endpoint.rest.model.CrupdateGrade;
import school.hei.haapi.endpoint.rest.model.StudentGrade;
import school.hei.haapi.integration.conf.FacadeITMockedThirdParties;
import school.hei.haapi.integration.conf.TestUtils;
import school.hei.haapi.model.User;
import school.hei.haapi.repository.GradeRepository;
import school.hei.haapi.repository.UserRepository;
import school.hei.haapi.service.UserService;

Expand All @@ -49,6 +51,8 @@
class GradeIT extends FacadeITMockedThirdParties {
@Autowired UserRepository userRepository;
@Autowired UserService userService;
@Autowired GradeRepository gradeRepository;
@Autowired GradeMapper gradeMapper;

private ApiClient anApiClient(String token) {
return TestUtils.anApiClient(token, localPort);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package school.hei.haapi.unit.objectMapper;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import school.hei.haapi.endpoint.rest.mapper.GradeMapper;
import school.hei.haapi.endpoint.rest.model.CrupdateGrade;
import school.hei.haapi.model.Exam;
import school.hei.haapi.model.Grade;
import school.hei.haapi.model.User;
import school.hei.haapi.model.exception.NotFoundException;
import school.hei.haapi.repository.GradeRepository;
import school.hei.haapi.service.ExamService;
import school.hei.haapi.service.GradeService;

class GradeMapperTest {
GradeMapper subject;
ExamService examService;
GradeRepository gradeRepository;
GradeService gradeService;

@BeforeEach
void setUp() {
gradeService = mock();
examService = mock();
gradeRepository = mock();
Comment on lines +33 to +35

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use mock(GradeService.class) for readability

subject = new GradeMapper(mock(), gradeService, examService, mock(), mock(), gradeRepository);
}

@Test
void combine_student_with_bad_exam_to_get_grade_ko() {
User student1 = new User();
student1.setId("student1");
Comment on lines +41 to +42

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

builder style for fewer lines

User student2 = new User();
student2.setId("student2");
Exam exam = new Exam();
exam.setGrades(List.of(new Grade("", student2, new Exam(), null, null)));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

exam.setGrades, and the given Grade is not even linked to the exam where we add it?


NotFoundException notFoundException =
assertThrows(NotFoundException.class, () -> subject.toRestStudentExamGrade(student1, exam));
assertEquals(
"Student %s have no grade for the exam %s".formatted(student1.getId(), exam.getId()),
notFoundException.getMessage());
}

@Test
void map_grade_to_grade_or_create_grade() {
when(examService.getExamById(any())).thenReturn(new Exam(null, 1, null, null, null, null));
when(gradeRepository.getGradeByExamIdAndStudentRef(any(), any())).thenReturn(Optional.empty());
Grade gradeSaved = new Grade("", new User(), new Exam(), 1., Instant.now());
when(gradeService.crupdateParticipantGrade(anyList())).thenReturn(List.of(gradeSaved));

Grade grade = subject.toDomain(new CrupdateGrade().score(gradeSaved.getScore()), "", "");

assertEquals(gradeSaved, grade);
}
}