Compare commits

...

5 commits

Author SHA1 Message Date
Kevin Schmidt
a78d24f711 TD-18: Match Creation
All checks were successful
Quality Check / Validate OAS (push) Successful in 42s
Quality Check / Linting (push) Successful in 1m22s
Quality Check / Validate OAS (pull_request) Successful in 41s
Quality Check / Static Analysis (push) Successful in 1m29s
Quality Check / Testing (push) Successful in 1m21s
Quality Check / Linting (pull_request) Successful in 1m13s
Quality Check / Testing (pull_request) Successful in 1m5s
Quality Check / Static Analysis (pull_request) Successful in 1m9s
2025-03-05 12:17:04 +01:00
dfcd56c7b5
Merge pull request '[Fix]: API Spec' (!8) from TD-34-spieler-listen-endpunkt into trunk
All checks were successful
Quality Check / Validate OAS (push) Successful in 37s
Build Application / build (push) Successful in 1m6s
Quality Check / Linting (push) Successful in 1m10s
Quality Check / Static Analysis (push) Successful in 1m16s
Quality Check / Testing (push) Successful in 1m12s
Build Application / build-docker (push) Successful in 20s
Build Application / release (push) Successful in 8s
Reviewed-on: #8
Reviewed-by: Snoweuph <snow+git@euph.email>
2025-03-05 10:18:07 +00:00
e38ca38e41 NOTICKET: Fix API Spec
All checks were successful
Quality Check / Validate OAS (pull_request) Successful in 40s
Quality Check / Validate OAS (push) Successful in 41s
Quality Check / Linting (push) Successful in 1m21s
Quality Check / Testing (push) Successful in 1m21s
Quality Check / Static Analysis (push) Successful in 1m32s
Quality Check / Linting (pull_request) Successful in 1m12s
Quality Check / Static Analysis (pull_request) Successful in 1m15s
Quality Check / Testing (pull_request) Successful in 49s
2025-03-05 11:15:46 +01:00
9223823239
Merge pull request '[Feature]: Spieler Listen Endpunkt' (!6) from TD-34-spieler-listen-endpunkt into trunk
All checks were successful
Quality Check / Validate OAS (push) Successful in 40s
Build Application / build (push) Successful in 1m8s
Quality Check / Testing (push) Successful in 1m11s
Quality Check / Linting (push) Successful in 1m13s
Quality Check / Static Analysis (push) Successful in 1m17s
Build Application / build-docker (push) Successful in 13s
Build Application / release (push) Successful in 11s
Reviewed-on: #6
Reviewed-by: SZUT-Kevin <kevin.schmidt9101@gmail.com>
Reviewed-by: Snoweuph <snow+git@euph.email>
2025-03-05 09:39:18 +00:00
417739e6b0 TD-34: Endpoint for getting all players and tests for this endpoint
All checks were successful
Quality Check / Validate OAS (push) Successful in 36s
Quality Check / Validate OAS (pull_request) Successful in 37s
Quality Check / Testing (push) Successful in 1m19s
Quality Check / Linting (push) Successful in 1m21s
Quality Check / Static Analysis (push) Successful in 1m27s
Quality Check / Linting (pull_request) Successful in 1m11s
Quality Check / Static Analysis (pull_request) Successful in 1m12s
Quality Check / Testing (pull_request) Successful in 45s
2025-03-05 10:33:53 +01:00
22 changed files with 530 additions and 86 deletions

View file

@ -7,7 +7,7 @@ servers:
- url: /api/v1
- url: http://localhost:8080/api/v1
security:
- JWTAuth: []
- JWTAuth: [ ]
components:
securitySchemes:
@ -83,9 +83,47 @@ components:
type: object
properties:
username:
type: string
type: string
required:
- username
#############################################
# AdministratablePlayer #
#############################################
AdministratablePlayer:
description: a Player
type: object
properties:
username:
type: string
required:
- username
#############################################
# PlayerFilter #
#############################################
PlayerFilter:
description: Configuration data for query for the getting all players endpoint
type: object
properties:
page:
type: integer
description: "Page number (zero-based index)."
pageSize:
type: integer
description: "Number of players per page."
sortBy:
type: string
description: "Field to sort by (default is username)."
order:
type: string
enum: [ ascending, descending ]
description: "Sorting order (asc or desc)."
username:
type: string
description: "Filter players by username (case-insensitive, partial match)."
required:
- page
- pageSize
- order
responses:
201PlayerCreated:
description: "201 - Player Created"
@ -198,5 +236,32 @@ paths:
$ref: "#/components/responses/401Unauthorized"
500:
$ref: "#/components/responses/500InternalError"
503:
$ref: "#/components/responses/503ServiceUnavailable"
/admin/players:
post:
operationId: "GetAllPlayers"
tags:
- admin
summary: "Retrieve a paginated list of players"
description: "Returns a paginat#ed list of players, optionally filtered by username."
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/PlayerFilter"
responses:
200:
description: "A List of all Player"
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/AdministratablePlayer"
401:
$ref: "#/components/responses/401Unauthorized"
500:
$ref: "#/components/responses/500InternalError"
503:
$ref: "#/components/responses/503ServiceUnavailable"

View file

@ -1,16 +1,26 @@
package de.towerdefence.server.admin;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.towerdefence.server.auth.UserSession;
import de.towerdefence.server.oas.AdminApi;
import de.towerdefence.server.oas.models.AdminAuthInfo;
import de.towerdefence.server.oas.models.AdministratablePlayer;
import de.towerdefence.server.oas.models.PlayerFilter;
import de.towerdefence.server.player.Player;
import de.towerdefence.server.player.PlayerRepository;
import de.towerdefence.server.utils.OrderToDirectionMapperService;
import de.towerdefence.server.utils.PlayerMapperService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.Optional;
@Controller
@ -20,6 +30,16 @@ public class AdminApiController implements AdminApi {
@Autowired
UserSession userSession;
@Autowired
PlayerRepository playerRepository;
@Autowired
PlayerMapperService playerMapperService;
@Autowired
OrderToDirectionMapperService orderToDirectionMapperService;
@Override
public Optional<ObjectMapper> getObjectMapper() {
return Optional.empty();
@ -36,4 +56,31 @@ public class AdminApiController implements AdminApi {
authInfo.setUsername(this.userSession.getUsername());
return ResponseEntity.ok(authInfo);
}
@Override
public ResponseEntity<List<AdministratablePlayer>> getAllPlayers(PlayerFilter body) {
PlayerFilter.OrderEnum order = body.getOrder();
Integer page = body.getPage();
Integer pageSize = body.getPageSize();
String sortBy = body.getSortBy();
String username = body.getUsername();
Sort.Direction direction = orderToDirectionMapperService.orderToDirection(order);
Pageable pageable = PageRequest.of(page, pageSize, Sort.by(direction, sortBy));
Page<Player> playerPage;
if (username != null && !username.isEmpty()) {
playerPage = playerRepository.findByUsernameContainingIgnoreCase(username, pageable);
} else {
playerPage = playerRepository.findAll(pageable);
}
List<AdministratablePlayer> playersMapped =
playerMapperService.mapPlayersToAdministratablePlayers(playerPage.getContent());
return ResponseEntity.ok(playersMapped);
}
}

View file

@ -1,5 +1,6 @@
package de.towerdefence.server.match;
import de.towerdefence.server.match.confirmation.ConfirmationCallbacks;
import de.towerdefence.server.player.Player;
import lombok.AllArgsConstructor;
import lombok.Getter;
@ -7,7 +8,8 @@ import lombok.Getter;
@AllArgsConstructor
@Getter
public class Match {
private final String matchId;
private final Player playerOne;
private final Player playerTwo;
private final Player player1;
private final Player player2;
}

View file

@ -0,0 +1,22 @@
package de.towerdefence.server.match;
import de.towerdefence.server.player.Player;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class MatchService {
private final Map<Player, Match> playerMatches = new HashMap<>();
public void createMatch(String matchId, Player player1, Player player2) {
Match match = new Match(matchId, player1, player2);
playerMatches.put(player1, match);
playerMatches.put(player2, match);
}
public Match get(Player player) {
return playerMatches.get(player);
}
}

View file

@ -1,28 +1,76 @@
package de.towerdefence.server.match.confirmation;
import de.towerdefence.server.match.MatchService;
import de.towerdefence.server.player.Player;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.*;
@AllArgsConstructor
@Service
public class MatchConfirmationService {
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private final Map<Player, UnconfirmedMatch> unconfirmedMatch = new HashMap<>();
final Map<UnconfirmedMatch, ScheduledFuture<?>> matchAbortTasks = new ConcurrentHashMap<>();
@Autowired
private final MatchService matchService;
public UnconfirmedMatch createMatch(Player player1,
Player player2,
ConfirmationCallbacks player1Callbacks,
ConfirmationCallbacks player2callbacks) {
Player player2,
ConfirmationCallbacks player1Callbacks,
ConfirmationCallbacks player2Callbacks) {
UnconfirmedMatch match = new UnconfirmedMatch(
player1,
player2,
player1Callbacks,
player2callbacks);
player1,
player2,
player1Callbacks,
player2Callbacks);
unconfirmedMatch.put(player1, match);
unconfirmedMatch.put(player2, match);
ScheduledFuture<?> scheduledTask = scheduler.schedule(
() -> {
matchAbortTasks.remove(match);
unconfirmedMatch.remove(match.getPlayer1());
unconfirmedMatch.remove(match.getPlayer2());
if (match.getPlayer1State() == PlayerMatchConfirmState.CONFIRMED ) {
player1Callbacks.getRequeueCallback().call(
match.getPlayer1(),
match.getMatchId(),
player1Callbacks.getFoundCallback(),
player1Callbacks.getQueuedCallback(),
player1Callbacks.getAbortCallback(),
player1Callbacks.getEstablishedCallback());
} else {
player1Callbacks.getAbortCallback().call(
match.getPlayer1(),
match.getMatchId()
);
}
if (match.getPlayer2State() == PlayerMatchConfirmState.CONFIRMED) {
player2Callbacks.getRequeueCallback().call(
match.getPlayer2(),
match.getMatchId(),
player2Callbacks.getFoundCallback(),
player2Callbacks.getQueuedCallback(),
player2Callbacks.getAbortCallback(),
player2Callbacks.getEstablishedCallback());
} else {
player2Callbacks.getAbortCallback().call(
match.getPlayer2(),
match.getMatchId()
);
}
},
UnconfirmedMatch.TTL,
TimeUnit.MILLISECONDS
);
matchAbortTasks.put(match, scheduledTask);
return match;
}
@ -63,6 +111,8 @@ public class MatchConfirmationService {
if (state == UnconfirmedMatchState.WAITING) {
return;
}
matchAbortTasks.get(match).cancel(true);
matchAbortTasks.remove(match);
unconfirmedMatch.remove(match.getPlayer1());
unconfirmedMatch.remove(match.getPlayer2());
@ -71,30 +121,91 @@ public class MatchConfirmationService {
ConfirmationCallbacks player2Callbacks = match.getPlayer2Callbacks();
switch (state) {
case ABORTED -> {
if (match.getPlayer1State() == PlayerMatchConfirmState.CONFIRMED) {
player1Callbacks.getRequeueCallback().call(
match.getPlayer1(),
match.getMatchId(),
player1Callbacks.getFoundCallback(),
player1Callbacks.getQueuedCallback(),
player1Callbacks.getAbortCallback(),
player1Callbacks.getEstablishedCallback());
}
if (match.getPlayer2State() == PlayerMatchConfirmState.CONFIRMED) {
player2Callbacks.getRequeueCallback().call(
match.getPlayer2(),
match.getMatchId(),
player2Callbacks.getFoundCallback(),
player2Callbacks.getQueuedCallback(),
player2Callbacks.getAbortCallback(),
player2Callbacks.getEstablishedCallback());
}
case ABORTED -> {
if (match.getPlayer1State() != PlayerMatchConfirmState.ABORTED ) {
player1Callbacks.getRequeueCallback().call(
match.getPlayer1(),
match.getMatchId(),
player1Callbacks.getFoundCallback(),
player1Callbacks.getQueuedCallback(),
player1Callbacks.getAbortCallback(),
player1Callbacks.getEstablishedCallback());
} else {
player1Callbacks.getAbortCallback().call(
match.getPlayer1(),
match.getMatchId()
);
}
case CONFIRMED -> {
// TODO: Create Match and Send Players the info that the Match is created
if (match.getPlayer2State() != PlayerMatchConfirmState.ABORTED) {
player2Callbacks.getRequeueCallback().call(
match.getPlayer2(),
match.getMatchId(),
player2Callbacks.getFoundCallback(),
player2Callbacks.getQueuedCallback(),
player2Callbacks.getAbortCallback(),
player2Callbacks.getEstablishedCallback());
} else {
player2Callbacks.getAbortCallback().call(
match.getPlayer2(),
match.getMatchId()
);
}
}
case CONFIRMED -> {
boolean player1successful = sendPlayerEstablished(
match.getMatchId(),
player1Callbacks.getEstablishedCallback(),
match.getPlayer1(),
match.getPlayer2()
);
boolean player2successful = sendPlayerEstablished(
match.getMatchId(),
player2Callbacks.getEstablishedCallback(),
match.getPlayer2(),
match.getPlayer1()
);
if (!player1successful || !player2successful) {
if (player1successful) {
player1Callbacks.getRequeueCallback().call(
match.getPlayer1(),
match.getMatchId(),
player1Callbacks.getFoundCallback(),
player1Callbacks.getQueuedCallback(),
player1Callbacks.getAbortCallback(),
player1Callbacks.getEstablishedCallback());
}
if (player2successful) {
player2Callbacks.getRequeueCallback().call(
match.getPlayer2(),
match.getMatchId(),
player2Callbacks.getFoundCallback(),
player2Callbacks.getQueuedCallback(),
player2Callbacks.getAbortCallback(),
player2Callbacks.getEstablishedCallback());
}
return;
}
matchService.createMatch(match.getMatchId(), match.getPlayer1(), match.getPlayer2());
}
}
}
/**
* @return if successful
*/
private boolean sendPlayerEstablished(
String matchId,
EstablishedCallback callback,
Player player,
Player opponent
) {
try {
callback.call(player, matchId, opponent);
} catch (IOException ignored) {
return false;
}
return true;
}
private Optional<UnconfirmedMatch> getPlayerMatch(Player player, String matchId) {

View file

@ -18,10 +18,10 @@ public class UnconfirmedMatch {
private final ConfirmationCallbacks player2Callbacks;
public UnconfirmedMatch(
Player player1,
Player player2,
ConfirmationCallbacks player1Callbacks,
ConfirmationCallbacks player2Callbacks) {
Player player1,
Player player2,
ConfirmationCallbacks player1Callbacks,
ConfirmationCallbacks player2Callbacks) {
this.player1 = player1;
this.player2 = player2;
this.player1Callbacks = player1Callbacks;
@ -35,16 +35,21 @@ public class UnconfirmedMatch {
public Optional<UnconfirmedMatchState> setPlayerConfirmState(Player player, PlayerMatchConfirmState state) {
Optional<MatchPlayer> matchPlayer = getMatchPlayer(player);
if(matchPlayer.isEmpty()){
if (matchPlayer.isEmpty()) {
return Optional.empty();
}
switch (matchPlayer.get()){
case ONE -> player1State = state;
case TWO -> player2State = state;
switch (matchPlayer.get()) {
case ONE -> player1State = state;
case TWO -> player2State = state;
}
if (player1State == PlayerMatchConfirmState.ABORTED || player2State == PlayerMatchConfirmState.ABORTED) {
boolean timedOut = Instant.now().toEpochMilli() > created + TTL;
if (
timedOut
|| player1State == PlayerMatchConfirmState.ABORTED
|| player2State == PlayerMatchConfirmState.ABORTED
) {
return Optional.of(UnconfirmedMatchState.ABORTED);
}
if (player1State == PlayerMatchConfirmState.UNKNOWN || player2State == PlayerMatchConfirmState.UNKNOWN) {
@ -53,31 +58,31 @@ public class UnconfirmedMatch {
return Optional.of(UnconfirmedMatchState.CONFIRMED);
}
public Optional<PlayerMatchConfirmState> getPlayerState(Player player){
public Optional<PlayerMatchConfirmState> getPlayerState(Player player) {
Optional<MatchPlayer> matchPlayer = getMatchPlayer(player);
if(matchPlayer.isEmpty()){
if (matchPlayer.isEmpty()) {
return Optional.empty();
}
return switch (matchPlayer.get()){
return switch (matchPlayer.get()) {
case ONE -> Optional.of(player1State);
case TWO -> Optional.of(player2State);
};
}
private enum MatchPlayer{
private enum MatchPlayer {
ONE,
TWO
}
private Optional<MatchPlayer> getMatchPlayer(Player player){
private Optional<MatchPlayer> getMatchPlayer(Player player) {
boolean isPlayerOne = player.equals(player1);
boolean isPlayerTwo = player.equals(player2);
if (!isPlayerOne && !isPlayerTwo) {
return Optional.empty();
}
if (isPlayerOne){
if (isPlayerOne) {
return Optional.of(MatchPlayer.ONE);
}
return Optional.of(MatchPlayer.TWO);

View file

@ -1,8 +1,11 @@
package de.towerdefence.server.player;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PlayerRepository extends JpaRepository<Player, Long> {
Player findByUsername(String username);
boolean existsByUsername(String username);
Page<Player> findByUsernameContainingIgnoreCase(String username, Pageable pageable);
}

View file

@ -1,11 +1,12 @@
package de.towerdefence.server.server.channels;
import de.towerdefence.server.match.MatchService;
import de.towerdefence.server.match.confirmation.MatchConfirmationService;
import de.towerdefence.server.match.queue.MatchQueueService;
import de.towerdefence.server.server.JsonWebsocketHandler;
import de.towerdefence.server.server.channels.connection.ConnectionWebsocketHandler;
import de.towerdefence.server.server.channels.match.MatchWebsocketHandler;
import de.towerdefence.server.server.channels.matchmaking.MatchmakingWebsocketHandler;
import de.towerdefence.server.server.channels.time.TimeWebsocketHandler;
import de.towerdefence.server.session.SessionsService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
@ -25,6 +26,8 @@ public class WebsocketConfig implements WebSocketConfigurer {
private final MatchQueueService matchQueueService;
@Autowired
private final MatchConfirmationService matchConfirmationService;
@Autowired
private final MatchService matchService;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
@ -34,7 +37,7 @@ public class WebsocketConfig implements WebSocketConfigurer {
this.matchQueueService,
this.matchConfirmationService
));
registerJsonChannel(registry, new TimeWebsocketHandler(this.sessionsService));
registerJsonChannel(registry, new MatchWebsocketHandler(this.sessionsService, this.matchService));
}
private void registerJsonChannel(WebSocketHandlerRegistry registry, JsonWebsocketHandler handler){

View file

@ -34,6 +34,9 @@ public class ConnectionWebsocketHandler extends JsonWebsocketHandler {
private void handleRequestConnectionToken(WebSocketSession session, String payload) throws Exception {
RequestConnectionTokenMessage msg = objectMapper.readValue(payload, RequestConnectionTokenMessage.class);
Player player = this.sessionPlayers.get(session);
if (msg.getChannel() != Channel.MATCHMAKING) {
return;
}
String jwt = this.sessionsService.createSession(player, msg.getChannel());
new ProvidedConnectionTokenMessage(msg.getChannel(), jwt).send(session);
}

View file

@ -1,5 +1,6 @@
package de.towerdefence.server.server.channels.time;
package de.towerdefence.server.server.channels.match;
import de.towerdefence.server.match.MatchService;
import de.towerdefence.server.server.JsonWebsocketHandler;
import de.towerdefence.server.session.Channel;
import de.towerdefence.server.session.SessionsService;
@ -9,24 +10,25 @@ import java.io.IOException;
import java.util.Map;
import java.util.concurrent.*;
public class TimeWebsocketHandler extends JsonWebsocketHandler {
public class MatchWebsocketHandler extends JsonWebsocketHandler {
private final Map<WebSocketSession, ScheduledFuture<?>> sessionTaskMap = new ConcurrentHashMap<>();
final Map<WebSocketSession, ScheduledFuture<?>> sessionTaskMap = new ConcurrentHashMap<>();
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private final MatchService matchService;
public TimeWebsocketHandler(SessionsService sessionsService) {
super(Channel.TIME, sessionsService);
public MatchWebsocketHandler(SessionsService sessionsService, MatchService matchService) {
super(Channel.MATCH, sessionsService);
this.matchService = matchService;
}
@Override
public void afterConnectionEstablished(WebSocketSession session) {
super.afterConnectionEstablished(session);
ScheduledFuture<?> scheduledTask = scheduler.scheduleAtFixedRate(
() -> sendCurrentTime(session),
0,
1,
TimeUnit.MILLISECONDS
() -> sendCurrentTime(session),
0,
1,
TimeUnit.SECONDS
);
sessionTaskMap.put(session, scheduledTask);
}
@ -34,10 +36,13 @@ public class TimeWebsocketHandler extends JsonWebsocketHandler {
private void sendCurrentTime(WebSocketSession session) {
ScheduledFuture<?> task = sessionTaskMap.get(session);
try {
if(!session.isOpen()){
if (!session.isOpen()) {
throw new RuntimeException("Session is not open");
}
new TimeMessage(System.currentTimeMillis()).send(session);
new TimeMessage(
System.currentTimeMillis(),
matchService.get(this.sessionPlayers.get(session)).getMatchId()
).send(session);
} catch (RuntimeException | IOException e) {
task.cancel(true);
sessionTaskMap.remove(session);

View file

@ -1,4 +1,4 @@
package de.towerdefence.server.server.channels.time;
package de.towerdefence.server.server.channels.match;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
@ -10,6 +10,7 @@ import java.util.Map;
@AllArgsConstructor
public class TimeMessage extends JsonMessage {
private final long time;
private final String matchId;
@Override
protected String getMessageId() {
@ -18,6 +19,9 @@ public class TimeMessage extends JsonMessage {
@Override
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
return Map.of("time", factory.numberNode(this.time));
return Map.of(
"time", factory.numberNode(this.time),
"matchId", factory.textNode(this.matchId)
);
}
}

View file

@ -46,6 +46,7 @@ public class MatchmakingWebsocketHandler extends JsonWebsocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
try {
String payload = message.getPayload();
switch (objectMapper.readTree(payload).get("$id").asText()) {
case MatchSetSearchStateMessage.MESSAGE_ID -> handleMatchSetSearchStateMessage(session, payload);
@ -96,7 +97,8 @@ public class MatchmakingWebsocketHandler extends JsonWebsocketHandler {
private void onEstablished(Player player, String matchId, Player opponent) throws IOException {
WebSocketSession session = playerSessions.get(player);
MatchEstablishedMessage msg = new MatchEstablishedMessage(matchId, opponent.getUsername());
String token = this.sessionsService.createSession(player, Channel.MATCH);
MatchEstablishedMessage msg = new MatchEstablishedMessage(matchId, opponent.getUsername(), token);
msg.send(session);
}

View file

@ -1,5 +1,6 @@
package de.towerdefence.server.server.channels.matchmaking.bi;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
@ -12,7 +13,6 @@ import java.util.Map;
@Getter
@NotNull
@AllArgsConstructor
public class MatchSetSearchStateMessage extends JsonMessage {
public static final String MESSAGE_ID = "MatchSetSearchState";
@ -26,6 +26,15 @@ public class MatchSetSearchStateMessage extends JsonMessage {
this(MESSAGE_ID, searching);
}
@JsonCreator
public MatchSetSearchStateMessage(
@JsonProperty("$id") String messageId,
@JsonProperty("searching") boolean searching
) {
this.messageId = messageId;
this.searching = searching;
}
@Override
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
return Map.of(

View file

@ -11,6 +11,7 @@ import java.util.Map;
public class MatchEstablishedMessage extends JsonMessage {
private String matchId;
private String opponentName;
private String token;
@Override
protected String getMessageId() {
@ -20,8 +21,9 @@ public class MatchEstablishedMessage extends JsonMessage {
@Override
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
return Map.of(
"matchId", factory.textNode(this.matchId),
"opponentName", factory.textNode(this.opponentName)
"matchId", factory.textNode(this.matchId),
"opponentName", factory.textNode(this.opponentName),
"token", factory.textNode(this.token)
);
}
}

View file

@ -9,7 +9,7 @@ import lombok.Getter;
public enum Channel {
CONNECTION("connection"),
MATCHMAKING("matchmaking"),
TIME("time");
MATCH("match");
private final String jsonName;

View file

@ -0,0 +1,18 @@
package de.towerdefence.server.utils;
import de.towerdefence.server.oas.models.PlayerFilter;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
@Component
public class OrderToDirectionMapperService {
public Sort.Direction orderToDirection(PlayerFilter.OrderEnum order) {
if (order == PlayerFilter.OrderEnum.ASCENDING) {
return Sort.Direction.ASC;
} else {
return Sort.Direction.DESC;
}
}
}

View file

@ -0,0 +1,28 @@
package de.towerdefence.server.utils;
import de.towerdefence.server.oas.models.AdministratablePlayer;
import de.towerdefence.server.player.Player;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class PlayerMapperService {
public List<AdministratablePlayer> mapPlayersToAdministratablePlayers(List<Player> players) {
List<AdministratablePlayer> administratablePlayers = new ArrayList<>();
for (Player player : players) {
AdministratablePlayer apiPlayer = new AdministratablePlayer();
apiPlayer.setUsername(player.getUsername());
administratablePlayers.add(apiPlayer);
}
return administratablePlayers;
}
public AdministratablePlayer mapPlayerToAdministratablePlayer(Player player) {
AdministratablePlayer administratablePlayer = new AdministratablePlayer();
administratablePlayer.setUsername(player.getUsername());
return administratablePlayer;
}
}

View file

@ -14,4 +14,9 @@
<Class name="de.towerdefence.server.session.JwtService"/>
<Bug code="M,B,CT"/>
</Match>
<Match>
<!-- Spotbugs does not detect that the other cases are handled above in an if-->
<Class name="de.towerdefence.server.match.confirmation.MatchConfirmationService"/>
<Bug code="M,D,SF"/>
</Match>
</FindBugsFilter>

View file

@ -1,7 +1,9 @@
package de.towerdefence.server;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.towerdefence.server.player.Player;
import de.towerdefence.server.player.PlayerRepository;
import de.towerdefence.server.player.PlayerService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
@ -10,6 +12,10 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@ActiveProfiles("test")
@ -23,10 +29,27 @@ public abstract class IntegrationTest {
protected ObjectMapper objectMapper;
@Autowired
protected PlayerRepository playerRepository;
@Autowired
protected PlayerService playerService;
@BeforeEach
void setUp() {
playerRepository.deleteAll();
Map<String, String> players = new HashMap<>();
players.put("Alex", "1234");
players.put("Zorro", "1234");
players.forEach((username, password) -> {
Player player = new Player();
player.setUsername(username);
try {
playerService.setPassword(player, password);
playerRepository.saveAndFlush(player);
} catch (NoSuchAlgorithmException e) {
System.err.println("Error setting password for player: " + username);
}
});
}
@AfterEach
@ -34,5 +57,5 @@ public abstract class IntegrationTest {
playerRepository.deleteAll();
}
}
}

View file

@ -0,0 +1,85 @@
package de.towerdefence.server.server;
import de.towerdefence.server.IntegrationTest;
import de.towerdefence.server.oas.models.PlayerFilter;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
class GetAllPlayersTest extends IntegrationTest {
private MockHttpServletRequestBuilder createGetAllPlayersRequest(String requestBody) {
return MockMvcRequestBuilders.post(baseUri + "/admin/players")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody);
}
@Test
void playersExist() throws Exception {
PlayerFilter playerFilter = new PlayerFilter();
playerFilter.setPage(0);
playerFilter.setPageSize(10);
playerFilter.setOrder(PlayerFilter.OrderEnum.DESCENDING);
playerFilter.setUsername("");
playerFilter.setSortBy("username");
String requestBody = this.objectMapper.writeValueAsString(playerFilter);
this.mvc.perform(createGetAllPlayersRequest(requestBody))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$[0]").exists());
}
@Test
void playersSortedByAsc() throws Exception {
PlayerFilter playerFilter = new PlayerFilter();
playerFilter.setPage(0);
playerFilter.setPageSize(10);
playerFilter.setOrder(PlayerFilter.OrderEnum.ASCENDING);
playerFilter.setUsername("");
playerFilter.setSortBy("username");
String requestBody = this.objectMapper.writeValueAsString(playerFilter);
this.mvc.perform(createGetAllPlayersRequest(requestBody))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].username").value("Alex"))
.andExpect(jsonPath("$[1].username").value("Zorro"));
}
@Test
void playersSortedByDesc() throws Exception {
PlayerFilter playerFilter = new PlayerFilter();
playerFilter.setPage(0);
playerFilter.setPageSize(10);
playerFilter.setOrder(PlayerFilter.OrderEnum.DESCENDING);
playerFilter.setUsername("");
playerFilter.setSortBy("username");
String requestBody = this.objectMapper.writeValueAsString(playerFilter);
this.mvc.perform(createGetAllPlayersRequest(requestBody))
.andExpect(status().isOk())
.andExpect(jsonPath("$[1].username").value("Alex"))
.andExpect(jsonPath("$[0].username").value("Zorro"));
}
@Test
void playersFiltered() throws Exception {
PlayerFilter playerFilter = new PlayerFilter();
playerFilter.setPage(0);
playerFilter.setPageSize(10);
playerFilter.setOrder(PlayerFilter.OrderEnum.ASCENDING);
playerFilter.setUsername("Alex");
playerFilter.setSortBy("username");
String requestBody = this.objectMapper.writeValueAsString(playerFilter);
this.mvc.perform(createGetAllPlayersRequest(requestBody))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].username").value("Alex"))
.andExpect(jsonPath("$").isNotEmpty());
}
}

View file

@ -30,6 +30,4 @@ public class PlayerRegistrationTest extends IntegrationTest {
.content(this.objectMapper.writeValueAsString(playerRegistrationData))
.contentType(MediaType.APPLICATION_JSON);
}
}

View file

@ -66,7 +66,7 @@ channels:
matchmaking:
title: Matchmaking
description: |
description: |
A Channel used to search for a match and
to receive one
messages:
@ -147,16 +147,18 @@ channels:
type: string
opponentName:
type: string
token:
$ref: "#/components/schemas/JWT"
required:
- $id
- matchId
- opponentName
- token
time:
title: Time
match:
title: Match
description: |
A Simple example channel for receiving
the current Unix time
Channel for managing an active match
messages:
CurrentUnixTime:
description: The Current time in Unix Time
@ -170,9 +172,14 @@ channels:
time:
type: integer
format: int64
matchId:
type: string
required:
- $id
- time
- matchId
operations:
requestConnectionToken:
@ -227,13 +234,13 @@ operations:
$ref: "#/channels/matchmaking"
messages:
- $ref: "#/channels/matchmaking/messages/MatchEstablished"
updateTime:
title: Updates of the current Unix Time
matchUpdate:
title: MatchUpdate
action: receive
channel:
$ref: "#/channels/time"
$ref: "#/channels/match"
messages:
- $ref: "#/channels/time/messages/CurrentUnixTime"
- $ref: "#/channels/match/messages/CurrentUnixTime"
components:
securitySchemes:
@ -252,7 +259,4 @@ components:
Channel:
type: string
enum:
- connection
- matchmaking
- time