exception-update #5
@ -1,15 +1,49 @@
|
||||
package com.pvt.TeamMS;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.context.request.WebRequest;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
@ControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
// Error 4xx - delegated from manually thrown ResponseStatusException
|
||||
@ExceptionHandler(ResponseStatusException.class)
|
||||
public ResponseEntity<String> handleResponseStatusException(ResponseStatusException ex) {
|
||||
return new ResponseEntity<>(ex.getReason(), ex.getStatusCode());
|
||||
}
|
||||
// Error 400 - bad request
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException ex, WebRequest request) {
|
||||
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
// Error 404 - not found
|
||||
@ExceptionHandler(NoSuchElementException.class)
|
||||
public ResponseEntity<String> handleNoSuchElement(NoSuchElementException ex, WebRequest request) {
|
||||
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
|
||||
}
|
||||
// Error 400 - bad request
|
||||
@ExceptionHandler(NumberFormatException.class)
|
||||
public ResponseEntity<String> handleNumberFormat(NumberFormatException ex, WebRequest request) {
|
||||
return new ResponseEntity<>("Invalid input format", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
// Error 400 - bad request
|
||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
||||
public ResponseEntity<String> handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
|
||||
String param = ex.getName();
|
||||
String expectedType = ex.getRequiredType() != null ? ex.getRequiredType().getSimpleName() : "unknown";
|
||||
String providedValue = ex.getValue() != null ? ex.getValue().toString() : "null";
|
||||
String message = String.format("Parameter '%s' should be a valid %s (was '%s')", param, expectedType, providedValue);
|
||||
return new ResponseEntity<>(message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
// Error 500 - internal server error
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<String> handleAllOtherExceptions(Exception ex, WebRequest request) {
|
||||
return new ResponseEntity<>("Something went wrong: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
@ -28,9 +28,6 @@ public class Team {
|
||||
@Column(name = "user_email") // Column that stores the email
|
||||
private Set<String> userEmails = new HashSet<>();
|
||||
|
||||
|
||||
//test value, will probably not be used in the actual code
|
||||
//private LocalDateTime lastContribution;
|
||||
public Team() {
|
||||
}
|
||||
public Team(String name, String imageUrl) {
|
||||
|
||||
@ -2,10 +2,8 @@ package com.pvt.TeamMS.Team;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(path = "/")
|
||||
@ -24,59 +22,42 @@ public class TeamController {
|
||||
public @ResponseBody Iterable<Team> getAllTeams() {
|
||||
return teamService.getAllTeams();
|
||||
}
|
||||
|
||||
// Get a specific team by their id. Team: id, name, score
|
||||
@GetMapping("/get-team/{teamId}")
|
||||
public @ResponseBody Optional<Team> getTeam(@PathVariable int teamId) {
|
||||
try {
|
||||
return teamService.getTeamById(teamId);
|
||||
} catch (NoSuchElementException e) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
|
||||
}
|
||||
return teamService.getTeamById(teamId);
|
||||
}
|
||||
|
||||
// Gets all members in a team.
|
||||
@GetMapping("/team-members/{teamId}")
|
||||
public ResponseEntity<?> getTeamMembers(@PathVariable int teamId) {
|
||||
try {
|
||||
Set<String> members = teamService.getTeamMembers(teamId);
|
||||
return new ResponseEntity<>(members, HttpStatus.OK);
|
||||
} catch (NoSuchElementException e) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
|
||||
}
|
||||
Set<String> members = teamService.getTeamMembers(teamId);
|
||||
return ResponseEntity.ok(members);
|
||||
}
|
||||
|
||||
// Creates an instance of Team.
|
||||
@PostMapping("/create-team")
|
||||
public @ResponseBody Team createNewTeam(@RequestBody Team team) {
|
||||
// Makes sure name of the team isn't null
|
||||
public ResponseEntity<?> createNewTeam(@RequestBody Team team) {
|
||||
if (team.getName() == null || team.getName().trim().isEmpty()) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Team name cannot be empty");
|
||||
}
|
||||
try {
|
||||
return teamService.createTeam(team.getName(), team.getImageUrl());
|
||||
} catch (IllegalArgumentException e) {
|
||||
// Catch your duplicate name exception and respond with 400
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
|
||||
throw new IllegalArgumentException("Team name cannot be empty");
|
||||
}
|
||||
Team created = teamService.createTeam(team.getName(), team.getImageUrl());
|
||||
return ResponseEntity.ok(created);
|
||||
}
|
||||
|
||||
// Updates a Teams score.
|
||||
@PutMapping(path = "/change/{teamId}/{scoreDelta}")
|
||||
public String changeTeamScore(@PathVariable int teamId, @PathVariable int scoreDelta) {
|
||||
try {
|
||||
teamService.updateScore(teamId, scoreDelta);
|
||||
return "Score updated";
|
||||
} catch (NoSuchElementException e) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
|
||||
}
|
||||
public ResponseEntity<?> changeTeamScore(@PathVariable int teamId, @PathVariable int scoreDelta) {
|
||||
teamService.updateScore(teamId, scoreDelta);
|
||||
return ResponseEntity.ok("Score updated");
|
||||
}
|
||||
|
||||
// Changes a Teams avatar.
|
||||
@PutMapping(path = "/change-avatar")
|
||||
public ResponseEntity<?> changeTeamAvatar(@RequestBody Team team) {
|
||||
if(teamService.updateAvatarSuccess(team.getId(), team.getImageUrl())) {
|
||||
return new ResponseEntity<>("Avatar updated", HttpStatus.OK);
|
||||
if (teamService.updateAvatarSuccess(team.getId(), team.getImageUrl())) {
|
||||
return ResponseEntity.ok("Avatar updated");
|
||||
} else {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Something went wrong");
|
||||
throw new NoSuchElementException("Avatar update failed: team not found or invalid");
|
||||
}
|
||||
}
|
||||
|
||||
// Adds a User to a Team.
|
||||
@PostMapping(path = "/add-user-to-team")
|
||||
public ResponseEntity<?> addUserToTeamPost(@RequestBody Map<String, Object> request) {
|
||||
String email = (String) request.get("email");
|
||||
@ -89,52 +70,43 @@ public class TeamController {
|
||||
} else if (teamIdObj instanceof String) {
|
||||
teamId = Integer.parseInt((String) teamIdObj);
|
||||
} else {
|
||||
return new ResponseEntity<>("Invalid teamId format", HttpStatus.BAD_REQUEST);
|
||||
throw new IllegalArgumentException("Invalid teamId format");
|
||||
}
|
||||
|
||||
// Always attempt to add the user without checking if they're already in this or
|
||||
// another team
|
||||
boolean added = teamService.addUser(email, teamId);
|
||||
if (added) {
|
||||
return new ResponseEntity<>("User added to team", HttpStatus.OK);
|
||||
return ResponseEntity.ok("User added to team");
|
||||
} else {
|
||||
return new ResponseEntity<>("Failed to add user to team", HttpStatus.BAD_REQUEST);
|
||||
throw new IllegalArgumentException("Failed to add user to team");
|
||||
}
|
||||
}
|
||||
|
||||
// Removes a User to a Team.
|
||||
@DeleteMapping("/remove-user-from-team/{email}/{teamId}")
|
||||
public ResponseEntity<?> removeUserFromTeam(@PathVariable String email, @PathVariable int teamId) {
|
||||
// Check if the team exists
|
||||
if (!teamService.getTeamById(teamId).isPresent()) {
|
||||
return new ResponseEntity<>("Team not found", HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
// REMOVED: Check if the user is actually in the team - for testing purposes
|
||||
teamService.getTeamById(teamId).orElseThrow(() -> new NoSuchElementException("Team not found"));
|
||||
|
||||
if (teamService.removeUser(email, teamId)) {
|
||||
return new ResponseEntity<>("User removed from team", HttpStatus.OK);
|
||||
return ResponseEntity.ok("User removed from team");
|
||||
} else {
|
||||
return new ResponseEntity<>("Failed to remove user from team", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
throw new RuntimeException("Failed to remove user from team");
|
||||
}
|
||||
}
|
||||
|
||||
// Removes an instance of team.
|
||||
@DeleteMapping("/remove/{teamId}")
|
||||
public String removeTeam(@PathVariable int teamId) {
|
||||
try {
|
||||
String name = teamService.nameById(teamId);
|
||||
teamService.removeTeam(teamId);
|
||||
return "Removed team: " + name;
|
||||
} catch (NoSuchElementException e) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
|
||||
}
|
||||
public ResponseEntity<?> removeTeam(@PathVariable int teamId) {
|
||||
String name = teamService.nameById(teamId);
|
||||
teamService.removeTeam(teamId);
|
||||
return ResponseEntity.ok("Removed team: " + name);
|
||||
}
|
||||
|
||||
// TODO comment what this does
|
||||
@PutMapping("/toggle-return-scores")
|
||||
public ResponseEntity<?> toggleReturnScores() {
|
||||
teamService.toggleReturnScore();
|
||||
return new ResponseEntity<>("Return scores Toggled", HttpStatus.OK);
|
||||
return ResponseEntity.ok("Return scores Toggled");
|
||||
}
|
||||
|
||||
// TODO comment what this does
|
||||
@GetMapping("/get-toggle-state")
|
||||
public ResponseEntity<Map<String, Boolean>> getToggleState() {
|
||||
boolean state = teamService.getToggleState();
|
||||
|
||||
@ -73,16 +73,6 @@ public class TeamService {
|
||||
teamRepository.save(team);
|
||||
return team;
|
||||
}
|
||||
// public void createTeam(String teamName) {
|
||||
// if (teamName == null || teamName.trim().isEmpty()) {
|
||||
// throw new IllegalArgumentException("Team name cannot be empty");
|
||||
// }
|
||||
// if (hasName(teamName)) {
|
||||
// throw new IllegalArgumentException("Team name already exists");
|
||||
// }
|
||||
// Team team = new Team(teamName);
|
||||
// teamRepository.save(team);
|
||||
// }
|
||||
|
||||
public void updateScore(int teamId, int scoreDelta) throws NoSuchElementException {
|
||||
if (!teamExists(teamId)) {
|
||||
|
||||
@ -72,16 +72,21 @@ public class TeamControllerTests {
|
||||
.andExpect(content().string(containsString("Team ID not found")));
|
||||
}
|
||||
|
||||
//TODO make test for this method
|
||||
/* @GetMapping("/team-members/{teamId}")
|
||||
public ResponseEntity<?> getTeamMembers(@PathVariable int teamId) {
|
||||
try {
|
||||
Set<String> members = teamService.getTeamMembers(teamId);
|
||||
return new ResponseEntity<>(members, HttpStatus.OK);
|
||||
} catch (NoSuchElementException e) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
|
||||
}
|
||||
} */
|
||||
@Test
|
||||
public void getTeamMembers() throws Exception {
|
||||
Team team = allTeams.get(0);
|
||||
|
||||
// Should return members of existing team
|
||||
mockMvc.perform(get("/team-members/" + team.getId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType("application/json"))
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
|
||||
// Should return not found for non-existing team ID
|
||||
mockMvc.perform(get("/team-members/" + fakeId))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(content().string(containsString("Team ID not found")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addTeam() throws Exception {
|
||||
@ -170,8 +175,8 @@ public class TeamControllerTests {
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("User added to team"));
|
||||
|
||||
// TODO checks for strings that are not numbers (vet ej om det behövs då jag tror inte det är möjligt att lägga till såna på frontend, men kan vara bra att ha med i framtiden)
|
||||
/* json = """
|
||||
// Checks for strings that are not numbers
|
||||
json = """
|
||||
{
|
||||
"email": "testuser@example.com",
|
||||
"teamId": "not-a-number"
|
||||
@ -179,8 +184,8 @@ public class TeamControllerTests {
|
||||
""";
|
||||
mockMvc.perform(post("/add-user-to-team")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(badTeamIdJson))
|
||||
.andExpect(status().isBadRequest()); */
|
||||
.content(json))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
// checks for missing team tid
|
||||
json = """
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user