From 46d369c8ed3975623b08cbb79afbe147d074f845 Mon Sep 17 00:00:00 2001 From: vraskulin Date: Mon, 9 Jan 2017 19:47:03 +0300 Subject: [PATCH] Big refactoring (server) I used Intellij IDEA to automatically refactor code to achive 3 goals. 1) get rid of anonymouse classes, and replace the with lamba to get more readeable and clean code (like in TableWaitingDialog). 2) make effectively final variables actually final to avoid inadvertent changes on it in further releases and keep objects as immutable, as possible. 3) Get rid of unused imports (most of the changes) in whole project classes. --- Mage.Server/pom.xml | 4 +- .../mage/server/AuthorizedUserRepository.java | 2 +- .../main/java/mage/server/ChatManager.java | 4 +- .../java/mage/server/DisconnectReason.java | 2 +- .../java/mage/server/ExtensionPackage.java | 6 +- .../main/java/mage/server/MageServerImpl.java | 491 +++++++----------- .../src/main/java/mage/server/Main.java | 9 +- .../java/mage/server/TableController.java | 30 +- .../main/java/mage/server/TableManager.java | 15 +- .../src/main/java/mage/server/User.java | 2 +- .../main/java/mage/server/UserManager.java | 47 +- .../java/mage/server/draft/CubeFactory.java | 10 +- .../mage/server/draft/DraftController.java | 17 +- .../java/mage/server/draft/DraftSession.java | 15 +- .../server/game/DeckValidatorFactory.java | 4 +- .../java/mage/server/game/GameController.java | 428 ++++++--------- .../java/mage/server/game/GameFactory.java | 4 +- .../java/mage/server/game/GameReplay.java | 10 +- .../mage/server/game/GameSessionPlayer.java | 45 +- .../mage/server/game/GameSessionWatcher.java | 6 +- .../java/mage/server/game/GamesRoomImpl.java | 19 +- .../java/mage/server/game/PlayerFactory.java | 4 +- .../java/mage/server/game/ReplaySession.java | 2 +- .../server/record/TableRecordRepository.java | 2 +- .../server/record/UserStatsRepository.java | 2 +- .../services/impl/FeedbackServiceImpl.java | 2 +- .../tournament/TournamentController.java | 117 ++--- .../server/tournament/TournamentFactory.java | 4 +- .../server/tournament/TournamentSession.java | 17 +- .../mage/server/util/ServerMessagesUtil.java | 7 +- .../java/mage/server/util/SystemUtil.java | 5 +- 31 files changed, 510 insertions(+), 822 deletions(-) diff --git a/Mage.Server/pom.xml b/Mage.Server/pom.xml index fbd5e36462..7aa1add141 100644 --- a/Mage.Server/pom.xml +++ b/Mage.Server/pom.xml @@ -229,8 +229,8 @@ org.apache.maven.plugins maven-compiler-plugin - 1.7 - 1.7 + 1.8 + 1.8 diff --git a/Mage.Server/src/main/java/mage/server/AuthorizedUserRepository.java b/Mage.Server/src/main/java/mage/server/AuthorizedUserRepository.java index 4829a2fbdf..a081704944 100644 --- a/Mage.Server/src/main/java/mage/server/AuthorizedUserRepository.java +++ b/Mage.Server/src/main/java/mage/server/AuthorizedUserRepository.java @@ -33,7 +33,7 @@ public enum AuthorizedUserRepository { private Dao dao; - private AuthorizedUserRepository() { + AuthorizedUserRepository() { File file = new File("db"); if (!file.exists()) { file.mkdirs(); diff --git a/Mage.Server/src/main/java/mage/server/ChatManager.java b/Mage.Server/src/main/java/mage/server/ChatManager.java index 6ee8435d10..d9581e0cc7 100644 --- a/Mage.Server/src/main/java/mage/server/ChatManager.java +++ b/Mage.Server/src/main/java/mage/server/ChatManager.java @@ -50,7 +50,7 @@ import org.apache.log4j.Logger; public class ChatManager { private static final Logger logger = Logger.getLogger(ChatManager.class); - private static HashMap userMessages = new HashMap<>(); + private static final HashMap userMessages = new HashMap<>(); private static final ChatManager INSTANCE = new ChatManager(); @@ -117,7 +117,7 @@ public class ChatManager { return false; } - Pattern cardNamePattern = Pattern.compile("\\[(.*?)\\]"); + final Pattern cardNamePattern = Pattern.compile("\\[(.*?)\\]"); public void broadcast(UUID chatId, String userName, String message, MessageColor color, boolean withTime, MessageType messageType, SoundToPlay soundToPlay) { ChatSession chatSession = chatSessions.get(chatId); diff --git a/Mage.Server/src/main/java/mage/server/DisconnectReason.java b/Mage.Server/src/main/java/mage/server/DisconnectReason.java index 8f1bf126f2..c751814f7b 100644 --- a/Mage.Server/src/main/java/mage/server/DisconnectReason.java +++ b/Mage.Server/src/main/java/mage/server/DisconnectReason.java @@ -6,5 +6,5 @@ package mage.server; */ public enum DisconnectReason { - LostConnection, Disconnected, CleaningUp, ConnectingOtherInstance, AdminDisconnect, SessionExpired, Undefined; + LostConnection, Disconnected, CleaningUp, ConnectingOtherInstance, AdminDisconnect, SessionExpired, Undefined } diff --git a/Mage.Server/src/main/java/mage/server/ExtensionPackage.java b/Mage.Server/src/main/java/mage/server/ExtensionPackage.java index 1d49c39c5b..1a9d0c4c5c 100644 --- a/Mage.Server/src/main/java/mage/server/ExtensionPackage.java +++ b/Mage.Server/src/main/java/mage/server/ExtensionPackage.java @@ -40,9 +40,9 @@ import java.util.Map; * @author Lymia */ public abstract class ExtensionPackage { - protected List expansions = new ArrayList<>(); - protected Map deckTypes = new HashMap<>(); - protected Map draftCubes = new HashMap<>(); + protected final List expansions = new ArrayList<>(); + protected final Map deckTypes = new HashMap<>(); + protected final Map draftCubes = new HashMap<>(); /** * @return A list of expansions included in this custom set package. diff --git a/Mage.Server/src/main/java/mage/server/MageServerImpl.java b/Mage.Server/src/main/java/mage/server/MageServerImpl.java index 7b77141f30..5e14476ce6 100644 --- a/Mage.Server/src/main/java/mage/server/MageServerImpl.java +++ b/Mage.Server/src/main/java/mage/server/MageServerImpl.java @@ -314,12 +314,9 @@ public class MageServerImpl implements MageServer { @Override public void removeTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { - execute("removeTable", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().removeTable(userId, tableId); - } + execute("removeTable", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().removeTable(userId, tableId); }); } @@ -377,13 +374,10 @@ public class MageServerImpl implements MageServer { @Override public void updateDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) throws MageException, GameException { - execute("updateDeck", sessionId, new Action() { - @Override - public void execute() throws MageException { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().updateDeck(userId, tableId, deckList); - logger.trace("Session " + sessionId + " updated deck"); - } + execute("updateDeck", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().updateDeck(userId, tableId, deckList); + logger.trace("Session " + sessionId + " updated deck"); }); } @@ -470,12 +464,9 @@ public class MageServerImpl implements MageServer { if (!TableManager.getInstance().getController(tableId).changeTableStateToStarting()) { return false; } - execute("startMatch", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().startMatch(userId, roomId, tableId); - } + execute("startMatch", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().startMatch(userId, roomId, tableId); }); return true; } @@ -495,12 +486,9 @@ public class MageServerImpl implements MageServer { if (!TableManager.getInstance().getController(tableId).changeTableStateToStarting()) { return false; } - execute("startTournament", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().startTournament(userId, roomId, tableId); - } + execute("startTournament", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().startTournament(userId, roomId, tableId); }); return true; } @@ -521,12 +509,7 @@ public class MageServerImpl implements MageServer { public void sendChatMessage(final UUID chatId, final String userName, final String message) throws MageException { try { callExecutor.execute( - new Runnable() { - @Override - public void run() { - ChatManager.getInstance().broadcast(chatId, userName, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE, true, ChatMessage.MessageType.TALK, null); - } - } + () -> ChatManager.getInstance().broadcast(chatId, userName, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE, true, ChatMessage.MessageType.TALK, null) ); } catch (Exception ex) { handleException(ex); @@ -535,26 +518,20 @@ public class MageServerImpl implements MageServer { @Override public void joinChat(final UUID chatId, final String sessionId, final String userName) throws MageException { - execute("joinChat", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ChatManager.getInstance().joinChat(chatId, userId); - } + execute("joinChat", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ChatManager.getInstance().joinChat(chatId, userId); }); } @Override public void leaveChat(final UUID chatId, final String sessionId) throws MageException { - execute("leaveChat", sessionId, new Action() { - @Override - public void execute() { - if (chatId != null) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ChatManager.getInstance().leaveChat(chatId, userId); - } else { - logger.warn("The chatId is null. sessionId = " + sessionId); - } + execute("leaveChat", sessionId, () -> { + if (chatId != null) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ChatManager.getInstance().leaveChat(chatId, userId); + } else { + logger.warn("The chatId is null. sessionId = " + sessionId); } }); } @@ -594,12 +571,9 @@ public class MageServerImpl implements MageServer { @Override public void swapSeats(final String sessionId, final UUID roomId, final UUID tableId, final int seatNum1, final int seatNum2) throws MageException { - execute("swapSeats", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2); - } + execute("swapSeats", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2); }); } @@ -610,12 +584,9 @@ public class MageServerImpl implements MageServer { // table was already started, so player can't leave anymore now return false; } - execute("leaveTable", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId); - } + execute("leaveTable", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId); }); return true; } @@ -633,34 +604,25 @@ public class MageServerImpl implements MageServer { @Override public void joinGame(final UUID gameId, final String sessionId) throws MageException { - execute("joinGame", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().joinGame(gameId, userId); - } + execute("joinGame", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().joinGame(gameId, userId); }); } @Override public void joinDraft(final UUID draftId, final String sessionId) throws MageException { - execute("joinDraft", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - DraftManager.getInstance().joinDraft(draftId, userId); - } + execute("joinDraft", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + DraftManager.getInstance().joinDraft(draftId, userId); }); } @Override public void joinTournament(final UUID tournamentId, final String sessionId) throws MageException { - execute("joinTournament", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TournamentManager.getInstance().joinTournament(tournamentId, userId); - } + execute("joinTournament", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TournamentManager.getInstance().joinTournament(tournamentId, userId); }); } @@ -688,76 +650,61 @@ public class MageServerImpl implements MageServer { @Override public void sendPlayerUUID(final UUID gameId, final String sessionId, final UUID data) throws MageException { - execute("sendPlayerUUID", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { + execute("sendPlayerUUID", sessionId, () -> { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { // logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName()); - user.sendPlayerUUID(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } + user.sendPlayerUUID(gameId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); } }); } @Override public void sendPlayerString(final UUID gameId, final String sessionId, final String data) throws MageException { - execute("sendPlayerString", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerString(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } + execute("sendPlayerString", sessionId, () -> { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { + user.sendPlayerString(gameId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); } }); } @Override public void sendPlayerManaType(final UUID gameId, final UUID playerId, final String sessionId, final ManaType data) throws MageException { - execute("sendPlayerManaType", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerManaType(gameId, playerId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } + execute("sendPlayerManaType", sessionId, () -> { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { + user.sendPlayerManaType(gameId, playerId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); } }); } @Override public void sendPlayerBoolean(final UUID gameId, final String sessionId, final Boolean data) throws MageException { - execute("sendPlayerBoolean", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerBoolean(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } + execute("sendPlayerBoolean", sessionId, () -> { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { + user.sendPlayerBoolean(gameId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); } }); } @Override public void sendPlayerInteger(final UUID gameId, final String sessionId, final Integer data) throws MageException { - execute("sendPlayerInteger", sessionId, new Action() { - @Override - public void execute() { - User user = SessionManager.getInstance().getUser(sessionId); - if (user != null) { - user.sendPlayerInteger(gameId, data); - } else { - logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); - } + execute("sendPlayerInteger", sessionId, () -> { + User user = SessionManager.getInstance().getUser(sessionId); + if (user != null) { + user.sendPlayerInteger(gameId, data); + } else { + logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); } }); } @@ -780,81 +727,66 @@ public class MageServerImpl implements MageServer { @Override public void sendCardMark(final UUID draftId, final String sessionId, final UUID cardPick) throws MageException { - execute("sendCardMark", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - DraftManager.getInstance().sendCardMark(draftId, session.getUserId(), cardPick); - } else { - logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); - } + execute("sendCardMark", sessionId, () -> { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) { + DraftManager.getInstance().sendCardMark(draftId, session.getUserId(), cardPick); + } else { + logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); } }); } @Override public void quitMatch(final UUID gameId, final String sessionId) throws MageException { - execute("quitMatch", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - GameManager.getInstance().quitMatch(gameId, session.getUserId()); - } else { - logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); - } + execute("quitMatch", sessionId, () -> { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) { + GameManager.getInstance().quitMatch(gameId, session.getUserId()); + } else { + logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); } }); } @Override public void quitTournament(final UUID tournamentId, final String sessionId) throws MageException { - execute("quitTournament", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session != null) { - TournamentManager.getInstance().quit(tournamentId, session.getUserId()); - } else { - logger.error("Session not found sessionId: " + sessionId + " tournamentId:" + tournamentId); - } + execute("quitTournament", sessionId, () -> { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session != null) { + TournamentManager.getInstance().quit(tournamentId, session.getUserId()); + } else { + logger.error("Session not found sessionId: " + sessionId + " tournamentId:" + tournamentId); } }); } @Override public void quitDraft(final UUID draftId, final String sessionId) throws MageException { - execute("quitDraft", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session == null) { - logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); - return; - } - UUID tableId = DraftManager.getInstance().getControllerByDraftId(draftId).getTableId(); - Table table = TableManager.getInstance().getTable(tableId); - if (table.isTournament()) { - UUID tournamentId = table.getTournament().getId(); - TournamentManager.getInstance().quit(tournamentId, session.getUserId()); - } + execute("quitDraft", sessionId, () -> { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session == null) { + logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); + return; + } + UUID tableId = DraftManager.getInstance().getControllerByDraftId(draftId).getTableId(); + Table table = TableManager.getInstance().getTable(tableId); + if (table.isTournament()) { + UUID tournamentId = table.getTournament().getId(); + TournamentManager.getInstance().quit(tournamentId, session.getUserId()); } }); } @Override public void sendPlayerAction(final PlayerAction playerAction, final UUID gameId, final String sessionId, final Object data) throws MageException { - execute("sendPlayerAction", sessionId, new Action() { - @Override - public void execute() { - Session session = SessionManager.getInstance().getSession(sessionId); - if (session == null) { - logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); - return; - } - GameManager.getInstance().sendPlayerAction(playerAction, gameId, session.getUserId(), data); + execute("sendPlayerAction", sessionId, () -> { + Session session = SessionManager.getInstance().getSession(sessionId); + if (session == null) { + logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); + return; } + GameManager.getInstance().sendPlayerAction(playerAction, gameId, session.getUserId(), data); }); } @@ -882,94 +814,70 @@ public class MageServerImpl implements MageServer { @Override public void watchGame(final UUID gameId, final String sessionId) throws MageException { - execute("watchGame", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().watchGame(gameId, userId); - } + execute("watchGame", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().watchGame(gameId, userId); }); } @Override public void stopWatching(final UUID gameId, final String sessionId) throws MageException { - execute("stopWatching", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - User user = UserManager.getInstance().getUser(userId); - if (user != null) { - GameManager.getInstance().stopWatching(gameId, userId); - user.removeGameWatchInfo(gameId); - } - + execute("stopWatching", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + User user = UserManager.getInstance().getUser(userId); + if (user != null) { + GameManager.getInstance().stopWatching(gameId, userId); + user.removeGameWatchInfo(gameId); } + }); } @Override public void replayGame(final UUID gameId, final String sessionId) throws MageException { - execute("replayGame", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().replayGame(gameId, userId); - } + execute("replayGame", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().replayGame(gameId, userId); }); } @Override public void startReplay(final UUID gameId, final String sessionId) throws MageException { - execute("startReplay", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().startReplay(gameId, userId); - } + execute("startReplay", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().startReplay(gameId, userId); }); } @Override public void stopReplay(final UUID gameId, final String sessionId) throws MageException { - execute("stopReplay", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().stopReplay(gameId, userId); - } + execute("stopReplay", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().stopReplay(gameId, userId); }); } @Override public void nextPlay(final UUID gameId, final String sessionId) throws MageException { - execute("nextPlay", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().nextPlay(gameId, userId); - } + execute("nextPlay", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().nextPlay(gameId, userId); }); } @Override public void previousPlay(final UUID gameId, final String sessionId) throws MageException { - execute("previousPlay", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().previousPlay(gameId, userId); - } + execute("previousPlay", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().previousPlay(gameId, userId); }); } @Override public void skipForward(final UUID gameId, final String sessionId, final int moves) throws MageException { - execute("skipForward", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - ReplayManager.getInstance().skipForward(gameId, userId, moves); - } + execute("skipForward", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + ReplayManager.getInstance().skipForward(gameId, userId, moves); }); } @@ -996,13 +904,10 @@ public class MageServerImpl implements MageServer { @Override public void cheat(final UUID gameId, final String sessionId, final UUID playerId, final DeckCardLists deckList) throws MageException { - execute("cheat", sessionId, new Action() { - @Override - public void execute() { - if (testMode) { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - GameManager.getInstance().cheat(gameId, userId, playerId, deckList); - } + execute("cheat", sessionId, () -> { + if (testMode) { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + GameManager.getInstance().cheat(gameId, userId, playerId, deckList); } }); } @@ -1071,74 +976,55 @@ public class MageServerImpl implements MageServer { @Override public void disconnectUser(final String sessionId, final String userSessionId) throws MageException { - execute("disconnectUser", sessionId, new Action() { - @Override - public void execute() { - SessionManager.getInstance().disconnectUser(sessionId, userSessionId); - } - }); + execute("disconnectUser", sessionId, () -> SessionManager.getInstance().disconnectUser(sessionId, userSessionId)); } @Override public void muteUser(final String sessionId, final String userName, final long durationMinutes) throws MageException { - execute("muteUser", sessionId, new Action() { - @Override - public void execute() { - User user = UserManager.getInstance().getUserByName(userName); - if (user != null) { - Date muteUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE)); - user.showUserMessage("Admin info", "You were muted for chat messages until " + SystemUtil.dateFormat.format(muteUntil) + "."); - user.setChatLockedUntil(muteUntil); - } - + execute("muteUser", sessionId, () -> { + User user = UserManager.getInstance().getUserByName(userName); + if (user != null) { + Date muteUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE)); + user.showUserMessage("Admin info", "You were muted for chat messages until " + SystemUtil.dateFormat.format(muteUntil) + "."); + user.setChatLockedUntil(muteUntil); } + }); } @Override public void lockUser(final String sessionId, final String userName, final long durationMinutes) throws MageException { - execute("lockUser", sessionId, new Action() { - @Override - public void execute() { - User user = UserManager.getInstance().getUserByName(userName); - if (user != null) { - Date lockUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE)); - user.showUserMessage("Admin info", "Your user profile was locked until " + SystemUtil.dateFormat.format(lockUntil) + "."); - user.setLockedUntil(lockUntil); - if (user.isConnected()) { - SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId()); - } + execute("lockUser", sessionId, () -> { + User user = UserManager.getInstance().getUserByName(userName); + if (user != null) { + Date lockUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE)); + user.showUserMessage("Admin info", "Your user profile was locked until " + SystemUtil.dateFormat.format(lockUntil) + "."); + user.setLockedUntil(lockUntil); + if (user.isConnected()) { + SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId()); } - } + }); } @Override public void toggleActivation(final String sessionId, final String userName) throws MageException { - execute("toggleActivation", sessionId, new Action() { - @Override - public void execute() { - User user = UserManager.getInstance().getUserByName(userName); - if (user != null) { - user.setActive(!user.isActive()); - if (!user.isActive() && user.isConnected()) { - SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId()); - } + execute("toggleActivation", sessionId, () -> { + User user = UserManager.getInstance().getUserByName(userName); + if (user != null) { + user.setActive(!user.isActive()); + if (!user.isActive() && user.isConnected()) { + SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId()); } - } + }); } @Override public void endUserSession(final String sessionId, final String userSessionId) throws MageException { - execute("endUserSession", sessionId, new Action() { - @Override - public void execute() { - SessionManager.getInstance().endUserSession(sessionId, userSessionId); - } - }); + execute("endUserSession", sessionId, () -> SessionManager.getInstance().endUserSession(sessionId, userSessionId)); } /** @@ -1150,12 +1036,9 @@ public class MageServerImpl implements MageServer { */ @Override public void removeTable(final String sessionId, final UUID tableId) throws MageException { - execute("removeTable", sessionId, new Action() { - @Override - public void execute() { - UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); - TableManager.getInstance().removeTable(userId, tableId); - } + execute("removeTable", sessionId, () -> { + UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); + TableManager.getInstance().removeTable(userId, tableId); }); } @@ -1172,12 +1055,9 @@ public class MageServerImpl implements MageServer { @Override public void sendFeedbackMessage(final String sessionId, final String username, final String title, final String type, final String message, final String email) throws MageException { if (title != null && message != null) { - execute("sendFeedbackMessage", sessionId, new Action() { - @Override - public void execute() { - String host = SessionManager.getInstance().getSession(sessionId).getHost(); - FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host); - } + execute("sendFeedbackMessage", sessionId, () -> { + String host = SessionManager.getInstance().getSession(sessionId).getHost(); + FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host); }); } } @@ -1185,15 +1065,12 @@ public class MageServerImpl implements MageServer { @Override public void sendBroadcastMessage(final String sessionId, final String message) throws MageException { if (message != null) { - execute("sendBroadcastMessage", sessionId, new Action() { - @Override - public void execute() { - for (User user : UserManager.getInstance().getUsers()) { - if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) { - user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.RED))); - } else { - user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.BLUE))); - } + execute("sendBroadcastMessage", sessionId, () -> { + for (User user : UserManager.getInstance().getUsers()) { + if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) { + user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.RED))); + } else { + user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.BLUE))); } } }, true); @@ -1201,12 +1078,7 @@ public class MageServerImpl implements MageServer { } private void sendErrorMessageToClient(final String sessionId, final String message) throws MageException { - execute("sendErrorMessageToClient", sessionId, new Action() { - @Override - public void execute() { - SessionManager.getInstance().sendErrorMessageToClient(sessionId, message); - } - }); + execute("sendErrorMessageToClient", sessionId, () -> SessionManager.getInstance().sendErrorMessageToClient(sessionId, message)); } protected void execute(final String actionName, final String sessionId, final Action action, boolean checkAdminRights) throws MageException { @@ -1222,18 +1094,15 @@ public class MageServerImpl implements MageServer { if (SessionManager.getInstance().isValidSession(sessionId)) { try { callExecutor.execute( - new Runnable() { - @Override - public void run() { - if (SessionManager.getInstance().isValidSession(sessionId)) { - try { - action.execute(); - } catch (MageException me) { - throw new RuntimeException(me); + () -> { + if (SessionManager.getInstance().isValidSession(sessionId)) { + try { + action.execute(); + } catch (MageException me) { + throw new RuntimeException(me); + } } } - } - } ); } catch (Exception ex) { handleException(ex); diff --git a/Mage.Server/src/main/java/mage/server/Main.java b/Mage.Server/src/main/java/mage/server/Main.java index 0da06d742a..9c13dfb7aa 100644 --- a/Mage.Server/src/main/java/mage/server/Main.java +++ b/Mage.Server/src/main/java/mage/server/Main.java @@ -92,7 +92,7 @@ public class Main { private static final File pluginFolder = new File("plugins"); private static final File extensionFolder = new File("extensions"); - public static PluginClassLoader classLoader = new PluginClassLoader(); + public static final PluginClassLoader classLoader = new PluginClassLoader(); public static TransporterServer server; protected static boolean testMode; protected static boolean fastDbMode; @@ -437,12 +437,7 @@ public class Main { directory.mkdirs(); } File[] files = directory.listFiles( - new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.endsWith(".game"); - } - } + (dir, name) -> name.endsWith(".game") ); for (File file : files) { file.delete(); diff --git a/Mage.Server/src/main/java/mage/server/TableController.java b/Mage.Server/src/main/java/mage/server/TableController.java index 6b1704182f..e19dfefc47 100644 --- a/Mage.Server/src/main/java/mage/server/TableController.java +++ b/Mage.Server/src/main/java/mage/server/TableController.java @@ -90,7 +90,7 @@ public class TableController { private Tournament tournament; private ScheduledFuture futureTimeout; - protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); + protected static final ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); public TableController(UUID roomId, UUID userId, MatchOptions options) { this.userId = userId; @@ -128,20 +128,17 @@ public class TableController { private void init() { match.addTableEventListener( - new Listener() { - @Override - public void event(TableEvent event) { - try { - switch (event.getEventType()) { - case SIDEBOARD: - sideboard(event.getPlayerId(), event.getDeck()); - break; + (Listener) event -> { + try { + switch (event.getEventType()) { + case SIDEBOARD: + sideboard(event.getPlayerId(), event.getDeck()); + break; + } + } catch (MageException ex) { + logger.fatal("Table event listener error", ex); } - } catch (MageException ex) { - logger.fatal("Table event listener error", ex); } - } - } ); } @@ -814,12 +811,7 @@ public class TableController { cancelTimeout(); if (seconds > 0) { futureTimeout = timeoutExecutor.schedule( - new Runnable() { - @Override - public void run() { - autoSideboard(); - } - }, + () -> autoSideboard(), seconds, TimeUnit.SECONDS ); } diff --git a/Mage.Server/src/main/java/mage/server/TableManager.java b/Mage.Server/src/main/java/mage/server/TableManager.java index 1ba1e242b4..155ffdf59b 100644 --- a/Mage.Server/src/main/java/mage/server/TableManager.java +++ b/Mage.Server/src/main/java/mage/server/TableManager.java @@ -64,7 +64,7 @@ import org.apache.log4j.Logger; */ public class TableManager { - protected static ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor(); + protected static final ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor(); // protected static ScheduledExecutorService expireExecutor = ThreadExecutor.getInstance().getExpireExecutor(); @@ -87,14 +87,11 @@ public class TableManager { } private TableManager() { - expireExecutor.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - try { - checkTableHealthState(); - } catch(Exception ex) { - logger.fatal("Check table health state job error:", ex); - } + expireExecutor.scheduleAtFixedRate(() -> { + try { + checkTableHealthState(); + } catch(Exception ex) { + logger.fatal("Check table health state job error:", ex); } }, EXPIRE_CHECK_PERIOD, EXPIRE_CHECK_PERIOD, TimeUnit.MINUTES); } diff --git a/Mage.Server/src/main/java/mage/server/User.java b/Mage.Server/src/main/java/mage/server/User.java index af9677dec5..ef37a1e07b 100644 --- a/Mage.Server/src/main/java/mage/server/User.java +++ b/Mage.Server/src/main/java/mage/server/User.java @@ -70,7 +70,7 @@ public class User { public enum UserState { - Created, Connected, Disconnected, Reconnected, Expired; + Created, Connected, Disconnected, Reconnected, Expired } private final UUID userId; diff --git a/Mage.Server/src/main/java/mage/server/UserManager.java b/Mage.Server/src/main/java/mage/server/UserManager.java index 867a17c25b..aadf74bc92 100644 --- a/Mage.Server/src/main/java/mage/server/UserManager.java +++ b/Mage.Server/src/main/java/mage/server/UserManager.java @@ -52,7 +52,7 @@ import org.apache.log4j.Logger; */ public class UserManager { - protected static ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor(); + protected static final ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor(); private static final Logger LOGGER = Logger.getLogger(UserManager.class); @@ -68,12 +68,7 @@ public class UserManager { } private UserManager() { - expireExecutor.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - checkExpired(); - } - }, 60, 60, TimeUnit.SECONDS); + expireExecutor.scheduleAtFixedRate(() -> checkExpired(), 60, 60, TimeUnit.SECONDS); } public User createUser(String userName, String host, AuthorizedUser authorizedUser) { @@ -137,21 +132,18 @@ public class UserManager { final User user = users.get(userId); if (user != null) { USER_EXECUTOR.execute( - new Runnable() { - @Override - public void run() { - try { - LOGGER.info("USER REMOVE - " + user.getName() + " (" + reason.toString() + ") userId: " + userId + " [" + user.getGameInfo() + "]"); - user.remove(reason); - LOGGER.debug("USER REMOVE END - " + user.getName()); - } catch (Exception ex) { - handleException(ex); - } finally { - users.remove(userId); - usersByName.remove(user.getName()); + () -> { + try { + LOGGER.info("USER REMOVE - " + user.getName() + " (" + reason.toString() + ") userId: " + userId + " [" + user.getGameInfo() + "]"); + user.remove(reason); + LOGGER.debug("USER REMOVE END - " + user.getName()); + } catch (Exception ex) { + handleException(ex); + } finally { + users.remove(userId); + usersByName.remove(user.getName()); + } } - } - } ); } else { LOGGER.warn("Trying to remove userId: " + userId + " - but it does not exist."); @@ -212,14 +204,11 @@ public class UserManager { } public void updateUserHistory() { - USER_EXECUTOR.execute(new Runnable() { - @Override - public void run() { - for (String updatedUser : UserStatsRepository.instance.updateUserStats()) { - User user = getUserByName(updatedUser); - if (user != null) { - user.resetUserStats(); - } + USER_EXECUTOR.execute(() -> { + for (String updatedUser : UserStatsRepository.instance.updateUserStats()) { + User user = getUserByName(updatedUser); + if (user != null) { + user.resetUserStats(); } } }); diff --git a/Mage.Server/src/main/java/mage/server/draft/CubeFactory.java b/Mage.Server/src/main/java/mage/server/draft/CubeFactory.java index ad10a8b3fc..d38208c1c5 100644 --- a/Mage.Server/src/main/java/mage/server/draft/CubeFactory.java +++ b/Mage.Server/src/main/java/mage/server/draft/CubeFactory.java @@ -44,7 +44,7 @@ public class CubeFactory { private static final CubeFactory INSTANCE = new CubeFactory(); private static final Logger logger = Logger.getLogger(CubeFactory.class); - private Map draftCubes = new LinkedHashMap(); + private final Map draftCubes = new LinkedHashMap(); public static CubeFactory getInstance() { return INSTANCE; @@ -57,8 +57,8 @@ public class CubeFactory { DraftCube draftCube; Constructor con; try { - con = draftCubes.get(draftCubeName).getConstructor(new Class[]{}); - draftCube = (DraftCube)con.newInstance(new Object[] {}); + con = draftCubes.get(draftCubeName).getConstructor(); + draftCube = (DraftCube)con.newInstance(); } catch (Exception ex) { logger.fatal("CubeFactory error", ex); return null; @@ -73,8 +73,8 @@ public class CubeFactory { DraftCube draftCube; Constructor con; try { - con = draftCubes.get(draftCubeName).getConstructor(new Class[]{Deck.class}); - draftCube = (DraftCube)con.newInstance(new Object[] {cubeFromDeck}); + con = draftCubes.get(draftCubeName).getConstructor(Deck.class); + draftCube = (DraftCube)con.newInstance(cubeFromDeck); } catch (Exception ex) { logger.fatal("CubeFactory error", ex); return null; diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftController.java b/Mage.Server/src/main/java/mage/server/draft/DraftController.java index b96417b679..02e45110a8 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftController.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftController.java @@ -74,9 +74,7 @@ public class DraftController { private void init() { draft.addTableEventListener( - new Listener () { - @Override - public void event(TableEvent event) { + (Listener) event -> { try { switch (event.getEventType()) { case UPDATE: @@ -91,12 +89,9 @@ public class DraftController { logger.fatal("Table event listener error", ex); } } - } ); draft.addPlayerQueryEventListener( - new Listener () { - @Override - public void event(PlayerQueryEvent event) { + (Listener) event -> { try { switch (event.getQueryType()) { case PICK_CARD: @@ -108,7 +103,6 @@ public class DraftController { logger.fatal("Table event listener error", ex); } } - } ); for (DraftPlayer player: draft.getPlayers()) { if (!player.getPlayer().isHuman()) { @@ -156,12 +150,7 @@ public class DraftController { if (!draft.isStarted() && allJoined()) { draft.setStarted(); ThreadExecutor.getInstance().getCallExecutor().execute( - new Runnable() { - @Override - public void run() { - startDraft(); - } - }); + () -> startDraft()); } } diff --git a/Mage.Server/src/main/java/mage/server/draft/DraftSession.java b/Mage.Server/src/main/java/mage/server/draft/DraftSession.java index 7a7d045fc1..068d58c04d 100644 --- a/Mage.Server/src/main/java/mage/server/draft/DraftSession.java +++ b/Mage.Server/src/main/java/mage/server/draft/DraftSession.java @@ -52,14 +52,14 @@ public class DraftSession { protected final static Logger logger = Logger.getLogger(DraftSession.class); - protected UUID userId; - protected UUID playerId; - protected Draft draft; + protected final UUID userId; + protected final UUID playerId; + protected final Draft draft; protected boolean killed = false; protected UUID markedCard; private ScheduledFuture futureTimeout; - protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); + protected static final ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); public DraftSession(Draft draft, UUID userId, UUID playerId) { this.userId = userId; @@ -125,12 +125,7 @@ public class DraftSession { cancelTimeout(); if (seconds > 0) { futureTimeout = timeoutExecutor.schedule( - new Runnable() { - @Override - public void run() { - DraftManager.getInstance().timeout(draft.getId(), userId); - } - }, + () -> DraftManager.getInstance().timeout(draft.getId(), userId), seconds, TimeUnit.SECONDS ); } diff --git a/Mage.Server/src/main/java/mage/server/game/DeckValidatorFactory.java b/Mage.Server/src/main/java/mage/server/game/DeckValidatorFactory.java index 4a693cbc66..ceff42329a 100644 --- a/Mage.Server/src/main/java/mage/server/game/DeckValidatorFactory.java +++ b/Mage.Server/src/main/java/mage/server/game/DeckValidatorFactory.java @@ -57,8 +57,8 @@ public class DeckValidatorFactory { DeckValidator validator; Constructor con; try { - con = deckTypes.get(deckType).getConstructor(new Class[]{}); - validator = (DeckValidator)con.newInstance(new Object[] {}); + con = deckTypes.get(deckType).getConstructor(); + validator = (DeckValidator)con.newInstance(); } catch (Exception ex) { logger.fatal("DeckValidatorFactory error", ex); return null; diff --git a/Mage.Server/src/main/java/mage/server/game/GameController.java b/Mage.Server/src/main/java/mage/server/game/GameController.java index 8794de5b56..79a9d63cdf 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameController.java +++ b/Mage.Server/src/main/java/mage/server/game/GameController.java @@ -99,24 +99,24 @@ public class GameController implements GameCallback { private static final ExecutorService gameExecutor = ThreadExecutor.getInstance().getGameExecutor(); private static final Logger logger = Logger.getLogger(GameController.class); - protected ScheduledExecutorService joinWaitingExecutor = Executors.newSingleThreadScheduledExecutor(); + protected final ScheduledExecutorService joinWaitingExecutor = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture futureTimeout; - protected static ScheduledExecutorService timeoutIdleExecutor = ThreadExecutor.getInstance().getTimeoutIdleExecutor(); + protected static final ScheduledExecutorService timeoutIdleExecutor = ThreadExecutor.getInstance().getTimeoutIdleExecutor(); - private ConcurrentHashMap gameSessions = new ConcurrentHashMap<>(); - private ConcurrentHashMap watchers = new ConcurrentHashMap<>(); - private ConcurrentHashMap timers = new ConcurrentHashMap<>(); + private final ConcurrentHashMap gameSessions = new ConcurrentHashMap<>(); + private final ConcurrentHashMap watchers = new ConcurrentHashMap<>(); + private final ConcurrentHashMap timers = new ConcurrentHashMap<>(); - private ConcurrentHashMap userPlayerMap; - private UUID gameSessionId; - private Game game; - private UUID chatId; - private UUID tableId; - private UUID choosingPlayerId; + private final ConcurrentHashMap userPlayerMap; + private final UUID gameSessionId; + private final Game game; + private final UUID chatId; + private final UUID tableId; + private final UUID choosingPlayerId; private Future gameFuture; private boolean useTimeout = true; - private GameOptions gameOptions; + private final GameOptions gameOptions; private UUID userReqestingRollback; private int turnsToRollback; @@ -155,133 +155,124 @@ public class GameController implements GameCallback { private void init() { game.addTableEventListener( - new Listener() { - @Override - public void event(TableEvent event) { - try { - PriorityTimer timer; - UUID playerId; - switch (event.getEventType()) { - case UPDATE: - updateGame(); - break; - case INFO: - ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, ChatMessage.MessageType.GAME, null); - logger.trace(game.getId() + " " + event.getMessage()); - break; - case STATUS: - ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.ORANGE, event.getWithTime(), ChatMessage.MessageType.GAME, null); - logger.trace(game.getId() + " " + event.getMessage()); - break; - case ERROR: - error(event.getMessage(), event.getException()); - break; - case END_GAME_INFO: - endGameInfo(); - break; - case INIT_TIMER: - final UUID initPlayerId = event.getPlayerId(); - if (initPlayerId == null) { - throw new MageException("INIT_TIMER: playerId can't be null"); - } - createPlayerTimer(event.getPlayerId(), game.getPriorityTime()); - break; - case RESUME_TIMER: - playerId = event.getPlayerId(); - if (playerId == null) { - throw new MageException("RESUME_TIMER: playerId can't be null"); - } - timer = timers.get(playerId); - if (timer == null) { - Player player = game.getState().getPlayer(playerId); - if (player != null) { - timer = createPlayerTimer(event.getPlayerId(), player.getPriorityTimeLeft()); - } else { - throw new MageException("RESUME_TIMER: player can't be null"); + (Listener) event -> { + try { + PriorityTimer timer; + UUID playerId; + switch (event.getEventType()) { + case UPDATE: + updateGame(); + break; + case INFO: + ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.GAME, null); + logger.trace(game.getId() + " " + event.getMessage()); + break; + case STATUS: + ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.ORANGE, event.getWithTime(), MessageType.GAME, null); + logger.trace(game.getId() + " " + event.getMessage()); + break; + case ERROR: + error(event.getMessage(), event.getException()); + break; + case END_GAME_INFO: + endGameInfo(); + break; + case INIT_TIMER: + final UUID initPlayerId = event.getPlayerId(); + if (initPlayerId == null) { + throw new MageException("INIT_TIMER: playerId can't be null"); } - } - timer.resume(); - break; - case PAUSE_TIMER: - playerId = event.getPlayerId(); - if (playerId == null) { - throw new MageException("PAUSE_TIMER: playerId can't be null"); - } - timer = timers.get(playerId); - if (timer == null) { - throw new MageException("PAUSE_TIMER: couldn't find timer for player: " + playerId); - } - timer.pause(); - break; + createPlayerTimer(event.getPlayerId(), game.getPriorityTime()); + break; + case RESUME_TIMER: + playerId = event.getPlayerId(); + if (playerId == null) { + throw new MageException("RESUME_TIMER: playerId can't be null"); + } + timer = timers.get(playerId); + if (timer == null) { + Player player = game.getState().getPlayer(playerId); + if (player != null) { + timer = createPlayerTimer(event.getPlayerId(), player.getPriorityTimeLeft()); + } else { + throw new MageException("RESUME_TIMER: player can't be null"); + } + } + timer.resume(); + break; + case PAUSE_TIMER: + playerId = event.getPlayerId(); + if (playerId == null) { + throw new MageException("PAUSE_TIMER: playerId can't be null"); + } + timer = timers.get(playerId); + if (timer == null) { + throw new MageException("PAUSE_TIMER: couldn't find timer for player: " + playerId); + } + timer.pause(); + break; + } + } catch (MageException ex) { + logger.fatal("Table event listener error ", ex); } - } catch (MageException ex) { - logger.fatal("Table event listener error ", ex); } - } - } ); game.addPlayerQueryEventListener( - new Listener() { - @Override - public void event(PlayerQueryEvent event) { - logger.trace(new StringBuilder(event.getPlayerId().toString()).append("--").append(event.getQueryType()).append("--").append(event.getMessage()).toString()); - try { - switch (event.getQueryType()) { - case ASK: - ask(event.getPlayerId(), event.getMessage(), event.getOptions()); - break; - case PICK_TARGET: - target(event.getPlayerId(), event.getMessage(), event.getCards(), event.getPerms(), event.getTargets(), event.isRequired(), event.getOptions()); - break; - case PICK_ABILITY: - target(event.getPlayerId(), event.getMessage(), event.getAbilities(), event.isRequired(), event.getOptions()); - break; - case SELECT: - select(event.getPlayerId(), event.getMessage(), event.getOptions()); - break; - case PLAY_MANA: - playMana(event.getPlayerId(), event.getMessage(), event.getOptions()); - break; - case PLAY_X_MANA: - playXMana(event.getPlayerId(), event.getMessage()); - break; - case CHOOSE_ABILITY: - String objectName = null; - if (event.getChoices() != null && event.getChoices().size() > 0) { - objectName = event.getChoices().iterator().next(); - } - chooseAbility(event.getPlayerId(), objectName, event.getAbilities()); - break; - case CHOOSE_PILE: - choosePile(event.getPlayerId(), event.getMessage(), event.getPile1(), event.getPile2()); - break; - case CHOOSE_MODE: - chooseMode(event.getPlayerId(), event.getModes()); - break; - case CHOOSE_CHOICE: - chooseChoice(event.getPlayerId(), event.getChoice()); - break; - case AMOUNT: - amount(event.getPlayerId(), event.getMessage(), event.getMin(), event.getMax()); - break; - case PERSONAL_MESSAGE: - informPersonal(event.getPlayerId(), event.getMessage()); - break; + (Listener) event -> { + logger.trace(new StringBuilder(event.getPlayerId().toString()).append("--").append(event.getQueryType()).append("--").append(event.getMessage()).toString()); + try { + switch (event.getQueryType()) { + case ASK: + ask(event.getPlayerId(), event.getMessage(), event.getOptions()); + break; + case PICK_TARGET: + target(event.getPlayerId(), event.getMessage(), event.getCards(), event.getPerms(), event.getTargets(), event.isRequired(), event.getOptions()); + break; + case PICK_ABILITY: + target(event.getPlayerId(), event.getMessage(), event.getAbilities(), event.isRequired(), event.getOptions()); + break; + case SELECT: + select(event.getPlayerId(), event.getMessage(), event.getOptions()); + break; + case PLAY_MANA: + playMana(event.getPlayerId(), event.getMessage(), event.getOptions()); + break; + case PLAY_X_MANA: + playXMana(event.getPlayerId(), event.getMessage()); + break; + case CHOOSE_ABILITY: + String objectName = null; + if (event.getChoices() != null && event.getChoices().size() > 0) { + objectName = event.getChoices().iterator().next(); + } + chooseAbility(event.getPlayerId(), objectName, event.getAbilities()); + break; + case CHOOSE_PILE: + choosePile(event.getPlayerId(), event.getMessage(), event.getPile1(), event.getPile2()); + break; + case CHOOSE_MODE: + chooseMode(event.getPlayerId(), event.getModes()); + break; + case CHOOSE_CHOICE: + chooseChoice(event.getPlayerId(), event.getChoice()); + break; + case AMOUNT: + amount(event.getPlayerId(), event.getMessage(), event.getMin(), event.getMax()); + break; + case PERSONAL_MESSAGE: + informPersonal(event.getPlayerId(), event.getMessage()); + break; + } + } catch (MageException ex) { + logger.fatal("Player event listener error ", ex); } - } catch (MageException ex) { - logger.fatal("Player event listener error ", ex); } - } - } ); - joinWaitingExecutor.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - try { - sendInfoAboutPlayersNotJoinedYet(); - } catch (Exception ex) { - logger.fatal("Send info about player not joined yet:", ex); - } + joinWaitingExecutor.scheduleAtFixedRate(() -> { + try { + sendInfoAboutPlayersNotJoinedYet(); + } catch (Exception ex) { + logger.fatal("Send info about player not joined yet:", ex); } }, 15, 15, TimeUnit.SECONDS); checkStart(); @@ -303,12 +294,9 @@ public class GameController implements GameCallback { final UUID initPlayerId = playerId; long delayMs = 250L; // run each 250 ms - Action executeOnNoTimeLeft = new Action() { - @Override - public void execute() throws MageException { - game.timerTimeout(initPlayerId); - logger.debug("Player has no time left to end the match: " + initPlayerId + ". Conceding."); - } + Action executeOnNoTimeLeft = () -> { + game.timerTimeout(initPlayerId); + logger.debug("Player has no time left to end the match: " + initPlayerId + ". Conceding."); }; PriorityTimer timer = new PriorityTimer(count, delayMs, executeOnNoTimeLeft); @@ -402,12 +390,7 @@ public class GameController implements GameCallback { if (allJoined()) { joinWaitingExecutor.shutdownNow(); ThreadExecutor.getInstance().getCallExecutor().execute( - new Runnable() { - @Override - public void run() { - startGame(); - } - }); + () -> startGame()); } } @@ -703,49 +686,24 @@ public class GameController implements GameCallback { } public void sendPlayerUUID(UUID userId, final UUID data) { - sendMessage(userId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).sendPlayerUUID(data); - } - }); + sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerUUID(data)); } public void sendPlayerString(UUID userId, final String data) { - sendMessage(userId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).sendPlayerString(data); - } - }); + sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerString(data)); } public void sendPlayerManaType(UUID userId, final UUID manaTypePlayerId, final ManaType data) { - sendMessage(userId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).sendPlayerManaType(data, manaTypePlayerId); - } - }); + sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerManaType(data, manaTypePlayerId)); } public void sendPlayerBoolean(UUID userId, final Boolean data) { - sendMessage(userId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).sendPlayerBoolean(data); - } - }); + sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerBoolean(data)); } public void sendPlayerInteger(UUID userId, final Integer data) { - sendMessage(userId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).sendPlayerInteger(data); - } - }); + sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerInteger(data)); } @@ -779,120 +737,69 @@ public class GameController implements GameCallback { } private synchronized void ask(UUID playerId, final String question, final Map options) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).ask(question, options); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).ask(question, options)); } private synchronized void chooseAbility(UUID playerId, final String objectName, final List choices) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).chooseAbility(new AbilityPickerView(objectName, choices)); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).chooseAbility(new AbilityPickerView(objectName, choices))); } private synchronized void choosePile(UUID playerId, final String message, final List pile1, final List pile2) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).choosePile(message, new CardsView(pile1), new CardsView(pile2)); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).choosePile(message, new CardsView(pile1), new CardsView(pile2))); } private synchronized void chooseMode(UUID playerId, final Map modes) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).chooseAbility(new AbilityPickerView(modes)); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).chooseAbility(new AbilityPickerView(modes))); } private synchronized void chooseChoice(UUID playerId, final Choice choice) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).chooseChoice(choice); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).chooseChoice(choice)); } private synchronized void target(UUID playerId, final String question, final Cards cards, final List perms, final Set targets, final boolean required, final Map options) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - if (cards != null) { - // Zone targetZone = (Zone) options.get("targetZone"); - // Are there really situations where a player selects from a list of face down cards? - // So always show face up for selection - // boolean showFaceDown = targetZone != null && targetZone.equals(Zone.PICK); - boolean showFaceDown = true; - getGameSession(playerId).target(question, new CardsView(game, cards.getCards(game), showFaceDown, true), targets, required, options); - } else if (perms != null) { - CardsView permsView = new CardsView(); - for (Permanent perm : perms) { - permsView.put(perm.getId(), new PermanentView(perm, game.getCard(perm.getId()), playerId, game)); - } - getGameSession(playerId).target(question, permsView, targets, required, options); - } else { - getGameSession(playerId).target(question, new CardsView(), targets, required, options); + perform(playerId, playerId1 -> { + if (cards != null) { + // Zone targetZone = (Zone) options.get("targetZone"); + // Are there really situations where a player selects from a list of face down cards? + // So always show face up for selection + // boolean showFaceDown = targetZone != null && targetZone.equals(Zone.PICK); + boolean showFaceDown = true; + getGameSession(playerId1).target(question, new CardsView(game, cards.getCards(game), showFaceDown, true), targets, required, options); + } else if (perms != null) { + CardsView permsView = new CardsView(); + for (Permanent perm : perms) { + permsView.put(perm.getId(), new PermanentView(perm, game.getCard(perm.getId()), playerId1, game)); } + getGameSession(playerId1).target(question, permsView, targets, required, options); + } else { + getGameSession(playerId1).target(question, new CardsView(), targets, required, options); } }); } private synchronized void target(UUID playerId, final String question, final Collection abilities, final boolean required, final Map options) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - CardsView cardsView = new CardsView(abilities, game); - getGameSession(playerId).target(question, cardsView, null, required, options); - } + perform(playerId, playerId1 -> { + CardsView cardsView = new CardsView(abilities, game); + getGameSession(playerId1).target(question, cardsView, null, required, options); }); } private synchronized void select(final UUID playerId, final String message, final Map options) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).select(message, options); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).select(message, options)); } private synchronized void playMana(UUID playerId, final String message, final Map options) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).playMana(message, options); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).playMana(message, options)); } private synchronized void playXMana(UUID playerId, final String message) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).playXMana(message); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).playXMana(message)); } private synchronized void amount(UUID playerId, final String message, final int min, final int max) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).getAmount(message, min, max); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).getAmount(message, min, max)); } private void informOthers(UUID playerId) throws MageException { @@ -939,12 +846,7 @@ public class GameController implements GameCallback { } private synchronized void informPersonal(UUID playerId, final String message) throws MageException { - perform(playerId, new Command() { - @Override - public void execute(UUID playerId) { - getGameSession(playerId).informPersonal(message); - } - }); + perform(playerId, playerId1 -> getGameSession(playerId1).informPersonal(message)); } private void error(String message, Exception ex) { @@ -977,12 +879,9 @@ public class GameController implements GameCallback { try { OutputStream file = new FileOutputStream("saved/" + game.getId().toString() + ".game"); OutputStream buffer = new BufferedOutputStream(file); - ObjectOutput output = new ObjectOutputStream(new GZIPOutputStream(buffer)); - try { + try (ObjectOutput output = new ObjectOutputStream(new GZIPOutputStream(buffer))) { output.writeObject(game); output.writeObject(game.getGameStates()); - } finally { - output.close(); } logger.debug("Saved game:" + game.getId()); return true; @@ -1074,12 +973,7 @@ public class GameController implements GameCallback { } cancelTimeout(); futureTimeout = timeoutIdleExecutor.schedule( - new Runnable() { - @Override - public void run() { - idleTimeout(playerId); - } - }, + () -> idleTimeout(playerId), Main.isTestMode() ? 3600 : ConfigSettings.getInstance().getMaxSecondsIdle(), TimeUnit.SECONDS ); diff --git a/Mage.Server/src/main/java/mage/server/game/GameFactory.java b/Mage.Server/src/main/java/mage/server/game/GameFactory.java index fe13cb3dd9..c3a22eb59b 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameFactory.java +++ b/Mage.Server/src/main/java/mage/server/game/GameFactory.java @@ -64,8 +64,8 @@ public class GameFactory { Match match; Constructor con; try { - con = games.get(gameType).getConstructor(new Class[]{MatchOptions.class}); - match = con.newInstance(new Object[] {options}); + con = games.get(gameType).getConstructor(MatchOptions.class); + match = con.newInstance(options); } catch (Exception ex) { logger.fatal("Error creating match - " + gameType, ex); return null; diff --git a/Mage.Server/src/main/java/mage/server/game/GameReplay.java b/Mage.Server/src/main/java/mage/server/game/GameReplay.java index d6e8b96158..820bc9a6d3 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameReplay.java +++ b/Mage.Server/src/main/java/mage/server/game/GameReplay.java @@ -87,16 +87,12 @@ public class GameReplay { try{ InputStream file = new FileInputStream("saved/" + gameId.toString() + ".game"); InputStream buffer = new BufferedInputStream(file); - ObjectInput input = new CopierObjectInputStream(Main.classLoader, new GZIPInputStream(buffer)); - try { - Game loadGame = (Game)input.readObject(); - GameStates states = (GameStates)input.readObject(); + try (ObjectInput input = new CopierObjectInputStream(Main.classLoader, new GZIPInputStream(buffer))) { + Game loadGame = (Game) input.readObject(); + GameStates states = (GameStates) input.readObject(); loadGame.loadGameStates(states); return loadGame; } - finally { - input.close(); - } } catch(ClassNotFoundException ex) { logger.fatal("Cannot load game. Class not found.", ex); diff --git a/Mage.Server/src/main/java/mage/server/game/GameSessionPlayer.java b/Mage.Server/src/main/java/mage/server/game/GameSessionPlayer.java index c9273f401d..76137efcca 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameSessionPlayer.java +++ b/Mage.Server/src/main/java/mage/server/game/GameSessionPlayer.java @@ -282,34 +282,31 @@ public class GameSessionPlayer extends GameSessionWatcher { final Player player = game.getPlayer(playerId); if (player != null && player.isInGame()) { callExecutor.execute( - new Runnable() { - @Override - public void run() { - try { - if (game.getStartTime() == null) { - // gameController is still waiting to start the game - player.leave(); - } else { - // game was already started - player.quit(game); - } - - } catch (Exception ex) { - if (ex != null) { - // It seems this can happen if two threads try to end the game at the exact same time (one wins and one ends here) - logger.fatal("Game session game quit exception " + (ex.getMessage() == null ? "null" : ex.getMessage())); - logger.debug("- gameId:" + game.getId() + " playerId: " + playerId); - if (ex.getCause() != null) { - logger.debug("- Cause: " + (ex.getCause().getMessage() == null ? "null" : ex.getCause().getMessage()), ex); + () -> { + try { + if (game.getStartTime() == null) { + // gameController is still waiting to start the game + player.leave(); } else { - logger.debug("- ex: " + ex.toString(), ex); + // game was already started + player.quit(game); + } + + } catch (Exception ex) { + if (ex != null) { + // It seems this can happen if two threads try to end the game at the exact same time (one wins and one ends here) + logger.fatal("Game session game quit exception " + (ex.getMessage() == null ? "null" : ex.getMessage())); + logger.debug("- gameId:" + game.getId() + " playerId: " + playerId); + if (ex.getCause() != null) { + logger.debug("- Cause: " + (ex.getCause().getMessage() == null ? "null" : ex.getCause().getMessage()), ex); + } else { + logger.debug("- ex: " + ex.toString(), ex); + } + } else { + logger.fatal("Game session game quit exception - null gameId:" + game.getId() + " playerId: " + playerId); } - } else { - logger.fatal("Game session game quit exception - null gameId:" + game.getId() + " playerId: " + playerId); } } - } - } ); } diff --git a/Mage.Server/src/main/java/mage/server/game/GameSessionWatcher.java b/Mage.Server/src/main/java/mage/server/game/GameSessionWatcher.java index 134899e36b..e1cd8bf9d1 100644 --- a/Mage.Server/src/main/java/mage/server/game/GameSessionWatcher.java +++ b/Mage.Server/src/main/java/mage/server/game/GameSessionWatcher.java @@ -51,10 +51,10 @@ public class GameSessionWatcher { protected final static Logger logger = Logger.getLogger(GameSessionWatcher.class); - protected UUID userId; - protected Game game; + protected final UUID userId; + protected final Game game; protected boolean killed = false; - protected boolean isPlayer; + protected final boolean isPlayer; public GameSessionWatcher(UUID userId, Game game, boolean isPlayer) { this.userId = userId; diff --git a/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java b/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java index e7f218b88e..521b770a0d 100644 --- a/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java +++ b/Mage.Server/src/main/java/mage/server/game/GamesRoomImpl.java @@ -73,16 +73,13 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { private final ConcurrentHashMap tables = new ConcurrentHashMap<>(); public GamesRoomImpl() { - UPDATE_EXECUTOR.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - try { - update(); - } catch (Exception ex) { - LOGGER.fatal("Games room update exception! " + ex.toString(), ex); - } - + UPDATE_EXECUTOR.scheduleAtFixedRate(() -> { + try { + update(); + } catch (Exception ex) { + LOGGER.fatal("Games room update exception! " + ex.toString(), ex); } + }, 2, 2, TimeUnit.SECONDS); } @@ -95,7 +92,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { ArrayList tableList = new ArrayList<>(); ArrayList matchList = new ArrayList<>(); List allTables = new ArrayList<>(tables.values()); - Collections.sort(allTables, new TableListSorter()); + allTables.sort(new TableListSorter()); for (Table table : allTables) { if (table.getState() != TableState.FINISHED) { tableList.add(new TableView(table)); @@ -136,7 +133,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable { } } - Collections.sort(users, new UserNameSorter()); + users.sort(new UserNameSorter()); List roomUserInfo = new ArrayList<>(); roomUserInfo.add(new RoomUsersView(users, GameManager.getInstance().getNumberActiveGames(), diff --git a/Mage.Server/src/main/java/mage/server/game/PlayerFactory.java b/Mage.Server/src/main/java/mage/server/game/PlayerFactory.java index 2bee468263..9d9581aa83 100644 --- a/Mage.Server/src/main/java/mage/server/game/PlayerFactory.java +++ b/Mage.Server/src/main/java/mage/server/game/PlayerFactory.java @@ -59,8 +59,8 @@ public class PlayerFactory { try { Class playerTypeClass = playerTypes.get(playerType); if (playerTypeClass != null) { - con = playerTypeClass.getConstructor(new Class[]{String.class, RangeOfInfluence.class, int.class}); - player = (Player)con.newInstance(new Object[] {name, range, skill}); + con = playerTypeClass.getConstructor(String.class, RangeOfInfluence.class, int.class); + player = (Player)con.newInstance(name, range, skill); logger.trace("Player created: " + name + " - " + player.getId()); return player; } diff --git a/Mage.Server/src/main/java/mage/server/game/ReplaySession.java b/Mage.Server/src/main/java/mage/server/game/ReplaySession.java index c426fbe7db..f7735c48b1 100644 --- a/Mage.Server/src/main/java/mage/server/game/ReplaySession.java +++ b/Mage.Server/src/main/java/mage/server/game/ReplaySession.java @@ -43,7 +43,7 @@ import mage.view.GameView; public class ReplaySession implements GameCallback { private final GameReplay replay; - protected UUID userId; + protected final UUID userId; ReplaySession(UUID gameId, UUID userId) { this.replay = new GameReplay(gameId); diff --git a/Mage.Server/src/main/java/mage/server/record/TableRecordRepository.java b/Mage.Server/src/main/java/mage/server/record/TableRecordRepository.java index 927a474c39..c5fec8d5c9 100644 --- a/Mage.Server/src/main/java/mage/server/record/TableRecordRepository.java +++ b/Mage.Server/src/main/java/mage/server/record/TableRecordRepository.java @@ -24,7 +24,7 @@ public enum TableRecordRepository { private Dao dao; - private TableRecordRepository() { + TableRecordRepository() { File file = new File("db"); if (!file.exists()) { file.mkdirs(); diff --git a/Mage.Server/src/main/java/mage/server/record/UserStatsRepository.java b/Mage.Server/src/main/java/mage/server/record/UserStatsRepository.java index 4da53b93e3..1bf6b3f474 100644 --- a/Mage.Server/src/main/java/mage/server/record/UserStatsRepository.java +++ b/Mage.Server/src/main/java/mage/server/record/UserStatsRepository.java @@ -30,7 +30,7 @@ public enum UserStatsRepository { private Dao dao; - private UserStatsRepository() { + UserStatsRepository() { File file = new File("db"); if (!file.exists()) { file.mkdirs(); diff --git a/Mage.Server/src/main/java/mage/server/services/impl/FeedbackServiceImpl.java b/Mage.Server/src/main/java/mage/server/services/impl/FeedbackServiceImpl.java index 1f26af508f..2f53fe21ca 100644 --- a/Mage.Server/src/main/java/mage/server/services/impl/FeedbackServiceImpl.java +++ b/Mage.Server/src/main/java/mage/server/services/impl/FeedbackServiceImpl.java @@ -12,7 +12,7 @@ import java.util.Calendar; public enum FeedbackServiceImpl implements FeedbackService { instance; - private static Logger log = Logger.getLogger(FeedbackServiceImpl.class); + private static final Logger log = Logger.getLogger(FeedbackServiceImpl.class); @Override public void feedback(String username, String title, String type, String message, String email, String host) { diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java index aabe8bf37a..c81ef1a64a 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentController.java @@ -88,68 +88,62 @@ public class TournamentController { private void init() { tournament.addTableEventListener( - new Listener() { - @Override - public void event(TableEvent event) { - switch (event.getEventType()) { - case CHECK_STATE_PLAYERS: - checkPlayersState(); - break; - case INFO: - ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.STATUS, null); - logger.debug(tournament.getId() + " " + event.getMessage()); - break; - case START_DRAFT: - startDraft(event.getDraft()); - break; - case CONSTRUCT: - if (!isAbort()) { - construct(); - } else { - endTournament(); - } - break; - case START_MATCH: - if (!isAbort()) { - initTournament(); // set state - startMatch(event.getPair(), event.getMatchOptions()); - } - break; - case START_MULTIPLAYER_MATCH: - if (!isAbort()) { - initTournament(); // set state - MatchOptions matchOptions = event.getMatchOptions(); - if (matchOptions != null && event.getMultiplayerRound() != null) { - for (TournamentPlayer player : event.getMultiplayerRound().getAllPlayers()) { - matchOptions.getPlayerTypes().add(player.getPlayerType()); - } - } - - startMultiplayerMatch(event.getMultiplayerRound(), event.getMatchOptions()); - } - break; - case END: - endTournament(); - break; - } - } - } - ); - tournament.addPlayerQueryEventListener( - new Listener() { - @Override - public void event(PlayerQueryEvent event) { - try { - switch (event.getQueryType()) { + (Listener) event -> { + switch (event.getEventType()) { + case CHECK_STATE_PLAYERS: + checkPlayersState(); + break; + case INFO: + ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.STATUS, null); + logger.debug(tournament.getId() + " " + event.getMessage()); + break; + case START_DRAFT: + startDraft(event.getDraft()); + break; case CONSTRUCT: - construct(event.getPlayerId(), event.getMax()); + if (!isAbort()) { + construct(); + } else { + endTournament(); + } + break; + case START_MATCH: + if (!isAbort()) { + initTournament(); // set state + startMatch(event.getPair(), event.getMatchOptions()); + } + break; + case START_MULTIPLAYER_MATCH: + if (!isAbort()) { + initTournament(); // set state + MatchOptions matchOptions = event.getMatchOptions(); + if (matchOptions != null && event.getMultiplayerRound() != null) { + for (TournamentPlayer player : event.getMultiplayerRound().getAllPlayers()) { + matchOptions.getPlayerTypes().add(player.getPlayerType()); + } + } + + startMultiplayerMatch(event.getMultiplayerRound(), event.getMatchOptions()); + } + break; + case END: + endTournament(); break; } - } catch (MageException ex) { - logger.fatal("Player event listener error", ex); } - } - } + ); + tournament.addPlayerQueryEventListener( + (Listener) event -> { + try { + switch (event.getQueryType()) { + case CONSTRUCT: + construct(event.getPlayerId(), event.getMax()); + break; + } + } catch (MageException ex) { + logger.fatal("Player event listener error", ex); + } + } ); for (TournamentPlayer player : tournament.getPlayers()) { if (!player.getPlayer().isHuman()) { @@ -208,12 +202,7 @@ public class TournamentController { private void checkStart() { if (!started && allJoined()) { ThreadExecutor.getInstance().getCallExecutor().execute( - new Runnable() { - @Override - public void run() { - startTournament(); - } - }); + () -> startTournament()); } } diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentFactory.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentFactory.java index ddfd7d1445..4a09cc84fe 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentFactory.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentFactory.java @@ -66,8 +66,8 @@ public class TournamentFactory { Tournament tournament; Constructor con; try { - con = tournaments.get(tournamentType).getConstructor(new Class[]{TournamentOptions.class}); - tournament = con.newInstance(new Object[] {options}); + con = tournaments.get(tournamentType).getConstructor(TournamentOptions.class); + tournament = con.newInstance(options); // transfer set information, create short info string for included sets tournament.setTournamentType(tournamentTypes.get(tournamentType)); if (tournament.getTournamentType().isLimited()) { diff --git a/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java b/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java index d0a16c7188..2ac77761d0 100644 --- a/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java +++ b/Mage.Server/src/main/java/mage/server/tournament/TournamentSession.java @@ -49,14 +49,14 @@ import java.util.concurrent.TimeUnit; public class TournamentSession { protected final static Logger logger = Logger.getLogger(TournamentSession.class); - protected UUID userId; - protected UUID playerId; - protected UUID tableId; - protected Tournament tournament; + protected final UUID userId; + protected final UUID playerId; + protected final UUID tableId; + protected final Tournament tournament; protected boolean killed = false; private ScheduledFuture futureTimeout; - protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); + protected static final ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor(); public TournamentSession(Tournament tournament, UUID userId, UUID tableId, UUID playerId) { this.userId = userId; @@ -129,16 +129,13 @@ public class TournamentSession { cancelTimeout(); if (seconds > 0) { futureTimeout = timeoutExecutor.schedule( - new Runnable() { - @Override - public void run() { + () -> { try { TournamentManager.getInstance().timeout(tournament.getId(), userId); } catch (Exception e) { logger.fatal("TournamentSession error - userId " + userId + " tId " + tournament.getId(), e); } - } - }, + }, seconds, TimeUnit.SECONDS ); } diff --git a/Mage.Server/src/main/java/mage/server/util/ServerMessagesUtil.java b/Mage.Server/src/main/java/mage/server/util/ServerMessagesUtil.java index 7ba4ca5cb4..fe2e2212b2 100644 --- a/Mage.Server/src/main/java/mage/server/util/ServerMessagesUtil.java +++ b/Mage.Server/src/main/java/mage/server/util/ServerMessagesUtil.java @@ -74,12 +74,7 @@ public class ServerMessagesUtil { public ServerMessagesUtil() { updateExecutor = Executors.newSingleThreadScheduledExecutor(); - updateExecutor.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - reloadMessages(); - } - }, 5, 5 * 60, TimeUnit.SECONDS); + updateExecutor.scheduleAtFixedRate(() -> reloadMessages(), 5, 5 * 60, TimeUnit.SECONDS); } public static ServerMessagesUtil getInstance() { diff --git a/Mage.Server/src/main/java/mage/server/util/SystemUtil.java b/Mage.Server/src/main/java/mage/server/util/SystemUtil.java index d7fb2254a6..3b55b760c7 100644 --- a/Mage.Server/src/main/java/mage/server/util/SystemUtil.java +++ b/Mage.Server/src/main/java/mage/server/util/SystemUtil.java @@ -56,8 +56,7 @@ public class SystemUtil { logger.info("Parsing init.txt... "); - Scanner scanner = new Scanner(f); - try { + try (Scanner scanner = new Scanner(f)) { while (scanner.hasNextLine()) { String line = scanner.nextLine().trim(); if (line.trim().isEmpty() || line.startsWith("#")) { @@ -114,8 +113,6 @@ public class SystemUtil { swapWithAnyCard(game, player, card, gameZone); } } - } finally { - scanner.close(); } } catch (Exception e) { logger.fatal("", e);