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.
This commit is contained in:
vraskulin 2017-01-09 19:47:03 +03:00
parent 076840df53
commit 46d369c8ed
31 changed files with 510 additions and 822 deletions

View file

@ -229,8 +229,8 @@
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<configuration> <configuration>
<source>1.7</source> <source>1.8</source>
<target>1.7</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>

View file

@ -33,7 +33,7 @@ public enum AuthorizedUserRepository {
private Dao<AuthorizedUser, Object> dao; private Dao<AuthorizedUser, Object> dao;
private AuthorizedUserRepository() { AuthorizedUserRepository() {
File file = new File("db"); File file = new File("db");
if (!file.exists()) { if (!file.exists()) {
file.mkdirs(); file.mkdirs();

View file

@ -50,7 +50,7 @@ import org.apache.log4j.Logger;
public class ChatManager { public class ChatManager {
private static final Logger logger = Logger.getLogger(ChatManager.class); private static final Logger logger = Logger.getLogger(ChatManager.class);
private static HashMap<String, String> userMessages = new HashMap<>(); private static final HashMap<String, String> userMessages = new HashMap<>();
private static final ChatManager INSTANCE = new ChatManager(); private static final ChatManager INSTANCE = new ChatManager();
@ -117,7 +117,7 @@ public class ChatManager {
return false; 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) { public void broadcast(UUID chatId, String userName, String message, MessageColor color, boolean withTime, MessageType messageType, SoundToPlay soundToPlay) {
ChatSession chatSession = chatSessions.get(chatId); ChatSession chatSession = chatSessions.get(chatId);

View file

@ -6,5 +6,5 @@ package mage.server;
*/ */
public enum DisconnectReason { public enum DisconnectReason {
LostConnection, Disconnected, CleaningUp, ConnectingOtherInstance, AdminDisconnect, SessionExpired, Undefined; LostConnection, Disconnected, CleaningUp, ConnectingOtherInstance, AdminDisconnect, SessionExpired, Undefined
} }

View file

@ -40,9 +40,9 @@ import java.util.Map;
* @author Lymia * @author Lymia
*/ */
public abstract class ExtensionPackage { public abstract class ExtensionPackage {
protected List<ExpansionSet> expansions = new ArrayList<>(); protected final List<ExpansionSet> expansions = new ArrayList<>();
protected Map<String, Class> deckTypes = new HashMap<>(); protected final Map<String, Class> deckTypes = new HashMap<>();
protected Map<String, Class> draftCubes = new HashMap<>(); protected final Map<String, Class> draftCubes = new HashMap<>();
/** /**
* @return A list of expansions included in this custom set package. * @return A list of expansions included in this custom set package.

View file

@ -314,12 +314,9 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void removeTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { public void removeTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
execute("removeTable", sessionId, new Action() { execute("removeTable", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableManager.getInstance().removeTable(userId, tableId); TableManager.getInstance().removeTable(userId, tableId);
}
}); });
} }
@ -377,13 +374,10 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void updateDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) throws MageException, GameException { public void updateDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) throws MageException, GameException {
execute("updateDeck", sessionId, new Action() { execute("updateDeck", sessionId, () -> {
@Override
public void execute() throws MageException {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableManager.getInstance().updateDeck(userId, tableId, deckList); TableManager.getInstance().updateDeck(userId, tableId, deckList);
logger.trace("Session " + sessionId + " updated deck"); logger.trace("Session " + sessionId + " updated deck");
}
}); });
} }
@ -470,12 +464,9 @@ public class MageServerImpl implements MageServer {
if (!TableManager.getInstance().getController(tableId).changeTableStateToStarting()) { if (!TableManager.getInstance().getController(tableId).changeTableStateToStarting()) {
return false; return false;
} }
execute("startMatch", sessionId, new Action() { execute("startMatch", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableManager.getInstance().startMatch(userId, roomId, tableId); TableManager.getInstance().startMatch(userId, roomId, tableId);
}
}); });
return true; return true;
} }
@ -495,12 +486,9 @@ public class MageServerImpl implements MageServer {
if (!TableManager.getInstance().getController(tableId).changeTableStateToStarting()) { if (!TableManager.getInstance().getController(tableId).changeTableStateToStarting()) {
return false; return false;
} }
execute("startTournament", sessionId, new Action() { execute("startTournament", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableManager.getInstance().startTournament(userId, roomId, tableId); TableManager.getInstance().startTournament(userId, roomId, tableId);
}
}); });
return true; 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 { public void sendChatMessage(final UUID chatId, final String userName, final String message) throws MageException {
try { try {
callExecutor.execute( callExecutor.execute(
new Runnable() { () -> ChatManager.getInstance().broadcast(chatId, userName, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE, true, ChatMessage.MessageType.TALK, null)
@Override
public void run() {
ChatManager.getInstance().broadcast(chatId, userName, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE, true, ChatMessage.MessageType.TALK, null);
}
}
); );
} catch (Exception ex) { } catch (Exception ex) {
handleException(ex); handleException(ex);
@ -535,27 +518,21 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void joinChat(final UUID chatId, final String sessionId, final String userName) throws MageException { public void joinChat(final UUID chatId, final String sessionId, final String userName) throws MageException {
execute("joinChat", sessionId, new Action() { execute("joinChat", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ChatManager.getInstance().joinChat(chatId, userId); ChatManager.getInstance().joinChat(chatId, userId);
}
}); });
} }
@Override @Override
public void leaveChat(final UUID chatId, final String sessionId) throws MageException { public void leaveChat(final UUID chatId, final String sessionId) throws MageException {
execute("leaveChat", sessionId, new Action() { execute("leaveChat", sessionId, () -> {
@Override
public void execute() {
if (chatId != null) { if (chatId != null) {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ChatManager.getInstance().leaveChat(chatId, userId); ChatManager.getInstance().leaveChat(chatId, userId);
} else { } else {
logger.warn("The chatId is null. sessionId = " + sessionId); logger.warn("The chatId is null. sessionId = " + sessionId);
} }
}
}); });
} }
@ -594,12 +571,9 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void swapSeats(final String sessionId, final UUID roomId, final UUID tableId, final int seatNum1, final int seatNum2) throws MageException { 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() { execute("swapSeats", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2); 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 // table was already started, so player can't leave anymore now
return false; return false;
} }
execute("leaveTable", sessionId, new Action() { execute("leaveTable", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId); GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId);
}
}); });
return true; return true;
} }
@ -633,34 +604,25 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void joinGame(final UUID gameId, final String sessionId) throws MageException { public void joinGame(final UUID gameId, final String sessionId) throws MageException {
execute("joinGame", sessionId, new Action() { execute("joinGame", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
GameManager.getInstance().joinGame(gameId, userId); GameManager.getInstance().joinGame(gameId, userId);
}
}); });
} }
@Override @Override
public void joinDraft(final UUID draftId, final String sessionId) throws MageException { public void joinDraft(final UUID draftId, final String sessionId) throws MageException {
execute("joinDraft", sessionId, new Action() { execute("joinDraft", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
DraftManager.getInstance().joinDraft(draftId, userId); DraftManager.getInstance().joinDraft(draftId, userId);
}
}); });
} }
@Override @Override
public void joinTournament(final UUID tournamentId, final String sessionId) throws MageException { public void joinTournament(final UUID tournamentId, final String sessionId) throws MageException {
execute("joinTournament", sessionId, new Action() { execute("joinTournament", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TournamentManager.getInstance().joinTournament(tournamentId, userId); TournamentManager.getInstance().joinTournament(tournamentId, userId);
}
}); });
} }
@ -688,9 +650,7 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void sendPlayerUUID(final UUID gameId, final String sessionId, final UUID data) throws MageException { public void sendPlayerUUID(final UUID gameId, final String sessionId, final UUID data) throws MageException {
execute("sendPlayerUUID", sessionId, new Action() { execute("sendPlayerUUID", sessionId, () -> {
@Override
public void execute() {
User user = SessionManager.getInstance().getUser(sessionId); User user = SessionManager.getInstance().getUser(sessionId);
if (user != null) { if (user != null) {
// logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName()); // logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName());
@ -698,67 +658,54 @@ public class MageServerImpl implements MageServer {
} else { } else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} }
}
}); });
} }
@Override @Override
public void sendPlayerString(final UUID gameId, final String sessionId, final String data) throws MageException { public void sendPlayerString(final UUID gameId, final String sessionId, final String data) throws MageException {
execute("sendPlayerString", sessionId, new Action() { execute("sendPlayerString", sessionId, () -> {
@Override
public void execute() {
User user = SessionManager.getInstance().getUser(sessionId); User user = SessionManager.getInstance().getUser(sessionId);
if (user != null) { if (user != null) {
user.sendPlayerString(gameId, data); user.sendPlayerString(gameId, data);
} else { } else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} }
}
}); });
} }
@Override @Override
public void sendPlayerManaType(final UUID gameId, final UUID playerId, final String sessionId, final ManaType data) throws MageException { public void sendPlayerManaType(final UUID gameId, final UUID playerId, final String sessionId, final ManaType data) throws MageException {
execute("sendPlayerManaType", sessionId, new Action() { execute("sendPlayerManaType", sessionId, () -> {
@Override
public void execute() {
User user = SessionManager.getInstance().getUser(sessionId); User user = SessionManager.getInstance().getUser(sessionId);
if (user != null) { if (user != null) {
user.sendPlayerManaType(gameId, playerId, data); user.sendPlayerManaType(gameId, playerId, data);
} else { } else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} }
}
}); });
} }
@Override @Override
public void sendPlayerBoolean(final UUID gameId, final String sessionId, final Boolean data) throws MageException { public void sendPlayerBoolean(final UUID gameId, final String sessionId, final Boolean data) throws MageException {
execute("sendPlayerBoolean", sessionId, new Action() { execute("sendPlayerBoolean", sessionId, () -> {
@Override
public void execute() {
User user = SessionManager.getInstance().getUser(sessionId); User user = SessionManager.getInstance().getUser(sessionId);
if (user != null) { if (user != null) {
user.sendPlayerBoolean(gameId, data); user.sendPlayerBoolean(gameId, data);
} else { } else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} }
}
}); });
} }
@Override @Override
public void sendPlayerInteger(final UUID gameId, final String sessionId, final Integer data) throws MageException { public void sendPlayerInteger(final UUID gameId, final String sessionId, final Integer data) throws MageException {
execute("sendPlayerInteger", sessionId, new Action() { execute("sendPlayerInteger", sessionId, () -> {
@Override
public void execute() {
User user = SessionManager.getInstance().getUser(sessionId); User user = SessionManager.getInstance().getUser(sessionId);
if (user != null) { if (user != null) {
user.sendPlayerInteger(gameId, data); user.sendPlayerInteger(gameId, data);
} else { } else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} }
}
}); });
} }
@ -780,54 +727,43 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void sendCardMark(final UUID draftId, final String sessionId, final UUID cardPick) throws MageException { public void sendCardMark(final UUID draftId, final String sessionId, final UUID cardPick) throws MageException {
execute("sendCardMark", sessionId, new Action() { execute("sendCardMark", sessionId, () -> {
@Override
public void execute() {
Session session = SessionManager.getInstance().getSession(sessionId); Session session = SessionManager.getInstance().getSession(sessionId);
if (session != null) { if (session != null) {
DraftManager.getInstance().sendCardMark(draftId, session.getUserId(), cardPick); DraftManager.getInstance().sendCardMark(draftId, session.getUserId(), cardPick);
} else { } else {
logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId);
} }
}
}); });
} }
@Override @Override
public void quitMatch(final UUID gameId, final String sessionId) throws MageException { public void quitMatch(final UUID gameId, final String sessionId) throws MageException {
execute("quitMatch", sessionId, new Action() { execute("quitMatch", sessionId, () -> {
@Override
public void execute() {
Session session = SessionManager.getInstance().getSession(sessionId); Session session = SessionManager.getInstance().getSession(sessionId);
if (session != null) { if (session != null) {
GameManager.getInstance().quitMatch(gameId, session.getUserId()); GameManager.getInstance().quitMatch(gameId, session.getUserId());
} else { } else {
logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId);
} }
}
}); });
} }
@Override @Override
public void quitTournament(final UUID tournamentId, final String sessionId) throws MageException { public void quitTournament(final UUID tournamentId, final String sessionId) throws MageException {
execute("quitTournament", sessionId, new Action() { execute("quitTournament", sessionId, () -> {
@Override
public void execute() {
Session session = SessionManager.getInstance().getSession(sessionId); Session session = SessionManager.getInstance().getSession(sessionId);
if (session != null) { if (session != null) {
TournamentManager.getInstance().quit(tournamentId, session.getUserId()); TournamentManager.getInstance().quit(tournamentId, session.getUserId());
} else { } else {
logger.error("Session not found sessionId: " + sessionId + " tournamentId:" + tournamentId); logger.error("Session not found sessionId: " + sessionId + " tournamentId:" + tournamentId);
} }
}
}); });
} }
@Override @Override
public void quitDraft(final UUID draftId, final String sessionId) throws MageException { public void quitDraft(final UUID draftId, final String sessionId) throws MageException {
execute("quitDraft", sessionId, new Action() { execute("quitDraft", sessionId, () -> {
@Override
public void execute() {
Session session = SessionManager.getInstance().getSession(sessionId); Session session = SessionManager.getInstance().getSession(sessionId);
if (session == null) { if (session == null) {
logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId);
@ -839,22 +775,18 @@ public class MageServerImpl implements MageServer {
UUID tournamentId = table.getTournament().getId(); UUID tournamentId = table.getTournament().getId();
TournamentManager.getInstance().quit(tournamentId, session.getUserId()); TournamentManager.getInstance().quit(tournamentId, session.getUserId());
} }
}
}); });
} }
@Override @Override
public void sendPlayerAction(final PlayerAction playerAction, final UUID gameId, final String sessionId, final Object data) throws MageException { public void sendPlayerAction(final PlayerAction playerAction, final UUID gameId, final String sessionId, final Object data) throws MageException {
execute("sendPlayerAction", sessionId, new Action() { execute("sendPlayerAction", sessionId, () -> {
@Override
public void execute() {
Session session = SessionManager.getInstance().getSession(sessionId); Session session = SessionManager.getInstance().getSession(sessionId);
if (session == null) { if (session == null) {
logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId);
return; return;
} }
GameManager.getInstance().sendPlayerAction(playerAction, gameId, session.getUserId(), data); GameManager.getInstance().sendPlayerAction(playerAction, gameId, session.getUserId(), data);
}
}); });
} }
@ -882,20 +814,15 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void watchGame(final UUID gameId, final String sessionId) throws MageException { public void watchGame(final UUID gameId, final String sessionId) throws MageException {
execute("watchGame", sessionId, new Action() { execute("watchGame", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
GameManager.getInstance().watchGame(gameId, userId); GameManager.getInstance().watchGame(gameId, userId);
}
}); });
} }
@Override @Override
public void stopWatching(final UUID gameId, final String sessionId) throws MageException { public void stopWatching(final UUID gameId, final String sessionId) throws MageException {
execute("stopWatching", sessionId, new Action() { execute("stopWatching", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
User user = UserManager.getInstance().getUser(userId); User user = UserManager.getInstance().getUser(userId);
if (user != null) { if (user != null) {
@ -903,73 +830,54 @@ public class MageServerImpl implements MageServer {
user.removeGameWatchInfo(gameId); user.removeGameWatchInfo(gameId);
} }
}
}); });
} }
@Override @Override
public void replayGame(final UUID gameId, final String sessionId) throws MageException { public void replayGame(final UUID gameId, final String sessionId) throws MageException {
execute("replayGame", sessionId, new Action() { execute("replayGame", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ReplayManager.getInstance().replayGame(gameId, userId); ReplayManager.getInstance().replayGame(gameId, userId);
}
}); });
} }
@Override @Override
public void startReplay(final UUID gameId, final String sessionId) throws MageException { public void startReplay(final UUID gameId, final String sessionId) throws MageException {
execute("startReplay", sessionId, new Action() { execute("startReplay", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ReplayManager.getInstance().startReplay(gameId, userId); ReplayManager.getInstance().startReplay(gameId, userId);
}
}); });
} }
@Override @Override
public void stopReplay(final UUID gameId, final String sessionId) throws MageException { public void stopReplay(final UUID gameId, final String sessionId) throws MageException {
execute("stopReplay", sessionId, new Action() { execute("stopReplay", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ReplayManager.getInstance().stopReplay(gameId, userId); ReplayManager.getInstance().stopReplay(gameId, userId);
}
}); });
} }
@Override @Override
public void nextPlay(final UUID gameId, final String sessionId) throws MageException { public void nextPlay(final UUID gameId, final String sessionId) throws MageException {
execute("nextPlay", sessionId, new Action() { execute("nextPlay", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ReplayManager.getInstance().nextPlay(gameId, userId); ReplayManager.getInstance().nextPlay(gameId, userId);
}
}); });
} }
@Override @Override
public void previousPlay(final UUID gameId, final String sessionId) throws MageException { public void previousPlay(final UUID gameId, final String sessionId) throws MageException {
execute("previousPlay", sessionId, new Action() { execute("previousPlay", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ReplayManager.getInstance().previousPlay(gameId, userId); ReplayManager.getInstance().previousPlay(gameId, userId);
}
}); });
} }
@Override @Override
public void skipForward(final UUID gameId, final String sessionId, final int moves) throws MageException { public void skipForward(final UUID gameId, final String sessionId, final int moves) throws MageException {
execute("skipForward", sessionId, new Action() { execute("skipForward", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ReplayManager.getInstance().skipForward(gameId, userId, moves); ReplayManager.getInstance().skipForward(gameId, userId, moves);
}
}); });
} }
@ -996,14 +904,11 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void cheat(final UUID gameId, final String sessionId, final UUID playerId, final DeckCardLists deckList) throws MageException { public void cheat(final UUID gameId, final String sessionId, final UUID playerId, final DeckCardLists deckList) throws MageException {
execute("cheat", sessionId, new Action() { execute("cheat", sessionId, () -> {
@Override
public void execute() {
if (testMode) { if (testMode) {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
GameManager.getInstance().cheat(gameId, userId, playerId, deckList); GameManager.getInstance().cheat(gameId, userId, playerId, deckList);
} }
}
}); });
} }
@ -1071,19 +976,12 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void disconnectUser(final String sessionId, final String userSessionId) throws MageException { public void disconnectUser(final String sessionId, final String userSessionId) throws MageException {
execute("disconnectUser", sessionId, new Action() { execute("disconnectUser", sessionId, () -> SessionManager.getInstance().disconnectUser(sessionId, userSessionId));
@Override
public void execute() {
SessionManager.getInstance().disconnectUser(sessionId, userSessionId);
}
});
} }
@Override @Override
public void muteUser(final String sessionId, final String userName, final long durationMinutes) throws MageException { public void muteUser(final String sessionId, final String userName, final long durationMinutes) throws MageException {
execute("muteUser", sessionId, new Action() { execute("muteUser", sessionId, () -> {
@Override
public void execute() {
User user = UserManager.getInstance().getUserByName(userName); User user = UserManager.getInstance().getUserByName(userName);
if (user != null) { if (user != null) {
Date muteUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE)); Date muteUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE));
@ -1091,15 +989,12 @@ public class MageServerImpl implements MageServer {
user.setChatLockedUntil(muteUntil); user.setChatLockedUntil(muteUntil);
} }
}
}); });
} }
@Override @Override
public void lockUser(final String sessionId, final String userName, final long durationMinutes) throws MageException { public void lockUser(final String sessionId, final String userName, final long durationMinutes) throws MageException {
execute("lockUser", sessionId, new Action() { execute("lockUser", sessionId, () -> {
@Override
public void execute() {
User user = UserManager.getInstance().getUserByName(userName); User user = UserManager.getInstance().getUserByName(userName);
if (user != null) { if (user != null) {
Date lockUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE)); Date lockUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE));
@ -1110,15 +1005,12 @@ public class MageServerImpl implements MageServer {
} }
} }
}
}); });
} }
@Override @Override
public void toggleActivation(final String sessionId, final String userName) throws MageException { public void toggleActivation(final String sessionId, final String userName) throws MageException {
execute("toggleActivation", sessionId, new Action() { execute("toggleActivation", sessionId, () -> {
@Override
public void execute() {
User user = UserManager.getInstance().getUserByName(userName); User user = UserManager.getInstance().getUserByName(userName);
if (user != null) { if (user != null) {
user.setActive(!user.isActive()); user.setActive(!user.isActive());
@ -1127,18 +1019,12 @@ public class MageServerImpl implements MageServer {
} }
} }
}
}); });
} }
@Override @Override
public void endUserSession(final String sessionId, final String userSessionId) throws MageException { public void endUserSession(final String sessionId, final String userSessionId) throws MageException {
execute("endUserSession", sessionId, new Action() { execute("endUserSession", sessionId, () -> SessionManager.getInstance().endUserSession(sessionId, userSessionId));
@Override
public void execute() {
SessionManager.getInstance().endUserSession(sessionId, userSessionId);
}
});
} }
/** /**
@ -1150,12 +1036,9 @@ public class MageServerImpl implements MageServer {
*/ */
@Override @Override
public void removeTable(final String sessionId, final UUID tableId) throws MageException { public void removeTable(final String sessionId, final UUID tableId) throws MageException {
execute("removeTable", sessionId, new Action() { execute("removeTable", sessionId, () -> {
@Override
public void execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TableManager.getInstance().removeTable(userId, tableId); TableManager.getInstance().removeTable(userId, tableId);
}
}); });
} }
@ -1172,12 +1055,9 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void sendFeedbackMessage(final String sessionId, final String username, final String title, final String type, final String message, final String email) throws MageException { 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) { if (title != null && message != null) {
execute("sendFeedbackMessage", sessionId, new Action() { execute("sendFeedbackMessage", sessionId, () -> {
@Override
public void execute() {
String host = SessionManager.getInstance().getSession(sessionId).getHost(); String host = SessionManager.getInstance().getSession(sessionId).getHost();
FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host); FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host);
}
}); });
} }
} }
@ -1185,9 +1065,7 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void sendBroadcastMessage(final String sessionId, final String message) throws MageException { public void sendBroadcastMessage(final String sessionId, final String message) throws MageException {
if (message != null) { if (message != null) {
execute("sendBroadcastMessage", sessionId, new Action() { execute("sendBroadcastMessage", sessionId, () -> {
@Override
public void execute() {
for (User user : UserManager.getInstance().getUsers()) { for (User user : UserManager.getInstance().getUsers()) {
if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) { if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) {
user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.RED))); user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.RED)));
@ -1195,18 +1073,12 @@ public class MageServerImpl implements MageServer {
user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.BLUE))); user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.BLUE)));
} }
} }
}
}, true); }, true);
} }
} }
private void sendErrorMessageToClient(final String sessionId, final String message) throws MageException { private void sendErrorMessageToClient(final String sessionId, final String message) throws MageException {
execute("sendErrorMessageToClient", sessionId, new Action() { execute("sendErrorMessageToClient", sessionId, () -> SessionManager.getInstance().sendErrorMessageToClient(sessionId, message));
@Override
public void execute() {
SessionManager.getInstance().sendErrorMessageToClient(sessionId, message);
}
});
} }
protected void execute(final String actionName, final String sessionId, final Action action, boolean checkAdminRights) throws MageException { protected void execute(final String actionName, final String sessionId, final Action action, boolean checkAdminRights) throws MageException {
@ -1222,9 +1094,7 @@ public class MageServerImpl implements MageServer {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
callExecutor.execute( callExecutor.execute(
new Runnable() { () -> {
@Override
public void run() {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
action.execute(); action.execute();
@ -1233,7 +1103,6 @@ public class MageServerImpl implements MageServer {
} }
} }
} }
}
); );
} catch (Exception ex) { } catch (Exception ex) {
handleException(ex); handleException(ex);

View file

@ -92,7 +92,7 @@ public class Main {
private static final File pluginFolder = new File("plugins"); private static final File pluginFolder = new File("plugins");
private static final File extensionFolder = new File("extensions"); 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; public static TransporterServer server;
protected static boolean testMode; protected static boolean testMode;
protected static boolean fastDbMode; protected static boolean fastDbMode;
@ -437,12 +437,7 @@ public class Main {
directory.mkdirs(); directory.mkdirs();
} }
File[] files = directory.listFiles( File[] files = directory.listFiles(
new FilenameFilter() { (dir, name) -> name.endsWith(".game")
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".game");
}
}
); );
for (File file : files) { for (File file : files) {
file.delete(); file.delete();

View file

@ -90,7 +90,7 @@ public class TableController {
private Tournament tournament; private Tournament tournament;
private ScheduledFuture<?> futureTimeout; 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) { public TableController(UUID roomId, UUID userId, MatchOptions options) {
this.userId = userId; this.userId = userId;
@ -128,9 +128,7 @@ public class TableController {
private void init() { private void init() {
match.addTableEventListener( match.addTableEventListener(
new Listener<TableEvent>() { (Listener<TableEvent>) event -> {
@Override
public void event(TableEvent event) {
try { try {
switch (event.getEventType()) { switch (event.getEventType()) {
case SIDEBOARD: case SIDEBOARD:
@ -141,7 +139,6 @@ public class TableController {
logger.fatal("Table event listener error", ex); logger.fatal("Table event listener error", ex);
} }
} }
}
); );
} }
@ -814,12 +811,7 @@ public class TableController {
cancelTimeout(); cancelTimeout();
if (seconds > 0) { if (seconds > 0) {
futureTimeout = timeoutExecutor.schedule( futureTimeout = timeoutExecutor.schedule(
new Runnable() { () -> autoSideboard(),
@Override
public void run() {
autoSideboard();
}
},
seconds, TimeUnit.SECONDS seconds, TimeUnit.SECONDS
); );
} }

View file

@ -64,7 +64,7 @@ import org.apache.log4j.Logger;
*/ */
public class TableManager { public class TableManager {
protected static ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor(); protected static final ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor();
// protected static ScheduledExecutorService expireExecutor = ThreadExecutor.getInstance().getExpireExecutor(); // protected static ScheduledExecutorService expireExecutor = ThreadExecutor.getInstance().getExpireExecutor();
@ -87,15 +87,12 @@ public class TableManager {
} }
private TableManager() { private TableManager() {
expireExecutor.scheduleAtFixedRate(new Runnable() { expireExecutor.scheduleAtFixedRate(() -> {
@Override
public void run() {
try { try {
checkTableHealthState(); checkTableHealthState();
} catch(Exception ex) { } catch(Exception ex) {
logger.fatal("Check table health state job error:", ex); logger.fatal("Check table health state job error:", ex);
} }
}
}, EXPIRE_CHECK_PERIOD, EXPIRE_CHECK_PERIOD, TimeUnit.MINUTES); }, EXPIRE_CHECK_PERIOD, EXPIRE_CHECK_PERIOD, TimeUnit.MINUTES);
} }

View file

@ -70,7 +70,7 @@ public class User {
public enum UserState { public enum UserState {
Created, Connected, Disconnected, Reconnected, Expired; Created, Connected, Disconnected, Reconnected, Expired
} }
private final UUID userId; private final UUID userId;

View file

@ -52,7 +52,7 @@ import org.apache.log4j.Logger;
*/ */
public class UserManager { 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); private static final Logger LOGGER = Logger.getLogger(UserManager.class);
@ -68,12 +68,7 @@ public class UserManager {
} }
private UserManager() { private UserManager() {
expireExecutor.scheduleAtFixedRate(new Runnable() { expireExecutor.scheduleAtFixedRate(() -> checkExpired(), 60, 60, TimeUnit.SECONDS);
@Override
public void run() {
checkExpired();
}
}, 60, 60, TimeUnit.SECONDS);
} }
public User createUser(String userName, String host, AuthorizedUser authorizedUser) { public User createUser(String userName, String host, AuthorizedUser authorizedUser) {
@ -137,9 +132,7 @@ public class UserManager {
final User user = users.get(userId); final User user = users.get(userId);
if (user != null) { if (user != null) {
USER_EXECUTOR.execute( USER_EXECUTOR.execute(
new Runnable() { () -> {
@Override
public void run() {
try { try {
LOGGER.info("USER REMOVE - " + user.getName() + " (" + reason.toString() + ") userId: " + userId + " [" + user.getGameInfo() + "]"); LOGGER.info("USER REMOVE - " + user.getName() + " (" + reason.toString() + ") userId: " + userId + " [" + user.getGameInfo() + "]");
user.remove(reason); user.remove(reason);
@ -151,7 +144,6 @@ public class UserManager {
usersByName.remove(user.getName()); usersByName.remove(user.getName());
} }
} }
}
); );
} else { } else {
LOGGER.warn("Trying to remove userId: " + userId + " - but it does not exist."); LOGGER.warn("Trying to remove userId: " + userId + " - but it does not exist.");
@ -212,16 +204,13 @@ public class UserManager {
} }
public void updateUserHistory() { public void updateUserHistory() {
USER_EXECUTOR.execute(new Runnable() { USER_EXECUTOR.execute(() -> {
@Override
public void run() {
for (String updatedUser : UserStatsRepository.instance.updateUserStats()) { for (String updatedUser : UserStatsRepository.instance.updateUserStats()) {
User user = getUserByName(updatedUser); User user = getUserByName(updatedUser);
if (user != null) { if (user != null) {
user.resetUserStats(); user.resetUserStats();
} }
} }
}
}); });
} }
} }

View file

@ -44,7 +44,7 @@ public class CubeFactory {
private static final CubeFactory INSTANCE = new CubeFactory(); private static final CubeFactory INSTANCE = new CubeFactory();
private static final Logger logger = Logger.getLogger(CubeFactory.class); private static final Logger logger = Logger.getLogger(CubeFactory.class);
private Map<String, Class> draftCubes = new LinkedHashMap<String, Class>(); private final Map<String, Class> draftCubes = new LinkedHashMap<String, Class>();
public static CubeFactory getInstance() { public static CubeFactory getInstance() {
return INSTANCE; return INSTANCE;
@ -57,8 +57,8 @@ public class CubeFactory {
DraftCube draftCube; DraftCube draftCube;
Constructor<?> con; Constructor<?> con;
try { try {
con = draftCubes.get(draftCubeName).getConstructor(new Class[]{}); con = draftCubes.get(draftCubeName).getConstructor();
draftCube = (DraftCube)con.newInstance(new Object[] {}); draftCube = (DraftCube)con.newInstance();
} catch (Exception ex) { } catch (Exception ex) {
logger.fatal("CubeFactory error", ex); logger.fatal("CubeFactory error", ex);
return null; return null;
@ -73,8 +73,8 @@ public class CubeFactory {
DraftCube draftCube; DraftCube draftCube;
Constructor<?> con; Constructor<?> con;
try { try {
con = draftCubes.get(draftCubeName).getConstructor(new Class[]{Deck.class}); con = draftCubes.get(draftCubeName).getConstructor(Deck.class);
draftCube = (DraftCube)con.newInstance(new Object[] {cubeFromDeck}); draftCube = (DraftCube)con.newInstance(cubeFromDeck);
} catch (Exception ex) { } catch (Exception ex) {
logger.fatal("CubeFactory error", ex); logger.fatal("CubeFactory error", ex);
return null; return null;

View file

@ -74,9 +74,7 @@ public class DraftController {
private void init() { private void init() {
draft.addTableEventListener( draft.addTableEventListener(
new Listener<TableEvent> () { (Listener<TableEvent>) event -> {
@Override
public void event(TableEvent event) {
try { try {
switch (event.getEventType()) { switch (event.getEventType()) {
case UPDATE: case UPDATE:
@ -91,12 +89,9 @@ public class DraftController {
logger.fatal("Table event listener error", ex); logger.fatal("Table event listener error", ex);
} }
} }
}
); );
draft.addPlayerQueryEventListener( draft.addPlayerQueryEventListener(
new Listener<PlayerQueryEvent> () { (Listener<PlayerQueryEvent>) event -> {
@Override
public void event(PlayerQueryEvent event) {
try { try {
switch (event.getQueryType()) { switch (event.getQueryType()) {
case PICK_CARD: case PICK_CARD:
@ -108,7 +103,6 @@ public class DraftController {
logger.fatal("Table event listener error", ex); logger.fatal("Table event listener error", ex);
} }
} }
}
); );
for (DraftPlayer player: draft.getPlayers()) { for (DraftPlayer player: draft.getPlayers()) {
if (!player.getPlayer().isHuman()) { if (!player.getPlayer().isHuman()) {
@ -156,12 +150,7 @@ public class DraftController {
if (!draft.isStarted() && allJoined()) { if (!draft.isStarted() && allJoined()) {
draft.setStarted(); draft.setStarted();
ThreadExecutor.getInstance().getCallExecutor().execute( ThreadExecutor.getInstance().getCallExecutor().execute(
new Runnable() { () -> startDraft());
@Override
public void run() {
startDraft();
}
});
} }
} }

View file

@ -52,14 +52,14 @@ public class DraftSession {
protected final static Logger logger = Logger.getLogger(DraftSession.class); protected final static Logger logger = Logger.getLogger(DraftSession.class);
protected UUID userId; protected final UUID userId;
protected UUID playerId; protected final UUID playerId;
protected Draft draft; protected final Draft draft;
protected boolean killed = false; protected boolean killed = false;
protected UUID markedCard; protected UUID markedCard;
private ScheduledFuture<?> futureTimeout; 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) { public DraftSession(Draft draft, UUID userId, UUID playerId) {
this.userId = userId; this.userId = userId;
@ -125,12 +125,7 @@ public class DraftSession {
cancelTimeout(); cancelTimeout();
if (seconds > 0) { if (seconds > 0) {
futureTimeout = timeoutExecutor.schedule( futureTimeout = timeoutExecutor.schedule(
new Runnable() { () -> DraftManager.getInstance().timeout(draft.getId(), userId),
@Override
public void run() {
DraftManager.getInstance().timeout(draft.getId(), userId);
}
},
seconds, TimeUnit.SECONDS seconds, TimeUnit.SECONDS
); );
} }

View file

@ -57,8 +57,8 @@ public class DeckValidatorFactory {
DeckValidator validator; DeckValidator validator;
Constructor<?> con; Constructor<?> con;
try { try {
con = deckTypes.get(deckType).getConstructor(new Class[]{}); con = deckTypes.get(deckType).getConstructor();
validator = (DeckValidator)con.newInstance(new Object[] {}); validator = (DeckValidator)con.newInstance();
} catch (Exception ex) { } catch (Exception ex) {
logger.fatal("DeckValidatorFactory error", ex); logger.fatal("DeckValidatorFactory error", ex);
return null; return null;

View file

@ -99,24 +99,24 @@ public class GameController implements GameCallback {
private static final ExecutorService gameExecutor = ThreadExecutor.getInstance().getGameExecutor(); private static final ExecutorService gameExecutor = ThreadExecutor.getInstance().getGameExecutor();
private static final Logger logger = Logger.getLogger(GameController.class); private static final Logger logger = Logger.getLogger(GameController.class);
protected ScheduledExecutorService joinWaitingExecutor = Executors.newSingleThreadScheduledExecutor(); protected final ScheduledExecutorService joinWaitingExecutor = Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture<?> futureTimeout; private ScheduledFuture<?> futureTimeout;
protected static ScheduledExecutorService timeoutIdleExecutor = ThreadExecutor.getInstance().getTimeoutIdleExecutor(); protected static final ScheduledExecutorService timeoutIdleExecutor = ThreadExecutor.getInstance().getTimeoutIdleExecutor();
private ConcurrentHashMap<UUID, GameSessionPlayer> gameSessions = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, GameSessionPlayer> gameSessions = new ConcurrentHashMap<>();
private ConcurrentHashMap<UUID, GameSessionWatcher> watchers = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, GameSessionWatcher> watchers = new ConcurrentHashMap<>();
private ConcurrentHashMap<UUID, PriorityTimer> timers = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, PriorityTimer> timers = new ConcurrentHashMap<>();
private ConcurrentHashMap<UUID, UUID> userPlayerMap; private final ConcurrentHashMap<UUID, UUID> userPlayerMap;
private UUID gameSessionId; private final UUID gameSessionId;
private Game game; private final Game game;
private UUID chatId; private final UUID chatId;
private UUID tableId; private final UUID tableId;
private UUID choosingPlayerId; private final UUID choosingPlayerId;
private Future<?> gameFuture; private Future<?> gameFuture;
private boolean useTimeout = true; private boolean useTimeout = true;
private GameOptions gameOptions; private final GameOptions gameOptions;
private UUID userReqestingRollback; private UUID userReqestingRollback;
private int turnsToRollback; private int turnsToRollback;
@ -155,9 +155,7 @@ public class GameController implements GameCallback {
private void init() { private void init() {
game.addTableEventListener( game.addTableEventListener(
new Listener<TableEvent>() { (Listener<TableEvent>) event -> {
@Override
public void event(TableEvent event) {
try { try {
PriorityTimer timer; PriorityTimer timer;
UUID playerId; UUID playerId;
@ -166,11 +164,11 @@ public class GameController implements GameCallback {
updateGame(); updateGame();
break; break;
case INFO: case INFO:
ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, ChatMessage.MessageType.GAME, null); ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.GAME, null);
logger.trace(game.getId() + " " + event.getMessage()); logger.trace(game.getId() + " " + event.getMessage());
break; break;
case STATUS: case STATUS:
ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.ORANGE, event.getWithTime(), ChatMessage.MessageType.GAME, null); ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.ORANGE, event.getWithTime(), MessageType.GAME, null);
logger.trace(game.getId() + " " + event.getMessage()); logger.trace(game.getId() + " " + event.getMessage());
break; break;
case ERROR: case ERROR:
@ -218,12 +216,9 @@ public class GameController implements GameCallback {
logger.fatal("Table event listener error ", ex); logger.fatal("Table event listener error ", ex);
} }
} }
}
); );
game.addPlayerQueryEventListener( game.addPlayerQueryEventListener(
new Listener<PlayerQueryEvent>() { (Listener<PlayerQueryEvent>) event -> {
@Override
public void event(PlayerQueryEvent event) {
logger.trace(new StringBuilder(event.getPlayerId().toString()).append("--").append(event.getQueryType()).append("--").append(event.getMessage()).toString()); logger.trace(new StringBuilder(event.getPlayerId().toString()).append("--").append(event.getQueryType()).append("--").append(event.getMessage()).toString());
try { try {
switch (event.getQueryType()) { switch (event.getQueryType()) {
@ -272,17 +267,13 @@ public class GameController implements GameCallback {
logger.fatal("Player event listener error ", ex); logger.fatal("Player event listener error ", ex);
} }
} }
}
); );
joinWaitingExecutor.scheduleAtFixedRate(new Runnable() { joinWaitingExecutor.scheduleAtFixedRate(() -> {
@Override
public void run() {
try { try {
sendInfoAboutPlayersNotJoinedYet(); sendInfoAboutPlayersNotJoinedYet();
} catch (Exception ex) { } catch (Exception ex) {
logger.fatal("Send info about player not joined yet:", ex); logger.fatal("Send info about player not joined yet:", ex);
} }
}
}, 15, 15, TimeUnit.SECONDS); }, 15, 15, TimeUnit.SECONDS);
checkStart(); checkStart();
} }
@ -303,12 +294,9 @@ public class GameController implements GameCallback {
final UUID initPlayerId = playerId; final UUID initPlayerId = playerId;
long delayMs = 250L; // run each 250 ms long delayMs = 250L; // run each 250 ms
Action executeOnNoTimeLeft = new Action() { Action executeOnNoTimeLeft = () -> {
@Override
public void execute() throws MageException {
game.timerTimeout(initPlayerId); game.timerTimeout(initPlayerId);
logger.debug("Player has no time left to end the match: " + initPlayerId + ". Conceding."); logger.debug("Player has no time left to end the match: " + initPlayerId + ". Conceding.");
}
}; };
PriorityTimer timer = new PriorityTimer(count, delayMs, executeOnNoTimeLeft); PriorityTimer timer = new PriorityTimer(count, delayMs, executeOnNoTimeLeft);
@ -402,12 +390,7 @@ public class GameController implements GameCallback {
if (allJoined()) { if (allJoined()) {
joinWaitingExecutor.shutdownNow(); joinWaitingExecutor.shutdownNow();
ThreadExecutor.getInstance().getCallExecutor().execute( ThreadExecutor.getInstance().getCallExecutor().execute(
new Runnable() { () -> startGame());
@Override
public void run() {
startGame();
}
});
} }
} }
@ -703,49 +686,24 @@ public class GameController implements GameCallback {
} }
public void sendPlayerUUID(UUID userId, final UUID data) { public void sendPlayerUUID(UUID userId, final UUID data) {
sendMessage(userId, new Command() { sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerUUID(data));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).sendPlayerUUID(data);
}
});
} }
public void sendPlayerString(UUID userId, final String data) { public void sendPlayerString(UUID userId, final String data) {
sendMessage(userId, new Command() { sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerString(data));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).sendPlayerString(data);
}
});
} }
public void sendPlayerManaType(UUID userId, final UUID manaTypePlayerId, final ManaType data) { public void sendPlayerManaType(UUID userId, final UUID manaTypePlayerId, final ManaType data) {
sendMessage(userId, new Command() { sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerManaType(data, manaTypePlayerId));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).sendPlayerManaType(data, manaTypePlayerId);
}
});
} }
public void sendPlayerBoolean(UUID userId, final Boolean data) { public void sendPlayerBoolean(UUID userId, final Boolean data) {
sendMessage(userId, new Command() { sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerBoolean(data));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).sendPlayerBoolean(data);
}
});
} }
public void sendPlayerInteger(UUID userId, final Integer data) { public void sendPlayerInteger(UUID userId, final Integer data) {
sendMessage(userId, new Command() { sendMessage(userId, playerId -> getGameSession(playerId).sendPlayerInteger(data));
@Override
public void execute(UUID 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<String, Serializable> options) throws MageException { private synchronized void ask(UUID playerId, final String question, final Map<String, Serializable> options) throws MageException {
perform(playerId, new Command() { perform(playerId, playerId1 -> getGameSession(playerId1).ask(question, options));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).ask(question, options);
}
});
} }
private synchronized void chooseAbility(UUID playerId, final String objectName, final List<? extends Ability> choices) throws MageException { private synchronized void chooseAbility(UUID playerId, final String objectName, final List<? extends Ability> choices) throws MageException {
perform(playerId, new Command() { perform(playerId, playerId1 -> getGameSession(playerId1).chooseAbility(new AbilityPickerView(objectName, choices)));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).chooseAbility(new AbilityPickerView(objectName, choices));
}
});
} }
private synchronized void choosePile(UUID playerId, final String message, final List<? extends Card> pile1, final List<? extends Card> pile2) throws MageException { private synchronized void choosePile(UUID playerId, final String message, final List<? extends Card> pile1, final List<? extends Card> pile2) throws MageException {
perform(playerId, new Command() { perform(playerId, playerId1 -> getGameSession(playerId1).choosePile(message, new CardsView(pile1), new CardsView(pile2)));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).choosePile(message, new CardsView(pile1), new CardsView(pile2));
}
});
} }
private synchronized void chooseMode(UUID playerId, final Map<UUID, String> modes) throws MageException { private synchronized void chooseMode(UUID playerId, final Map<UUID, String> modes) throws MageException {
perform(playerId, new Command() { perform(playerId, playerId1 -> getGameSession(playerId1).chooseAbility(new AbilityPickerView(modes)));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).chooseAbility(new AbilityPickerView(modes));
}
});
} }
private synchronized void chooseChoice(UUID playerId, final Choice choice) throws MageException { private synchronized void chooseChoice(UUID playerId, final Choice choice) throws MageException {
perform(playerId, new Command() { perform(playerId, playerId1 -> getGameSession(playerId1).chooseChoice(choice));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).chooseChoice(choice);
}
});
} }
private synchronized void target(UUID playerId, final String question, final Cards cards, final List<Permanent> perms, final Set<UUID> targets, final boolean required, final Map<String, Serializable> options) throws MageException { private synchronized void target(UUID playerId, final String question, final Cards cards, final List<Permanent> perms, final Set<UUID> targets, final boolean required, final Map<String, Serializable> options) throws MageException {
perform(playerId, new Command() { perform(playerId, playerId1 -> {
@Override
public void execute(UUID playerId) {
if (cards != null) { if (cards != null) {
// Zone targetZone = (Zone) options.get("targetZone"); // Zone targetZone = (Zone) options.get("targetZone");
// Are there really situations where a player selects from a list of face down cards? // Are there really situations where a player selects from a list of face down cards?
// So always show face up for selection // So always show face up for selection
// boolean showFaceDown = targetZone != null && targetZone.equals(Zone.PICK); // boolean showFaceDown = targetZone != null && targetZone.equals(Zone.PICK);
boolean showFaceDown = true; boolean showFaceDown = true;
getGameSession(playerId).target(question, new CardsView(game, cards.getCards(game), showFaceDown, true), targets, required, options); getGameSession(playerId1).target(question, new CardsView(game, cards.getCards(game), showFaceDown, true), targets, required, options);
} else if (perms != null) { } else if (perms != null) {
CardsView permsView = new CardsView(); CardsView permsView = new CardsView();
for (Permanent perm : perms) { for (Permanent perm : perms) {
permsView.put(perm.getId(), new PermanentView(perm, game.getCard(perm.getId()), playerId, game)); permsView.put(perm.getId(), new PermanentView(perm, game.getCard(perm.getId()), playerId1, game));
} }
getGameSession(playerId).target(question, permsView, targets, required, options); getGameSession(playerId1).target(question, permsView, targets, required, options);
} else { } else {
getGameSession(playerId).target(question, new CardsView(), targets, required, options); getGameSession(playerId1).target(question, new CardsView(), targets, required, options);
}
} }
}); });
} }
private synchronized void target(UUID playerId, final String question, final Collection<? extends Ability> abilities, final boolean required, final Map<String, Serializable> options) throws MageException { private synchronized void target(UUID playerId, final String question, final Collection<? extends Ability> abilities, final boolean required, final Map<String, Serializable> options) throws MageException {
perform(playerId, new Command() { perform(playerId, playerId1 -> {
@Override
public void execute(UUID playerId) {
CardsView cardsView = new CardsView(abilities, game); CardsView cardsView = new CardsView(abilities, game);
getGameSession(playerId).target(question, cardsView, null, required, options); getGameSession(playerId1).target(question, cardsView, null, required, options);
}
}); });
} }
private synchronized void select(final UUID playerId, final String message, final Map<String, Serializable> options) throws MageException { private synchronized void select(final UUID playerId, final String message, final Map<String, Serializable> options) throws MageException {
perform(playerId, new Command() { perform(playerId, playerId1 -> getGameSession(playerId1).select(message, options));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).select(message, options);
}
});
} }
private synchronized void playMana(UUID playerId, final String message, final Map<String, Serializable> options) throws MageException { private synchronized void playMana(UUID playerId, final String message, final Map<String, Serializable> options) throws MageException {
perform(playerId, new Command() { perform(playerId, playerId1 -> getGameSession(playerId1).playMana(message, options));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).playMana(message, options);
}
});
} }
private synchronized void playXMana(UUID playerId, final String message) throws MageException { private synchronized void playXMana(UUID playerId, final String message) throws MageException {
perform(playerId, new Command() { perform(playerId, playerId1 -> getGameSession(playerId1).playXMana(message));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).playXMana(message);
}
});
} }
private synchronized void amount(UUID playerId, final String message, final int min, final int max) throws MageException { private synchronized void amount(UUID playerId, final String message, final int min, final int max) throws MageException {
perform(playerId, new Command() { perform(playerId, playerId1 -> getGameSession(playerId1).getAmount(message, min, max));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).getAmount(message, min, max);
}
});
} }
private void informOthers(UUID playerId) throws MageException { 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 { private synchronized void informPersonal(UUID playerId, final String message) throws MageException {
perform(playerId, new Command() { perform(playerId, playerId1 -> getGameSession(playerId1).informPersonal(message));
@Override
public void execute(UUID playerId) {
getGameSession(playerId).informPersonal(message);
}
});
} }
private void error(String message, Exception ex) { private void error(String message, Exception ex) {
@ -977,12 +879,9 @@ public class GameController implements GameCallback {
try { try {
OutputStream file = new FileOutputStream("saved/" + game.getId().toString() + ".game"); OutputStream file = new FileOutputStream("saved/" + game.getId().toString() + ".game");
OutputStream buffer = new BufferedOutputStream(file); OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(new GZIPOutputStream(buffer)); try (ObjectOutput output = new ObjectOutputStream(new GZIPOutputStream(buffer))) {
try {
output.writeObject(game); output.writeObject(game);
output.writeObject(game.getGameStates()); output.writeObject(game.getGameStates());
} finally {
output.close();
} }
logger.debug("Saved game:" + game.getId()); logger.debug("Saved game:" + game.getId());
return true; return true;
@ -1074,12 +973,7 @@ public class GameController implements GameCallback {
} }
cancelTimeout(); cancelTimeout();
futureTimeout = timeoutIdleExecutor.schedule( futureTimeout = timeoutIdleExecutor.schedule(
new Runnable() { () -> idleTimeout(playerId),
@Override
public void run() {
idleTimeout(playerId);
}
},
Main.isTestMode() ? 3600 : ConfigSettings.getInstance().getMaxSecondsIdle(), Main.isTestMode() ? 3600 : ConfigSettings.getInstance().getMaxSecondsIdle(),
TimeUnit.SECONDS TimeUnit.SECONDS
); );

View file

@ -64,8 +64,8 @@ public class GameFactory {
Match match; Match match;
Constructor<Match> con; Constructor<Match> con;
try { try {
con = games.get(gameType).getConstructor(new Class[]{MatchOptions.class}); con = games.get(gameType).getConstructor(MatchOptions.class);
match = con.newInstance(new Object[] {options}); match = con.newInstance(options);
} catch (Exception ex) { } catch (Exception ex) {
logger.fatal("Error creating match - " + gameType, ex); logger.fatal("Error creating match - " + gameType, ex);
return null; return null;

View file

@ -87,16 +87,12 @@ public class GameReplay {
try{ try{
InputStream file = new FileInputStream("saved/" + gameId.toString() + ".game"); InputStream file = new FileInputStream("saved/" + gameId.toString() + ".game");
InputStream buffer = new BufferedInputStream(file); InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new CopierObjectInputStream(Main.classLoader, new GZIPInputStream(buffer)); try (ObjectInput input = new CopierObjectInputStream(Main.classLoader, new GZIPInputStream(buffer))) {
try {
Game loadGame = (Game) input.readObject(); Game loadGame = (Game) input.readObject();
GameStates states = (GameStates) input.readObject(); GameStates states = (GameStates) input.readObject();
loadGame.loadGameStates(states); loadGame.loadGameStates(states);
return loadGame; return loadGame;
} }
finally {
input.close();
}
} }
catch(ClassNotFoundException ex) { catch(ClassNotFoundException ex) {
logger.fatal("Cannot load game. Class not found.", ex); logger.fatal("Cannot load game. Class not found.", ex);

View file

@ -282,9 +282,7 @@ public class GameSessionPlayer extends GameSessionWatcher {
final Player player = game.getPlayer(playerId); final Player player = game.getPlayer(playerId);
if (player != null && player.isInGame()) { if (player != null && player.isInGame()) {
callExecutor.execute( callExecutor.execute(
new Runnable() { () -> {
@Override
public void run() {
try { try {
if (game.getStartTime() == null) { if (game.getStartTime() == null) {
// gameController is still waiting to start the game // gameController is still waiting to start the game
@ -309,7 +307,6 @@ public class GameSessionPlayer extends GameSessionWatcher {
} }
} }
} }
}
); );
} }

View file

@ -51,10 +51,10 @@ public class GameSessionWatcher {
protected final static Logger logger = Logger.getLogger(GameSessionWatcher.class); protected final static Logger logger = Logger.getLogger(GameSessionWatcher.class);
protected UUID userId; protected final UUID userId;
protected Game game; protected final Game game;
protected boolean killed = false; protected boolean killed = false;
protected boolean isPlayer; protected final boolean isPlayer;
public GameSessionWatcher(UUID userId, Game game, boolean isPlayer) { public GameSessionWatcher(UUID userId, Game game, boolean isPlayer) {
this.userId = userId; this.userId = userId;

View file

@ -73,16 +73,13 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
private final ConcurrentHashMap<UUID, Table> tables = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, Table> tables = new ConcurrentHashMap<>();
public GamesRoomImpl() { public GamesRoomImpl() {
UPDATE_EXECUTOR.scheduleAtFixedRate(new Runnable() { UPDATE_EXECUTOR.scheduleAtFixedRate(() -> {
@Override
public void run() {
try { try {
update(); update();
} catch (Exception ex) { } catch (Exception ex) {
LOGGER.fatal("Games room update exception! " + ex.toString(), ex); LOGGER.fatal("Games room update exception! " + ex.toString(), ex);
} }
}
}, 2, 2, TimeUnit.SECONDS); }, 2, 2, TimeUnit.SECONDS);
} }
@ -95,7 +92,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
ArrayList<TableView> tableList = new ArrayList<>(); ArrayList<TableView> tableList = new ArrayList<>();
ArrayList<MatchView> matchList = new ArrayList<>(); ArrayList<MatchView> matchList = new ArrayList<>();
List<Table> allTables = new ArrayList<>(tables.values()); List<Table> allTables = new ArrayList<>(tables.values());
Collections.sort(allTables, new TableListSorter()); allTables.sort(new TableListSorter());
for (Table table : allTables) { for (Table table : allTables) {
if (table.getState() != TableState.FINISHED) { if (table.getState() != TableState.FINISHED) {
tableList.add(new TableView(table)); 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<RoomUsersView> roomUserInfo = new ArrayList<>(); List<RoomUsersView> roomUserInfo = new ArrayList<>();
roomUserInfo.add(new RoomUsersView(users, roomUserInfo.add(new RoomUsersView(users,
GameManager.getInstance().getNumberActiveGames(), GameManager.getInstance().getNumberActiveGames(),

View file

@ -59,8 +59,8 @@ public class PlayerFactory {
try { try {
Class playerTypeClass = playerTypes.get(playerType); Class playerTypeClass = playerTypes.get(playerType);
if (playerTypeClass != null) { if (playerTypeClass != null) {
con = playerTypeClass.getConstructor(new Class[]{String.class, RangeOfInfluence.class, int.class}); con = playerTypeClass.getConstructor(String.class, RangeOfInfluence.class, int.class);
player = (Player)con.newInstance(new Object[] {name, range, skill}); player = (Player)con.newInstance(name, range, skill);
logger.trace("Player created: " + name + " - " + player.getId()); logger.trace("Player created: " + name + " - " + player.getId());
return player; return player;
} }

View file

@ -43,7 +43,7 @@ import mage.view.GameView;
public class ReplaySession implements GameCallback { public class ReplaySession implements GameCallback {
private final GameReplay replay; private final GameReplay replay;
protected UUID userId; protected final UUID userId;
ReplaySession(UUID gameId, UUID userId) { ReplaySession(UUID gameId, UUID userId) {
this.replay = new GameReplay(gameId); this.replay = new GameReplay(gameId);

View file

@ -24,7 +24,7 @@ public enum TableRecordRepository {
private Dao<TableRecord, Object> dao; private Dao<TableRecord, Object> dao;
private TableRecordRepository() { TableRecordRepository() {
File file = new File("db"); File file = new File("db");
if (!file.exists()) { if (!file.exists()) {
file.mkdirs(); file.mkdirs();

View file

@ -30,7 +30,7 @@ public enum UserStatsRepository {
private Dao<UserStats, Object> dao; private Dao<UserStats, Object> dao;
private UserStatsRepository() { UserStatsRepository() {
File file = new File("db"); File file = new File("db");
if (!file.exists()) { if (!file.exists()) {
file.mkdirs(); file.mkdirs();

View file

@ -12,7 +12,7 @@ import java.util.Calendar;
public enum FeedbackServiceImpl implements FeedbackService { public enum FeedbackServiceImpl implements FeedbackService {
instance; instance;
private static Logger log = Logger.getLogger(FeedbackServiceImpl.class); private static final Logger log = Logger.getLogger(FeedbackServiceImpl.class);
@Override @Override
public void feedback(String username, String title, String type, String message, String email, String host) { public void feedback(String username, String title, String type, String message, String email, String host) {

View file

@ -88,9 +88,7 @@ public class TournamentController {
private void init() { private void init() {
tournament.addTableEventListener( tournament.addTableEventListener(
new Listener<TableEvent>() { (Listener<TableEvent>) event -> {
@Override
public void event(TableEvent event) {
switch (event.getEventType()) { switch (event.getEventType()) {
case CHECK_STATE_PLAYERS: case CHECK_STATE_PLAYERS:
checkPlayersState(); checkPlayersState();
@ -133,12 +131,9 @@ public class TournamentController {
break; break;
} }
} }
}
); );
tournament.addPlayerQueryEventListener( tournament.addPlayerQueryEventListener(
new Listener<PlayerQueryEvent>() { (Listener<PlayerQueryEvent>) event -> {
@Override
public void event(PlayerQueryEvent event) {
try { try {
switch (event.getQueryType()) { switch (event.getQueryType()) {
case CONSTRUCT: case CONSTRUCT:
@ -149,7 +144,6 @@ public class TournamentController {
logger.fatal("Player event listener error", ex); logger.fatal("Player event listener error", ex);
} }
} }
}
); );
for (TournamentPlayer player : tournament.getPlayers()) { for (TournamentPlayer player : tournament.getPlayers()) {
if (!player.getPlayer().isHuman()) { if (!player.getPlayer().isHuman()) {
@ -208,12 +202,7 @@ public class TournamentController {
private void checkStart() { private void checkStart() {
if (!started && allJoined()) { if (!started && allJoined()) {
ThreadExecutor.getInstance().getCallExecutor().execute( ThreadExecutor.getInstance().getCallExecutor().execute(
new Runnable() { () -> startTournament());
@Override
public void run() {
startTournament();
}
});
} }
} }

View file

@ -66,8 +66,8 @@ public class TournamentFactory {
Tournament tournament; Tournament tournament;
Constructor<Tournament> con; Constructor<Tournament> con;
try { try {
con = tournaments.get(tournamentType).getConstructor(new Class[]{TournamentOptions.class}); con = tournaments.get(tournamentType).getConstructor(TournamentOptions.class);
tournament = con.newInstance(new Object[] {options}); tournament = con.newInstance(options);
// transfer set information, create short info string for included sets // transfer set information, create short info string for included sets
tournament.setTournamentType(tournamentTypes.get(tournamentType)); tournament.setTournamentType(tournamentTypes.get(tournamentType));
if (tournament.getTournamentType().isLimited()) { if (tournament.getTournamentType().isLimited()) {

View file

@ -49,14 +49,14 @@ import java.util.concurrent.TimeUnit;
public class TournamentSession { public class TournamentSession {
protected final static Logger logger = Logger.getLogger(TournamentSession.class); protected final static Logger logger = Logger.getLogger(TournamentSession.class);
protected UUID userId; protected final UUID userId;
protected UUID playerId; protected final UUID playerId;
protected UUID tableId; protected final UUID tableId;
protected Tournament tournament; protected final Tournament tournament;
protected boolean killed = false; protected boolean killed = false;
private ScheduledFuture<?> futureTimeout; 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) { public TournamentSession(Tournament tournament, UUID userId, UUID tableId, UUID playerId) {
this.userId = userId; this.userId = userId;
@ -129,15 +129,12 @@ public class TournamentSession {
cancelTimeout(); cancelTimeout();
if (seconds > 0) { if (seconds > 0) {
futureTimeout = timeoutExecutor.schedule( futureTimeout = timeoutExecutor.schedule(
new Runnable() { () -> {
@Override
public void run() {
try { try {
TournamentManager.getInstance().timeout(tournament.getId(), userId); TournamentManager.getInstance().timeout(tournament.getId(), userId);
} catch (Exception e) { } catch (Exception e) {
logger.fatal("TournamentSession error - userId " + userId + " tId " + tournament.getId(), e); logger.fatal("TournamentSession error - userId " + userId + " tId " + tournament.getId(), e);
} }
}
}, },
seconds, TimeUnit.SECONDS seconds, TimeUnit.SECONDS
); );

View file

@ -74,12 +74,7 @@ public class ServerMessagesUtil {
public ServerMessagesUtil() { public ServerMessagesUtil() {
updateExecutor = Executors.newSingleThreadScheduledExecutor(); updateExecutor = Executors.newSingleThreadScheduledExecutor();
updateExecutor.scheduleAtFixedRate(new Runnable() { updateExecutor.scheduleAtFixedRate(() -> reloadMessages(), 5, 5 * 60, TimeUnit.SECONDS);
@Override
public void run() {
reloadMessages();
}
}, 5, 5 * 60, TimeUnit.SECONDS);
} }
public static ServerMessagesUtil getInstance() { public static ServerMessagesUtil getInstance() {

View file

@ -56,8 +56,7 @@ public class SystemUtil {
logger.info("Parsing init.txt... "); logger.info("Parsing init.txt... ");
Scanner scanner = new Scanner(f); try (Scanner scanner = new Scanner(f)) {
try {
while (scanner.hasNextLine()) { while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim(); String line = scanner.nextLine().trim();
if (line.trim().isEmpty() || line.startsWith("#")) { if (line.trim().isEmpty() || line.startsWith("#")) {
@ -114,8 +113,6 @@ public class SystemUtil {
swapWithAnyCard(game, player, card, gameZone); swapWithAnyCard(game, player, card, gameZone);
} }
} }
} finally {
scanner.close();
} }
} catch (Exception e) { } catch (Exception e) {
logger.fatal("", e); logger.fatal("", e);