Skip to content

Commit

Permalink
Made some improvements to the software (#7)
Browse files Browse the repository at this point in the history
* Made some improvements to the software

* Fixed the test of permissions

* Modified test

* Modified permission controller

* Try again

* fixed test ~ added initTestMode()

---------

Co-authored-by: Code-Kata-Battle <luca.cattani@mail.polimi.it>
  • Loading branch information
Felle33 and SigCatta authored Feb 4, 2024
1 parent 312ba88 commit 098d450
Show file tree
Hide file tree
Showing 22 changed files with 248 additions and 179 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ public ResponseEntity<Object> signUp(@RequestBody SignUpRequest request) {
log.info("Account created for email {}", request.getEmail());

Long userID = userService.getUserIDByEmail(request.getEmail());
if (userID == null) return new ResponseEntity<>("Error creating account", getHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
if (userID == null) {
log.error("The email provided is already used by another user");
return new ResponseEntity<>("The email provided is already used by another user", getHeaders(), HttpStatus.BAD_REQUEST);
}

return new ResponseEntity<>(userID, getHeaders(), HttpStatus.CREATED);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ public CanCloseTournamentController(BattleService battleService) {
@PostMapping("/battles-finished")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<Boolean> canCloseTournament(@RequestBody CloseTournamentRequest request) {
log.info("[API REQUEST] Battle finished request with id tournament: {}", request.getTournamentID());
log.info("[API REQUEST] can close the tournament request with id tournament: {}", request.getTournamentID());
if (battleService.canCloseTournament(request.getTournamentID())) {
log.info("The tournament with id {} can be closed", request.getTournamentID());
return new ResponseEntity<>(true, getHeaders(), HttpStatus.OK);
}
log.info("The tournament with id {} cannot be closed", request.getTournamentID());
return ResponseEntity.badRequest().body(false);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public ResponseEntity<Object> createBattle(
.build();
return createBattle(battle);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,25 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/battle")
@Slf4j
public class GetTeamController extends Controller {
private final WebClient.Builder webClientBuilder;
private final WebClient webClient = WebClient.create();
private final BattleService battleService;

@Autowired
public GetTeamController(BattleService battleService) {
this.battleService = battleService;
this.webClientBuilder = WebClient.builder();
}

/**
Expand All @@ -45,22 +46,6 @@ public ResponseEntity<TeamInfoMessage> getTeam(@RequestBody GetTeamStudentReques
try {
Team team = battleService.getListParticipation(request.getBattleId(), request.getStudentId());

List<String> participationNames = team.getParticipation()
.stream()
.map(
participation -> {
try {
return getNameOfStudent(participation);
} catch (Exception e) {
log.error("[EXCEPTION] Error occurred while getting name of student {} : {}",
participation.getStudentId(), e.getMessage());
return null;
}
}
)
.filter(Objects::nonNull)
.toList();

List<String> participantNames = new ArrayList<>();
int errors = 0;
for (Participation participation : team.getParticipation()) {
Expand All @@ -79,7 +64,7 @@ public ResponseEntity<TeamInfoMessage> getTeam(@RequestBody GetTeamStudentReques
log.info("Successfully get all the components of the team {} : {}", team.getTeamId(), participantNames);
}

return ResponseEntity.ok(new TeamInfoMessage(participationNames, team.getTeamId()));
return ResponseEntity.ok(new TeamInfoMessage(participantNames, team.getTeamId()));
} catch (Exception e) {
log.error("[EXCEPTION] {}", e.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
Expand All @@ -106,8 +91,7 @@ public ResponseEntity<TeamsRankingMessage> getTeamsOfBattle(@RequestBody GetTeam
}

private String getNameOfStudent(Participation participation) throws Exception {
ResponseEntity<User> user = webClientBuilder.build()
.post()
ResponseEntity<User> user = webClient.post()
.uri(accountManagerUri + "/api/account/user")
.bodyValue(
participation.getStudentId()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,19 @@ public ResponseEntity<Object> inviteStudentToTeam(@RequestBody InviteStudentTeam
new DirectMailRequest(List.of(request.getIdStudent().toString()),
"You have been invited to join the team: " + request.getIdTeam()
+ ". Please join the team by clicking on the link below:\n" +
"link: " + "http://localhost:3000/invite.html?idTeam=" + request.getIdTeam() +
"link: " + "http://localhost:8080/invite.html?idTeam=" + request.getIdTeam() +
"&idUser=" + request.getIdStudent()
)
)
.retrieve()
.toEntity(String.class)
.block();
log.info("Successfully sent email: {}", response);
return ResponseEntity.ok().build();
} catch (Exception e) {
log.error("[EXCEPTION] {}", e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}

return ResponseEntity.ok().build();
}

}
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package ckb.BattleManager.controller;

import ckb.BattleManager.dto.output.DirectMailRequest;
import ckb.BattleManager.service.BattleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
Expand All @@ -13,14 +11,7 @@
@Slf4j
@Service
public class SendMailsToParticipants extends Controller {
private final WebClient webClient;
private final BattleService battleService;

@Autowired
public SendMailsToParticipants(BattleService battleService) {
this.battleService = battleService;
this.webClient = WebClient.create();
}
private final WebClient webClient = WebClient.create();

public void send(List<Long> participantIds, String content, String battleName) throws Exception {
ResponseEntity<String> response = webClient.post()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,10 @@
@RestController
@Slf4j
public class SendTeamsPointsController extends Controller {
private final WebClient.Builder webClientBuilder;
public SendTeamsPointsController() {
this.webClientBuilder = WebClient.builder();
}
private final WebClient webClient = WebClient.create();

public void sendIdUsersPointsFinishedBattle(Battle battle, List<WorkingPair<Long, Integer>> pairsIdUserPoints) {
ResponseEntity<String> response = webClientBuilder.build()
.post()
ResponseEntity<String> response = webClient.post()
.uri(tournamentManagerUri + "/api/tournament/update-score")
.bodyValue(
new UpdateScoreRequest(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import ckb.BattleManager.controller.CreateGHRepositoryBattleController;
import ckb.BattleManager.dto.input.CreateBattleRequest;
import ckb.BattleManager.model.Battle;
import ckb.BattleManager.model.Participation;
import ckb.BattleManager.model.Team;
import ckb.BattleManager.model.WorkingPair;
import ckb.BattleManager.repository.BattleRepository;
Expand Down Expand Up @@ -78,12 +79,23 @@ public List<Long> getBattlesTournament(Long idTournament) {
public void joinBattle(Long idStudent, Long idBattle) throws Exception {
Battle battle = getBattle(idBattle);

if (LocalDateTime.now().isBefore(battle.getRegDeadline())) {
teamService.createTeam(idStudent, battle);
} else {
if (LocalDateTime.now().isAfter(battle.getRegDeadline())) {
log.error("The registration deadline has passed");
throw new Exception("The registration deadline has passed");
}

List<Long> listStudentIdSubscribedToBattle = battle.getTeamsRegistered()
.stream()
.flatMap(team -> team.getParticipation().stream())
.map(Participation::getStudentId)
.toList();

if (listStudentIdSubscribedToBattle.contains(idStudent)) {
log.error("The student {} is already registered in the battle {}", idStudent, idBattle);
throw new Exception("The student is already registered in the battle");
}

teamService.createTeam(idStudent, battle);
}

public void leaveBattle(Long idStudent, Long idBattle) throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ public Team getTeam(Battle battle, Long idStudent) throws Exception {
}

public void createTeam(Long studentId, Battle battle) {
// TODO: how to set the repository link?
Team team = Team.builder()
.battle(battle)
.eduEvaluated(false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public ResponseEntity<Object> evaluate(@RequestBody EvaluationRequest request) {
if (staticAnalysisDeduction < 0) {
log.error("Error executing static analysis");
evaluationService.cleanUp(path);
return new ResponseEntity<>("Error executing static analysis", getHeaders(), HttpStatus.BAD_REQUEST);
return new ResponseEntity<>("Error executing static analysis", getHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
} else {
log.info("Deduction: " + staticAnalysisDeduction);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,27 +25,33 @@ public class CloseTournamentController extends Controller {

@PostMapping
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<Object> CloseTournament(@RequestBody CloseTournamentRequest request) {
public ResponseEntity<Object> closeTournament(@RequestBody CloseTournamentRequest request) {
// check if the request has valid data
ResponseEntity<Object> response = checkRequest(request);
if (response.getStatusCode().is4xxClientError()) return response;
if (contactBattleManager(request)) {
if (tournamentService.closeTournament(request)) {
Long tournamentID = request.getTournamentID();
String tournamentName = tournamentService.getTournament(tournamentID).getName();

List<String> studentIDs = tournamentService.getStudentsSubscribed(tournamentID).stream().map(Object::toString).toList();
log.info("Tournament {} is now closed", tournamentName);
if (!contactBattleManager(request)) {
log.error("Could not close tournament because or the there was an error contacting the battle manager or the battles are not closed");
return new ResponseEntity<>("Not possible to close", getHeaders(), HttpStatus.BAD_REQUEST);
}

sendMailToAllStudents(studentIDs, tournamentName);
return new ResponseEntity<>("Tournament closed", getHeaders(), HttpStatus.OK);
} else return new ResponseEntity<>("Not allowed to close tournament", getHeaders(), HttpStatus.BAD_REQUEST);
} else {
return new ResponseEntity<>("Not possible to close", getHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
try {
tournamentService.closeTournament(request);
Long tournamentID = request.getTournamentID();
String tournamentName = tournamentService.getTournament(tournamentID).getName();

List<String> studentIDs = tournamentService.getStudentsSubscribed(tournamentID).stream().map(Object::toString).toList();
log.info("Tournament {} is now closed", tournamentName);

sendMailToAllStudents(studentIDs, tournamentName);

return new ResponseEntity<>("Tournament closed", getHeaders(), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), getHeaders(), HttpStatus.BAD_REQUEST);
}
}

private void sendMailToAllStudents(List<String> studentIDs, String tournamentName) {
private void sendMailToAllStudents(List<String> studentIDs, String tournamentName) throws Exception {
DirectMailRequest request = DirectMailRequest.builder()
.userIDs(studentIDs)
.content("Tournament " + tournamentName + "has ended")
Expand All @@ -62,6 +68,7 @@ private void sendMailToAllStudents(List<String> studentIDs, String tournamentNam
log.info("Mail sent to all participants of {} to inform them of the tournament ending", tournamentName);
} else {
log.error("Failed to send email for ending tournament {}", tournamentName);
throw new Exception("Failed to send email for ending tournament");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import org.springframework.http.HttpHeaders;

public abstract class Controller {
String mailServiceUri = "http://mail-service:8085";
String accountManagerUri = "http://account-manager:8086";
String battleManagerUri = "http://battle-manager:8082";
static String mailServiceUri = "http://mail-service:8085";
static String accountManagerUri = "http://account-manager:8086";
static String battleManagerUri = "http://battle-manager:8082";

HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ public class GetAllTournamentsController extends Controller {
private final TournamentService tournamentService;

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Object> getTournaments(@RequestBody GetAllTournamentsRequest request) {
// check if the request has valid data
System.out.println("sending information");
Expand All @@ -29,8 +28,7 @@ public ResponseEntity<Object> getTournaments(@RequestBody GetAllTournamentsReque
for (Tournament tournament : t) {
answer.put(tournament.getTournamentID(), tournament.getName());
}
System.out.println(answer);
return new ResponseEntity<>(answer, getHeaders(), HttpStatus.CREATED);
return new ResponseEntity<>(answer, getHeaders(), HttpStatus.OK);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ public class GetTournamentPageController extends Controller {
private final WebClient webClient;

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<ResponseWrapper> getTournamentPage(@RequestBody GetTournamentPageRequest request) {
if (invalidRequest(request)) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
Expand All @@ -37,12 +36,11 @@ public ResponseEntity<ResponseWrapper> getTournamentPage(@RequestBody GetTournam
log.info("Tournament page retrieved");
List<Long> battles = getBattles(request.getTournamentID());
responseWrapper = new ResponseWrapper(battles, t);
return new ResponseEntity<>(responseWrapper, getHeaders(), HttpStatus.OK);
} catch (Exception e) {
log.error("[EXCEPTION] An exception occurred while retrieving battles {}", e.toString());
return ResponseEntity.badRequest().build();
}

return new ResponseEntity<>(responseWrapper, getHeaders(), HttpStatus.CREATED);
}

private List<Long> getBattles(Long tournamentID) throws Exception {
Expand All @@ -59,18 +57,18 @@ private List<Long> getBattles(Long tournamentID) throws Exception {
.block();

if (response == null) {
log.error("[ERROR] The response is null");
throw new Exception("The response is null");
log.error("The battle manager response is null");
throw new Exception("The battle manager response is null");
}

if (response.getStatusCode().is4xxClientError()) {
log.error("[ERROR] The response has an error {}", response.getBody());
throw new Exception("The response has an error");
log.error("The status code of the battle manager response is 4xx");
throw new Exception("The status code of the battle manager response is 4xx");
}

if (response.getBody() == null) {
log.error("[ERROR] The response body is null");
throw new Exception("The response body is null");
log.error("The battle manager response's body is null");
throw new Exception("The battle manager response's body is null");
}

log.info("Successfully retrieved the list of battles");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public ResponseEntity<Object> informStudents(@RequestBody InformStudentsRequest
.block();

if (response == null || response.getStatusCode().is4xxClientError()) {
log.error("[ERROR] Error while informing students of a tournament: {}", request.getTournamentId());
log.error("Error while informing students of a tournament: {}", request.getTournamentId());
return ResponseEntity.badRequest().build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ private void sendRequest(String content) throws Exception {
.block();

if (answer == null || answer.getStatusCode().is4xxClientError()) {
log.error("Error while sending mail to all students");
throw new Exception();
}
}
Expand Down
Loading

0 comments on commit 098d450

Please sign in to comment.