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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { TableManager.getInstance().removeTable(userId, tableId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() throws MageException { TableManager.getInstance().updateDeck(userId, tableId, deckList);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); logger.trace("Session " + sessionId + " updated deck");
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()) { if (!TableManager.getInstance().getController(tableId).changeTableStateToStarting()) {
return false; return false;
} }
execute("startMatch", sessionId, new Action() { execute("startMatch", sessionId, () -> {
@Override UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { TableManager.getInstance().startMatch(userId, roomId, tableId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { TableManager.getInstance().startTournament(userId, roomId, tableId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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,26 +518,20 @@ 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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { ChatManager.getInstance().joinChat(chatId, userId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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 if (chatId != null) {
public void execute() { UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
if (chatId != null) { ChatManager.getInstance().leaveChat(chatId, userId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); } else {
ChatManager.getInstance().leaveChat(chatId, userId); logger.warn("The chatId is null. sessionId = " + sessionId);
} else {
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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2);
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 // table was already started, so player can't leave anymore now
return false; return false;
} }
execute("leaveTable", sessionId, new Action() { execute("leaveTable", sessionId, () -> {
@Override UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { GameManager.getInstance().joinGame(gameId, userId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { DraftManager.getInstance().joinDraft(draftId, userId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { TournamentManager.getInstance().joinTournament(tournamentId, userId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
TournamentManager.getInstance().joinTournament(tournamentId, userId);
}
}); });
} }
@ -688,76 +650,61 @@ 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 User user = SessionManager.getInstance().getUser(sessionId);
public void execute() { if (user != null) {
User user = SessionManager.getInstance().getUser(sessionId);
if (user != null) {
// logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName()); // logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName());
user.sendPlayerUUID(gameId, data); user.sendPlayerUUID(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 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 User user = SessionManager.getInstance().getUser(sessionId);
public void execute() { if (user != null) {
User user = SessionManager.getInstance().getUser(sessionId); user.sendPlayerString(gameId, data);
if (user != null) { } else {
user.sendPlayerString(gameId, data); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} else {
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 User user = SessionManager.getInstance().getUser(sessionId);
public void execute() { if (user != null) {
User user = SessionManager.getInstance().getUser(sessionId); user.sendPlayerManaType(gameId, playerId, data);
if (user != null) { } else {
user.sendPlayerManaType(gameId, playerId, data); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} else {
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 User user = SessionManager.getInstance().getUser(sessionId);
public void execute() { if (user != null) {
User user = SessionManager.getInstance().getUser(sessionId); user.sendPlayerBoolean(gameId, data);
if (user != null) { } else {
user.sendPlayerBoolean(gameId, data); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} else {
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 User user = SessionManager.getInstance().getUser(sessionId);
public void execute() { if (user != null) {
User user = SessionManager.getInstance().getUser(sessionId); user.sendPlayerInteger(gameId, data);
if (user != null) { } else {
user.sendPlayerInteger(gameId, data); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
}
} }
}); });
} }
@ -780,81 +727,66 @@ 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 Session session = SessionManager.getInstance().getSession(sessionId);
public void execute() { if (session != null) {
Session session = SessionManager.getInstance().getSession(sessionId); DraftManager.getInstance().sendCardMark(draftId, session.getUserId(), cardPick);
if (session != null) { } else {
DraftManager.getInstance().sendCardMark(draftId, session.getUserId(), cardPick); logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId);
} else {
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 Session session = SessionManager.getInstance().getSession(sessionId);
public void execute() { if (session != null) {
Session session = SessionManager.getInstance().getSession(sessionId); GameManager.getInstance().quitMatch(gameId, session.getUserId());
if (session != null) { } else {
GameManager.getInstance().quitMatch(gameId, session.getUserId()); logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId);
} else {
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 Session session = SessionManager.getInstance().getSession(sessionId);
public void execute() { if (session != null) {
Session session = SessionManager.getInstance().getSession(sessionId); TournamentManager.getInstance().quit(tournamentId, session.getUserId());
if (session != null) { } else {
TournamentManager.getInstance().quit(tournamentId, session.getUserId()); logger.error("Session not found sessionId: " + sessionId + " tournamentId:" + tournamentId);
} else {
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 Session session = SessionManager.getInstance().getSession(sessionId);
public void execute() { if (session == null) {
Session session = SessionManager.getInstance().getSession(sessionId); logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId);
if (session == null) { return;
logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); }
return; UUID tableId = DraftManager.getInstance().getControllerByDraftId(draftId).getTableId();
} Table table = TableManager.getInstance().getTable(tableId);
UUID tableId = DraftManager.getInstance().getControllerByDraftId(draftId).getTableId(); if (table.isTournament()) {
Table table = TableManager.getInstance().getTable(tableId); UUID tournamentId = table.getTournament().getId();
if (table.isTournament()) { TournamentManager.getInstance().quit(tournamentId, session.getUserId());
UUID tournamentId = table.getTournament().getId();
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 Session session = SessionManager.getInstance().getSession(sessionId);
public void execute() { if (session == null) {
Session session = SessionManager.getInstance().getSession(sessionId); logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId);
if (session == null) { return;
logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId);
return;
}
GameManager.getInstance().sendPlayerAction(playerAction, gameId, session.getUserId(), data);
} }
GameManager.getInstance().sendPlayerAction(playerAction, gameId, session.getUserId(), data);
}); });
} }
@ -882,94 +814,70 @@ 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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { GameManager.getInstance().watchGame(gameId, userId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { User user = UserManager.getInstance().getUser(userId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); if (user != null) {
User user = UserManager.getInstance().getUser(userId); GameManager.getInstance().stopWatching(gameId, userId);
if (user != null) { user.removeGameWatchInfo(gameId);
GameManager.getInstance().stopWatching(gameId, userId);
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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { ReplayManager.getInstance().replayGame(gameId, userId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { ReplayManager.getInstance().startReplay(gameId, userId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { ReplayManager.getInstance().stopReplay(gameId, userId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { ReplayManager.getInstance().nextPlay(gameId, userId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { ReplayManager.getInstance().previousPlay(gameId, userId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { ReplayManager.getInstance().skipForward(gameId, userId, moves);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
ReplayManager.getInstance().skipForward(gameId, userId, moves);
}
}); });
} }
@ -996,13 +904,10 @@ 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 if (testMode) {
public void execute() { UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
if (testMode) { GameManager.getInstance().cheat(gameId, userId, playerId, deckList);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
GameManager.getInstance().cheat(gameId, userId, playerId, deckList);
}
} }
}); });
} }
@ -1071,74 +976,55 @@ 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 User user = UserManager.getInstance().getUserByName(userName);
public void execute() { if (user != null) {
User user = UserManager.getInstance().getUserByName(userName); Date muteUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE));
if (user != null) { user.showUserMessage("Admin info", "You were muted for chat messages until " + SystemUtil.dateFormat.format(muteUntil) + ".");
Date muteUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE)); user.setChatLockedUntil(muteUntil);
user.showUserMessage("Admin info", "You were muted for chat messages until " + SystemUtil.dateFormat.format(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 User user = UserManager.getInstance().getUserByName(userName);
public void execute() { if (user != null) {
User user = UserManager.getInstance().getUserByName(userName); Date lockUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE));
if (user != null) { user.showUserMessage("Admin info", "Your user profile was locked until " + SystemUtil.dateFormat.format(lockUntil) + ".");
Date lockUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE)); user.setLockedUntil(lockUntil);
user.showUserMessage("Admin info", "Your user profile was locked until " + SystemUtil.dateFormat.format(lockUntil) + "."); if (user.isConnected()) {
user.setLockedUntil(lockUntil); SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId());
if (user.isConnected()) {
SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId());
}
} }
} }
}); });
} }
@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 User user = UserManager.getInstance().getUserByName(userName);
public void execute() { if (user != null) {
User user = UserManager.getInstance().getUserByName(userName); user.setActive(!user.isActive());
if (user != null) { if (!user.isActive() && user.isConnected()) {
user.setActive(!user.isActive()); SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId());
if (!user.isActive() && user.isConnected()) {
SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId());
}
} }
} }
}); });
} }
@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 UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
public void execute() { TableManager.getInstance().removeTable(userId, tableId);
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
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 String host = SessionManager.getInstance().getSession(sessionId).getHost();
public void execute() { FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host);
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 @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 for (User user : UserManager.getInstance().getUsers()) {
public void execute() { if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) {
for (User user : UserManager.getInstance().getUsers()) { user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.RED)));
if (message.toLowerCase(Locale.ENGLISH).startsWith("warn")) { } else {
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.BLUE)));
} else {
user.fireCallback(new ClientCallback("serverMessage", null, new ChatMessage("SERVER", message, null, MessageColor.BLUE)));
}
} }
} }
}, true); }, true);
@ -1201,12 +1078,7 @@ public class MageServerImpl implements MageServer {
} }
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,18 +1094,15 @@ public class MageServerImpl implements MageServer {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.getInstance().isValidSession(sessionId)) {
try { try {
callExecutor.execute( callExecutor.execute(
new Runnable() { () -> {
@Override if (SessionManager.getInstance().isValidSession(sessionId)) {
public void run() { try {
if (SessionManager.getInstance().isValidSession(sessionId)) { action.execute();
try { } catch (MageException me) {
action.execute(); throw new RuntimeException(me);
} catch (MageException me) { }
throw new RuntimeException(me);
} }
} }
}
}
); );
} 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,20 +128,17 @@ public class TableController {
private void init() { private void init() {
match.addTableEventListener( match.addTableEventListener(
new Listener<TableEvent>() { (Listener<TableEvent>) event -> {
@Override try {
public void event(TableEvent event) { switch (event.getEventType()) {
try { case SIDEBOARD:
switch (event.getEventType()) { sideboard(event.getPlayerId(), event.getDeck());
case SIDEBOARD: break;
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(); 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,14 +87,11 @@ public class TableManager {
} }
private TableManager() { private TableManager() {
expireExecutor.scheduleAtFixedRate(new Runnable() { expireExecutor.scheduleAtFixedRate(() -> {
@Override try {
public void run() { checkTableHealthState();
try { } catch(Exception ex) {
checkTableHealthState(); logger.fatal("Check table health state job error:", ex);
} catch(Exception 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,21 +132,18 @@ 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 try {
public void run() { LOGGER.info("USER REMOVE - " + user.getName() + " (" + reason.toString() + ") userId: " + userId + " [" + user.getGameInfo() + "]");
try { user.remove(reason);
LOGGER.info("USER REMOVE - " + user.getName() + " (" + reason.toString() + ") userId: " + userId + " [" + user.getGameInfo() + "]"); LOGGER.debug("USER REMOVE END - " + user.getName());
user.remove(reason); } catch (Exception ex) {
LOGGER.debug("USER REMOVE END - " + user.getName()); handleException(ex);
} catch (Exception ex) { } finally {
handleException(ex); users.remove(userId);
} finally { usersByName.remove(user.getName());
users.remove(userId); }
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,14 +204,11 @@ public class UserManager {
} }
public void updateUserHistory() { public void updateUserHistory() {
USER_EXECUTOR.execute(new Runnable() { USER_EXECUTOR.execute(() -> {
@Override for (String updatedUser : UserStatsRepository.instance.updateUserStats()) {
public void run() { User user = getUserByName(updatedUser);
for (String updatedUser : UserStatsRepository.instance.updateUserStats()) { if (user != null) {
User user = getUserByName(updatedUser); user.resetUserStats();
if (user != null) {
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,133 +155,124 @@ public class GameController implements GameCallback {
private void init() { private void init() {
game.addTableEventListener( game.addTableEventListener(
new Listener<TableEvent>() { (Listener<TableEvent>) event -> {
@Override try {
public void event(TableEvent event) { PriorityTimer timer;
try { UUID playerId;
PriorityTimer timer; switch (event.getEventType()) {
UUID playerId; case UPDATE:
switch (event.getEventType()) { updateGame();
case UPDATE: break;
updateGame(); case INFO:
break; ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.GAME, null);
case INFO: logger.trace(game.getId() + " " + event.getMessage());
ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, ChatMessage.MessageType.GAME, null); break;
logger.trace(game.getId() + " " + event.getMessage()); case STATUS:
break; ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.ORANGE, event.getWithTime(), MessageType.GAME, null);
case STATUS: logger.trace(game.getId() + " " + event.getMessage());
ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.ORANGE, event.getWithTime(), ChatMessage.MessageType.GAME, null); break;
logger.trace(game.getId() + " " + event.getMessage()); case ERROR:
break; error(event.getMessage(), event.getException());
case ERROR: break;
error(event.getMessage(), event.getException()); case END_GAME_INFO:
break; endGameInfo();
case END_GAME_INFO: break;
endGameInfo(); case INIT_TIMER:
break; final UUID initPlayerId = event.getPlayerId();
case INIT_TIMER: if (initPlayerId == null) {
final UUID initPlayerId = event.getPlayerId(); throw new MageException("INIT_TIMER: playerId can't be null");
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");
} }
} createPlayerTimer(event.getPlayerId(), game.getPriorityTime());
timer.resume(); break;
break; case RESUME_TIMER:
case PAUSE_TIMER: playerId = event.getPlayerId();
playerId = event.getPlayerId(); if (playerId == null) {
if (playerId == null) { throw new MageException("RESUME_TIMER: playerId can't be null");
throw new MageException("PAUSE_TIMER: playerId can't be null"); }
} timer = timers.get(playerId);
timer = timers.get(playerId); if (timer == null) {
if (timer == null) { Player player = game.getState().getPlayer(playerId);
throw new MageException("PAUSE_TIMER: couldn't find timer for player: " + playerId); if (player != null) {
} timer = createPlayerTimer(event.getPlayerId(), player.getPriorityTimeLeft());
timer.pause(); } else {
break; 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( game.addPlayerQueryEventListener(
new Listener<PlayerQueryEvent>() { (Listener<PlayerQueryEvent>) event -> {
@Override logger.trace(new StringBuilder(event.getPlayerId().toString()).append("--").append(event.getQueryType()).append("--").append(event.getMessage()).toString());
public void event(PlayerQueryEvent event) { try {
logger.trace(new StringBuilder(event.getPlayerId().toString()).append("--").append(event.getQueryType()).append("--").append(event.getMessage()).toString()); switch (event.getQueryType()) {
try { case ASK:
switch (event.getQueryType()) { ask(event.getPlayerId(), event.getMessage(), event.getOptions());
case ASK: break;
ask(event.getPlayerId(), event.getMessage(), event.getOptions()); case PICK_TARGET:
break; target(event.getPlayerId(), event.getMessage(), event.getCards(), event.getPerms(), event.getTargets(), event.isRequired(), event.getOptions());
case PICK_TARGET: break;
target(event.getPlayerId(), event.getMessage(), event.getCards(), event.getPerms(), event.getTargets(), event.isRequired(), event.getOptions()); case PICK_ABILITY:
break; target(event.getPlayerId(), event.getMessage(), event.getAbilities(), event.isRequired(), event.getOptions());
case PICK_ABILITY: break;
target(event.getPlayerId(), event.getMessage(), event.getAbilities(), event.isRequired(), event.getOptions()); case SELECT:
break; select(event.getPlayerId(), event.getMessage(), event.getOptions());
case SELECT: break;
select(event.getPlayerId(), event.getMessage(), event.getOptions()); case PLAY_MANA:
break; playMana(event.getPlayerId(), event.getMessage(), event.getOptions());
case PLAY_MANA: break;
playMana(event.getPlayerId(), event.getMessage(), event.getOptions()); case PLAY_X_MANA:
break; playXMana(event.getPlayerId(), event.getMessage());
case PLAY_X_MANA: break;
playXMana(event.getPlayerId(), event.getMessage()); case CHOOSE_ABILITY:
break; String objectName = null;
case CHOOSE_ABILITY: if (event.getChoices() != null && event.getChoices().size() > 0) {
String objectName = null; objectName = event.getChoices().iterator().next();
if (event.getChoices() != null && event.getChoices().size() > 0) { }
objectName = event.getChoices().iterator().next(); chooseAbility(event.getPlayerId(), objectName, event.getAbilities());
} break;
chooseAbility(event.getPlayerId(), objectName, event.getAbilities()); case CHOOSE_PILE:
break; choosePile(event.getPlayerId(), event.getMessage(), event.getPile1(), event.getPile2());
case CHOOSE_PILE: break;
choosePile(event.getPlayerId(), event.getMessage(), event.getPile1(), event.getPile2()); case CHOOSE_MODE:
break; chooseMode(event.getPlayerId(), event.getModes());
case CHOOSE_MODE: break;
chooseMode(event.getPlayerId(), event.getModes()); case CHOOSE_CHOICE:
break; chooseChoice(event.getPlayerId(), event.getChoice());
case CHOOSE_CHOICE: break;
chooseChoice(event.getPlayerId(), event.getChoice()); case AMOUNT:
break; amount(event.getPlayerId(), event.getMessage(), event.getMin(), event.getMax());
case AMOUNT: break;
amount(event.getPlayerId(), event.getMessage(), event.getMin(), event.getMax()); case PERSONAL_MESSAGE:
break; informPersonal(event.getPlayerId(), event.getMessage());
case PERSONAL_MESSAGE: break;
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() { joinWaitingExecutor.scheduleAtFixedRate(() -> {
@Override try {
public void run() { sendInfoAboutPlayersNotJoinedYet();
try { } catch (Exception ex) {
sendInfoAboutPlayersNotJoinedYet(); logger.fatal("Send info about player not joined yet:", ex);
} catch (Exception 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 game.timerTimeout(initPlayerId);
public void execute() throws MageException { logger.debug("Player has no time left to end the match: " + initPlayerId + ". Conceding.");
game.timerTimeout(initPlayerId);
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 if (cards != null) {
public void execute(UUID playerId) { // Zone targetZone = (Zone) options.get("targetZone");
if (cards != null) { // Are there really situations where a player selects from a list of face down cards?
// Zone targetZone = (Zone) options.get("targetZone"); // So always show face up for selection
// Are there really situations where a player selects from a list of face down cards? // boolean showFaceDown = targetZone != null && targetZone.equals(Zone.PICK);
// So always show face up for selection boolean showFaceDown = true;
// boolean showFaceDown = targetZone != null && targetZone.equals(Zone.PICK); getGameSession(playerId1).target(question, new CardsView(game, cards.getCards(game), showFaceDown, true), targets, required, options);
boolean showFaceDown = true; } else if (perms != null) {
getGameSession(playerId).target(question, new CardsView(game, cards.getCards(game), showFaceDown, true), targets, required, options); CardsView permsView = new CardsView();
} else if (perms != null) { for (Permanent perm : perms) {
CardsView permsView = new CardsView(); permsView.put(perm.getId(), new PermanentView(perm, game.getCard(perm.getId()), playerId1, game));
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);
} }
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<? 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 CardsView cardsView = new CardsView(abilities, game);
public void execute(UUID playerId) { getGameSession(playerId1).target(question, cardsView, null, required, options);
CardsView cardsView = new CardsView(abilities, game);
getGameSession(playerId).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,34 +282,31 @@ 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 try {
public void run() { if (game.getStartTime() == null) {
try { // gameController is still waiting to start the game
if (game.getStartTime() == null) { player.leave();
// 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);
} else { } 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);
} }
} }
}
}
); );
} }

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 try {
public void run() { update();
try { } catch (Exception ex) {
update(); LOGGER.fatal("Games room update exception! " + ex.toString(), ex);
} catch (Exception 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,68 +88,62 @@ public class TournamentController {
private void init() { private void init() {
tournament.addTableEventListener( tournament.addTableEventListener(
new Listener<TableEvent>() { (Listener<TableEvent>) event -> {
@Override switch (event.getEventType()) {
public void event(TableEvent event) { case CHECK_STATE_PLAYERS:
switch (event.getEventType()) { checkPlayersState();
case CHECK_STATE_PLAYERS: break;
checkPlayersState(); case INFO:
break; ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.STATUS, null);
case INFO: logger.debug(tournament.getId() + " " + event.getMessage());
ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.STATUS, null); break;
logger.debug(tournament.getId() + " " + event.getMessage()); case START_DRAFT:
break; startDraft(event.getDraft());
case START_DRAFT: break;
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<PlayerQueryEvent>() {
@Override
public void event(PlayerQueryEvent event) {
try {
switch (event.getQueryType()) {
case CONSTRUCT: 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; break;
} }
} catch (MageException ex) {
logger.fatal("Player event listener error", ex);
} }
} );
} tournament.addPlayerQueryEventListener(
(Listener<PlayerQueryEvent>) 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()) { 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,16 +129,13 @@ 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);