Implement Caching and fix minor errors
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good

This commit is contained in:
2026-01-22 09:34:24 +01:00
parent 159c03142a
commit 917ed77a95
13 changed files with 208 additions and 47 deletions
@@ -0,0 +1,22 @@
package SuMoC.backend.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.web.filter.ShallowEtagHeaderFilter;
@Configuration
public class CachingConfig {
/**
* Register a filter that adds ETag headers to HTTP responses for caching purposes.
*/
@Bean
public FilterRegistrationBean<ShallowEtagHeaderFilter> etagFilter() {
FilterRegistrationBean<ShallowEtagHeaderFilter> filter = new FilterRegistrationBean<>(new ShallowEtagHeaderFilter());
filter.addUrlPatterns("/*");
filter.setName("etagFilter");
filter.setOrder(1);
return filter;
}
}
@@ -1,17 +1,23 @@
package SuMoC.backend.gamification.badges;
import SuMoC.backend.gamification.badges.models.Badge;
import SuMoC.backend.user.dtos.MaximalUserDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.annotation.security.RolesAllowed;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/badges")
@@ -27,7 +33,8 @@ public class BadgeController {
@Operation(summary = "Create a new badge")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Badge created successfully"),
@ApiResponse(responseCode = "201", description = "Badge created successfully",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = Badge.class))),
@ApiResponse(responseCode = "400", description = "Invalid input data"),
@ApiResponse(responseCode = "409", description = "Badge already exists")
})
@@ -53,7 +60,8 @@ public class BadgeController {
@Operation(summary = "Modify a badge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Badge modified successfully"),
@ApiResponse(responseCode = "200", description = "Badge modified successfully",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = Badge.class))),
@ApiResponse(responseCode = "404", description = "Badge not found"),
@ApiResponse(responseCode = "400", description = "Invalid input data")
})
@@ -67,25 +75,35 @@ public class BadgeController {
@Operation(summary = "Get a badge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Badge retrieved successfully"),
@ApiResponse(responseCode = "200", description = "Badge retrieved successfully",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = Badge.class))),
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
@ApiResponse(responseCode = "404", description = "Badge not found")
})
@GetMapping("/getBadge/{badgeId}")
public ResponseEntity<Badge> getBadgeById(@PathVariable Long badgeId) {
Badge badge = badgeService.getBadgeById(badgeId);
return ResponseEntity.status(HttpStatus.OK).body(badge);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(356, TimeUnit.DAYS))
.body(badge);
}
@Operation(summary = "Get all badges")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Badges retrieved successfully"),
@ApiResponse(responseCode = "200", description = "Badges retrieved successfully",
content = @Content(mediaType = "application/json",
array = @ArraySchema(schema = @Schema(implementation = Badge.class))
)),
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
@ApiResponse(responseCode = "404", description = "No badges found")
})
@GetMapping("/getAllBadges")
public ResponseEntity<List<Badge>> getAllBadges(){
List<Badge> badges = badgeService.getAllBadges();
return ResponseEntity.status(HttpStatus.OK).body(badges);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
.body(badges);
}
}
@@ -2,11 +2,15 @@ package SuMoC.backend.gamification.scoretable;
import SuMoC.backend.gamification.scoretable.models.Leaderboard;
import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.user.dtos.MaximalUserDTO;
import SuMoC.backend.user.models.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
@@ -15,9 +19,11 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/leaderboard")
class LeaderboardController {
public class LeaderboardController {
private LeaderboardService leaderboardService;
@Autowired
@@ -27,28 +33,34 @@ class LeaderboardController {
@Operation(summary = "Get the global score table")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved global score table"),
@ApiResponse(responseCode = "200", description = "Successfully retrieved global score table",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = Leaderboard.class))),
@ApiResponse(responseCode = "304", description = "Not modified"),
@ApiResponse(responseCode = "400", description = "Bad request")
})
@GetMapping("/getLeaderboard")
public ResponseEntity<Leaderboard> getLeaderboard(@AuthenticationPrincipal User user,
@RequestParam Timeframe timeframe,
public ResponseEntity<Leaderboard> getLeaderboard(@RequestParam Timeframe timeframe,
@RequestParam String field) {
Leaderboard leaderboard = this.leaderboardService.getLeaderboard(user, timeframe, field);
return ResponseEntity.status(HttpStatus.OK).body(leaderboard);
Leaderboard leaderboard = this.leaderboardService.getLeaderboard( timeframe, field);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(24, TimeUnit.HOURS))
.body(leaderboard);
}
@Operation(summary = "Get the friend score table")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved friend score table"),
@ApiResponse(responseCode = "200", description = "Successfully retrieved friend score table",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = Leaderboard.class))),
@ApiResponse(responseCode = "304", description = "Not modified"),
@ApiResponse(responseCode = "400", description = "Bad request")
})
@GetMapping("/getFriendLeaderboard")
public ResponseEntity<Leaderboard> getFriendLeaderboard(@AuthenticationPrincipal User user,
@RequestParam Timeframe timeframe,
public ResponseEntity<Leaderboard> getFriendLeaderboard(@RequestParam Timeframe timeframe,
@RequestParam String field) {
Leaderboard leaderboard = this.leaderboardService.getFriendLeaderboard(user, timeframe, field);
return ResponseEntity.status(HttpStatus.OK).body(leaderboard);
Leaderboard leaderboard = this.leaderboardService.getFriendLeaderboard(timeframe, field);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(24, TimeUnit.HOURS))
.body(leaderboard);
}
}
@@ -4,6 +4,7 @@ import SuMoC.backend.gamification.scoretable.models.Leaderboard;
import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.gamification.scoretable.models.LeaderboardEntry;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.service.CurrentUserService;
import SuMoC.backend.user.service.FriendshipService;
import SuMoC.backend.user.stats.*;
import org.springframework.data.domain.PageRequest;
@@ -21,36 +22,38 @@ import java.util.stream.Collectors;
public class LeaderboardService {
private final FriendshipService friendshipService;
private final StatsListRepository statsListRepository;
private final CurrentUserService currentUser;
public LeaderboardService(
FriendshipService friendshipService,
StatsListRepository statsListRepository
StatsListRepository statsListRepository,
CurrentUserService currentUser
) {
this.friendshipService = friendshipService;
this.statsListRepository = statsListRepository;
this.currentUser = currentUser;
}
/**
* Method Overload to get the score table with a default limit of 30.
* @param user
* @param timeframe
* @param field
* @return
*/
public Leaderboard getLeaderboard(User user, Timeframe timeframe, String field) {
return getLeaderboard(user, timeframe, field, 30);
public Leaderboard getLeaderboard(Timeframe timeframe, String field) {
return getLeaderboard( timeframe, field, 30);
}
/**
* Get the global score table for a given user, timeframe, score type, and limit.
* @param user
* @param timeframe
* @param field
* @param limit
* @return
*/
public Leaderboard getLeaderboard(User user, Timeframe timeframe, String field, int limit) {
public Leaderboard getLeaderboard(Timeframe timeframe, String field, int limit) {
User user = currentUser.get();
List<StatsList> topStats = getTopStats(timeframe, field, limit);
List<Long> topUserIds = topStats.stream()
@@ -103,25 +106,24 @@ public class LeaderboardService {
/**
* Method Overload to get the friend score table with a default limit of 30.
* @param user
* @param timeframe
* @param field
* @return
*/
public Leaderboard getFriendLeaderboard(User user, Timeframe timeframe, String field) {
return getFriendLeaderboard(user, timeframe, field, 30);
public Leaderboard getFriendLeaderboard(Timeframe timeframe, String field) {
return getFriendLeaderboard(timeframe, field, 30);
}
/**
* Get the friend score table for a given user, timeframe, score type, and limit.
* @param user
* @param timeframe
* @param field
* @param limit
* @return
*/
public Leaderboard getFriendLeaderboard(User user, Timeframe timeframe, String field, int limit) {
public Leaderboard getFriendLeaderboard(Timeframe timeframe, String field, int limit) {
User user = currentUser.get();
List<User> friends = friendshipService.getAcceptedFriends(user);
Leaderboard leaderboard = new Leaderboard();
@@ -1,8 +1,10 @@
package SuMoC.backend.user.models;
package SuMoC.backend.images;
import jakarta.persistence.*;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype")
public class ImageEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@@ -0,0 +1,8 @@
package SuMoC.backend.images;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ImageEntityRepository extends JpaRepository<ImageEntity, Long> {
}
@@ -4,26 +4,31 @@ import SuMoC.backend.user.dtos.FriendshipDTO;
import SuMoC.backend.user.dtos.MinimalUserDTO;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import SuMoC.backend.user.service.CurrentUserService;
import SuMoC.backend.user.service.FriendshipService;
import SuMoC.backend.user.service.PrivacyService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/friendship")
public class FriendshipController {
private final UserRepository userRepository;
private final FriendshipService friendshipService;
private final CurrentUserService currentUser;
@Autowired
public FriendshipController(UserRepository userRepository, FriendshipService friendshipService) {
public FriendshipController(UserRepository userRepository, FriendshipService friendshipService, CurrentUserService currentUser) {
this.userRepository = userRepository;
this.friendshipService = friendshipService;
this.currentUser = currentUser;
}
// TODO extend security context with user id to avoid unnecessary db query
@@ -46,15 +51,21 @@ public class FriendshipController {
""")
@GetMapping("/all")
public ResponseEntity<List<FriendshipDTO>> getFriendships() {
User user = getAuthenticatedUser();
return ResponseEntity.ok(friendshipService.getFriendships(user.getId()));
User user = currentUser.get();
List<FriendshipDTO> friendships = friendshipService.getFriendships(user.getId());
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
.body(friendships);
}
@Operation(summary = "Return all accepted friends of the logged in user.", description = "Returns all friends with accepted status.")
@GetMapping("/accepted")
public ResponseEntity<List<FriendshipDTO>> getAcceptedFriendships() {
User user = getAuthenticatedUser();
return ResponseEntity.ok(friendshipService.getAcceptedFriendships(user.getId()));
User user = currentUser.get();
List<FriendshipDTO> friendships = friendshipService.getAcceptedFriendships(user.getId());
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
.body(friendships);
}
@Operation(summary = "Request a friendship with another user.", description = "Sends a friendship request to another user from the logged in user.")
@@ -110,8 +121,10 @@ public class FriendshipController {
@Operation(summary = "Get all users the logged in user has blocked.", description = "Returns a list of all users that have been blocked by the logged in user.")
@GetMapping("/blocked")
public ResponseEntity<List<MinimalUserDTO>> blockedUsers() {
User user = getAuthenticatedUser();
return ResponseEntity.ok(friendshipService.getBlockedUsers(user.getId()));
User user = currentUser.get();
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
.body(friendshipService.getBlockedUsers(user.getId()));
}
private void checkSelfAction(Long userId, Long targetUserId) {
@@ -13,12 +13,15 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.concurrent.TimeUnit;
@Validated
@RestController
@RequestMapping("/user")
@@ -41,19 +44,27 @@ public class UserController {
})
@GetMapping("/profile/{id}")
public ResponseEntity<MinimalUserDTO> getUser(@PathVariable @NotNull long id) {
return new ResponseEntity<>(this.userService.getUser(id), HttpStatus.OK);
MinimalUserDTO user = this.userService.getUser(id);
return ResponseEntity.ok()
.cacheControl(CacheControl.noCache())
.body(user);
}
@Operation(summary = "Nutzer fragt sein eigenes Profil an", description = "Ein Nutzer kann sein eigenes Profil anfragen, um dessen Informationen einzusehen.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Nutzerprofil erfolgreich abgerufen",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = MaximalUserDTO.class))),
@ApiResponse(responseCode = "304", description = "Nutzerprofil wurde seit dem letzten Abruf nicht verändert",
content = @Content(mediaType = "application/json")),
@ApiResponse(responseCode = "404", description = "Der Nutzer existiert nicht",
content = @Content(mediaType = "application/json"))
})
@GetMapping("/profile")
public ResponseEntity<MaximalUserDTO> getUser() {
return new ResponseEntity<>(this.userService.getSelf(), HttpStatus.OK);
MaximalUserDTO dto = this.userService.getSelf();
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
.body(dto);
}
@Operation(summary = "Nutzer löscht sein eigenes Profil", description = "Ein Nutzer kann sein eigenes Profil löschen. Dies entfernt alle seine Daten aus dem System.")
@@ -1,11 +1,13 @@
package SuMoC.backend.user.models;
import SuMoC.backend.images.ImageEntity;
import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToOne;
@Entity
@DiscriminatorValue("PROFILE")
public class ProfileImageEntity extends ImageEntity {
@OneToOne