rewrote singleton to enum where applicable

This commit is contained in:
ingmargoudt 2017-03-14 16:31:57 +01:00
parent 3b62489ef5
commit 234cfe9519
872 changed files with 1796 additions and 2135 deletions

View file

@ -36,10 +36,10 @@ import mage.client.dialog.PreferencesDialog;
public class SortSettingBase extends SortSetting { public class SortSettingBase extends SortSetting {
private final static SortSettingBase fInstance = new SortSettingBase(); private final static SortSettingBase instance = new SortSettingBase();
public static SortSettingBase getInstance() { public static SortSettingBase getInstance() {
return fInstance; return instance;
} }
private SortSettingBase() { private SortSettingBase() {

View file

@ -36,10 +36,10 @@ import mage.client.dialog.PreferencesDialog;
public class SortSettingDeck extends SortSetting { public class SortSettingDeck extends SortSetting {
private final static SortSettingDeck fInstance = new SortSettingDeck(); private final static SortSettingDeck instance = new SortSettingDeck();
public static SortSettingDeck getInstance() { public static SortSettingDeck getInstance() {
return fInstance; return instance;
} }
private SortSettingDeck() { private SortSettingDeck() {

View file

@ -36,10 +36,10 @@ import mage.client.dialog.PreferencesDialog;
*/ */
public class SortSettingDraft extends SortSetting { public class SortSettingDraft extends SortSetting {
private final static SortSettingDraft fInstance = new SortSettingDraft(); private final static SortSettingDraft instance = new SortSettingDraft();
public static SortSettingDraft getInstance() { public static SortSettingDraft getInstance() {
return fInstance; return instance;
} }
private SortSettingDraft() { private SortSettingDraft() {

View file

@ -36,10 +36,10 @@ import mage.client.dialog.PreferencesDialog;
public class SortSettingSideboard extends SortSetting { public class SortSettingSideboard extends SortSetting {
private static final SortSettingSideboard fInstance = new SortSettingSideboard(); private static final SortSettingSideboard instance = new SortSettingSideboard();
public static SortSettingSideboard getInstance() { public static SortSettingSideboard getInstance() {
return fInstance; return instance;
} }
private SortSettingSideboard() { private SortSettingSideboard() {

View file

@ -35,7 +35,7 @@ public class Plugins implements MagePlugins {
public static final String PLUGINS_DIRECTORY = "plugins/"; public static final String PLUGINS_DIRECTORY = "plugins/";
private static final MagePlugins fINSTANCE = new Plugins(); private static final MagePlugins instance = new Plugins();
private static final Logger LOGGER = Logger.getLogger(Plugins.class); private static final Logger LOGGER = Logger.getLogger(Plugins.class);
private static PluginManager pm; private static PluginManager pm;
@ -46,7 +46,7 @@ public class Plugins implements MagePlugins {
private final Map<String, String> sortingOptions = new HashMap<>(); private final Map<String, String> sortingOptions = new HashMap<>();
public static MagePlugins getInstance() { public static MagePlugins getInstance() {
return fINSTANCE; return instance;
} }
@Override @Override

View file

@ -9,10 +9,10 @@ import java.util.Map;
public class DelayedViewerThread extends Thread { public class DelayedViewerThread extends Thread {
private static final DelayedViewerThread fInstance = new DelayedViewerThread(); private static final DelayedViewerThread instance = new DelayedViewerThread();
public static DelayedViewerThread getInstance() { public static DelayedViewerThread getInstance() {
return fInstance; return instance;
} }
private final Map<Component, Long> delayedViewers; private final Map<Component, Long> delayedViewers;

View file

@ -8,10 +8,10 @@ import java.util.UUID;
* @author nantuko * @author nantuko
*/ */
public class GameManager { public class GameManager {
private static final GameManager fInstance = new GameManager(); private static final GameManager instance = new GameManager();
public static GameManager getInstance() { public static GameManager getInstance() {
return fInstance; return instance;
} }
public void setStackSize(int stackSize) { public void setStackSize(int stackSize) {

View file

@ -10,10 +10,10 @@ import org.mage.card.arcane.CardPanel;
* @author nantuko * @author nantuko
*/ */
public class SettingsManager { public class SettingsManager {
private static final SettingsManager fInstance = new SettingsManager(); private static final SettingsManager instance = new SettingsManager();
public static SettingsManager getInstance() { public static SettingsManager getInstance() {
return fInstance; return instance;
} }
public int getScreenWidth() { public int getScreenWidth() {

View file

@ -19,10 +19,10 @@ import org.mage.plugins.card.utils.Transparency;
public class ImageManagerImpl implements ImageManager { public class ImageManagerImpl implements ImageManager {
private static final ImageManagerImpl fInstance = new ImageManagerImpl(); private static final ImageManagerImpl instance = new ImageManagerImpl();
public static ImageManagerImpl getInstance() { public static ImageManagerImpl getInstance() {
return fInstance; return instance;
} }
public ImageManagerImpl() { public ImageManagerImpl() {

View file

@ -44,19 +44,12 @@ import java.util.regex.Pattern;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class ChatManager { public enum ChatManager {
instance;
private static final Logger logger = Logger.getLogger(ChatManager.class); private static final Logger logger = Logger.getLogger(ChatManager.class);
private static final HashMap<String, String> userMessages = new HashMap<>(); private static final HashMap<String, String> userMessages = new HashMap<>();
private static final ChatManager INSTANCE = new ChatManager();
public static ChatManager getInstance() {
return INSTANCE;
}
private ChatManager() {
}
private final ConcurrentHashMap<UUID, ChatSession> chatSessions = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, ChatSession> chatSessions = new ConcurrentHashMap<>();
@ -113,7 +106,7 @@ public class ChatManager {
ChatSession chatSession = chatSessions.get(chatId); ChatSession chatSession = chatSessions.get(chatId);
if (chatSession != null) { if (chatSession != null) {
if (message.startsWith("\\") || message.startsWith("/")) { if (message.startsWith("\\") || message.startsWith("/")) {
User user = UserManager.getInstance().getUserByName(userName); User user = UserManager.instance.getUserByName(userName);
if (user != null) { if (user != null) {
if (!performUserCommand(user, message, chatId, false)) { if (!performUserCommand(user, message, chatId, false)) {
performUserCommand(user, message, chatId, true); performUserCommand(user, message, chatId, true);
@ -123,7 +116,7 @@ public class ChatManager {
} }
if (messageType != MessageType.GAME) { if (messageType != MessageType.GAME) {
User user = UserManager.getInstance().getUserByName(userName); User user = UserManager.instance.getUserByName(userName);
if (message != null && userName != null && !userName.isEmpty()) { if (message != null && userName != null && !userName.isEmpty()) {
if (message.equals(userMessages.get(userName))) { if (message.equals(userMessages.get(userName))) {
@ -205,12 +198,12 @@ public class ChatManager {
} }
if (command.startsWith("H ") || command.startsWith("HISTORY ")) { if (command.startsWith("H ") || command.startsWith("HISTORY ")) {
message += "<br/>" + UserManager.getInstance().getUserHistory(message.substring(command.startsWith("H ") ? 3 : 9)); message += "<br/>" + UserManager.instance.getUserHistory(message.substring(command.startsWith("H ") ? 3 : 9));
chatSessions.get(chatId).broadcastInfoToUser(user, message); chatSessions.get(chatId).broadcastInfoToUser(user, message);
return true; return true;
} }
if (command.equals("ME")) { if (command.equals("ME")) {
message += "<br/>" + UserManager.getInstance().getUserHistory(user.getName()); message += "<br/>" + UserManager.instance.getUserHistory(user.getName());
chatSessions.get(chatId).broadcastInfoToUser(user, message); chatSessions.get(chatId).broadcastInfoToUser(user, message);
return true; return true;
} }
@ -220,7 +213,7 @@ public class ChatManager {
if (first > 1) { if (first > 1) {
String userToName = rest.substring(0, first); String userToName = rest.substring(0, first);
rest = rest.substring(first + 1).trim(); rest = rest.substring(first + 1).trim();
User userTo = UserManager.getInstance().getUserByName(userToName); User userTo = UserManager.instance.getUserByName(userToName);
if (userTo != null) { if (userTo != null) {
if (!chatSessions.get(chatId).broadcastWhisperToUser(user, userTo, rest)) { if (!chatSessions.get(chatId).broadcastWhisperToUser(user, userTo, rest)) {
message += new StringBuilder("<br/>User ").append(userToName).append(" not found").toString(); message += new StringBuilder("<br/>User ").append(userToName).append(" not found").toString();
@ -251,7 +244,7 @@ public class ChatManager {
* @param color * @param color
*/ */
public void broadcast(UUID userId, String message, MessageColor color) throws UserNotFoundException { public void broadcast(UUID userId, String message, MessageColor color) throws UserNotFoundException {
UserManager.getInstance().getUser(userId).ifPresent(user-> { UserManager.instance.getUser(userId).ifPresent(user-> {
chatSessions.values() chatSessions.values()
.stream() .stream()
.filter(chat -> chat.hasUser(userId)) .filter(chat -> chat.hasUser(userId))
@ -261,7 +254,7 @@ public class ChatManager {
} }
public void sendReconnectMessage(UUID userId) { public void sendReconnectMessage(UUID userId) {
UserManager.getInstance().getUser(userId).ifPresent(user -> UserManager.instance.getUser(userId).ifPresent(user ->
chatSessions.values() chatSessions.values()
.stream() .stream()
.filter(chat -> chat.hasUser(userId)) .filter(chat -> chat.hasUser(userId))

View file

@ -61,7 +61,7 @@ public class ChatSession {
} }
public void join(UUID userId) { public void join(UUID userId) {
UserManager.getInstance().getUser(userId).ifPresent(user-> { UserManager.instance.getUser(userId).ifPresent(user-> {
if (!clients.containsKey(userId)) { if (!clients.containsKey(userId)) {
String userName = user.getName(); String userName = user.getName();
clients.put(userId, userName); clients.put(userId, userName);
@ -142,7 +142,7 @@ public class ChatSession {
HashSet<UUID> clientsToRemove = null; HashSet<UUID> clientsToRemove = null;
ClientCallback clientCallback = new ClientCallback("chatMessage", chatId, new ChatMessage(userName, message, (withTime ? timeFormatter.format(new Date()) : ""), color, messageType, soundToPlay)); ClientCallback clientCallback = new ClientCallback("chatMessage", chatId, new ChatMessage(userName, message, (withTime ? timeFormatter.format(new Date()) : ""), color, messageType, soundToPlay));
for (UUID userId : clients.keySet()) { for (UUID userId : clients.keySet()) {
Optional<User> user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
if (user.isPresent()) { if (user.isPresent()) {
user.get().fireCallback(clientCallback); user.get().fireCallback(clientCallback);
} else { } else {

View file

@ -80,8 +80,8 @@ public final class GmailClient {
Message message = new Message(); Message message = new Message();
message.setRaw(Base64.encodeBase64URLSafeString(baos.toByteArray())); message.setRaw(Base64.encodeBase64URLSafeString(baos.toByteArray()));
gmail.users().messages().send(ConfigSettings.getInstance().getGoogleAccount() gmail.users().messages().send(ConfigSettings.instance.getGoogleAccount()
+ (ConfigSettings.getInstance().getGoogleAccount().endsWith("@gmail.com") ? "" : "@gmail.com"), message).execute(); + (ConfigSettings.instance.getGoogleAccount().endsWith("@gmail.com") ? "" : "@gmail.com"), message).execute();
return true; return true;
} catch (MessagingException | IOException ex) { } catch (MessagingException | IOException ex) {
logger.error("Error sending message", ex); logger.error("Error sending message", ex);

View file

@ -90,12 +90,12 @@ public class MageServerImpl implements MageServer {
public MageServerImpl(String adminPassword, boolean testMode) { public MageServerImpl(String adminPassword, boolean testMode) {
this.adminPassword = adminPassword; this.adminPassword = adminPassword;
this.testMode = testMode; this.testMode = testMode;
ServerMessagesUtil.getInstance().getMessages(); ServerMessagesUtil.instance.getMessages();
} }
@Override @Override
public boolean registerUser(String sessionId, String userName, String password, String email) throws MageException { public boolean registerUser(String sessionId, String userName, String password, String email) throws MageException {
return SessionManager.getInstance().registerUser(sessionId, userName, password, email); return SessionManager.instance.registerUser(sessionId, userName, password, email);
} }
// generateAuthToken returns a uniformly distributed 6-digits string. // generateAuthToken returns a uniformly distributed 6-digits string.
@ -105,7 +105,7 @@ public class MageServerImpl implements MageServer {
@Override @Override
public boolean emailAuthToken(String sessionId, String email) throws MageException { public boolean emailAuthToken(String sessionId, String email) throws MageException {
if (!ConfigSettings.getInstance().isAuthenticationActivated()) { if (!ConfigSettings.instance.isAuthenticationActivated()) {
sendErrorMessageToClient(sessionId, "Registration is disabled by the server config"); sendErrorMessageToClient(sessionId, "Registration is disabled by the server config");
return false; return false;
} }
@ -121,7 +121,7 @@ public class MageServerImpl implements MageServer {
String text = "Use this auth token to reset " + authorizedUser.name + "'s password: " + authToken + '\n' String text = "Use this auth token to reset " + authorizedUser.name + "'s password: " + authToken + '\n'
+ "It's valid until the next server restart."; + "It's valid until the next server restart.";
boolean success; boolean success;
if (!ConfigSettings.getInstance().getMailUser().isEmpty()) { if (!ConfigSettings.instance.getMailUser().isEmpty()) {
success = MailClient.sendMessage(email, subject, text); success = MailClient.sendMessage(email, subject, text);
} else { } else {
success = MailgunClient.sendMessage(email, subject, text); success = MailgunClient.sendMessage(email, subject, text);
@ -135,7 +135,7 @@ public class MageServerImpl implements MageServer {
@Override @Override
public boolean resetPassword(String sessionId, String email, String authToken, String password) throws MageException { public boolean resetPassword(String sessionId, String email, String authToken, String password) throws MageException {
if (!ConfigSettings.getInstance().isAuthenticationActivated()) { if (!ConfigSettings.instance.isAuthenticationActivated()) {
sendErrorMessageToClient(sessionId, "Registration is disabled by the server config"); sendErrorMessageToClient(sessionId, "Registration is disabled by the server config");
return false; return false;
} }
@ -164,7 +164,7 @@ public class MageServerImpl implements MageServer {
logger.info("MageVersionException: userName=" + userName + ", version=" + version); logger.info("MageVersionException: userName=" + userName + ", version=" + version);
throw new MageVersionException(version, Main.getVersion()); throw new MageVersionException(version, Main.getVersion());
} }
return SessionManager.getInstance().connectUser(sessionId, userName, password, userIdStr); return SessionManager.instance.connectUser(sessionId, userName, password, userIdStr);
} catch (MageException ex) { } catch (MageException ex) {
if (ex instanceof MageVersionException) { if (ex instanceof MageVersionException) {
throw (MageVersionException) ex; throw (MageVersionException) ex;
@ -179,7 +179,7 @@ public class MageServerImpl implements MageServer {
return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() { return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() {
@Override @Override
public Boolean execute() throws MageException { public Boolean execute() throws MageException {
return SessionManager.getInstance().setUserData(userName, sessionId, userData, clientVersion, userIdStr); return SessionManager.instance.setUserData(userName, sessionId, userData, clientVersion, userIdStr);
} }
}); });
} }
@ -193,7 +193,7 @@ public class MageServerImpl implements MageServer {
if (!adminPassword.equals(this.adminPassword)) { if (!adminPassword.equals(this.adminPassword)) {
throw new MageException("Wrong password"); throw new MageException("Wrong password");
} }
return SessionManager.getInstance().connectAdmin(sessionId); return SessionManager.instance.connectAdmin(sessionId);
} catch (Exception ex) { } catch (Exception ex) {
handleException(ex); handleException(ex);
} }
@ -211,8 +211,8 @@ public class MageServerImpl implements MageServer {
@Override @Override
public TableView execute() throws MageException { public TableView execute() throws MageException {
try { try {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
Optional<User> _user = UserManager.getInstance().getUser(userId); Optional<User> _user = UserManager.instance.getUser(userId);
if (!_user.isPresent()) { if (!_user.isPresent()) {
logger.error("User for session not found. session = " + sessionId); logger.error("User for session not found. session = " + sessionId);
return null; return null;
@ -225,7 +225,7 @@ public class MageServerImpl implements MageServer {
throw new MageException("No message"); throw new MageException("No message");
} }
// check AI players max // check AI players max
String maxAiOpponents = ConfigSettings.getInstance().getMaxAiOpponents(); String maxAiOpponents = ConfigSettings.instance.getMaxAiOpponents();
if (maxAiOpponents != null) { if (maxAiOpponents != null) {
int aiPlayers = 0; int aiPlayers = 0;
for (String playerType : options.getPlayerTypes()) { for (String playerType : options.getPlayerTypes()) {
@ -247,7 +247,7 @@ public class MageServerImpl implements MageServer {
user.showUserMessage("Create tournament", message); user.showUserMessage("Create tournament", message);
throw new MageException("No message"); throw new MageException("No message");
} }
TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTournamentTable(userId, options); TableView table = GamesRoomManager.instance.getRoom(roomId).createTournamentTable(userId, options);
logger.debug("Tournament table " + table.getTableId() + " created"); logger.debug("Tournament table " + table.getTableId() + " created");
return table; return table;
} catch (Exception ex) { } catch (Exception ex) {
@ -261,8 +261,8 @@ 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, () -> { execute("removeTable", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
TableManager.getInstance().removeTable(userId, tableId); TableManager.instance.removeTable(userId, tableId);
}); });
} }
@ -271,13 +271,13 @@ public class MageServerImpl implements MageServer {
return executeWithResult("joinTable", sessionId, new ActionWithBooleanResult() { return executeWithResult("joinTable", sessionId, new ActionWithBooleanResult() {
@Override @Override
public Boolean execute() throws MageException { public Boolean execute() throws MageException {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
logger.debug(name + " joins tableId: " + tableId); logger.debug(name + " joins tableId: " + tableId);
if (userId == null) { if (userId == null) {
logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId);
return false; return false;
} }
return GamesRoomManager.getInstance().getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList, password); return GamesRoomManager.instance.getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList, password);
} }
}); });
@ -288,16 +288,16 @@ public class MageServerImpl implements MageServer {
return executeWithResult("joinTournamentTable", sessionId, new ActionWithBooleanResult() { return executeWithResult("joinTournamentTable", sessionId, new ActionWithBooleanResult() {
@Override @Override
public Boolean execute() throws MageException { public Boolean execute() throws MageException {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
Optional<User> user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
user.ifPresent(user1 -> logger.trace("join tourn. tableId: " + tableId + ' ' + name)); user.ifPresent(user1 -> logger.trace("join tourn. tableId: " + tableId + ' ' + name));
} }
if (userId == null) { if (userId == null) {
logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId);
return false; return false;
} }
return GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill, deckList, password); return GamesRoomManager.instance.getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill, deckList, password);
} }
}); });
@ -308,8 +308,8 @@ public class MageServerImpl implements MageServer {
return executeWithResult("submitDeck", sessionId, new ActionWithBooleanResult() { return executeWithResult("submitDeck", sessionId, new ActionWithBooleanResult() {
@Override @Override
public Boolean execute() throws MageException { public Boolean execute() throws MageException {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
boolean ret = TableManager.getInstance().submitDeck(userId, tableId, deckList); boolean ret = TableManager.instance.submitDeck(userId, tableId, deckList);
logger.debug("Session " + sessionId + " submitted deck"); logger.debug("Session " + sessionId + " submitted deck");
return ret; return ret;
} }
@ -319,8 +319,8 @@ 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, () -> { execute("updateDeck", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
TableManager.getInstance().updateDeck(userId, tableId, deckList); TableManager.instance.updateDeck(userId, tableId, deckList);
logger.trace("Session " + sessionId + " updated deck"); logger.trace("Session " + sessionId + " updated deck");
}); });
} }
@ -329,7 +329,7 @@ public class MageServerImpl implements MageServer {
//FIXME: why no sessionId here??? //FIXME: why no sessionId here???
public List<TableView> getTables(UUID roomId) throws MageException { public List<TableView> getTables(UUID roomId) throws MageException {
try { try {
GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); GamesRoom room = GamesRoomManager.instance.getRoom(roomId);
if (room != null) { if (room != null) {
return room.getTables(); return room.getTables();
} else { } else {
@ -345,7 +345,7 @@ public class MageServerImpl implements MageServer {
//FIXME: why no sessionId here??? //FIXME: why no sessionId here???
public List<MatchView> getFinishedMatches(UUID roomId) throws MageException { public List<MatchView> getFinishedMatches(UUID roomId) throws MageException {
try { try {
GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); GamesRoom room = GamesRoomManager.instance.getRoom(roomId);
if (room != null) { if (room != null) {
return room.getFinished(); return room.getFinished();
} else { } else {
@ -360,7 +360,7 @@ public class MageServerImpl implements MageServer {
@Override @Override
public List<RoomUsersView> getRoomUsers(UUID roomId) throws MageException { public List<RoomUsersView> getRoomUsers(UUID roomId) throws MageException {
try { try {
GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); GamesRoom room = GamesRoomManager.instance.getRoom(roomId);
if (room != null) { if (room != null) {
return room.getRoomUsersInfo(); return room.getRoomUsersInfo();
} else { } else {
@ -376,7 +376,7 @@ public class MageServerImpl implements MageServer {
//FIXME: why no sessionId here??? //FIXME: why no sessionId here???
public TableView getTable(UUID roomId, UUID tableId) throws MageException { public TableView getTable(UUID roomId, UUID tableId) throws MageException {
try { try {
GamesRoom room = GamesRoomManager.getInstance().getRoom(roomId); GamesRoom room = GamesRoomManager.instance.getRoom(roomId);
if (room != null) { if (room != null) {
return room.getTable(tableId); return room.getTable(tableId);
} else { } else {
@ -390,7 +390,7 @@ public class MageServerImpl implements MageServer {
@Override @Override
public boolean ping(String sessionId, String pingInfo) { public boolean ping(String sessionId, String pingInfo) {
return SessionManager.getInstance().extendUserSession(sessionId, pingInfo); return SessionManager.instance.extendUserSession(sessionId, pingInfo);
} }
// @Override // @Override
@ -398,19 +398,19 @@ public class MageServerImpl implements MageServer {
// execute("deregisterClient", sessionId, new Action() { // execute("deregisterClient", sessionId, new Action() {
// @Override // @Override
// public void execute() { // public void execute() {
// SessionManager.getInstance().disconnect(sessionId, true); // SessionManager.instance.disconnect(sessionId, true);
// logger.debug("Client deregistered ..."); // logger.debug("Client deregistered ...");
// } // }
// }); // });
// } // }
@Override @Override
public boolean startMatch(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { public boolean startMatch(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
if (!TableManager.getInstance().getController(tableId).changeTableStateToStarting()) { if (!TableManager.instance.getController(tableId).changeTableStateToStarting()) {
return false; return false;
} }
execute("startMatch", sessionId, () -> { execute("startMatch", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
TableManager.getInstance().startMatch(userId, roomId, tableId); TableManager.instance.startMatch(userId, roomId, tableId);
}); });
return true; return true;
} }
@ -420,19 +420,19 @@ public class MageServerImpl implements MageServer {
// execute("startChallenge", sessionId, new Action() { // execute("startChallenge", sessionId, new Action() {
// @Override // @Override
// public void execute() { // public void execute() {
// UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); // UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
// TableManager.getInstance().startChallenge(userId, roomId, tableId, challengeId); // TableManager.instance.startChallenge(userId, roomId, tableId, challengeId);
// } // }
// }); // });
// } // }
@Override @Override
public boolean startTournament(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { public boolean startTournament(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
if (!TableManager.getInstance().getController(tableId).changeTableStateToStarting()) { if (!TableManager.instance.getController(tableId).changeTableStateToStarting()) {
return false; return false;
} }
execute("startTournament", sessionId, () -> { execute("startTournament", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
TableManager.getInstance().startTournament(userId, roomId, tableId); TableManager.instance.startTournament(userId, roomId, tableId);
}); });
return true; return true;
} }
@ -441,7 +441,7 @@ public class MageServerImpl implements MageServer {
//FIXME: why no sessionId here??? //FIXME: why no sessionId here???
public TournamentView getTournament(UUID tournamentId) throws MageException { public TournamentView getTournament(UUID tournamentId) throws MageException {
try { try {
return TournamentManager.getInstance().getTournamentView(tournamentId); return TournamentManager.instance.getTournamentView(tournamentId);
} catch (Exception ex) { } catch (Exception ex) {
handleException(ex); handleException(ex);
} }
@ -453,7 +453,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(
() -> ChatManager.getInstance().broadcast(chatId, userName, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE, true, ChatMessage.MessageType.TALK, null) () -> ChatManager.instance.broadcast(chatId, userName, StringEscapeUtils.escapeHtml4(message), MessageColor.BLUE, true, ChatMessage.MessageType.TALK, null)
); );
} catch (Exception ex) { } catch (Exception ex) {
handleException(ex); handleException(ex);
@ -463,8 +463,8 @@ 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, () -> { execute("joinChat", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
ChatManager.getInstance().joinChat(chatId, userId); ChatManager.instance.joinChat(chatId, userId);
}); });
} }
@ -472,8 +472,8 @@ public class MageServerImpl implements MageServer {
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, () -> { execute("leaveChat", sessionId, () -> {
if (chatId != null) { if (chatId != null) {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
ChatManager.getInstance().leaveChat(chatId, userId); ChatManager.instance.leaveChat(chatId, userId);
} else { } else {
logger.warn("The chatId is null. sessionId = " + sessionId); logger.warn("The chatId is null. sessionId = " + sessionId);
} }
@ -484,7 +484,7 @@ public class MageServerImpl implements MageServer {
//FIXME: why no sessionId here??? //FIXME: why no sessionId here???
public UUID getMainRoomId() throws MageException { public UUID getMainRoomId() throws MageException {
try { try {
return GamesRoomManager.getInstance().getMainRoomId(); return GamesRoomManager.instance.getMainRoomId();
} catch (Exception ex) { } catch (Exception ex) {
handleException(ex); handleException(ex);
} }
@ -495,7 +495,7 @@ public class MageServerImpl implements MageServer {
//FIXME: why no sessionId here??? //FIXME: why no sessionId here???
public UUID getRoomChatId(UUID roomId) throws MageException { public UUID getRoomChatId(UUID roomId) throws MageException {
try { try {
return GamesRoomManager.getInstance().getRoom(roomId).getChatId(); return GamesRoomManager.instance.getRoom(roomId).getChatId();
} catch (Exception ex) { } catch (Exception ex) {
handleException(ex); handleException(ex);
} }
@ -507,8 +507,8 @@ public class MageServerImpl implements MageServer {
return executeWithResult("isTableOwner", sessionId, new ActionWithBooleanResult() { return executeWithResult("isTableOwner", sessionId, new ActionWithBooleanResult() {
@Override @Override
public Boolean execute() { public Boolean execute() {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
return TableManager.getInstance().isTableOwner(tableId, userId); return TableManager.instance.isTableOwner(tableId, userId);
} }
}); });
} }
@ -516,21 +516,21 @@ 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, () -> { execute("swapSeats", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2); TableManager.instance.swapSeats(tableId, userId, seatNum1, seatNum2);
}); });
} }
@Override @Override
public boolean leaveTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException { public boolean leaveTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
TableState tableState = TableManager.getInstance().getController(tableId).getTableState(); TableState tableState = TableManager.instance.getController(tableId).getTableState();
if (tableState != TableState.WAITING && tableState != TableState.READY_TO_START) { if (tableState != TableState.WAITING && tableState != TableState.READY_TO_START) {
// 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, () -> { execute("leaveTable", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId); GamesRoomManager.instance.getRoom(roomId).leaveTable(userId, tableId);
}); });
return true; return true;
} }
@ -539,7 +539,7 @@ public class MageServerImpl implements MageServer {
//FIXME: why no sessionId here??? //FIXME: why no sessionId here???
public UUID getTableChatId(UUID tableId) throws MageException { public UUID getTableChatId(UUID tableId) throws MageException {
try { try {
return TableManager.getInstance().getChatId(tableId); return TableManager.instance.getChatId(tableId);
} catch (Exception ex) { } catch (Exception ex) {
handleException(ex); handleException(ex);
} }
@ -549,24 +549,24 @@ 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, () -> { execute("joinGame", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
GameManager.getInstance().joinGame(gameId, userId); GameManager.instance.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, () -> { execute("joinDraft", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
DraftManager.getInstance().joinDraft(draftId, userId); DraftManager.instance.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, () -> { execute("joinTournament", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
TournamentManager.getInstance().joinTournament(tournamentId, userId); TournamentManager.instance.joinTournament(tournamentId, userId);
}); });
} }
@ -574,7 +574,7 @@ public class MageServerImpl implements MageServer {
//FIXME: why no sessionId here??? //FIXME: why no sessionId here???
public UUID getGameChatId(UUID gameId) throws MageException { public UUID getGameChatId(UUID gameId) throws MageException {
try { try {
return GameManager.getInstance().getChatId(gameId); return GameManager.instance.getChatId(gameId);
} catch (Exception ex) { } catch (Exception ex) {
handleException(ex); handleException(ex);
} }
@ -585,7 +585,7 @@ public class MageServerImpl implements MageServer {
//FIXME: why no sessionId here??? //FIXME: why no sessionId here???
public UUID getTournamentChatId(UUID tournamentId) throws MageException { public UUID getTournamentChatId(UUID tournamentId) throws MageException {
try { try {
return TournamentManager.getInstance().getChatId(tournamentId); return TournamentManager.instance.getChatId(tournamentId);
} catch (Exception ex) { } catch (Exception ex) {
handleException(ex); handleException(ex);
} }
@ -595,7 +595,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, () -> { execute("sendPlayerUUID", sessionId, () -> {
Optional<User> user = SessionManager.getInstance().getUser(sessionId); Optional<User> user = SessionManager.instance.getUser(sessionId);
if (user.isPresent()) { if (user.isPresent()) {
// logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName()); // logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName());
user.get().sendPlayerUUID(gameId, data); user.get().sendPlayerUUID(gameId, data);
@ -608,7 +608,7 @@ public class MageServerImpl implements MageServer {
@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, () -> { execute("sendPlayerString", sessionId, () -> {
Optional<User> user = SessionManager.getInstance().getUser(sessionId); Optional<User> user = SessionManager.instance.getUser(sessionId);
if (user.isPresent()) { if (user.isPresent()) {
user.get().sendPlayerString(gameId, data); user.get().sendPlayerString(gameId, data);
} else { } else {
@ -620,7 +620,7 @@ public class MageServerImpl implements MageServer {
@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, () -> { execute("sendPlayerManaType", sessionId, () -> {
Optional<User> user = SessionManager.getInstance().getUser(sessionId); Optional<User> user = SessionManager.instance.getUser(sessionId);
if (user.isPresent()) { if (user.isPresent()) {
user.get().sendPlayerManaType(gameId, playerId, data); user.get().sendPlayerManaType(gameId, playerId, data);
} else { } else {
@ -632,7 +632,7 @@ public class MageServerImpl implements MageServer {
@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, () -> { execute("sendPlayerBoolean", sessionId, () -> {
Optional<User> user = SessionManager.getInstance().getUser(sessionId); Optional<User> user = SessionManager.instance.getUser(sessionId);
if (user.isPresent()) { if (user.isPresent()) {
user.get().sendPlayerBoolean(gameId, data); user.get().sendPlayerBoolean(gameId, data);
} else { } else {
@ -644,7 +644,7 @@ public class MageServerImpl implements MageServer {
@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, () -> { execute("sendPlayerInteger", sessionId, () -> {
Optional<User> user = SessionManager.getInstance().getUser(sessionId); Optional<User> user = SessionManager.instance.getUser(sessionId);
if (user.isPresent()) { if (user.isPresent()) {
user.get().sendPlayerInteger(gameId, data); user.get().sendPlayerInteger(gameId, data);
} else { } else {
@ -661,9 +661,9 @@ 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, () -> { execute("sendCardMark", sessionId, () -> {
Session session = SessionManager.getInstance().getSession(sessionId); Session session = SessionManager.instance.getSession(sessionId);
if (session != null) { if (session != null) {
DraftManager.getInstance().sendCardMark(draftId, session.getUserId(), cardPick); DraftManager.instance.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);
} }
@ -673,9 +673,9 @@ public class MageServerImpl implements MageServer {
@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, () -> { execute("quitMatch", sessionId, () -> {
Session session = SessionManager.getInstance().getSession(sessionId); Session session = SessionManager.instance.getSession(sessionId);
if (session != null) { if (session != null) {
GameManager.getInstance().quitMatch(gameId, session.getUserId()); GameManager.instance.quitMatch(gameId, session.getUserId());
} else { } else {
logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId); logger.error("Session not found sessionId: " + sessionId + " gameId:" + gameId);
} }
@ -685,9 +685,9 @@ public class MageServerImpl implements MageServer {
@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, () -> { execute("quitTournament", sessionId, () -> {
Session session = SessionManager.getInstance().getSession(sessionId); Session session = SessionManager.instance.getSession(sessionId);
if (session != null) { if (session != null) {
TournamentManager.getInstance().quit(tournamentId, session.getUserId()); TournamentManager.instance.quit(tournamentId, session.getUserId());
} else { } else {
logger.error("Session not found sessionId: " + sessionId + " tournamentId:" + tournamentId); logger.error("Session not found sessionId: " + sessionId + " tournamentId:" + tournamentId);
} }
@ -697,16 +697,16 @@ public class MageServerImpl implements MageServer {
@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, () -> { execute("quitDraft", sessionId, () -> {
Session session = SessionManager.getInstance().getSession(sessionId); Session session = SessionManager.instance.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);
return; return;
} }
UUID tableId = DraftManager.getInstance().getControllerByDraftId(draftId).getTableId(); UUID tableId = DraftManager.instance.getControllerByDraftId(draftId).getTableId();
Table table = TableManager.getInstance().getTable(tableId); Table table = TableManager.instance.getTable(tableId);
if (table.isTournament()) { if (table.isTournament()) {
UUID tournamentId = table.getTournament().getId(); UUID tournamentId = table.getTournament().getId();
TournamentManager.getInstance().quit(tournamentId, session.getUserId()); TournamentManager.instance.quit(tournamentId, session.getUserId());
} }
}); });
} }
@ -714,12 +714,12 @@ public class MageServerImpl implements MageServer {
@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, () -> { execute("sendPlayerAction", sessionId, () -> {
Session session = SessionManager.getInstance().getSession(sessionId); Session session = SessionManager.instance.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.instance.sendPlayerAction(playerAction, gameId, session.getUserId(), data);
}); });
} }
@ -728,8 +728,8 @@ public class MageServerImpl implements MageServer {
return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() { return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() {
@Override @Override
public Boolean execute() throws MageException { public Boolean execute() throws MageException {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
return GamesRoomManager.getInstance().getRoom(roomId).watchTable(userId, tableId); return GamesRoomManager.instance.getRoom(roomId).watchTable(userId, tableId);
} }
}); });
} }
@ -742,17 +742,17 @@ 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, () -> { execute("watchGame", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
GameManager.getInstance().watchGame(gameId, userId); GameManager.instance.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, () -> { execute("stopWatching", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
UserManager.getInstance().getUser(userId).ifPresent(user -> { UserManager.instance.getUser(userId).ifPresent(user -> {
GameManager.getInstance().stopWatching(gameId, userId); GameManager.instance.stopWatching(gameId, userId);
user.removeGameWatchInfo(gameId); user.removeGameWatchInfo(gameId);
}); });
@ -762,48 +762,48 @@ public class MageServerImpl implements MageServer {
@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, () -> { execute("replayGame", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
ReplayManager.getInstance().replayGame(gameId, userId); ReplayManager.instance.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, () -> { execute("startReplay", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
ReplayManager.getInstance().startReplay(gameId, userId); ReplayManager.instance.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, () -> { execute("stopReplay", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
ReplayManager.getInstance().stopReplay(gameId, userId); ReplayManager.instance.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, () -> { execute("nextPlay", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
ReplayManager.getInstance().nextPlay(gameId, userId); ReplayManager.instance.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, () -> { execute("previousPlay", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
ReplayManager.getInstance().previousPlay(gameId, userId); ReplayManager.instance.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, () -> { execute("skipForward", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
ReplayManager.getInstance().skipForward(gameId, userId, moves); ReplayManager.instance.skipForward(gameId, userId, moves);
}); });
} }
@ -832,8 +832,8 @@ public class MageServerImpl implements MageServer {
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, () -> { execute("cheat", sessionId, () -> {
if (testMode) { if (testMode) {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
GameManager.getInstance().cheat(gameId, userId, playerId, deckList); GameManager.instance.cheat(gameId, userId, playerId, deckList);
} }
}); });
} }
@ -844,8 +844,8 @@ public class MageServerImpl implements MageServer {
@Override @Override
public Boolean execute() { public Boolean execute() {
if (testMode) { if (testMode) {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
return GameManager.getInstance().cheat(gameId, userId, playerId, cardName); return GameManager.instance.cheat(gameId, userId, playerId, cardName);
} }
return false; return false;
} }
@ -878,13 +878,13 @@ 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, () -> SessionManager.getInstance().disconnectUser(sessionId, userSessionId)); execute("disconnectUser", sessionId, () -> SessionManager.instance.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, () -> { execute("muteUser", sessionId, () -> {
User user = UserManager.getInstance().getUserByName(userName); User user = UserManager.instance.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));
user.showUserMessage("Admin info", "You were muted for chat messages until " + SystemUtil.dateFormat.format(muteUntil) + '.'); user.showUserMessage("Admin info", "You were muted for chat messages until " + SystemUtil.dateFormat.format(muteUntil) + '.');
@ -897,13 +897,13 @@ public class MageServerImpl implements MageServer {
@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, () -> { execute("lockUser", sessionId, () -> {
User user = UserManager.getInstance().getUserByName(userName); User user = UserManager.instance.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));
user.showUserMessage("Admin info", "Your user profile was locked until " + SystemUtil.dateFormat.format(lockUntil) + '.'); user.showUserMessage("Admin info", "Your user profile was locked until " + SystemUtil.dateFormat.format(lockUntil) + '.');
user.setLockedUntil(lockUntil); user.setLockedUntil(lockUntil);
if (user.isConnected()) { if (user.isConnected()) {
SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId()); SessionManager.instance.disconnectUser(sessionId, user.getSessionId());
} }
} }
@ -914,11 +914,11 @@ public class MageServerImpl implements MageServer {
public void setActivation(final String sessionId, final String userName, boolean active) throws MageException { public void setActivation(final String sessionId, final String userName, boolean active) throws MageException {
execute("setActivation", sessionId, () -> { execute("setActivation", sessionId, () -> {
AuthorizedUser authorizedUser = AuthorizedUserRepository.instance.getByName(userName); AuthorizedUser authorizedUser = AuthorizedUserRepository.instance.getByName(userName);
User user = UserManager.getInstance().getUserByName(userName); User user = UserManager.instance.getUserByName(userName);
if (user != null) { if (user != null) {
user.setActive(active); user.setActive(active);
if (!user.isActive() && user.isConnected()) { if (!user.isActive() && user.isConnected()) {
SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId()); SessionManager.instance.disconnectUser(sessionId, user.getSessionId());
} }
} else if (authorizedUser != null) { } else if (authorizedUser != null) {
User theUser = new User(userName, "localhost", authorizedUser); User theUser = new User(userName, "localhost", authorizedUser);
@ -931,11 +931,11 @@ 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, () -> { execute("toggleActivation", sessionId, () -> {
User user = UserManager.getInstance().getUserByName(userName); User user = UserManager.instance.getUserByName(userName);
if (user != null) { if (user != null) {
user.setActive(!user.isActive()); user.setActive(!user.isActive());
if (!user.isActive() && user.isConnected()) { if (!user.isActive() && user.isConnected()) {
SessionManager.getInstance().disconnectUser(sessionId, user.getSessionId()); SessionManager.instance.disconnectUser(sessionId, user.getSessionId());
} }
} }
@ -944,7 +944,7 @@ 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, () -> SessionManager.getInstance().endUserSession(sessionId, userSessionId)); execute("endUserSession", sessionId, () -> SessionManager.instance.endUserSession(sessionId, userSessionId));
} }
/** /**
@ -957,8 +957,8 @@ 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, () -> { execute("removeTable", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
TableManager.getInstance().removeTable(userId, tableId); TableManager.instance.removeTable(userId, tableId);
}); });
} }
@ -971,7 +971,7 @@ public class MageServerImpl implements MageServer {
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, () -> { execute("sendFeedbackMessage", sessionId, () -> {
String host = SessionManager.getInstance().getSession(sessionId).getHost(); String host = SessionManager.instance.getSession(sessionId).getHost();
FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host); FeedbackServiceImpl.instance.feedback(username, title, type, message, email, host);
}); });
} }
@ -981,7 +981,7 @@ public class MageServerImpl implements MageServer {
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, () -> { execute("sendBroadcastMessage", sessionId, () -> {
for (User user : UserManager.getInstance().getUsers()) { for (User user : UserManager.instance.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)));
} else { } else {
@ -993,12 +993,12 @@ 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, () -> SessionManager.getInstance().sendErrorMessageToClient(sessionId, message)); execute("sendErrorMessageToClient", sessionId, () -> SessionManager.instance.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 {
if (checkAdminRights) { if (checkAdminRights) {
if (!SessionManager.getInstance().isAdmin(sessionId)) { if (!SessionManager.instance.isAdmin(sessionId)) {
return; return;
} }
} }
@ -1006,11 +1006,11 @@ public class MageServerImpl implements MageServer {
} }
protected void execute(final String actionName, final String sessionId, final Action action) throws MageException { protected void execute(final String actionName, final String sessionId, final Action action) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.instance.isValidSession(sessionId)) {
try { try {
callExecutor.execute( callExecutor.execute(
() -> { () -> {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.instance.isValidSession(sessionId)) {
try { try {
action.execute(); action.execute();
} catch (MageException me) { } catch (MageException me) {
@ -1027,7 +1027,7 @@ public class MageServerImpl implements MageServer {
protected <T> T executeWithResult(String actionName, final String sessionId, final ActionWithResult<T> action, boolean checkAdminRights) throws MageException { protected <T> T executeWithResult(String actionName, final String sessionId, final ActionWithResult<T> action, boolean checkAdminRights) throws MageException {
if (checkAdminRights) { if (checkAdminRights) {
if (!SessionManager.getInstance().isAdmin(sessionId)) { if (!SessionManager.instance.isAdmin(sessionId)) {
return action.negativeResult(); return action.negativeResult();
} }
} }
@ -1036,7 +1036,7 @@ public class MageServerImpl implements MageServer {
//TODO: also run in threads with future task //TODO: also run in threads with future task
protected <T> T executeWithResult(String actionName, final String sessionId, final ActionWithResult<T> action) throws MageException { protected <T> T executeWithResult(String actionName, final String sessionId, final ActionWithResult<T> action) throws MageException {
if (SessionManager.getInstance().isValidSession(sessionId)) { if (SessionManager.instance.isValidSession(sessionId)) {
try { try {
return action.execute(); return action.execute();
} catch (Exception ex) { } catch (Exception ex) {
@ -1065,7 +1065,7 @@ public class MageServerImpl implements MageServer {
private static class MyActionWithNullNegativeResult extends ActionWithNullNegativeResult<Object> { private static class MyActionWithNullNegativeResult extends ActionWithNullNegativeResult<Object> {
@Override @Override
public Object execute() throws MageException { public Object execute() throws MageException {
return CompressUtil.compress(ServerMessagesUtil.getInstance().getMessages()); return CompressUtil.compress(ServerMessagesUtil.instance.getMessages());
} }
} }
@ -1073,7 +1073,7 @@ public class MageServerImpl implements MageServer {
@Override @Override
public List<UserView> execute() throws MageException { public List<UserView> execute() throws MageException {
List<UserView> users = new ArrayList<>(); List<UserView> users = new ArrayList<>();
for (User user : UserManager.getInstance().getUsers()) { for (User user : UserManager.instance.getUsers()) {
users.add(new UserView( users.add(new UserView(
user.getName(), user.getName(),
user.getHost(), user.getHost(),
@ -1104,8 +1104,8 @@ public class MageServerImpl implements MageServer {
@Override @Override
public GameView execute() throws MageException { public GameView execute() throws MageException {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
return GameManager.getInstance().getGameView(gameId, userId, playerId); return GameManager.instance.getGameView(gameId, userId, playerId);
} }
} }
@ -1120,8 +1120,8 @@ public class MageServerImpl implements MageServer {
@Override @Override
public Boolean execute() throws MageException { public Boolean execute() throws MageException {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
return TableManager.getInstance().watchTable(userId, tableId); return TableManager.instance.watchTable(userId, tableId);
} }
} }
@ -1140,9 +1140,9 @@ public class MageServerImpl implements MageServer {
@Override @Override
public DraftPickView execute() { public DraftPickView execute() {
Session session = SessionManager.getInstance().getSession(sessionId); Session session = SessionManager.instance.getSession(sessionId);
if (session != null) { if (session != null) {
return DraftManager.getInstance().sendCardPick(draftId, session.getUserId(), cardPick, hiddenCards); return DraftManager.instance.sendCardPick(draftId, session.getUserId(), cardPick, hiddenCards);
} else { } else {
logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId); logger.error("Session not found sessionId: " + sessionId + " draftId:" + draftId);
} }
@ -1163,8 +1163,8 @@ public class MageServerImpl implements MageServer {
@Override @Override
public TableView execute() throws MageException { public TableView execute() throws MageException {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.instance.getSession(sessionId).getUserId();
Optional<User> _user = UserManager.getInstance().getUser(userId); Optional<User> _user = UserManager.instance.getUser(userId);
if (!_user.isPresent()) { if (!_user.isPresent()) {
logger.error("User for session not found. session = " + sessionId); logger.error("User for session not found. session = " + sessionId);
return null; return null;
@ -1183,11 +1183,11 @@ public class MageServerImpl implements MageServer {
throw new MageException("No message"); throw new MageException("No message");
} }
TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTable(userId, options); TableView table = GamesRoomManager.instance.getRoom(roomId).createTable(userId, options);
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("TABLE created - tableId: " + table.getTableId() + ' ' + table.getTableName()); logger.debug("TABLE created - tableId: " + table.getTableId() + ' ' + table.getTableName());
logger.debug("- " + user.getName() + " userId: " + user.getId()); logger.debug("- " + user.getName() + " userId: " + user.getId());
logger.debug("- chatId: " + TableManager.getInstance().getChatId(table.getTableId())); logger.debug("- chatId: " + TableManager.instance.getChatId(table.getTableId()));
} }
return table; return table;
} }

View file

@ -19,7 +19,7 @@ public final class MailClient {
logger.info("Email is not sent because the address is empty"); logger.info("Email is not sent because the address is empty");
return false; return false;
} }
ConfigSettings config = ConfigSettings.getInstance(); ConfigSettings config = ConfigSettings.instance;
Properties properties = System.getProperties(); Properties properties = System.getProperties();
properties.setProperty("mail.smtps.host", config.getMailSmtpHost()); properties.setProperty("mail.smtps.host", config.getMailSmtpHost());

View file

@ -19,8 +19,8 @@ public final class MailgunClient {
return false; return false;
} }
Client client = Client.create(); Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("api", ConfigSettings.getInstance().getMailgunApiKey())); client.addFilter(new HTTPBasicAuthFilter("api", ConfigSettings.instance.getMailgunApiKey()));
String domain = ConfigSettings.getInstance().getMailgunDomain(); String domain = ConfigSettings.instance.getMailgunDomain();
WebResource webResource = client.resource("https://api.mailgun.net/v3/" + domain + "/messages"); WebResource webResource = client.resource("https://api.mailgun.net/v3/" + domain + "/messages");
MultivaluedMapImpl formData = new MultivaluedMapImpl(); MultivaluedMapImpl formData = new MultivaluedMapImpl();
formData.add("from", "XMage <postmaster@" + domain + '>'); formData.add("from", "XMage <postmaster@" + domain + '>');

View file

@ -107,7 +107,7 @@ public final class Main {
} }
} }
if (ConfigSettings.getInstance().isAuthenticationActivated()) { if (ConfigSettings.instance.isAuthenticationActivated()) {
logger.info("Check authorized user DB version ..."); logger.info("Check authorized user DB version ...");
if (!AuthorizedUserRepository.instance.checkAlterAndMigrateAuthorizedUser()) { if (!AuthorizedUserRepository.instance.checkAlterAndMigrateAuthorizedUser()) {
logger.fatal("Failed to start server."); logger.fatal("Failed to start server.");
@ -162,7 +162,7 @@ public final class Main {
UserStatsRepository.instance.updateUserStats(); UserStatsRepository.instance.updateUserStats();
logger.info("Done."); logger.info("Done.");
deleteSavedGames(); deleteSavedGames();
ConfigSettings config = ConfigSettings.getInstance(); ConfigSettings config = ConfigSettings.instance;
for (GamePlugin plugin : config.getGameTypes()) { for (GamePlugin plugin : config.getGameTypes()) {
GameFactory.getInstance().addGameType(plugin.getName(), loadGameType(plugin), loadPlugin(plugin)); GameFactory.getInstance().addGameType(plugin.getName(), loadGameType(plugin), loadPlugin(plugin));
} }
@ -240,7 +240,7 @@ public final class Main {
} }
static void initStatistics() { static void initStatistics() {
ServerMessagesUtil.getInstance().setStartDate(System.currentTimeMillis()); ServerMessagesUtil.instance.setStartDate(System.currentTimeMillis());
} }
static boolean isAlreadyRunning(InvokerLocator serverLocator) { static boolean isAlreadyRunning(InvokerLocator serverLocator) {
@ -263,11 +263,11 @@ public final class Main {
@Override @Override
public void handleConnectionException(Throwable throwable, Client client) { public void handleConnectionException(Throwable throwable, Client client) {
Session session = SessionManager.getInstance().getSession(client.getSessionId()); Session session = SessionManager.instance.getSession(client.getSessionId());
if (session != null) { if (session != null) {
StringBuilder sessionInfo = new StringBuilder(); StringBuilder sessionInfo = new StringBuilder();
Optional<User> user = UserManager.getInstance().getUser(session.getUserId()); Optional<User> user = UserManager.instance.getUser(session.getUserId());
if (user.isPresent()) { if (user.isPresent()) {
sessionInfo.append(user.get().getName()).append(" [").append(user.get().getGameInfo()).append(']'); sessionInfo.append(user.get().getName()).append(" [").append(user.get().getGameInfo()).append(']');
} else { } else {
@ -277,12 +277,12 @@ public final class Main {
if (throwable instanceof ClientDisconnectedException) { if (throwable instanceof ClientDisconnectedException) {
// Seems like the random diconnects from public server land here and should not be handled as explicit disconnects // Seems like the random diconnects from public server land here and should not be handled as explicit disconnects
// So it should be possible to reconnect to server and continue games if DisconnectReason is set to LostConnection // So it should be possible to reconnect to server and continue games if DisconnectReason is set to LostConnection
//SessionManager.getInstance().disconnect(client.getSessionId(), DisconnectReason.Disconnected); //SessionManager.instance.disconnect(client.getSessionId(), DisconnectReason.Disconnected);
SessionManager.getInstance().disconnect(client.getSessionId(), DisconnectReason.LostConnection); SessionManager.instance.disconnect(client.getSessionId(), DisconnectReason.LostConnection);
logger.info("CLIENT DISCONNECTED - " + sessionInfo); logger.info("CLIENT DISCONNECTED - " + sessionInfo);
logger.debug("Stack Trace", throwable); logger.debug("Stack Trace", throwable);
} else { } else {
SessionManager.getInstance().disconnect(client.getSessionId(), DisconnectReason.LostConnection); SessionManager.instance.disconnect(client.getSessionId(), DisconnectReason.LostConnection);
logger.info("LOST CONNECTION - " + sessionInfo); logger.info("LOST CONNECTION - " + sessionInfo);
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
if (throwable == null) { if (throwable == null) {
@ -305,7 +305,7 @@ public final class Main {
public MageTransporterServer(InvokerLocator locator, Object target, String subsystem, MageServerInvocationHandler serverInvocationHandler) throws Exception { public MageTransporterServer(InvokerLocator locator, Object target, String subsystem, MageServerInvocationHandler serverInvocationHandler) throws Exception {
super(locator, target, subsystem); super(locator, target, subsystem);
connector.addInvocationHandler("callback", serverInvocationHandler); connector.addInvocationHandler("callback", serverInvocationHandler);
connector.setLeasePeriod(ConfigSettings.getInstance().getLeasePeriod()); connector.setLeasePeriod(ConfigSettings.instance.getLeasePeriod());
connector.addConnectionListener(new ClientConnectionListener()); connector.addConnectionListener(new ClientConnectionListener());
} }
@ -343,9 +343,9 @@ public final class Main {
@Override @Override
public void setInvoker(ServerInvoker invoker) { public void setInvoker(ServerInvoker invoker) {
((BisocketServerInvoker) invoker).setSecondaryBindPort(ConfigSettings.getInstance().getSecondaryBindPort()); ((BisocketServerInvoker) invoker).setSecondaryBindPort(ConfigSettings.instance.getSecondaryBindPort());
((BisocketServerInvoker) invoker).setBacklog(ConfigSettings.getInstance().getBacklogSize()); ((BisocketServerInvoker) invoker).setBacklog(ConfigSettings.instance.getBacklogSize());
((BisocketServerInvoker) invoker).setNumAcceptThreads(ConfigSettings.getInstance().getNumAcceptThreads()); ((BisocketServerInvoker) invoker).setNumAcceptThreads(ConfigSettings.instance.getNumAcceptThreads());
} }
@Override @Override
@ -354,7 +354,7 @@ public final class Main {
ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler; ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler;
try { try {
String sessionId = handler.getClientSessionId(); String sessionId = handler.getClientSessionId();
SessionManager.getInstance().createSession(sessionId, callbackHandler); SessionManager.instance.createSession(sessionId, callbackHandler);
} catch (Throwable ex) { } catch (Throwable ex) {
logger.fatal("", ex); logger.fatal("", ex);
} }
@ -372,7 +372,7 @@ public final class Main {
} else { } else {
host = "localhost"; host = "localhost";
} }
SessionManager.getInstance().getSession(sessionId).setHost(host); SessionManager.instance.getSession(sessionId).setHost(host);
return null; return null;
} }
@ -380,7 +380,7 @@ public final class Main {
public void removeListener(InvokerCallbackHandler callbackHandler) { public void removeListener(InvokerCallbackHandler callbackHandler) {
ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler; ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler;
String sessionId = handler.getClientSessionId(); String sessionId = handler.getClientSessionId();
SessionManager.getInstance().disconnect(sessionId, DisconnectReason.Disconnected); SessionManager.instance.disconnect(sessionId, DisconnectReason.Disconnected);
} }
} }

View file

@ -41,7 +41,7 @@ public abstract class RoomImpl implements Room {
public RoomImpl() { public RoomImpl() {
roomId = UUID.randomUUID(); roomId = UUID.randomUUID();
chatId = ChatManager.getInstance().createChatSession("Room " + roomId); chatId = ChatManager.instance.createChatSession("Room " + roomId);
} }
/** /**

View file

@ -76,7 +76,7 @@ public class Session {
} }
public String registerUser(String userName, String password, String email) throws MageException { public String registerUser(String userName, String password, String email) throws MageException {
if (!ConfigSettings.getInstance().isAuthenticationActivated()) { if (!ConfigSettings.instance.isAuthenticationActivated()) {
String returnMessage = "Registration is disabled by the server config"; String returnMessage = "Registration is disabled by the server config";
sendErrorMessageToClient(returnMessage); sendErrorMessageToClient(returnMessage);
return returnMessage; return returnMessage;
@ -106,7 +106,7 @@ public class Session {
boolean success; boolean success;
String subject = "XMage Registration Completed"; String subject = "XMage Registration Completed";
if (!ConfigSettings.getInstance().getMailUser().isEmpty()) { if (!ConfigSettings.instance.getMailUser().isEmpty()) {
success = MailClient.sendMessage(email, subject, text); success = MailClient.sendMessage(email, subject, text);
} else { } else {
success = MailgunClient.sendMessage(email, subject, text); success = MailgunClient.sendMessage(email, subject, text);
@ -133,14 +133,14 @@ public class Session {
if (userName.equals("Admin")) { if (userName.equals("Admin")) {
return "User name Admin already in use"; return "User name Admin already in use";
} }
ConfigSettings config = ConfigSettings.getInstance(); ConfigSettings config = ConfigSettings.instance;
if (userName.length() < config.getMinUserNameLength()) { if (userName.length() < config.getMinUserNameLength()) {
return "User name may not be shorter than " + config.getMinUserNameLength() + " characters"; return "User name may not be shorter than " + config.getMinUserNameLength() + " characters";
} }
if (userName.length() > config.getMaxUserNameLength()) { if (userName.length() > config.getMaxUserNameLength()) {
return "User name may not be longer than " + config.getMaxUserNameLength() + " characters"; return "User name may not be longer than " + config.getMaxUserNameLength() + " characters";
} }
Pattern invalidUserNamePattern = Pattern.compile(ConfigSettings.getInstance().getInvalidUserNamePattern(), Pattern.CASE_INSENSITIVE); Pattern invalidUserNamePattern = Pattern.compile(ConfigSettings.instance.getInvalidUserNamePattern(), Pattern.CASE_INSENSITIVE);
Matcher m = invalidUserNamePattern.matcher(userName); Matcher m = invalidUserNamePattern.matcher(userName);
if (m.find()) { if (m.find()) {
return "User name '" + userName + "' includes not allowed characters: use a-z, A-Z and 0-9"; return "User name '" + userName + "' includes not allowed characters: use a-z, A-Z and 0-9";
@ -153,7 +153,7 @@ public class Session {
} }
static private String validatePassword(String password, String userName) { static private String validatePassword(String password, String userName) {
ConfigSettings config = ConfigSettings.getInstance(); ConfigSettings config = ConfigSettings.instance;
if (password.length() < config.getMinPasswordLength()) { if (password.length() < config.getMinPasswordLength()) {
return "Password may not be shorter than " + config.getMinPasswordLength() + " characters"; return "Password may not be shorter than " + config.getMinPasswordLength() + " characters";
} }
@ -198,7 +198,7 @@ public class Session {
public String connectUserHandling(String userName, String password) throws MageException { public String connectUserHandling(String userName, String password) throws MageException {
this.isAdmin = false; this.isAdmin = false;
AuthorizedUser authorizedUser = null; AuthorizedUser authorizedUser = null;
if (ConfigSettings.getInstance().isAuthenticationActivated()) { if (ConfigSettings.instance.isAuthenticationActivated()) {
authorizedUser = AuthorizedUserRepository.instance.getByName(userName); authorizedUser = AuthorizedUserRepository.instance.getByName(userName);
String errorMsg = "Wrong username or password. In case you haven't, please register your account first."; String errorMsg = "Wrong username or password. In case you haven't, please register your account first.";
if (authorizedUser == null) { if (authorizedUser == null) {
@ -216,19 +216,19 @@ public class Session {
if (authorizedUser.lockedUntil.compareTo(Calendar.getInstance().getTime()) > 0) { if (authorizedUser.lockedUntil.compareTo(Calendar.getInstance().getTime()) > 0) {
return "Your profile is deactivated until " + SystemUtil.dateFormat.format(authorizedUser.lockedUntil); return "Your profile is deactivated until " + SystemUtil.dateFormat.format(authorizedUser.lockedUntil);
} else { } else {
User user = UserManager.getInstance().createUser(userName, host, authorizedUser); User user = UserManager.instance.createUser(userName, host, authorizedUser);
if (user != null && authorizedUser.lockedUntil != null) { if (user != null && authorizedUser.lockedUntil != null) {
user.setLockedUntil(null); user.setLockedUntil(null);
} }
} }
} }
} }
User user = UserManager.getInstance().createUser(userName, host, authorizedUser); User user = UserManager.instance.createUser(userName, host, authorizedUser);
boolean reconnect = false; boolean reconnect = false;
if (user == null) { // user already exists if (user == null) { // user already exists
user = UserManager.getInstance().getUserByName(userName); user = UserManager.instance.getUserByName(userName);
// If authentication is not activated, check the identity using IP address. // If authentication is not activated, check the identity using IP address.
if (ConfigSettings.getInstance().isAuthenticationActivated() || user.getHost().equals(host)) { if (ConfigSettings.instance.isAuthenticationActivated() || user.getHost().equals(host)) {
user.updateLastActivity(null); // minimizes possible expiration user.updateLastActivity(null); // minimizes possible expiration
this.userId = user.getId(); this.userId = user.getId();
if (user.getSessionId().isEmpty()) { if (user.getSessionId().isEmpty()) {
@ -237,43 +237,43 @@ public class Session {
} else { } else {
//disconnect previous session //disconnect previous session
logger.info("Disconnecting another user instance: " + userName); logger.info("Disconnecting another user instance: " + userName);
SessionManager.getInstance().disconnect(user.getSessionId(), DisconnectReason.ConnectingOtherInstance); SessionManager.instance.disconnect(user.getSessionId(), DisconnectReason.ConnectingOtherInstance);
} }
} else { } else {
return "User name " + userName + " already in use (or your IP address changed)"; return "User name " + userName + " already in use (or your IP address changed)";
} }
} }
if (!UserManager.getInstance().connectToSession(sessionId, user.getId())) { if (!UserManager.instance.connectToSession(sessionId, user.getId())) {
return "Error connecting " + userName; return "Error connecting " + userName;
} }
this.userId = user.getId(); this.userId = user.getId();
if (reconnect) { // must be connected to receive the message if (reconnect) { // must be connected to receive the message
UUID chatId = GamesRoomManager.getInstance().getRoom(GamesRoomManager.getInstance().getMainRoomId()).getChatId(); UUID chatId = GamesRoomManager.instance.getRoom(GamesRoomManager.instance.getMainRoomId()).getChatId();
if (chatId != null) { if (chatId != null) {
ChatManager.getInstance().joinChat(chatId, userId); ChatManager.instance.joinChat(chatId, userId);
} }
ChatManager.getInstance().sendReconnectMessage(userId); ChatManager.instance.sendReconnectMessage(userId);
} }
return null; return null;
} }
public void connectAdmin() { public void connectAdmin() {
this.isAdmin = true; this.isAdmin = true;
User user = UserManager.getInstance().createUser("Admin", host, null); User user = UserManager.instance.createUser("Admin", host, null);
if (user == null) { if (user == null) {
user = UserManager.getInstance().getUserByName("Admin"); user = UserManager.instance.getUserByName("Admin");
} }
UserData adminUserData = UserData.getDefaultUserDataView(); UserData adminUserData = UserData.getDefaultUserDataView();
adminUserData.setGroupId(UserGroup.ADMIN.getGroupId()); adminUserData.setGroupId(UserGroup.ADMIN.getGroupId());
user.setUserData(adminUserData); user.setUserData(adminUserData);
if (!UserManager.getInstance().connectToSession(sessionId, user.getId())) { if (!UserManager.instance.connectToSession(sessionId, user.getId())) {
logger.info("Error connecting Admin!"); logger.info("Error connecting Admin!");
} }
this.userId = user.getId(); this.userId = user.getId();
} }
public boolean setUserData(String userName, UserData userData, String clientVersion, String userIdStr) { public boolean setUserData(String userName, UserData userData, String clientVersion, String userIdStr) {
User user = UserManager.getInstance().getUserByName(userName); User user = UserManager.instance.getUserByName(userName);
if (user != null) { if (user != null) {
if (clientVersion != null) { if (clientVersion != null) {
user.setClientVersion(clientVersion); user.setClientVersion(clientVersion);
@ -326,7 +326,7 @@ public class Session {
} else { } else {
logger.error("CAN'T GET LOCK - userId: " + userId + " hold count: " + lock.getHoldCount()); logger.error("CAN'T GET LOCK - userId: " + userId + " hold count: " + lock.getHoldCount());
} }
Optional<User> _user = UserManager.getInstance().getUser(userId); Optional<User> _user = UserManager.instance.getUser(userId);
if (!_user.isPresent()) { if (!_user.isPresent()) {
return; //user was already disconnected by other thread return; //user was already disconnected by other thread
} }
@ -340,7 +340,7 @@ public class Session {
return; return;
} }
// logger.info("LOST CONNECTION - " + user.getName() + " id: " + userId); // logger.info("LOST CONNECTION - " + user.getName() + " id: " + userId);
UserManager.getInstance().disconnect(userId, DisconnectReason.LostConnection); UserManager.instance.disconnect(userId, DisconnectReason.LostConnection);
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
logger.error("SESSION LOCK lost connection - userId: " + userId, ex); logger.error("SESSION LOCK lost connection - userId: " + userId, ex);
@ -362,7 +362,7 @@ public class Session {
} else { } else {
logger.error("SESSION LOCK - kill: userId " + userId); logger.error("SESSION LOCK - kill: userId " + userId);
} }
UserManager.getInstance().removeUser(userId, reason); UserManager.instance.removeUser(userId, reason);
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
logger.error("SESSION LOCK - kill: userId " + userId, ex); logger.error("SESSION LOCK - kill: userId " + userId, ex);
} finally { } finally {
@ -381,7 +381,7 @@ public class Session {
callbackHandler.handleCallbackOneway(new Callback(call)); callbackHandler.handleCallbackOneway(new Callback(call));
} catch (HandleCallbackException ex) { } catch (HandleCallbackException ex) {
ex.printStackTrace(); ex.printStackTrace();
UserManager.getInstance().getUser(userId).ifPresent(user-> { UserManager.instance.getUser(userId).ifPresent(user-> {
logger.warn("SESSION CALLBACK EXCEPTION - " + user.getName() + " userId " + userId); logger.warn("SESSION CALLBACK EXCEPTION - " + user.getName() + " userId " + userId);
logger.warn(" - method: " + call.getMethod()); logger.warn(" - method: " + call.getMethod());
logger.warn(" - cause: " + getBasicCause(ex).toString()); logger.warn(" - cause: " + getBasicCause(ex).toString());

View file

@ -42,20 +42,16 @@ import javax.annotation.Nonnull;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class SessionManager { public enum SessionManager {
instance;
private static final Logger logger = Logger.getLogger(SessionManager.class); private static final Logger logger = Logger.getLogger(SessionManager.class);
private static final SessionManager INSTANCE = new SessionManager();
public static SessionManager getInstance() {
return INSTANCE;
}
private final ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
public Session getSession(@Nonnull String sessionId) { public Session getSession(@Nonnull String sessionId) {
Session session = sessions.get(sessionId); Session session = sessions.get(sessionId);
if (session != null && session.getUserId() != null && UserManager.getInstance().getUser(session.getUserId()) == null) { if (session != null && session.getUserId() != null && UserManager.instance.getUser(session.getUserId()) == null) {
logger.error("User for session " + sessionId + " with userId " + session.getUserId() + " is missing. Session removed."); logger.error("User for session " + sessionId + " with userId " + session.getUserId() + " is missing. Session removed.");
// can happen if user from same host signs in multiple time with multiple clients, after he disconnects with one client // can happen if user from same host signs in multiple time with multiple clients, after he disconnects with one client
disconnect(sessionId, DisconnectReason.ConnectingOtherInstance); disconnect(sessionId, DisconnectReason.ConnectingOtherInstance);
@ -191,7 +187,7 @@ public class SessionManager {
if (session == null) { if (session == null) {
return null; return null;
} }
return UserManager.getInstance().getUser(session.getUserId()).get(); return UserManager.instance.getUser(session.getUserId()).get();
} }
public void endUserSession(String sessionId, String userSessionId) { public void endUserSession(String sessionId, String userSessionId) {
@ -215,7 +211,7 @@ public class SessionManager {
public Optional<User> getUser(@Nonnull String sessionId) { public Optional<User> getUser(@Nonnull String sessionId) {
Session session = sessions.get(sessionId); Session session = sessions.get(sessionId);
if (session != null) { if (session != null) {
return UserManager.getInstance().getUser(sessions.get(sessionId).getUserId()); return UserManager.instance.getUser(sessions.get(sessionId).getUserId());
} }
logger.error(String.format("Session %s could not be found", sessionId)); logger.error(String.format("Session %s could not be found", sessionId));
return Optional.empty(); return Optional.empty();
@ -224,7 +220,7 @@ public class SessionManager {
public boolean extendUserSession(String sessionId, String pingInfo) { public boolean extendUserSession(String sessionId, String pingInfo) {
Session session = sessions.get(sessionId); Session session = sessions.get(sessionId);
if (session != null) { if (session != null) {
return UserManager.getInstance().extendUserSession(session.getUserId(), pingInfo); return UserManager.instance.extendUserSession(session.getUserId(), pingInfo);
} }
return false; return false;
} }

View file

@ -94,14 +94,14 @@ public class TableController {
this.options = options; this.options = options;
match = GameFactory.getInstance().createMatch(options.getGameType(), options); match = GameFactory.getInstance().createMatch(options.getGameType(), options);
if (userId != null) { if (userId != null) {
Optional<User> user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
// TODO: Handle if user == null // TODO: Handle if user == null
controllerName = user.map(User::getName).orElse("undefined"); controllerName = user.map(User::getName).orElse("undefined");
} else { } else {
controllerName = "System"; controllerName = "System";
} }
table = new Table(roomId, options.getGameType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getDeckType()), options.getPlayerTypes(), TableRecorderImpl.getInstance(), match, options.getBannedUsers()); table = new Table(roomId, options.getGameType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getDeckType()), options.getPlayerTypes(), TableRecorderImpl.getInstance(), match, options.getBannedUsers());
chatId = ChatManager.getInstance().createChatSession("Match Table " + table.getId()); chatId = ChatManager.instance.createChatSession("Match Table " + table.getId());
init(); init();
} }
@ -109,7 +109,7 @@ public class TableController {
this.userId = userId; this.userId = userId;
tournament = TournamentFactory.getInstance().createTournament(options.getTournamentType(), options); tournament = TournamentFactory.getInstance().createTournament(options.getTournamentType(), options);
if (userId != null) { if (userId != null) {
Optional<User> user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
if (!user.isPresent()) { if (!user.isPresent()) {
logger.fatal(new StringBuilder("User for userId ").append(userId).append(" could not be retrieved from UserManager").toString()); logger.fatal(new StringBuilder("User for userId ").append(userId).append(" could not be retrieved from UserManager").toString());
controllerName = "[unknown]"; controllerName = "[unknown]";
@ -120,7 +120,7 @@ public class TableController {
controllerName = "System"; controllerName = "System";
} }
table = new Table(roomId, options.getTournamentType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getMatchOptions().getDeckType()), options.getPlayerTypes(), TableRecorderImpl.getInstance(), tournament, options.getMatchOptions().getBannedUsers()); table = new Table(roomId, options.getTournamentType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getMatchOptions().getDeckType()), options.getPlayerTypes(), TableRecorderImpl.getInstance(), tournament, options.getMatchOptions().getBannedUsers());
chatId = ChatManager.getInstance().createChatSession("Tourn. table " + table.getId()); chatId = ChatManager.instance.createChatSession("Tourn. table " + table.getId());
} }
private void init() { private void init() {
@ -148,7 +148,7 @@ public class TableController {
if (seat == null) { if (seat == null) {
throw new GameException("No available seats."); throw new GameException("No available seats.");
} }
Optional<User> _user = UserManager.getInstance().getUser(userId); Optional<User> _user = UserManager.instance.getUser(userId);
if (!_user.isPresent()) { if (!_user.isPresent()) {
logger.fatal(new StringBuilder("couldn't get user ").append(name).append(" for join tournament userId = ").append(userId).toString()); logger.fatal(new StringBuilder("couldn't get user ").append(name).append(" for join tournament userId = ").append(userId).toString());
return false; return false;
@ -182,7 +182,7 @@ public class TableController {
user.showUserMessage("Join Table", sb.toString()); user.showUserMessage("Join Table", sb.toString());
if (isOwner(userId)) { if (isOwner(userId)) {
logger.debug("New table removed because owner submitted invalid deck tableId " + table.getId()); logger.debug("New table removed because owner submitted invalid deck tableId " + table.getId());
TableManager.getInstance().removeTable(table.getId()); TableManager.instance.removeTable(table.getId());
} }
return false; return false;
} }
@ -242,12 +242,12 @@ public class TableController {
newTournamentPlayer.setState(oldTournamentPlayer.getState()); newTournamentPlayer.setState(oldTournamentPlayer.getState());
newTournamentPlayer.setReplacedTournamentPlayer(oldTournamentPlayer); newTournamentPlayer.setReplacedTournamentPlayer(oldTournamentPlayer);
DraftManager.getInstance().getController(table.getId()).replacePlayer(oldPlayer, newPlayer); DraftManager.instance.getController(table.getId()).replacePlayer(oldPlayer, newPlayer);
return true; return true;
} }
public synchronized boolean joinTable(UUID userId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException { public synchronized boolean joinTable(UUID userId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException {
Optional<User> _user = UserManager.getInstance().getUser(userId); Optional<User> _user = UserManager.instance.getUser(userId);
if (!_user.isPresent()) { if (!_user.isPresent()) {
return false; return false;
} }
@ -283,7 +283,7 @@ public class TableController {
user.showUserMessage("Join Table", sb.toString()); user.showUserMessage("Join Table", sb.toString());
if (isOwner(userId)) { if (isOwner(userId)) {
logger.debug("New table removed because owner submitted invalid deck tableId " + table.getId()); logger.debug("New table removed because owner submitted invalid deck tableId " + table.getId());
TableManager.getInstance().removeTable(table.getId()); TableManager.instance.removeTable(table.getId());
} }
return false; return false;
} }
@ -433,17 +433,17 @@ public class TableController {
private void submitDeck(UUID userId, UUID playerId, Deck deck) { private void submitDeck(UUID userId, UUID playerId, Deck deck) {
if (table.getState() == TableState.SIDEBOARDING) { if (table.getState() == TableState.SIDEBOARDING) {
match.submitDeck(playerId, deck); match.submitDeck(playerId, deck);
UserManager.getInstance().getUser(userId).ifPresent(user -> user.removeSideboarding(table.getId())); UserManager.instance.getUser(userId).ifPresent(user -> user.removeSideboarding(table.getId()));
} else { } else {
TournamentManager.getInstance().submitDeck(tournament.getId(), playerId, deck); TournamentManager.instance.submitDeck(tournament.getId(), playerId, deck);
UserManager.getInstance().getUser(userId).ifPresent(user -> user.removeConstructing(playerId)); UserManager.instance.getUser(userId).ifPresent(user -> user.removeConstructing(playerId));
} }
} }
private void updateDeck(UUID userId, UUID playerId, Deck deck) { private void updateDeck(UUID userId, UUID playerId, Deck deck) {
if (table.isTournament()) { if (table.isTournament()) {
if (tournament != null) { if (tournament != null) {
TournamentManager.getInstance().updateDeck(tournament.getId(), playerId, deck); TournamentManager.instance.updateDeck(tournament.getId(), playerId, deck);
} else { } else {
logger.fatal("Tournament == null table: " + table.getId() + " userId: " + userId); logger.fatal("Tournament == null table: " + table.getId() + " userId: " + userId);
} }
@ -456,7 +456,7 @@ public class TableController {
public boolean watchTable(UUID userId) { public boolean watchTable(UUID userId) {
if (table.isTournament()) { if (table.isTournament()) {
UserManager.getInstance().getUser(userId).ifPresent(user -> user.ccShowTournament(table.getTournament().getId())); UserManager.instance.getUser(userId).ifPresent(user -> user.ccShowTournament(table.getTournament().getId()));
return true; return true;
} else { } else {
if (table.isTournamentSubTable() && !table.getTournament().getOptions().isWatchingAllowed()) { if (table.isTournamentSubTable() && !table.getTournament().getOptions().isWatchingAllowed()) {
@ -469,7 +469,7 @@ public class TableController {
if (userPlayerMap.get(userId) != null) { if (userPlayerMap.get(userId) != null) {
return false; return false;
} }
return UserManager.getInstance().getUser(userId).get().ccWatchGame(match.getGame().getId()); return UserManager.instance.getUser(userId).get().ccWatchGame(match.getGame().getId());
} }
} }
@ -477,7 +477,7 @@ public class TableController {
// if (table.getState() != TableState.FINISHED) { // if (table.getState() != TableState.FINISHED) {
// return false; // return false;
// } // }
// ReplayManager.getInstance().replayGame(table.getId(), userId); // ReplayManager.instance.replayGame(table.getId(), userId);
// return true; // return true;
// } // }
private Optional<Player> createPlayer(String name, String playerType, int skill) { private Optional<Player> createPlayer(String name, String playerType, int skill) {
@ -514,7 +514,7 @@ public class TableController {
&& (table.getState() == TableState.WAITING && (table.getState() == TableState.WAITING
|| table.getState() == TableState.READY_TO_START)) { || table.getState() == TableState.READY_TO_START)) {
// table not started yet and user is the owner, remove the table // table not started yet and user is the owner, remove the table
TableManager.getInstance().removeTable(table.getId()); TableManager.instance.removeTable(table.getId());
} else { } else {
UUID playerId = userPlayerMap.get(userId); UUID playerId = userPlayerMap.get(userId);
if (playerId != null) { if (playerId != null) {
@ -525,9 +525,9 @@ public class TableController {
} else { } else {
match.quitMatch(playerId); match.quitMatch(playerId);
} }
Optional<User> user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
if (!user.isPresent()) { if (!user.isPresent()) {
ChatManager.getInstance().broadcast(chatId, user.get().getName(), "has left the table", ChatMessage.MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, ChatMessage.SoundToPlay.PlayerLeft); ChatManager.instance.broadcast(chatId, user.get().getName(), "has left the table", ChatMessage.MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, ChatMessage.SoundToPlay.PlayerLeft);
if (!table.isTournamentSubTable()) { if (!table.isTournamentSubTable()) {
user.get().removeTable(playerId); user.get().removeTable(playerId);
} }
@ -538,9 +538,9 @@ public class TableController {
} else if (table.getState() != TableState.FINISHED) { } else if (table.getState() != TableState.FINISHED) {
if (table.isTournament()) { if (table.isTournament()) {
logger.debug("Quit tournament sub tables for userId: " + userId); logger.debug("Quit tournament sub tables for userId: " + userId);
TableManager.getInstance().userQuitTournamentSubTables(tournament.getId(), userId); TableManager.instance.userQuitTournamentSubTables(tournament.getId(), userId);
logger.debug("Quit tournament Id: " + table.getTournament().getId() + '(' + table.getTournament().getTournamentState() + ')'); logger.debug("Quit tournament Id: " + table.getTournament().getId() + '(' + table.getTournament().getTournamentState() + ')');
TournamentManager.getInstance().quit(tournament.getId(), userId); TournamentManager.instance.quit(tournament.getId(), userId);
} else { } else {
MatchPlayer matchPlayer = match.getPlayer(playerId); MatchPlayer matchPlayer = match.getPlayer(playerId);
if (matchPlayer != null && !match.hasEnded() && !matchPlayer.hasQuit()) { if (matchPlayer != null && !match.hasEnded() && !matchPlayer.hasQuit()) {
@ -548,7 +548,7 @@ public class TableController {
if (game != null && !game.hasEnded()) { if (game != null && !game.hasEnded()) {
Player player = match.getPlayer(playerId).getPlayer(); Player player = match.getPlayer(playerId).getPlayer();
if (player != null && player.isInGame()) { if (player != null && player.isInGame()) {
GameManager.getInstance().quitMatch(game.getId(), userId); GameManager.instance.quitMatch(game.getId(), userId);
} }
match.quitMatch(playerId); match.quitMatch(playerId);
} else { } else {
@ -586,7 +586,7 @@ public class TableController {
if (table.isTournamentSubTable()) { if (table.isTournamentSubTable()) {
logger.info("Tourn. match started id:" + match.getId() + " tournId: " + table.getTournament().getId()); logger.info("Tourn. match started id:" + match.getId() + " tournId: " + table.getTournament().getId());
} else { } else {
UserManager.getInstance().getUser(userId).ifPresent(user -> { UserManager.instance.getUser(userId).ifPresent(user -> {
logger.info("MATCH started [" + match.getName() + "] " + match.getId() + '(' + user.getName() + ')'); logger.info("MATCH started [" + match.getName() + "] " + match.getId() + '(' + user.getName() + ')');
logger.debug("- " + match.getOptions().getGameType() + " - " + match.getOptions().getDeckType()); logger.debug("- " + match.getOptions().getGameType() + " - " + match.getOptions().getDeckType());
}); });
@ -607,12 +607,12 @@ public class TableController {
GameOptions gameOptions = new GameOptions(); GameOptions gameOptions = new GameOptions();
gameOptions.rollbackTurnsAllowed = match.getOptions().isRollbackTurnsAllowed(); gameOptions.rollbackTurnsAllowed = match.getOptions().isRollbackTurnsAllowed();
match.getGame().setGameOptions(gameOptions); match.getGame().setGameOptions(gameOptions);
GameManager.getInstance().createGameSession(match.getGame(), userPlayerMap, table.getId(), choosingPlayerId, gameOptions); GameManager.instance.createGameSession(match.getGame(), userPlayerMap, table.getId(), choosingPlayerId, gameOptions);
String creator = null; String creator = null;
StringBuilder opponent = new StringBuilder(); StringBuilder opponent = new StringBuilder();
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) { // do only for no AI players for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) { // do only for no AI players
if (match.getPlayer(entry.getValue()) != null && !match.getPlayer(entry.getValue()).hasQuit()) { if (match.getPlayer(entry.getValue()) != null && !match.getPlayer(entry.getValue()).hasQuit()) {
Optional<User> _user = UserManager.getInstance().getUser(entry.getKey()); Optional<User> _user = UserManager.instance.getUser(entry.getKey());
if (_user.isPresent()) { if (_user.isPresent()) {
User user = _user.get(); User user = _user.get();
user.ccGameStarted(match.getGame().getId(), entry.getValue()); user.ccGameStarted(match.getGame().getId(), entry.getValue());
@ -643,23 +643,23 @@ public class TableController {
opponent.append(mPlayer.getName()); opponent.append(mPlayer.getName());
} }
} }
ServerMessagesUtil.getInstance().incGamesStarted(); ServerMessagesUtil.instance.incGamesStarted();
// log about game started // log about game started
logger.info("GAME started " + (match.getGame() != null ? match.getGame().getId() : "no Game") + " [" + match.getName() + "] " + creator + " - " + opponent.toString()); logger.info("GAME started " + (match.getGame() != null ? match.getGame().getId() : "no Game") + " [" + match.getName() + "] " + creator + " - " + opponent.toString());
logger.debug("- matchId: " + match.getId() + " [" + match.getName() + ']'); logger.debug("- matchId: " + match.getId() + " [" + match.getName() + ']');
if (match.getGame() != null) { if (match.getGame() != null) {
logger.debug("- chatId: " + GameManager.getInstance().getChatId(match.getGame().getId())); logger.debug("- chatId: " + GameManager.instance.getChatId(match.getGame().getId()));
} }
} catch (Exception ex) { } catch (Exception ex) {
logger.fatal("Error starting game table: " + table.getId(), ex); logger.fatal("Error starting game table: " + table.getId(), ex);
if (table != null) { if (table != null) {
TableManager.getInstance().removeTable(table.getId()); TableManager.instance.removeTable(table.getId());
} }
if (match != null) { if (match != null) {
Game game = match.getGame(); Game game = match.getGame();
if (game != null) { if (game != null) {
GameManager.getInstance().removeGame(game.getId()); GameManager.instance.removeGame(game.getId());
} }
} }
} }
@ -669,27 +669,27 @@ public class TableController {
try { try {
if (userId.equals(this.userId) && table.getState() == TableState.STARTING) { if (userId.equals(this.userId) && table.getState() == TableState.STARTING) {
tournament.setStartTime(); tournament.setStartTime();
TournamentManager.getInstance().createTournamentSession(tournament, userPlayerMap, table.getId()); TournamentManager.instance.createTournamentSession(tournament, userPlayerMap, table.getId());
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) { for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
UserManager.getInstance().getUser(entry.getKey()).ifPresent(user -> { UserManager.instance.getUser(entry.getKey()).ifPresent(user -> {
logger.info(new StringBuilder("User ").append(user.getName()).append(" tournament started: ").append(tournament.getId()).append(" userId: ").append(user.getId())); logger.info(new StringBuilder("User ").append(user.getName()).append(" tournament started: ").append(tournament.getId()).append(" userId: ").append(user.getId()));
user.ccTournamentStarted(tournament.getId(), entry.getValue()); user.ccTournamentStarted(tournament.getId(), entry.getValue());
}); });
} }
ServerMessagesUtil.getInstance().incTournamentsStarted(); ServerMessagesUtil.instance.incTournamentsStarted();
} }
} catch (Exception ex) { } catch (Exception ex) {
logger.fatal("Error starting tournament", ex); logger.fatal("Error starting tournament", ex);
TableManager.getInstance().removeTable(table.getId()); TableManager.instance.removeTable(table.getId());
TournamentManager.getInstance().quit(tournament.getId(), userId); TournamentManager.instance.quit(tournament.getId(), userId);
} }
} }
public void startDraft(Draft draft) { public void startDraft(Draft draft) {
table.initDraft(); table.initDraft();
DraftManager.getInstance().createDraftSession(draft, userPlayerMap, table.getId()); DraftManager.instance.createDraftSession(draft, userPlayerMap, table.getId());
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) { for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
Optional<User> user = UserManager.getInstance().getUser(entry.getKey()); Optional<User> user = UserManager.instance.getUser(entry.getKey());
if (user.isPresent()) { if (user.isPresent()) {
logger.info(new StringBuilder("User ").append(user.get().getName()).append(" draft started: ").append(draft.getId()).append(" userId: ").append(user.get().getId())); logger.info(new StringBuilder("User ").append(user.get().getName()).append(" draft started: ").append(draft.getId()).append(" userId: ").append(user.get().getId()));
user.get().ccDraftStarted(draft.getId(), entry.getValue()); user.get().ccDraftStarted(draft.getId(), entry.getValue());
@ -703,7 +703,7 @@ public class TableController {
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) { for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
if (entry.getValue().equals(playerId)) { if (entry.getValue().equals(playerId)) {
Optional<User> user = UserManager.getInstance().getUser(entry.getKey()); Optional<User> user = UserManager.instance.getUser(entry.getKey());
int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS); int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS);
user.ifPresent(user1 -> user1.ccSideboard(deck, table.getId(), remaining, options.isLimited())); user.ifPresent(user1 -> user1.ccSideboard(deck, table.getId(), remaining, options.isLimited()));
break; break;
@ -744,12 +744,12 @@ public class TableController {
} }
UUID choosingPlayerId = match.getChooser(); UUID choosingPlayerId = match.getChooser();
match.endGame(); match.endGame();
if (ConfigSettings.getInstance().isSaveGameActivated() && !game.isSimulation()) { if (ConfigSettings.instance.isSaveGameActivated() && !game.isSimulation()) {
if (GameManager.getInstance().saveGame(game.getId())) { if (GameManager.instance.saveGame(game.getId())) {
match.setReplayAvailable(true); match.setReplayAvailable(true);
} }
} }
GameManager.getInstance().removeGame(game.getId()); GameManager.instance.removeGame(game.getId());
try { try {
if (!match.hasEnded()) { if (!match.hasEnded()) {
if (match.getGame() != null && match.getGame().getGameType().isSideboardingAllowed()) { if (match.getGame() != null && match.getGame().getGameType().isSideboardingAllowed()) {
@ -810,7 +810,7 @@ public class TableController {
// opponent(s) left during sideboarding // opponent(s) left during sideboarding
if (matchPlayer != null) { if (matchPlayer != null) {
if (!matchPlayer.hasQuit()) { if (!matchPlayer.hasQuit()) {
UserManager.getInstance().getUser(entry.getKey()).ifPresent(user -> { UserManager.instance.getUser(entry.getKey()).ifPresent(user -> {
if (table.getState() == TableState.SIDEBOARDING) { if (table.getState() == TableState.SIDEBOARDING) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (table.isTournamentSubTable()) { if (table.isTournamentSubTable()) {
@ -835,7 +835,7 @@ public class TableController {
} }
} }
// free resources no longer needed // free resources no longer needed
match.cleanUpOnMatchEnd(ConfigSettings.getInstance().isSaveGameActivated(), table.isTournament()); match.cleanUpOnMatchEnd(ConfigSettings.instance.isSaveGameActivated(), table.isTournament());
} }
} }
} }
@ -907,7 +907,7 @@ public class TableController {
public boolean isTournamentStillValid() { public boolean isTournamentStillValid() {
if (table.getTournament() != null) { if (table.getTournament() != null) {
if (table.getState() != TableState.WAITING && table.getState() != TableState.READY_TO_START && table.getState() != TableState.STARTING) { if (table.getState() != TableState.WAITING && table.getState() != TableState.READY_TO_START && table.getState() != TableState.STARTING) {
TournamentController tournamentController = TournamentManager.getInstance().getTournamentController(table.getTournament().getId()); TournamentController tournamentController = TournamentManager.instance.getTournamentController(table.getTournament().getId());
if (tournamentController != null) { if (tournamentController != null) {
return tournamentController.isTournamentStillValid(table.getState()); return tournamentController.isTournamentStillValid(table.getState());
} else { } else {
@ -915,7 +915,7 @@ public class TableController {
} }
} else { } else {
// check if table creator is still a valid user, if not remove table // check if table creator is still a valid user, if not remove table
return UserManager.getInstance().getUser(userId).isPresent(); return UserManager.instance.getUser(userId).isPresent();
} }
} }
return false; return false;
@ -981,7 +981,7 @@ public class TableController {
|| table.getState() == TableState.READY_TO_START) || table.getState() == TableState.READY_TO_START)
|| !match.isDoneSideboarding() || !match.isDoneSideboarding()
|| (!matchPlayer.hasQuit() && match.getGame() != null && matchPlayer.getPlayer().isInGame())) { || (!matchPlayer.hasQuit() && match.getGame() != null && matchPlayer.getPlayer().isInGame())) {
Optional<User> user = UserManager.getInstance().getUser(userPlayerEntry.getKey()); Optional<User> user = UserManager.instance.getUser(userPlayerEntry.getKey());
if (!user.isPresent()) { if (!user.isPresent()) {
logger.debug("- Active user of match is missing: " + matchPlayer.getName()); logger.debug("- Active user of match is missing: " + matchPlayer.getName());
logger.debug("-- matchId:" + match.getId()); logger.debug("-- matchId:" + match.getId());
@ -1005,12 +1005,12 @@ public class TableController {
void cleanUp() { void cleanUp() {
if (!table.isTournamentSubTable()) { if (!table.isTournamentSubTable()) {
for (Map.Entry<UUID, UUID> entry : userPlayerMap.entrySet()) { for (Map.Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
UserManager.getInstance().getUser(entry.getKey()).ifPresent(user UserManager.instance.getUser(entry.getKey()).ifPresent(user
-> user.removeTable(entry.getValue())); -> user.removeTable(entry.getValue()));
} }
} }
ChatManager.getInstance().destroyChatSession(chatId); ChatManager.instance.destroyChatSession(chatId);
} }
public synchronized TableState getTableState() { public synchronized TableState getTableState() {

View file

@ -59,14 +59,13 @@ import org.apache.log4j.Logger;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class TableManager { public enum TableManager {
instance;
protected static final ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor(); protected final ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor();
// protected static ScheduledExecutorService expireExecutor = ThreadExecutor.getInstance().getExpireExecutor(); // protected static ScheduledExecutorService expireExecutor = ThreadExecutor.getInstance().getExpireExecutor();
private static final TableManager INSTANCE = new TableManager(); private final Logger logger = Logger.getLogger(TableManager.class);
private static final Logger logger = Logger.getLogger(TableManager.class);
private static final DateFormat formatter = new SimpleDateFormat("HH:mm:ss"); private static final DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
private final ConcurrentHashMap<UUID, TableController> controllers = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, TableController> controllers = new ConcurrentHashMap<>();
@ -79,11 +78,8 @@ public class TableManager {
*/ */
private static final int EXPIRE_CHECK_PERIOD = 10; private static final int EXPIRE_CHECK_PERIOD = 10;
public static TableManager getInstance() {
return INSTANCE;
}
private TableManager() { TableManager() {
expireExecutor.scheduleAtFixedRate(() -> { expireExecutor.scheduleAtFixedRate(() -> {
try { try {
checkTableHealthState(); checkTableHealthState();
@ -151,7 +147,7 @@ public class TableManager {
if (controllers.containsKey(tableId)) { if (controllers.containsKey(tableId)) {
return controllers.get(tableId).submitDeck(userId, deckList); return controllers.get(tableId).submitDeck(userId, deckList);
} }
UserManager.getInstance().getUser(userId).ifPresent(user -> { UserManager.instance.getUser(userId).ifPresent(user -> {
user.removeSideboarding(tableId); user.removeSideboarding(tableId);
user.showUserMessage("Submit deck", "Table no longer active"); user.showUserMessage("Submit deck", "Table no longer active");
@ -198,12 +194,12 @@ public class TableManager {
} }
public boolean removeTable(UUID userId, UUID tableId) { public boolean removeTable(UUID userId, UUID tableId) {
if (isTableOwner(tableId, userId) || UserManager.getInstance().isAdmin(userId)) { if (isTableOwner(tableId, userId) || UserManager.instance.isAdmin(userId)) {
logger.debug("Table remove request - userId: " + userId + " tableId: " + tableId); logger.debug("Table remove request - userId: " + userId + " tableId: " + tableId);
TableController tableController = controllers.get(tableId); TableController tableController = controllers.get(tableId);
if (tableController != null) { if (tableController != null) {
tableController.leaveTableAll(); tableController.leaveTableAll();
ChatManager.getInstance().destroyChatSession(tableController.getChatId()); ChatManager.instance.destroyChatSession(tableController.getChatId());
removeTable(tableId); removeTable(tableId);
} }
return true; return true;
@ -236,7 +232,7 @@ public class TableManager {
if (controllers.containsKey(tableId)) { if (controllers.containsKey(tableId)) {
controllers.get(tableId).startMatch(userId); controllers.get(tableId).startMatch(userId);
// chat of start dialog can be killed // chat of start dialog can be killed
ChatManager.getInstance().destroyChatSession(controllers.get(tableId).getChatId()); ChatManager.instance.destroyChatSession(controllers.get(tableId).getChatId());
} }
} }
@ -255,7 +251,7 @@ public class TableManager {
public void startTournament(UUID userId, UUID roomId, UUID tableId) { public void startTournament(UUID userId, UUID roomId, UUID tableId) {
if (controllers.containsKey(tableId)) { if (controllers.containsKey(tableId)) {
controllers.get(tableId).startTournament(userId); controllers.get(tableId).startTournament(userId);
ChatManager.getInstance().destroyChatSession(controllers.get(tableId).getChatId()); ChatManager.instance.destroyChatSession(controllers.get(tableId).getChatId());
} }
} }
@ -343,9 +339,9 @@ public class TableManager {
// If table is not finished, the table has to be removed completly because it's not a normal state (if finished it will be removed in GamesRoomImpl.Update()) // If table is not finished, the table has to be removed completly because it's not a normal state (if finished it will be removed in GamesRoomImpl.Update())
if (table.getState() != TableState.FINISHED) { if (table.getState() != TableState.FINISHED) {
if (game != null) { if (game != null) {
GameManager.getInstance().removeGame(game.getId()); GameManager.instance.removeGame(game.getId());
} }
GamesRoomManager.getInstance().removeTable(tableId); GamesRoomManager.instance.removeTable(tableId);
} }
} }
@ -353,10 +349,10 @@ public class TableManager {
public void debugServerState() { public void debugServerState() {
logger.debug("--- Server state ----------------------------------------------"); logger.debug("--- Server state ----------------------------------------------");
Collection<User> users = UserManager.getInstance().getUsers(); Collection<User> users = UserManager.instance.getUsers();
logger.debug("--------User: " + users.size() + " [userId | since | lock | name -----------------------"); logger.debug("--------User: " + users.size() + " [userId | since | lock | name -----------------------");
for (User user : users) { for (User user : users) {
Session session = SessionManager.getInstance().getSession(user.getSessionId()); Session session = SessionManager.instance.getSession(user.getSessionId());
String sessionState = "N"; String sessionState = "N";
if (session != null) { if (session != null) {
if (session.isLocked()) { if (session.isLocked()) {
@ -370,14 +366,14 @@ public class TableManager {
+ " | " + sessionState + " | " + sessionState
+ " | " + user.getName() + " (" + user.getUserState().toString() + " - " + user.getPingInfo() + ')'); + " | " + user.getName() + " (" + user.getUserState().toString() + " - " + user.getPingInfo() + ')');
} }
ArrayList<ChatSession> chatSessions = ChatManager.getInstance().getChatSessions(); ArrayList<ChatSession> chatSessions = ChatManager.instance.getChatSessions();
logger.debug("------- ChatSessions: " + chatSessions.size() + " ----------------------------------"); logger.debug("------- ChatSessions: " + chatSessions.size() + " ----------------------------------");
for (ChatSession chatSession : chatSessions) { for (ChatSession chatSession : chatSessions) {
logger.debug(chatSession.getChatId() + " " + formatter.format(chatSession.getCreateTime()) + ' ' + chatSession.getInfo() + ' ' + chatSession.getClients().values().toString()); logger.debug(chatSession.getChatId() + " " + formatter.format(chatSession.getCreateTime()) + ' ' + chatSession.getInfo() + ' ' + chatSession.getClients().values().toString());
} }
logger.debug("------- Games: " + GameManager.getInstance().getNumberActiveGames() + " --------------------------------------------"); logger.debug("------- Games: " + GameManager.instance.getNumberActiveGames() + " --------------------------------------------");
logger.debug(" Active Game Worker: " + ThreadExecutor.getInstance().getActiveThreads(ThreadExecutor.getInstance().getGameExecutor())); logger.debug(" Active Game Worker: " + ThreadExecutor.getInstance().getActiveThreads(ThreadExecutor.getInstance().getGameExecutor()));
for (Entry<UUID, GameController> entry : GameManager.getInstance().getGameController().entrySet()) { for (Entry<UUID, GameController> entry : GameManager.instance.getGameController().entrySet()) {
logger.debug(entry.getKey() + entry.getValue().getPlayerNameList()); logger.debug(entry.getKey() + entry.getValue().getPlayerNameList());
} }
logger.debug("--- Server state END ------------------------------------------"); logger.debug("--- Server state END ------------------------------------------");

View file

@ -210,10 +210,10 @@ public class User {
// Because watched games don't get restored after reconnection call stop watching // Because watched games don't get restored after reconnection call stop watching
for (Iterator<UUID> iterator = watchedGames.iterator(); iterator.hasNext();) { for (Iterator<UUID> iterator = watchedGames.iterator(); iterator.hasNext();) {
UUID gameId = iterator.next(); UUID gameId = iterator.next();
GameManager.getInstance().stopWatching(gameId, userId); GameManager.instance.stopWatching(gameId, userId);
iterator.remove(); iterator.remove();
} }
ServerMessagesUtil.getInstance().incLostConnection(); ServerMessagesUtil.instance.incLostConnection();
} }
public boolean isConnected() { public boolean isConnected() {
@ -246,7 +246,7 @@ public class User {
public void fireCallback(final ClientCallback call) { public void fireCallback(final ClientCallback call) {
if (isConnected()) { if (isConnected()) {
Session session = SessionManager.getInstance().getSession(sessionId); Session session = SessionManager.instance.getSession(sessionId);
if (session != null) { if (session != null) {
session.fireCallback(call); session.fireCallback(call);
} }
@ -304,27 +304,27 @@ public class User {
public void sendPlayerUUID(final UUID gameId, final UUID data) { public void sendPlayerUUID(final UUID gameId, final UUID data) {
lastActivity = new Date(); lastActivity = new Date();
GameManager.getInstance().sendPlayerUUID(gameId, userId, data); GameManager.instance.sendPlayerUUID(gameId, userId, data);
} }
public void sendPlayerString(final UUID gameId, final String data) { public void sendPlayerString(final UUID gameId, final String data) {
lastActivity = new Date(); lastActivity = new Date();
GameManager.getInstance().sendPlayerString(gameId, userId, data); GameManager.instance.sendPlayerString(gameId, userId, data);
} }
public void sendPlayerManaType(final UUID gameId, final UUID playerId, final ManaType data) { public void sendPlayerManaType(final UUID gameId, final UUID playerId, final ManaType data) {
lastActivity = new Date(); lastActivity = new Date();
GameManager.getInstance().sendPlayerManaType(gameId, playerId, userId, data); GameManager.instance.sendPlayerManaType(gameId, playerId, userId, data);
} }
public void sendPlayerBoolean(final UUID gameId, final Boolean data) { public void sendPlayerBoolean(final UUID gameId, final Boolean data) {
lastActivity = new Date(); lastActivity = new Date();
GameManager.getInstance().sendPlayerBoolean(gameId, userId, data); GameManager.instance.sendPlayerBoolean(gameId, userId, data);
} }
public void sendPlayerInteger(final UUID gameId, final Integer data) { public void sendPlayerInteger(final UUID gameId, final Integer data) {
lastActivity = new Date(); lastActivity = new Date();
GameManager.getInstance().sendPlayerInteger(gameId, userId, data); GameManager.instance.sendPlayerInteger(gameId, userId, data);
} }
public void updateLastActivity(String pingInfo) { public void updateLastActivity(String pingInfo) {
@ -355,7 +355,7 @@ public class User {
ccJoinedTable(entry.getValue().getRoomId(), entry.getValue().getId(), entry.getValue().isTournament()); ccJoinedTable(entry.getValue().getRoomId(), entry.getValue().getId(), entry.getValue().isTournament());
} }
for (Entry<UUID, UUID> entry : userTournaments.entrySet()) { for (Entry<UUID, UUID> entry : userTournaments.entrySet()) {
TournamentController tournamentController = TournamentManager.getInstance().getTournamentController(entry.getValue()); TournamentController tournamentController = TournamentManager.instance.getTournamentController(entry.getValue());
if (tournamentController != null) { if (tournamentController != null) {
ccTournamentStarted(entry.getValue(), entry.getKey()); ccTournamentStarted(entry.getValue(), entry.getKey());
tournamentController.rejoin(entry.getKey()); tournamentController.rejoin(entry.getKey());
@ -365,7 +365,7 @@ public class User {
for (Entry<UUID, GameSessionPlayer> entry : gameSessions.entrySet()) { for (Entry<UUID, GameSessionPlayer> entry : gameSessions.entrySet()) {
ccGameStarted(entry.getValue().getGameId(), entry.getKey()); ccGameStarted(entry.getValue().getGameId(), entry.getKey());
entry.getValue().init(); entry.getValue().init();
GameManager.getInstance().sendPlayerString(entry.getValue().getGameId(), userId, ""); GameManager.instance.sendPlayerString(entry.getValue().getGameId(), userId, "");
} }
for (Entry<UUID, DraftSession> entry : draftSessions.entrySet()) { for (Entry<UUID, DraftSession> entry : draftSessions.entrySet()) {
@ -378,10 +378,10 @@ public class User {
entry.getValue().construct(0); // TODO: Check if this is correct entry.getValue().construct(0); // TODO: Check if this is correct
} }
for (Entry<UUID, Deck> entry : sideboarding.entrySet()) { for (Entry<UUID, Deck> entry : sideboarding.entrySet()) {
TableController controller = TableManager.getInstance().getController(entry.getKey()); TableController controller = TableManager.instance.getController(entry.getKey());
ccSideboard(entry.getValue(), entry.getKey(), controller.getRemainingTime(), controller.getOptions().isLimited()); ccSideboard(entry.getValue(), entry.getKey(), controller.getRemainingTime(), controller.getOptions().isLimited());
} }
ServerMessagesUtil.getInstance().incReconnects(); ServerMessagesUtil.instance.incReconnects();
logger.trace(userName + " ended reconnect"); logger.trace(userName + " ended reconnect");
} }
@ -437,29 +437,29 @@ public class User {
draftSessions.clear(); draftSessions.clear();
logger.trace("REMOVE " + userName + " Tournament sessions " + userTournaments.size()); logger.trace("REMOVE " + userName + " Tournament sessions " + userTournaments.size());
for (UUID tournamentId : userTournaments.values()) { for (UUID tournamentId : userTournaments.values()) {
TournamentManager.getInstance().quit(tournamentId, userId); TournamentManager.instance.quit(tournamentId, userId);
} }
userTournaments.clear(); userTournaments.clear();
logger.trace("REMOVE " + userName + " Tables " + tables.size()); logger.trace("REMOVE " + userName + " Tables " + tables.size());
for (Entry<UUID, Table> entry : tables.entrySet()) { for (Entry<UUID, Table> entry : tables.entrySet()) {
logger.debug("-- leave tableId: " + entry.getValue().getId()); logger.debug("-- leave tableId: " + entry.getValue().getId());
TableManager.getInstance().leaveTable(userId, entry.getValue().getId()); TableManager.instance.leaveTable(userId, entry.getValue().getId());
} }
tables.clear(); tables.clear();
logger.trace("REMOVE " + userName + " Game sessions: " + gameSessions.size()); logger.trace("REMOVE " + userName + " Game sessions: " + gameSessions.size());
for (GameSessionPlayer gameSessionPlayer : gameSessions.values()) { for (GameSessionPlayer gameSessionPlayer : gameSessions.values()) {
logger.debug("-- kill game session of gameId: " + gameSessionPlayer.getGameId()); logger.debug("-- kill game session of gameId: " + gameSessionPlayer.getGameId());
GameManager.getInstance().quitMatch(gameSessionPlayer.getGameId(), userId); GameManager.instance.quitMatch(gameSessionPlayer.getGameId(), userId);
gameSessionPlayer.quitGame(); gameSessionPlayer.quitGame();
} }
gameSessions.clear(); gameSessions.clear();
logger.trace("REMOVE " + userName + " watched Games " + watchedGames.size()); logger.trace("REMOVE " + userName + " watched Games " + watchedGames.size());
for (UUID gameId : watchedGames) { for (UUID gameId : watchedGames) {
GameManager.getInstance().stopWatching(gameId, userId); GameManager.instance.stopWatching(gameId, userId);
} }
watchedGames.clear(); watchedGames.clear();
logger.trace("REMOVE " + userName + " Chats "); logger.trace("REMOVE " + userName + " Chats ");
ChatManager.getInstance().removeUser(userId, reason); ChatManager.instance.removeUser(userId, reason);
} }
public void setUserData(UserData userData) { public void setUserData(UserData userData) {
@ -784,7 +784,7 @@ public class User {
if (table.getState() == TableState.FINISHED) { if (table.getState() == TableState.FINISHED) {
number++; number++;
} else { } else {
TableController tableController = TableManager.getInstance().getController(table.getId()); TableController tableController = TableManager.instance.getController(table.getId());
if (tableController != null && tableController.isUserStillActive(userId)) { if (tableController != null && tableController.isUserStillActive(userId)) {
number++; number++;
} }

View file

@ -42,9 +42,10 @@ import java.util.concurrent.*;
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class UserManager { public enum UserManager {
instance;
protected static final ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor(); protected final ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor();
private static final Logger LOGGER = Logger.getLogger(UserManager.class); private static final Logger LOGGER = Logger.getLogger(UserManager.class);
@ -53,13 +54,7 @@ public class UserManager {
private static final ExecutorService USER_EXECUTOR = ThreadExecutor.getInstance().getCallExecutor(); private static final ExecutorService USER_EXECUTOR = ThreadExecutor.getInstance().getCallExecutor();
private static final UserManager INSTANCE = new UserManager(); UserManager() {
public static UserManager getInstance() {
return INSTANCE;
}
private UserManager() {
expireExecutor.scheduleAtFixedRate(this::checkExpired, 60, 60, TimeUnit.SECONDS); expireExecutor.scheduleAtFixedRate(this::checkExpired, 60, 60, TimeUnit.SECONDS);
} }
@ -112,7 +107,7 @@ public class UserManager {
if (user != null) { if (user != null) {
user.setSessionId(""); // Session will be set again with new id if user reconnects user.setSessionId(""); // Session will be set again with new id if user reconnects
} }
ChatManager.getInstance().removeUser(userId, reason); ChatManager.instance.removeUser(userId, reason);
} }
} }

View file

@ -14,10 +14,10 @@ import mage.game.match.Match;
*/ */
public class ChallengeManager { public class ChallengeManager {
public static final ChallengeManager fInstance = new ChallengeManager(); public static final ChallengeManager instance = new ChallengeManager();
public static ChallengeManager getInstance() { public static ChallengeManager getInstance() {
return fInstance; return instance;
} }
public void prepareChallenge(UUID playerId, Match match) { public void prepareChallenge(UUID playerId, Match match) {

View file

@ -121,7 +121,7 @@ public class DraftController {
UUID playerId = userPlayerMap.get(userId); UUID playerId = userPlayerMap.get(userId);
DraftSession draftSession = new DraftSession(draft, userId, playerId); DraftSession draftSession = new DraftSession(draft, userId, playerId);
draftSessions.put(playerId, draftSession); draftSessions.put(playerId, draftSession);
UserManager.getInstance().getUser(userId).ifPresent(user-> { UserManager.instance.getUser(userId).ifPresent(user-> {
user.addDraft(playerId, draftSession); user.addDraft(playerId, draftSession);
logger.debug("User " + user.getName() + " has joined draft " + draft.getId()); logger.debug("User " + user.getName() + " has joined draft " + draft.getId());
draft.getPlayer(playerId).setJoined(); draft.getPlayer(playerId).setJoined();
@ -187,8 +187,8 @@ public class DraftController {
draftSession.draftOver(); draftSession.draftOver();
draftSession.removeDraft(); draftSession.removeDraft();
} }
TableManager.getInstance().endDraft(tableId, draft); TableManager.instance.endDraft(tableId, draft);
DraftManager.getInstance().removeDraft(draft.getId()); DraftManager.instance.removeDraft(draft.getId());
} }
public void kill(UUID userId) { public void kill(UUID userId) {

View file

@ -38,14 +38,8 @@ import mage.view.DraftPickView;
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class DraftManager { public enum DraftManager {
private static final DraftManager INSTANCE = new DraftManager(); instance;
public static DraftManager getInstance() {
return INSTANCE;
}
private DraftManager() {}
private final ConcurrentHashMap<UUID, DraftController> draftControllers = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, DraftController> draftControllers = new ConcurrentHashMap<>();

View file

@ -71,7 +71,7 @@ public class DraftSession {
public boolean init() { public boolean init() {
if (!killed) { if (!killed) {
Optional<User> user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
if (user.isPresent()) { if (user.isPresent()) {
if (futureTimeout != null && !futureTimeout.isDone()) { if (futureTimeout != null && !futureTimeout.isDone()) {
int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS); int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS);
@ -85,7 +85,7 @@ public class DraftSession {
public void update() { public void update() {
if (!killed) { if (!killed) {
UserManager.getInstance() UserManager.instance
.getUser(userId). .getUser(userId).
ifPresent(user -> user.fireCallback( ifPresent(user -> user.fireCallback(
new ClientCallback("draftUpdate", draft.getId(), getDraftView()))); new ClientCallback("draftUpdate", draft.getId(), getDraftView())));
@ -96,7 +96,7 @@ public class DraftSession {
// //
public void inform(final String message) { public void inform(final String message) {
if (!killed) { if (!killed) {
UserManager.getInstance() UserManager.instance
.getUser(userId) .getUser(userId)
.ifPresent(user -> user.fireCallback(new ClientCallback("draftInform", draft.getId(), new DraftClientMessage(getDraftView(), message)))); .ifPresent(user -> user.fireCallback(new ClientCallback("draftInform", draft.getId(), new DraftClientMessage(getDraftView(), message))));
} }
@ -105,7 +105,7 @@ public class DraftSession {
public void draftOver() { public void draftOver() {
if (!killed) { if (!killed) {
UserManager.getInstance() UserManager.instance
.getUser(userId) .getUser(userId)
.ifPresent(user -> user.fireCallback(new ClientCallback("draftOver", draft.getId()))); .ifPresent(user -> user.fireCallback(new ClientCallback("draftOver", draft.getId())));
@ -115,7 +115,7 @@ public class DraftSession {
public void pickCard(int timeout) { public void pickCard(int timeout) {
if (!killed) { if (!killed) {
setupTimeout(timeout); setupTimeout(timeout);
UserManager.getInstance() UserManager.instance
.getUser(userId) .getUser(userId)
.ifPresent(user -> user.fireCallback(new ClientCallback("draftPick", draft.getId(), new DraftClientMessage(getDraftPickView(timeout))))); .ifPresent(user -> user.fireCallback(new ClientCallback("draftPick", draft.getId(), new DraftClientMessage(getDraftPickView(timeout)))));
@ -126,7 +126,7 @@ public class DraftSession {
cancelTimeout(); cancelTimeout();
if (seconds > 0) { if (seconds > 0) {
futureTimeout = timeoutExecutor.schedule( futureTimeout = timeoutExecutor.schedule(
() -> DraftManager.getInstance().timeout(draft.getId(), userId), () -> DraftManager.instance.timeout(draft.getId(), userId),
seconds, TimeUnit.SECONDS seconds, TimeUnit.SECONDS
); );
} }
@ -140,7 +140,7 @@ public class DraftSession {
protected void handleRemoteException(RemoteException ex) { protected void handleRemoteException(RemoteException ex) {
logger.fatal("DraftSession error ", ex); logger.fatal("DraftSession error ", ex);
DraftManager.getInstance().kill(draft.getId(), userId); DraftManager.instance.kill(draft.getId(), userId);
} }
public void setKilled() { public void setKilled() {
@ -156,7 +156,7 @@ public class DraftSession {
} }
public void removeDraft() { public void removeDraft() {
UserManager.getInstance().getUser(userId).ifPresent(user -> user.removeDraft(playerId)); UserManager.instance.getUser(userId).ifPresent(user -> user.removeDraft(playerId));
} }

View file

@ -119,10 +119,10 @@ public class GameController implements GameCallback {
public GameController(Game game, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId, UUID choosingPlayerId, GameOptions gameOptions) { public GameController(Game game, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId, UUID choosingPlayerId, GameOptions gameOptions) {
gameSessionId = UUID.randomUUID(); gameSessionId = UUID.randomUUID();
this.userPlayerMap = userPlayerMap; this.userPlayerMap = userPlayerMap;
chatId = ChatManager.getInstance().createChatSession("Game " + game.getId()); chatId = ChatManager.instance.createChatSession("Game " + game.getId());
this.userReqestingRollback = null; this.userReqestingRollback = null;
this.game = game; this.game = game;
this.game.setSaveGame(ConfigSettings.getInstance().isSaveGameActivated()); this.game.setSaveGame(ConfigSettings.instance.isSaveGameActivated());
this.tableId = tableId; this.tableId = tableId;
this.choosingPlayerId = choosingPlayerId; this.choosingPlayerId = choosingPlayerId;
this.gameOptions = gameOptions; this.gameOptions = gameOptions;
@ -141,7 +141,7 @@ public class GameController implements GameCallback {
for (GameSessionPlayer gameSessionPlayer : gameSessions.values()) { for (GameSessionPlayer gameSessionPlayer : gameSessions.values()) {
gameSessionPlayer.cleanUp(); gameSessionPlayer.cleanUp();
} }
ChatManager.getInstance().destroyChatSession(chatId); ChatManager.instance.destroyChatSession(chatId);
for (PriorityTimer priorityTimer : timers.values()) { for (PriorityTimer priorityTimer : timers.values()) {
priorityTimer.cancel(); priorityTimer.cancel();
} }
@ -158,11 +158,11 @@ public class GameController implements GameCallback {
updateGame(); updateGame();
break; break;
case INFO: case INFO:
ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.GAME, null); ChatManager.instance.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(), MessageType.GAME, null); ChatManager.instance.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:
@ -305,7 +305,7 @@ public class GameController implements GameCallback {
public void join(UUID userId) { public void join(UUID userId) {
UUID playerId = userPlayerMap.get(userId); UUID playerId = userPlayerMap.get(userId);
Optional<User> user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
if (userId == null || playerId == null) { if (userId == null || playerId == null) {
logger.fatal("Join game failed!"); logger.fatal("Join game failed!");
logger.fatal("- gameId: " + game.getId()); logger.fatal("- gameId: " + game.getId());
@ -332,7 +332,7 @@ public class GameController implements GameCallback {
} }
user.get().addGame(playerId, gameSession); user.get().addGame(playerId, gameSession);
logger.debug("Player " + player.getName() + ' ' + playerId + " has " + joinType + " gameId: " + game.getId()); logger.debug("Player " + player.getName() + ' ' + playerId + " has " + joinType + " gameId: " + game.getId());
ChatManager.getInstance().broadcast(chatId, "", game.getPlayer(playerId).getLogName() + " has " + joinType + " the game", MessageColor.ORANGE, true, MessageType.GAME, null); ChatManager.instance.broadcast(chatId, "", game.getPlayer(playerId).getLogName() + " has " + joinType + " the game", MessageColor.ORANGE, true, MessageType.GAME, null);
checkStart(); checkStart();
} }
@ -356,10 +356,10 @@ public class GameController implements GameCallback {
if (gameSessions.get(player.getId()) == null) { if (gameSessions.get(player.getId()) == null) {
// join the game because player has not joined are was removed because of disconnect // join the game because player has not joined are was removed because of disconnect
user.removeConstructing(player.getId()); user.removeConstructing(player.getId());
GameManager.getInstance().joinGame(game.getId(), user.getId()); GameManager.instance.joinGame(game.getId(), user.getId());
logger.debug("Player " + player.getName() + " (disconnected) has joined gameId: " + game.getId()); logger.debug("Player " + player.getName() + " (disconnected) has joined gameId: " + game.getId());
} }
ChatManager.getInstance().broadcast(chatId, player.getName(), user.getPingInfo() + " is pending to join the game", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, null); ChatManager.instance.broadcast(chatId, player.getName(), user.getPingInfo() + " is pending to join the game", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, null);
if (user.getSecondsDisconnected() > 240) { if (user.getSecondsDisconnected() > 240) {
// Cancel player join possibility lately after 4 minutes // Cancel player join possibility lately after 4 minutes
logger.debug("Player " + player.getName() + " - canceled game (after 240 seconds) gameId: " + game.getId()); logger.debug("Player " + player.getName() + " - canceled game (after 240 seconds) gameId: " + game.getId());
@ -379,7 +379,7 @@ public class GameController implements GameCallback {
private Optional<User> getUserByPlayerId(UUID playerId) { private Optional<User> getUserByPlayerId(UUID playerId) {
for (Map.Entry<UUID, UUID> entry : userPlayerMap.entrySet()) { for (Map.Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
if (entry.getValue().equals(playerId)) { if (entry.getValue().equals(playerId)) {
return UserManager.getInstance().getUser(entry.getKey()); return UserManager.instance.getUser(entry.getKey());
} }
} }
return Optional.empty(); return Optional.empty();
@ -418,19 +418,19 @@ public class GameController implements GameCallback {
// You can't watch a game if you already watch it // You can't watch a game if you already watch it
return; return;
} }
UserManager.getInstance().getUser(userId).ifPresent(user -> { UserManager.instance.getUser(userId).ifPresent(user -> {
GameSessionWatcher gameWatcher = new GameSessionWatcher(userId, game, false); GameSessionWatcher gameWatcher = new GameSessionWatcher(userId, game, false);
watchers.put(userId, gameWatcher); watchers.put(userId, gameWatcher);
gameWatcher.init(); gameWatcher.init();
user.addGameWatchInfo(game.getId()); user.addGameWatchInfo(game.getId());
ChatManager.getInstance().broadcast(chatId, user.getName(), " has started watching", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, null); ChatManager.instance.broadcast(chatId, user.getName(), " has started watching", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, null);
}); });
} }
public void stopWatching(UUID userId) { public void stopWatching(UUID userId) {
watchers.remove(userId); watchers.remove(userId);
UserManager.getInstance().getUser(userId).ifPresent(user -> { UserManager.instance.getUser(userId).ifPresent(user -> {
ChatManager.getInstance().broadcast(chatId, user.getName(), " has stopped watching", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, null); ChatManager.instance.broadcast(chatId, user.getName(), " has stopped watching", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, null);
}); });
} }
@ -599,7 +599,7 @@ public class GameController implements GameCallback {
gameSession.requestPermissionToSeeHandCards(userIdRequester); gameSession.requestPermissionToSeeHandCards(userIdRequester);
} else { } else {
// player does not allow the request // player does not allow the request
UserManager.getInstance().getUser(userIdRequester).ifPresent(requester -> { UserManager.instance.getUser(userIdRequester).ifPresent(requester -> {
requester.showUserMessage("Request to show hand cards", "Player " + grantingPlayer.getName() + " does not allow to request to show hand cards!"); requester.showUserMessage("Request to show hand cards", "Player " + grantingPlayer.getName() + " does not allow to request to show hand cards!");
}); });
} }
@ -611,7 +611,7 @@ public class GameController implements GameCallback {
} }
} else { } else {
// user can already see the cards // user can already see the cards
UserManager.getInstance().getUser(userIdRequester).ifPresent(requester -> { UserManager.instance.getUser(userIdRequester).ifPresent(requester -> {
requester.showUserMessage("Request to show hand cards", "You can see already the hand cards of player " + grantingPlayer.getName() + '!'); requester.showUserMessage("Request to show hand cards", "You can see already the hand cards of player " + grantingPlayer.getName() + '!');
}); });
@ -653,8 +653,8 @@ public class GameController implements GameCallback {
if (player != null) { if (player != null) {
String sb = player.getLogName() String sb = player.getLogName()
+ " has timed out (player had priority and was not active for " + " has timed out (player had priority and was not active for "
+ ConfigSettings.getInstance().getMaxSecondsIdle() + " seconds ) - Auto concede."; + ConfigSettings.instance.getMaxSecondsIdle() + " seconds ) - Auto concede.";
ChatManager.getInstance().broadcast(chatId, "", sb, MessageColor.BLACK, true, MessageType.STATUS, null); ChatManager.instance.broadcast(chatId, "", sb, MessageColor.BLACK, true, MessageType.STATUS, null);
game.idleTimeout(playerId); game.idleTimeout(playerId);
} }
} }
@ -667,7 +667,7 @@ public class GameController implements GameCallback {
for (final GameSessionWatcher gameWatcher : watchers.values()) { for (final GameSessionWatcher gameWatcher : watchers.values()) {
gameWatcher.gameOver(message); gameWatcher.gameOver(message);
} }
TableManager.getInstance().endGame(tableId); TableManager.instance.endGame(tableId);
} }
public UUID getSessionId() { public UUID getSessionId() {
@ -718,7 +718,7 @@ public class GameController implements GameCallback {
} }
private synchronized void endGameInfo() { private synchronized void endGameInfo() {
Table table = TableManager.getInstance().getTable(tableId); Table table = TableManager.instance.getTable(tableId);
if (table != null) { if (table != null) {
if (table.getMatch() != null) { if (table.getMatch() != null) {
for (final GameSessionPlayer gameSession : gameSessions.values()) { for (final GameSessionPlayer gameSession : gameSessions.values()) {
@ -967,7 +967,7 @@ public class GameController implements GameCallback {
cancelTimeout(); cancelTimeout();
futureTimeout = timeoutIdleExecutor.schedule( futureTimeout = timeoutIdleExecutor.schedule(
() -> idleTimeout(playerId), () -> idleTimeout(playerId),
Main.isTestMode() ? 3600 : ConfigSettings.getInstance().getMaxSecondsIdle(), Main.isTestMode() ? 3600 : ConfigSettings.instance.getMaxSecondsIdle(),
TimeUnit.SECONDS TimeUnit.SECONDS
); );
} }

View file

@ -41,14 +41,8 @@ import mage.view.GameView;
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class GameManager { public enum GameManager {
private static final GameManager INSTANCE = new GameManager(); instance;
public static GameManager getInstance() {
return INSTANCE;
}
private GameManager() {}
private final ConcurrentHashMap<UUID, GameController> gameControllers = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, GameController> gameControllers = new ConcurrentHashMap<>();

View file

@ -68,14 +68,14 @@ public class GameSessionPlayer extends GameSessionWatcher {
public void ask(final String question, final Map<String, Serializable> options) { public void ask(final String question, final Map<String, Serializable> options) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameAsk", game.getId(), new GameClientMessage(getGameView(), question, options))) UserManager.instance.getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameAsk", game.getId(), new GameClientMessage(getGameView(), question, options)))
); );
} }
} }
public void target(final String question, final CardsView cardView, final Set<UUID> targets, final boolean required, final Map<String, Serializable> options) { public void target(final String question, final CardsView cardView, final Set<UUID> targets, final boolean required, final Map<String, Serializable> options) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user -> { UserManager.instance.getUser(userId).ifPresent(user -> {
user.fireCallback(new ClientCallback("gameTarget", game.getId(), new GameClientMessage(getGameView(), question, cardView, targets, required, options))); user.fireCallback(new ClientCallback("gameTarget", game.getId(), new GameClientMessage(getGameView(), question, cardView, targets, required, options)));
}); });
@ -84,13 +84,13 @@ public class GameSessionPlayer extends GameSessionWatcher {
public void select(final String message, final Map<String, Serializable> options) { public void select(final String message, final Map<String, Serializable> options) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameSelect", game.getId(), new GameClientMessage(getGameView(), message, options)))); UserManager.instance.getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameSelect", game.getId(), new GameClientMessage(getGameView(), message, options))));
} }
} }
public void chooseAbility(final AbilityPickerView abilities) { public void chooseAbility(final AbilityPickerView abilities) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user UserManager.instance.getUser(userId).ifPresent(user
-> user.fireCallback(new ClientCallback("gameChooseAbility", game.getId(), abilities))); -> user.fireCallback(new ClientCallback("gameChooseAbility", game.getId(), abilities)));
} }
@ -98,7 +98,7 @@ public class GameSessionPlayer extends GameSessionWatcher {
public void choosePile(final String message, final CardsView pile1, final CardsView pile2) { public void choosePile(final String message, final CardsView pile1, final CardsView pile2) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user UserManager.instance.getUser(userId).ifPresent(user
-> user.fireCallback(new ClientCallback("gameChoosePile", game.getId(), new GameClientMessage(message, pile1, pile2)))); -> user.fireCallback(new ClientCallback("gameChoosePile", game.getId(), new GameClientMessage(message, pile1, pile2))));
} }
@ -106,7 +106,7 @@ public class GameSessionPlayer extends GameSessionWatcher {
public void chooseChoice(final Choice choice) { public void chooseChoice(final Choice choice) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user UserManager.instance.getUser(userId).ifPresent(user
-> user.fireCallback(new ClientCallback("gameChooseChoice", game.getId(), new GameClientMessage(choice)))); -> user.fireCallback(new ClientCallback("gameChooseChoice", game.getId(), new GameClientMessage(choice))));
} }
@ -114,14 +114,14 @@ public class GameSessionPlayer extends GameSessionWatcher {
public void playMana(final String message, final Map<String, Serializable> options) { public void playMana(final String message, final Map<String, Serializable> options) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user UserManager.instance.getUser(userId).ifPresent(user
-> user.fireCallback(new ClientCallback("gamePlayMana", game.getId(), new GameClientMessage(getGameView(), message, options)))); -> user.fireCallback(new ClientCallback("gamePlayMana", game.getId(), new GameClientMessage(getGameView(), message, options))));
} }
} }
public void playXMana(final String message) { public void playXMana(final String message) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user UserManager.instance.getUser(userId).ifPresent(user
-> user.fireCallback(new ClientCallback("gamePlayXMana", game.getId(), new GameClientMessage(getGameView(), message)))); -> user.fireCallback(new ClientCallback("gamePlayXMana", game.getId(), new GameClientMessage(getGameView(), message))));
} }
@ -129,7 +129,7 @@ public class GameSessionPlayer extends GameSessionWatcher {
public void getAmount(final String message, final int min, final int max) { public void getAmount(final String message, final int min, final int max) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user -> { UserManager.instance.getUser(userId).ifPresent(user -> {
user.fireCallback(new ClientCallback("gameSelectAmount", game.getId(), new GameClientMessage(message, min, max))); user.fireCallback(new ClientCallback("gameSelectAmount", game.getId(), new GameClientMessage(message, min, max)));
}); });
} }
@ -137,15 +137,15 @@ public class GameSessionPlayer extends GameSessionWatcher {
public void endGameInfo(Table table) { public void endGameInfo(Table table) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("endGameInfo", game.getId(), getGameEndView(playerId, table)))); UserManager.instance.getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("endGameInfo", game.getId(), getGameEndView(playerId, table))));
} }
} }
public void requestPermissionToRollbackTurn(UUID requestingUserId, int numberTurns) { public void requestPermissionToRollbackTurn(UUID requestingUserId, int numberTurns) {
if (!killed) { if (!killed) {
Optional<User> requestingUser = UserManager.getInstance().getUser(requestingUserId); Optional<User> requestingUser = UserManager.instance.getUser(requestingUserId);
Optional<User> requestedUser = UserManager.getInstance().getUser(userId); Optional<User> requestedUser = UserManager.instance.getUser(userId);
if (requestedUser.isPresent() && requestingUser.isPresent()) { if (requestedUser.isPresent() && requestingUser.isPresent()) {
String message; String message;
switch (numberTurns) { switch (numberTurns) {
@ -171,8 +171,8 @@ public class GameSessionPlayer extends GameSessionWatcher {
public void requestPermissionToSeeHandCards(UUID watcherId) { public void requestPermissionToSeeHandCards(UUID watcherId) {
if (!killed) { if (!killed) {
Optional<User> watcher = UserManager.getInstance().getUser(watcherId); Optional<User> watcher = UserManager.instance.getUser(watcherId);
Optional<User> user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
if (user.isPresent() && watcher.isPresent()) { if (user.isPresent() && watcher.isPresent()) {
UserRequestMessage userRequestMessage = new UserRequestMessage( UserRequestMessage userRequestMessage = new UserRequestMessage(
"User request", "User request",
@ -241,7 +241,7 @@ public class GameSessionPlayer extends GameSessionWatcher {
} }
public void removeGame() { public void removeGame() {
UserManager.getInstance().getUser(userId).ifPresent(user -> user.removeGame(playerId)); UserManager.instance.getUser(userId).ifPresent(user -> user.removeGame(playerId));
} }

View file

@ -65,7 +65,7 @@ public class GameSessionWatcher {
public boolean init() { public boolean init() {
if (!killed) { if (!killed) {
Optional<User> user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
if (user.isPresent()) { if (user.isPresent()) {
user.get().fireCallback(new ClientCallback("gameInit", game.getId(), getGameView())); user.get().fireCallback(new ClientCallback("gameInit", game.getId(), getGameView()));
return true; return true;
@ -76,28 +76,28 @@ public class GameSessionWatcher {
public void update() { public void update() {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameUpdate", game.getId(), getGameView()))); UserManager.instance.getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameUpdate", game.getId(), getGameView())));
} }
} }
public void inform(final String message) { public void inform(final String message) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameInform", game.getId(), new GameClientMessage(getGameView(), message)))); UserManager.instance.getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameInform", game.getId(), new GameClientMessage(getGameView(), message))));
} }
} }
public void informPersonal(final String message) { public void informPersonal(final String message) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameInformPersonal", game.getId(), new GameClientMessage(getGameView(), message)))); UserManager.instance.getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameInformPersonal", game.getId(), new GameClientMessage(getGameView(), message))));
} }
} }
public void gameOver(final String message) { public void gameOver(final String message) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user -> { UserManager.instance.getUser(userId).ifPresent(user -> {
user.removeGameWatchInfo(game.getId()); user.removeGameWatchInfo(game.getId());
user.fireCallback(new ClientCallback("gameOver", game.getId(), message)); user.fireCallback(new ClientCallback("gameOver", game.getId(), message));
}); });
@ -113,7 +113,7 @@ public class GameSessionWatcher {
public void gameError(final String message) { public void gameError(final String message) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameError", game.getId(), message))); UserManager.instance.getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameError", game.getId(), message)));
} }
} }

View file

@ -100,7 +100,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
} else { } else {
// more since 50 matches finished since this match so remove it // more since 50 matches finished since this match so remove it
if (table.isTournament()) { if (table.isTournament()) {
TournamentManager.getInstance().removeTournament(table.getTournament().getId()); TournamentManager.instance.removeTournament(table.getTournament().getId());
} }
this.removeTable(table.getId()); this.removeTable(table.getId());
} }
@ -108,7 +108,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
tableView = tableList; tableView = tableList;
matchView = matchList; matchView = matchList;
List<UsersView> users = new ArrayList<>(); List<UsersView> users = new ArrayList<>();
for (User user : UserManager.getInstance().getUsers()) { for (User user : UserManager.instance.getUsers()) {
try { try {
users.add(new UsersView(user.getUserData().getFlagName(), user.getName(), users.add(new UsersView(user.getUserData().getFlagName(), user.getName(),
user.getMatchHistory(), user.getMatchQuitRatio(), user.getTourneyHistory(), user.getMatchHistory(), user.getMatchQuitRatio(), user.getTourneyHistory(),
@ -135,9 +135,9 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
users.sort((one, two) -> one.getUserName().compareToIgnoreCase(two.getUserName())); users.sort((one, two) -> one.getUserName().compareToIgnoreCase(two.getUserName()));
List<RoomUsersView> roomUserInfo = new ArrayList<>(); List<RoomUsersView> roomUserInfo = new ArrayList<>();
roomUserInfo.add(new RoomUsersView(users, roomUserInfo.add(new RoomUsersView(users,
GameManager.getInstance().getNumberActiveGames(), GameManager.instance.getNumberActiveGames(),
ThreadExecutor.getInstance().getActiveThreads(ThreadExecutor.getInstance().getGameExecutor()), ThreadExecutor.getInstance().getActiveThreads(ThreadExecutor.getInstance().getGameExecutor()),
ConfigSettings.getInstance().getMaxGameThreads() ConfigSettings.instance.getMaxGameThreads()
)); ));
roomUsersView = roomUserInfo; roomUsersView = roomUserInfo;
} }
@ -150,7 +150,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
@Override @Override
public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException { public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws MageException {
if (tables.containsKey(tableId)) { if (tables.containsKey(tableId)) {
return TableManager.getInstance().joinTable(userId, tableId, name, playerType, skill, deckList, password); return TableManager.instance.joinTable(userId, tableId, name, playerType, skill, deckList, password);
} else { } else {
return false; return false;
} }
@ -158,7 +158,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
@Override @Override
public TableView createTable(UUID userId, MatchOptions options) { public TableView createTable(UUID userId, MatchOptions options) {
Table table = TableManager.getInstance().createTable(this.getRoomId(), userId, options); Table table = TableManager.instance.createTable(this.getRoomId(), userId, options);
tables.put(table.getId(), table); tables.put(table.getId(), table);
return new TableView(table); return new TableView(table);
} }
@ -166,7 +166,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
@Override @Override
public boolean joinTournamentTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws GameException { public boolean joinTournamentTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList, String password) throws GameException {
if (tables.containsKey(tableId)) { if (tables.containsKey(tableId)) {
return TableManager.getInstance().joinTournament(userId, tableId, name, playerType, skill, deckList, password); return TableManager.instance.joinTournament(userId, tableId, name, playerType, skill, deckList, password);
} else { } else {
return false; return false;
} }
@ -174,7 +174,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
@Override @Override
public TableView createTournamentTable(UUID userId, TournamentOptions options) { public TableView createTournamentTable(UUID userId, TournamentOptions options) {
Table table = TableManager.getInstance().createTournamentTable(this.getRoomId(), userId, options); Table table = TableManager.instance.createTournamentTable(this.getRoomId(), userId, options);
tables.put(table.getId(), table); tables.put(table.getId(), table);
return new TableView(table); return new TableView(table);
} }
@ -206,12 +206,12 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
@Override @Override
public void leaveTable(UUID userId, UUID tableId) { public void leaveTable(UUID userId, UUID tableId) {
TableManager.getInstance().leaveTable(userId, tableId); TableManager.instance.leaveTable(userId, tableId);
} }
@Override @Override
public boolean watchTable(UUID userId, UUID tableId) throws MageException { public boolean watchTable(UUID userId, UUID tableId) throws MageException {
return TableManager.getInstance().watchTable(userId, tableId); return TableManager.instance.watchTable(userId, tableId);
} }
@Override @Override

View file

@ -32,22 +32,16 @@ import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class GamesRoomManager { public enum GamesRoomManager {
instance;
private static final GamesRoomManager INSTANCE = new GamesRoomManager();
// private static final Logger logger = Logger.getLogger(GamesRoomManager.class);
private final ConcurrentHashMap<UUID, GamesRoom> rooms = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, GamesRoom> rooms = new ConcurrentHashMap<>();
private final UUID mainRoomId; private final UUID mainRoomId;
public static GamesRoomManager getInstance() {
return INSTANCE;
}
private GamesRoomManager() { GamesRoomManager() {
GamesRoom mainRoom = new GamesRoomImpl(); GamesRoom mainRoom = new GamesRoomImpl();
mainRoomId = mainRoom.getRoomId(); mainRoomId = mainRoom.getRoomId();
rooms.put(mainRoomId, mainRoom); rooms.put(mainRoomId, mainRoom);

View file

@ -36,21 +36,15 @@ import mage.server.UserManager;
* *
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class ReplayManager { public enum ReplayManager {
private static final ReplayManager INSTANCE = new ReplayManager(); instance;
public static ReplayManager getInstance() {
return INSTANCE;
}
private ReplayManager() {}
private final ConcurrentHashMap<String, ReplaySession> replaySessions = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, ReplaySession> replaySessions = new ConcurrentHashMap<>();
public void replayGame(UUID gameId, UUID userId) { public void replayGame(UUID gameId, UUID userId) {
ReplaySession replaySession = new ReplaySession(gameId, userId); ReplaySession replaySession = new ReplaySession(gameId, userId);
replaySessions.put(gameId.toString() + userId.toString(), replaySession); replaySessions.put(gameId.toString() + userId.toString(), replaySession);
UserManager.getInstance().getUser(userId).ifPresent(user->user.ccReplayGame(gameId)); UserManager.instance.getUser(userId).ifPresent(user->user.ccReplayGame(gameId));
} }
public void startReplay(UUID gameId, UUID userId) { public void startReplay(UUID gameId, UUID userId) {

View file

@ -51,7 +51,7 @@ public class ReplaySession implements GameCallback {
public void replay() { public void replay() {
replay.start(); replay.start();
UserManager.getInstance().getUser(userId).ifPresent(user -> UserManager.instance.getUser(userId).ifPresent(user ->
user.fireCallback(new ClientCallback("replayInit", replay.getGame().getId(), new GameView(replay.next(), replay.getGame(), null, null)))); user.fireCallback(new ClientCallback("replayInit", replay.getGame().getId(), new GameView(replay.next(), replay.getGame(), null, null))));
} }
@ -77,17 +77,17 @@ public class ReplaySession implements GameCallback {
@Override @Override
public void gameResult(final String result) { public void gameResult(final String result) {
UserManager.getInstance().getUser(userId).ifPresent(user -> UserManager.instance.getUser(userId).ifPresent(user ->
user.fireCallback(new ClientCallback("replayDone", replay.getGame().getId(), result))); user.fireCallback(new ClientCallback("replayDone", replay.getGame().getId(), result)));
ReplayManager.getInstance().endReplay(replay.getGame().getId(), userId); ReplayManager.instance.endReplay(replay.getGame().getId(), userId);
} }
private void updateGame(final GameState state, Game game) { private void updateGame(final GameState state, Game game) {
if (state == null) { if (state == null) {
gameResult("game ended"); gameResult("game ended");
} else { } else {
UserManager.getInstance().getUser(userId).ifPresent(user -> UserManager.instance.getUser(userId).ifPresent(user ->
user.fireCallback(new ClientCallback("replayUpdate", replay.getGame().getId(), new GameView(state, game, null, null)))); user.fireCallback(new ClientCallback("replayUpdate", replay.getGame().getId(), new GameView(state, game, null, null))));
} }

View file

@ -17,6 +17,6 @@ public class TableRecorderImpl implements TableRecorder {
public void record(Table table) { public void record(Table table) {
TableProto proto = table.toProto(); TableProto proto = table.toProto();
TableRecordRepository.instance.add(new TableRecord(proto, proto.getEndTimeMs())); TableRecordRepository.instance.add(new TableRecord(proto, proto.getEndTimeMs()));
UserManager.getInstance().updateUserHistory(); UserManager.instance.updateUserHistory();
} }
} }

View file

@ -77,7 +77,7 @@ public class TournamentController {
public TournamentController(Tournament tournament, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) { public TournamentController(Tournament tournament, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {
this.userPlayerMap = userPlayerMap; this.userPlayerMap = userPlayerMap;
chatId = ChatManager.getInstance().createChatSession("Tournament " + tournament.getId()); chatId = ChatManager.instance.createChatSession("Tournament " + tournament.getId());
this.tournament = tournament; this.tournament = tournament;
this.tableId = tableId; this.tableId = tableId;
init(); init();
@ -91,7 +91,7 @@ public class TournamentController {
checkPlayersState(); checkPlayersState();
break; break;
case INFO: case INFO:
ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.STATUS, null); ChatManager.instance.broadcast(chatId, "", event.getMessage(), MessageColor.BLACK, true, MessageType.STATUS, null);
logger.debug(tournament.getId() + " " + event.getMessage()); logger.debug(tournament.getId() + " " + event.getMessage());
break; break;
case START_DRAFT: case START_DRAFT:
@ -146,7 +146,7 @@ public class TournamentController {
if (!player.getPlayer().isHuman()) { if (!player.getPlayer().isHuman()) {
player.setJoined(); player.setJoined();
logger.debug("player " + player.getPlayer().getId() + " has joined tournament " + tournament.getId()); logger.debug("player " + player.getPlayer().getId() + " has joined tournament " + tournament.getId());
ChatManager.getInstance().broadcast(chatId, "", player.getPlayer().getLogName() + " has joined the tournament", MessageColor.BLACK, true, MessageType.STATUS, null); ChatManager.instance.broadcast(chatId, "", player.getPlayer().getLogName() + " has joined the tournament", MessageColor.BLACK, true, MessageType.STATUS, null);
} }
} }
checkStart(); checkStart();
@ -156,7 +156,7 @@ public class TournamentController {
UUID playerId = userPlayerMap.get(userId); UUID playerId = userPlayerMap.get(userId);
if (playerId == null) { if (playerId == null) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
UserManager.getInstance().getUser(userId).ifPresent(user -> UserManager.instance.getUser(userId).ifPresent(user ->
logger.debug(user.getName() + " shows tournament panel tournamentId: " + tournament.getId())); logger.debug(user.getName() + " shows tournament panel tournamentId: " + tournament.getId()));
} }
@ -169,14 +169,14 @@ public class TournamentController {
// first join of player // first join of player
TournamentSession tournamentSession = new TournamentSession(tournament, userId, tableId, playerId); TournamentSession tournamentSession = new TournamentSession(tournament, userId, tableId, playerId);
tournamentSessions.put(playerId, tournamentSession); tournamentSessions.put(playerId, tournamentSession);
Optional<User> _user = UserManager.getInstance().getUser(userId); Optional<User> _user = UserManager.instance.getUser(userId);
if (_user.isPresent()) { if (_user.isPresent()) {
User user = _user.get(); User user = _user.get();
user.addTournament(playerId, tournament.getId()); user.addTournament(playerId, tournament.getId());
TournamentPlayer player = tournament.getPlayer(playerId); TournamentPlayer player = tournament.getPlayer(playerId);
player.setJoined(); player.setJoined();
logger.debug("player " + player.getPlayer().getName() + " - client has joined tournament " + tournament.getId()); logger.debug("player " + player.getPlayer().getName() + " - client has joined tournament " + tournament.getId());
ChatManager.getInstance().broadcast(chatId, "", player.getPlayer().getLogName() + " has joined the tournament", MessageColor.BLACK, true, MessageType.STATUS, null); ChatManager.instance.broadcast(chatId, "", player.getPlayer().getLogName() + " has joined the tournament", MessageColor.BLACK, true, MessageType.STATUS, null);
checkStart(); checkStart();
} else { } else {
logger.error("User not found userId: " + userId + " tournamentId: " + tournament.getId()); logger.error("User not found userId: " + userId + " tournamentId: " + tournament.getId());
@ -235,15 +235,15 @@ public class TournamentController {
tournamentSession.tournamentOver(); tournamentSession.tournamentOver();
} }
this.tournamentSessions.clear(); this.tournamentSessions.clear();
TableManager.getInstance().endTournament(tableId, tournament); TableManager.instance.endTournament(tableId, tournament);
tournament.cleanUpOnTournamentEnd(); tournament.cleanUpOnTournamentEnd();
} }
private void startMatch(TournamentPairing pair, MatchOptions matchOptions) { private void startMatch(TournamentPairing pair, MatchOptions matchOptions) {
try { try {
TableManager tableManager = TableManager.getInstance(); TableManager tableManager = TableManager.instance;
Table table = tableManager.createTable(GamesRoomManager.getInstance().getMainRoomId(), matchOptions); Table table = tableManager.createTable(GamesRoomManager.instance.getMainRoomId(), matchOptions);
table.setTournamentSubTable(true); table.setTournamentSubTable(true);
table.setTournament(tournament); table.setTournament(tournament);
table.setState(TableState.WAITING); table.setState(TableState.WAITING);
@ -266,8 +266,8 @@ public class TournamentController {
private void startMultiplayerMatch(MultiplayerRound round, MatchOptions matchOptions) { private void startMultiplayerMatch(MultiplayerRound round, MatchOptions matchOptions) {
try { try {
TableManager tableManager = TableManager.getInstance(); TableManager tableManager = TableManager.instance;
Table table = tableManager.createTable(GamesRoomManager.getInstance().getMainRoomId(), matchOptions); Table table = tableManager.createTable(GamesRoomManager.instance.getMainRoomId(), matchOptions);
table.setTournamentSubTable(true); table.setTournamentSubTable(true);
table.setTournament(tournament); table.setTournament(tournament);
table.setState(TableState.WAITING); table.setState(TableState.WAITING);
@ -290,16 +290,16 @@ public class TournamentController {
} }
private void startDraft(Draft draft) { private void startDraft(Draft draft) {
TableManager.getInstance().startDraft(tableId, draft); TableManager.instance.startDraft(tableId, draft);
} }
private void construct() { private void construct() {
TableManager.getInstance().construct(tableId); TableManager.instance.construct(tableId);
} }
private void initTournament() { private void initTournament() {
if (TableManager.getInstance().getTable(tableId).getState() != TableState.DUELING) { if (TableManager.instance.getTable(tableId).getState() != TableState.DUELING) {
TableManager.getInstance().initTournament(tableId); TableManager.instance.initTournament(tableId);
} }
} }
@ -307,7 +307,7 @@ public class TournamentController {
if (tournamentSessions.containsKey(playerId)) { if (tournamentSessions.containsKey(playerId)) {
TournamentSession tournamentSession = tournamentSessions.get(playerId); TournamentSession tournamentSession = tournamentSessions.get(playerId);
tournamentSession.construct(timeout); tournamentSession.construct(timeout);
UserManager.getInstance().getUser(getPlayerUserId(playerId)).get().addConstructing(playerId, tournamentSession); UserManager.instance.getUser(getPlayerUserId(playerId)).get().addConstructing(playerId, tournamentSession);
TournamentPlayer player = tournament.getPlayer(playerId); TournamentPlayer player = tournament.getPlayer(playerId);
player.setState(TournamentPlayerState.CONSTRUCTING); player.setState(TournamentPlayerState.CONSTRUCTING);
} }
@ -318,7 +318,7 @@ public class TournamentController {
TournamentPlayer player = tournament.getPlayer(playerId); TournamentPlayer player = tournament.getPlayer(playerId);
if (player != null && !player.hasQuit()) { if (player != null && !player.hasQuit()) {
tournamentSessions.get(playerId).submitDeck(deck); tournamentSessions.get(playerId).submitDeck(deck);
ChatManager.getInstance().broadcast(chatId, "", player.getPlayer().getLogName() + " has submitted his or her tournament deck", MessageColor.BLACK, true, MessageType.STATUS, SoundToPlay.PlayerSubmittedDeck); ChatManager.instance.broadcast(chatId, "", player.getPlayer().getLogName() + " has submitted his or her tournament deck", MessageColor.BLACK, true, MessageType.STATUS, SoundToPlay.PlayerSubmittedDeck);
} }
} }
} }
@ -336,7 +336,7 @@ public class TournamentController {
tournament.autoSubmit(userPlayerMap.get(userId), tournamentPlayer.generateDeck()); tournament.autoSubmit(userPlayerMap.get(userId), tournamentPlayer.generateDeck());
} else { } else {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
UserManager.getInstance().getUser(userId).ifPresent(user -> UserManager.instance.getUser(userId).ifPresent(user ->
sb.append(user.getName())); sb.append(user.getName()));
sb.append(" - no deck found for auto submit"); sb.append(" - no deck found for auto submit");
@ -378,18 +378,18 @@ public class TournamentController {
if (tournament.isDoneConstructing()) { if (tournament.isDoneConstructing()) {
info = new StringBuilder("during round ").append(tournament.getRounds().size()).toString(); info = new StringBuilder("during round ").append(tournament.getRounds().size()).toString();
// quit active matches of that tournament // quit active matches of that tournament
TableManager.getInstance().userQuitTournamentSubTables(tournament.getId(), userId); TableManager.instance.userQuitTournamentSubTables(tournament.getId(), userId);
status = TourneyQuitStatus.DURING_ROUND; status = TourneyQuitStatus.DURING_ROUND;
} else if (tournamentPlayer.getState() == TournamentPlayerState.DRAFTING) { } else if (tournamentPlayer.getState() == TournamentPlayerState.DRAFTING) {
info = "during Draft phase"; info = "during Draft phase";
if (!checkToReplaceDraftPlayerByAi(userId, tournamentPlayer)) { if (!checkToReplaceDraftPlayerByAi(userId, tournamentPlayer)) {
this.abortDraftTournament(); this.abortDraftTournament();
} else { } else {
DraftController draftController = DraftManager.getInstance().getController(tableId); DraftController draftController = DraftManager.instance.getController(tableId);
if (draftController != null) { if (draftController != null) {
DraftSession draftSession = draftController.getDraftSession(playerId); DraftSession draftSession = draftController.getDraftSession(playerId);
if (draftSession != null) { if (draftSession != null) {
DraftManager.getInstance().kill(draftSession.getDraftId(), userId); DraftManager.instance.kill(draftSession.getDraftId(), userId);
} }
} }
} }
@ -404,7 +404,7 @@ public class TournamentController {
tournamentPlayer.setQuit(info, status); tournamentPlayer.setQuit(info, status);
tournament.quit(playerId); tournament.quit(playerId);
tournamentSession.quit(); tournamentSession.quit();
ChatManager.getInstance().broadcast(chatId, "", tournamentPlayer.getPlayer().getLogName() + " has quit the tournament", MessageColor.BLACK, true, MessageType.STATUS, SoundToPlay.PlayerQuitTournament); ChatManager.instance.broadcast(chatId, "", tournamentPlayer.getPlayer().getLogName() + " has quit the tournament", MessageColor.BLACK, true, MessageType.STATUS, SoundToPlay.PlayerQuitTournament);
} }
} }
@ -418,8 +418,8 @@ public class TournamentController {
} }
// replace player that quits with draft bot // replace player that quits with draft bot
if (humans > 1) { if (humans > 1) {
Optional<User> user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
TableController tableController = TableManager.getInstance().getController(tableId); TableController tableController = TableManager.instance.getController(tableId);
if (tableController != null) { if (tableController != null) {
String replacePlayerName = "Draftbot"; String replacePlayerName = "Draftbot";
if (user.isPresent()) { if (user.isPresent()) {
@ -431,7 +431,7 @@ public class TournamentController {
user.get().removeTable(leavingPlayer.getPlayer().getId()); user.get().removeTable(leavingPlayer.getPlayer().getId());
user.get().removeTournament(leavingPlayer.getPlayer().getId()); user.get().removeTournament(leavingPlayer.getPlayer().getId());
} }
ChatManager.getInstance().broadcast(chatId, "", leavingPlayer.getPlayer().getLogName() + " was replaced by draftbot", MessageColor.BLACK, true, MessageType.STATUS, null); ChatManager.instance.broadcast(chatId, "", leavingPlayer.getPlayer().getLogName() + " was replaced by draftbot", MessageColor.BLACK, true, MessageType.STATUS, null);
} }
return true; return true;
} }
@ -453,7 +453,7 @@ public class TournamentController {
private void abortDraftTournament() { private void abortDraftTournament() {
tournament.setAbort(true); tournament.setAbort(true);
DraftManager.getInstance().getController(tableId).abortDraft(); DraftManager.instance.getController(tableId).abortDraft();
} }
public boolean isAbort() { public boolean isAbort() {
@ -478,7 +478,7 @@ public class TournamentController {
} }
public void cleanUpOnRemoveTournament() { public void cleanUpOnRemoveTournament() {
ChatManager.getInstance().destroyChatSession(chatId); ChatManager.instance.destroyChatSession(chatId);
} }
/** /**
@ -496,7 +496,7 @@ public class TournamentController {
if (tournamentPlayer != null) { if (tournamentPlayer != null) {
if (!tournamentPlayer.hasQuit()) { if (!tournamentPlayer.hasQuit()) {
if (tournamentPlayer.getPlayer().isHuman()) { if (tournamentPlayer.getPlayer().isHuman()) {
Optional<User> user = UserManager.getInstance().getUser(entry.getKey()); Optional<User> user = UserManager.instance.getUser(entry.getKey());
if (!user.isPresent()) { if (!user.isPresent()) {
logger.debug("Tournament user is missing but player active -> start quit - tournamentId: " + tournament.getId() + " state: " + tableState.toString()); logger.debug("Tournament user is missing but player active -> start quit - tournamentId: " + tournament.getId() + " state: " + tableState.toString());
// active tournament player but the user is no longer online // active tournament player but the user is no longer online

View file

@ -30,25 +30,19 @@ package mage.server.tournament;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import mage.cards.decks.Deck; import mage.cards.decks.Deck;
import mage.game.tournament.Tournament; import mage.game.tournament.Tournament;
import mage.view.TournamentView; import mage.view.TournamentView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class TournamentManager { public enum TournamentManager {
instance;
private static final TournamentManager INSTANCE = new TournamentManager();
private final ConcurrentHashMap<UUID, TournamentController> controllers = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, TournamentController> controllers = new ConcurrentHashMap<>();
public static TournamentManager getInstance() {
return INSTANCE;
}
public TournamentController getTournamentController(UUID tournamentId) { public TournamentController getTournamentController(UUID tournamentId) {
return controllers.get(tournamentId); return controllers.get(tournamentId);
} }

View file

@ -67,7 +67,7 @@ public class TournamentSession {
public boolean init() { public boolean init() {
if (!killed) { if (!killed) {
Optional<User> user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.instance.getUser(userId);
if (user.isPresent()) { if (user.isPresent()) {
user.get().fireCallback(new ClientCallback("tournamentInit", tournament.getId(), getTournamentView())); user.get().fireCallback(new ClientCallback("tournamentInit", tournament.getId(), getTournamentView()));
return true; return true;
@ -78,7 +78,7 @@ public class TournamentSession {
public void update() { public void update() {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user -> UserManager.instance.getUser(userId).ifPresent(user ->
user.fireCallback(new ClientCallback("tournamentUpdate", tournament.getId(), getTournamentView()))); user.fireCallback(new ClientCallback("tournamentUpdate", tournament.getId(), getTournamentView())));
} }
@ -86,7 +86,7 @@ public class TournamentSession {
public void gameOver(final String message) { public void gameOver(final String message) {
if (!killed) { if (!killed) {
UserManager.getInstance().getUser(userId).ifPresent(user -> UserManager.instance.getUser(userId).ifPresent(user ->
user.fireCallback(new ClientCallback("tournamentOver", tournament.getId(), message))); user.fireCallback(new ClientCallback("tournamentOver", tournament.getId(), message)));
} }
@ -95,7 +95,7 @@ public class TournamentSession {
public void construct(int timeout) { public void construct(int timeout) {
if (!killed) { if (!killed) {
setupTimeout(timeout); setupTimeout(timeout);
UserManager.getInstance().getUser(userId).ifPresent(user -> { UserManager.instance.getUser(userId).ifPresent(user -> {
int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS); int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS);
user.ccConstruct(tournament.getPlayer(playerId).getDeck(), tableId, remaining); user.ccConstruct(tournament.getPlayer(playerId).getDeck(), tableId, remaining);
}); });
@ -128,7 +128,7 @@ public class TournamentSession {
futureTimeout = timeoutExecutor.schedule( futureTimeout = timeoutExecutor.schedule(
() -> { () -> {
try { try {
TournamentManager.getInstance().timeout(tournament.getId(), userId); TournamentManager.instance.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);
} }
@ -170,7 +170,7 @@ public class TournamentSession {
} }
private void removeTournamentForUser() { private void removeTournamentForUser() {
UserManager.getInstance().getUser(userId).ifPresent(user -> UserManager.instance.getUser(userId).ifPresent(user ->
user.removeTournament(playerId)); user.removeTournament(playerId));

View file

@ -33,27 +33,23 @@ import java.util.List;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller; import javax.xml.bind.Unmarshaller;
import mage.server.util.config.Config; import mage.server.util.config.Config;
import mage.server.util.config.GamePlugin; import mage.server.util.config.GamePlugin;
import mage.server.util.config.Plugin; import mage.server.util.config.Plugin;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class ConfigSettings { public enum ConfigSettings {
instance;
private static final Logger logger = Logger.getLogger(ConfigSettings.class); private final Logger logger = Logger.getLogger(ConfigSettings.class);
private static final ConfigSettings INSTANCE = new ConfigSettings();
private Config config; private Config config;
public static ConfigSettings getInstance() {
return INSTANCE;
}
private ConfigSettings() { ConfigSettings() {
try { try {
JAXBContext jaxbContext = JAXBContext.newInstance("mage.server.util.config"); JAXBContext jaxbContext = JAXBContext.newInstance("mage.server.util.config");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

View file

@ -48,13 +48,11 @@ import java.util.concurrent.locks.ReentrantReadWriteLock;
* *
* @author nantuko * @author nantuko
*/ */
public class ServerMessagesUtil { public enum ServerMessagesUtil {
instance;
private static final ServerMessagesUtil instance = new ServerMessagesUtil();
private static final Logger log = Logger.getLogger(ServerMessagesUtil.class); private static final Logger log = Logger.getLogger(ServerMessagesUtil.class);
private static final String SERVER_MSG_TXT_FILE = "server.msg.txt"; private static final String SERVER_MSG_TXT_FILE = "server.msg.txt";
private static ScheduledExecutorService updateExecutor; private ScheduledExecutorService updateExecutor;
private final List<String> messages = new ArrayList<>(); private final List<String> messages = new ArrayList<>();
private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final ReadWriteLock lock = new ReentrantReadWriteLock();
@ -73,14 +71,12 @@ public class ServerMessagesUtil {
pathToExternalMessages = System.getProperty("messagesPath"); pathToExternalMessages = System.getProperty("messagesPath");
} }
public ServerMessagesUtil() { ServerMessagesUtil() {
updateExecutor = Executors.newSingleThreadScheduledExecutor(); updateExecutor = Executors.newSingleThreadScheduledExecutor();
updateExecutor.scheduleAtFixedRate(this::reloadMessages, 5, 5 * 60, TimeUnit.SECONDS); updateExecutor.scheduleAtFixedRate(this::reloadMessages, 5, 5 * 60, TimeUnit.SECONDS);
} }
public static ServerMessagesUtil getInstance() {
return instance;
}
public List<String> getMessages() { public List<String> getMessages() {
lock.readLock().lock(); lock.readLock().lock();

View file

@ -42,7 +42,7 @@ public class ThreadExecutor {
private static final ExecutorService callExecutor = Executors.newCachedThreadPool(); private static final ExecutorService callExecutor = Executors.newCachedThreadPool();
private static final ExecutorService userExecutor = Executors.newCachedThreadPool(); private static final ExecutorService userExecutor = Executors.newCachedThreadPool();
private static final ExecutorService gameExecutor = Executors.newFixedThreadPool(ConfigSettings.getInstance().getMaxGameThreads()); private static final ExecutorService gameExecutor = Executors.newFixedThreadPool(ConfigSettings.instance.getMaxGameThreads());
private static final ScheduledExecutorService timeoutExecutor = Executors.newScheduledThreadPool(4); private static final ScheduledExecutorService timeoutExecutor = Executors.newScheduledThreadPool(4);
private static final ScheduledExecutorService timeoutIdleExecutor = Executors.newScheduledThreadPool(4); private static final ScheduledExecutorService timeoutIdleExecutor = Executors.newScheduledThreadPool(4);

View file

@ -54,7 +54,7 @@ public class AbzanBeastmaster extends CardImpl {
// At the beginning of your upkeep, draw a card if you control the creature with the greatest toughness or tied for the greatest toughness. // At the beginning of your upkeep, draw a card if you control the creature with the greatest toughness or tied for the greatest toughness.
this.addAbility(new ConditionalTriggeredAbility( this.addAbility(new ConditionalTriggeredAbility(
new BeginningOfUpkeepTriggeredAbility(new DrawCardSourceControllerEffect(1), TargetController.YOU, false), new BeginningOfUpkeepTriggeredAbility(new DrawCardSourceControllerEffect(1), TargetController.YOU, false),
ControlsCreatureGreatestToughnessCondition.getInstance(), ControlsCreatureGreatestToughnessCondition.instance,
"At the beginning of your upkeep, draw a card if you control the creature with the greatest toughness or tied for the greatest toughness." "At the beginning of your upkeep, draw a card if you control the creature with the greatest toughness or tied for the greatest toughness."
)); ));
} }

View file

@ -61,7 +61,7 @@ public class AetherFigment extends CardImpl {
// If Aether Figment was kicked, it enters the battlefield with two +1/+1 counters on it // If Aether Figment was kicked, it enters the battlefield with two +1/+1 counters on it
Ability ability = new EntersBattlefieldAbility( Ability ability = new EntersBattlefieldAbility(
new AddCountersSourceEffect(CounterType.P1P1.createInstance(2)), new AddCountersSourceEffect(CounterType.P1P1.createInstance(2)),
KickedCondition.getInstance(), KickedCondition.instance,
"If {this} was kicked, it enters the battlefield with two +1/+1 counters on it", "If {this} was kicked, it enters the battlefield with two +1/+1 counters on it",
""); "");
this.addAbility(ability); this.addAbility(ability);

View file

@ -61,7 +61,7 @@ public class AfflictedDeserter extends CardImpl {
// At the beginning of each upkeep, if no spells were cast last turn, transform Afflicted Deserter. // At the beginning of each upkeep, if no spells were cast last turn, transform Afflicted Deserter.
this.addAbility(new TransformAbility()); this.addAbility(new TransformAbility());
TriggeredAbility ability = new BeginningOfUpkeepTriggeredAbility(new TransformSourceEffect(true), TargetController.ANY, false); TriggeredAbility ability = new BeginningOfUpkeepTriggeredAbility(new TransformSourceEffect(true), TargetController.ANY, false);
this.addAbility(new ConditionalTriggeredAbility(ability, NoSpellsWereCastLastTurnCondition.getInstance(), TransformAbility.NO_SPELLS_TRANSFORM_RULE)); this.addAbility(new ConditionalTriggeredAbility(ability, NoSpellsWereCastLastTurnCondition.instance, TransformAbility.NO_SPELLS_TRANSFORM_RULE));
} }
public AfflictedDeserter(final AfflictedDeserter card) { public AfflictedDeserter(final AfflictedDeserter card) {

View file

@ -67,7 +67,7 @@ public class AgonizingDemise extends CardImpl {
//If Agonizing Demise was kicked, it deals damage equal to that creature's power to the creature's controller. //If Agonizing Demise was kicked, it deals damage equal to that creature's power to the creature's controller.
this.getSpellAbility().addEffect(new ConditionalOneShotEffect( this.getSpellAbility().addEffect(new ConditionalOneShotEffect(
new DamageTargetControllerEffect(new TargetPermanentPowerCount()), new DamageTargetControllerEffect(new TargetPermanentPowerCount()),
KickedCondition.getInstance(), KickedCondition.instance,
"If {this} was kicked, it deals damage equal to that creature's power to the creature's controller.")); "If {this} was kicked, it deals damage equal to that creature's power to the creature's controller."));
} }

View file

@ -63,7 +63,7 @@ public class AidFromTheCowl extends CardImpl {
// <i>Revolt</i> &mdash; At the beginning of your end step, if a permanent you controlled left the battlefield this turn, // <i>Revolt</i> &mdash; At the beginning of your end step, if a permanent you controlled left the battlefield this turn,
// reveal the top card of your library. If it is a permanent card, you may put it onto the battlefield. Otherwise, put it on the bottom of your library. // reveal the top card of your library. If it is a permanent card, you may put it onto the battlefield. Otherwise, put it on the bottom of your library.
TriggeredAbility ability = new BeginningOfYourEndStepTriggeredAbility(new AidFromTheCowlEffect(), false); TriggeredAbility ability = new BeginningOfYourEndStepTriggeredAbility(new AidFromTheCowlEffect(), false);
this.addAbility(new ConditionalTriggeredAbility(ability, RevoltCondition.getInstance(), ruleText), new RevoltWatcher()); this.addAbility(new ConditionalTriggeredAbility(ability, RevoltCondition.instance, ruleText), new RevoltWatcher());
} }
public AidFromTheCowl(final AidFromTheCowl card) { public AidFromTheCowl(final AidFromTheCowl card) {

View file

@ -60,7 +60,7 @@ public class AirdropAeronauts extends CardImpl {
// <i>Revolt</i> &mdash; When Airdrop Aeronauts enters the battlefield, if a permanent you controlled left the battlefield this turn, you gain 5 life. // <i>Revolt</i> &mdash; When Airdrop Aeronauts enters the battlefield, if a permanent you controlled left the battlefield this turn, you gain 5 life.
Ability ability = new ConditionalTriggeredAbility(new EntersBattlefieldTriggeredAbility( Ability ability = new ConditionalTriggeredAbility(new EntersBattlefieldTriggeredAbility(
new GainLifeEffect(5), false), RevoltCondition.getInstance(), new GainLifeEffect(5), false), RevoltCondition.instance,
"<i>Revolt</i> &mdash; When {this} enters the battlefield, if a permanent you controlled left" "<i>Revolt</i> &mdash; When {this} enters the battlefield, if a permanent you controlled left"
+ " the battlefield this turn, you gain 5 life." + " the battlefield this turn, you gain 5 life."
); );

View file

@ -57,7 +57,7 @@ public class Aleatory extends CardImpl {
super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{1}{R}"); super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{1}{R}");
// Cast Aleatory only during combat after blockers are declared. // Cast Aleatory only during combat after blockers are declared.
this.addAbility(new CastOnlyDuringPhaseStepSourceAbility(TurnPhase.COMBAT, AfterBlockersAreDeclaredCondition.getInstance())); this.addAbility(new CastOnlyDuringPhaseStepSourceAbility(TurnPhase.COMBAT, AfterBlockersAreDeclaredCondition.instance));
// Flip a coin. If you win the flip, target creature gets +1/+1 until end of turn. // Flip a coin. If you win the flip, target creature gets +1/+1 until end of turn.
this.getSpellAbility().addEffect(new AleatoryEffect()); this.getSpellAbility().addEffect(new AleatoryEffect());

View file

@ -102,7 +102,7 @@ class AlurenRuleEffect extends ContinuousEffectImpl {
filter.add(new ConvertedManaCostPredicate(ComparisonType.LessThan, 4)); filter.add(new ConvertedManaCostPredicate(ComparisonType.LessThan, 4));
} }
static AlternativeCostSourceAbility alternativeCastingCostAbility = new AlternativeCostSourceAbility(null, SourceIsSpellCondition.getInstance(), null, filter, true); static AlternativeCostSourceAbility alternativeCastingCostAbility = new AlternativeCostSourceAbility(null, SourceIsSpellCondition.instance, null, filter, true);
public AlurenRuleEffect() { public AlurenRuleEffect() {
super(Duration.WhileOnBattlefield, Outcome.Detriment); super(Duration.WhileOnBattlefield, Outcome.Detriment);

View file

@ -73,7 +73,7 @@ public class AngelOfDeliverance extends CardImpl {
// exile target creature an opponent controls. // exile target creature an opponent controls.
Ability ability = new ConditionalTriggeredAbility( Ability ability = new ConditionalTriggeredAbility(
new AngelOfDeliveranceDealsDamageTriggeredAbility(), new AngelOfDeliveranceDealsDamageTriggeredAbility(),
new DeliriumCondition(), DeliriumCondition.instance,
"<i>Delirium</i> &mdash; Whenever {this} deals damage, if there are four or more card types among cards in your graveyard, exile target creature an opponent controls" "<i>Delirium</i> &mdash; Whenever {this} deals damage, if there are four or more card types among cards in your graveyard, exile target creature an opponent controls"
); );
ability.addTarget(new TargetCreaturePermanent(filter)); ability.addTarget(new TargetCreaturePermanent(filter));

View file

@ -72,7 +72,7 @@ public class AngryMob extends CardImpl {
PermanentsOnBattlefieldCount swamps = new PermanentsOnBattlefieldCount(filter); PermanentsOnBattlefieldCount swamps = new PermanentsOnBattlefieldCount(filter);
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new ConditionalContinuousEffect( this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new ConditionalContinuousEffect(
new BoostSourceEffect(swamps, swamps, Duration.WhileOnBattlefield), new BoostSourceEffect(swamps, swamps, Duration.WhileOnBattlefield),
MyTurnCondition.getInstance(), MyTurnCondition.instance,
"As long as it's your turn, Angry Mob's power and toughness are each equal to 2 plus the number of Swamps your opponents control. As long as it's not your turn, Angry Mob's power and toughness are each 2"))); "As long as it's your turn, Angry Mob's power and toughness are each equal to 2 plus the number of Swamps your opponents control. As long as it's not your turn, Angry Mob's power and toughness are each 2")));
} }

View file

@ -83,10 +83,10 @@ public class AngusMackenzie extends CardImpl {
} }
class BeforeCombatDamageCondition implements Condition { class BeforeCombatDamageCondition implements Condition {
private static final BeforeCombatDamageCondition fInstance = new BeforeCombatDamageCondition(); private static final BeforeCombatDamageCondition instance = new BeforeCombatDamageCondition();
public static Condition getInstance() { public static Condition getInstance() {
return fInstance; return instance;
} }
@Override @Override

View file

@ -103,7 +103,7 @@ class AnimistsAwakeningEffect extends OneShotEffect {
controller.moveCards(toBattlefield, Zone.BATTLEFIELD, source, game, true, false, true, null); controller.moveCards(toBattlefield, Zone.BATTLEFIELD, source, game, true, false, true, null);
controller.putCardsOnBottomOfLibrary(cards, game, source, true); controller.putCardsOnBottomOfLibrary(cards, game, source, true);
if (SpellMasteryCondition.getInstance().apply(game, source)) { if (SpellMasteryCondition.instance.apply(game, source)) {
for (Card card : toBattlefield) { for (Card card : toBattlefield) {
Permanent land = game.getPermanent(card.getId()); Permanent land = game.getPermanent(card.getId());
if (land != null) { if (land != null) {

View file

@ -28,6 +28,7 @@
package mage.cards.a; package mage.cards.a;
import java.util.UUID; import java.util.UUID;
import mage.abilities.Ability; import mage.abilities.Ability;
import mage.abilities.common.AttacksCreatureYouControlTriggeredAbility; import mage.abilities.common.AttacksCreatureYouControlTriggeredAbility;
import mage.abilities.common.SimpleStaticAbility; import mage.abilities.common.SimpleStaticAbility;
@ -46,7 +47,6 @@ import mage.game.Game;
import mage.game.events.GameEvent; import mage.game.events.GameEvent;
/** /**
*
* @author JotaPeRL * @author JotaPeRL
*/ */
public class AnthemOfRakdos extends CardImpl { public class AnthemOfRakdos extends CardImpl {
@ -101,7 +101,7 @@ class AnthemOfRakdosHellbentEffect extends ReplacementEffectImpl {
@Override @Override
public boolean applies(GameEvent event, Ability source, Game game) { public boolean applies(GameEvent event, Ability source, Game game) {
return game.getControllerId(event.getSourceId()).equals(source.getControllerId()) && HellbentCondition.getInstance().apply(game, source); return game.getControllerId(event.getSourceId()).equals(source.getControllerId()) && HellbentCondition.instance.apply(game, source);
} }
@Override @Override

View file

@ -73,7 +73,7 @@ public class AnyaMercilessAngel extends CardImpl {
// As long as an opponent's life total is less than half his or her starting life total, Anya has indestructible. // As long as an opponent's life total is less than half his or her starting life total, Anya has indestructible.
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD,
new ConditionalContinuousEffect(new GainAbilitySourceEffect(IndestructibleAbility.getInstance(), Duration.WhileOnBattlefield), new ConditionalContinuousEffect(new GainAbilitySourceEffect(IndestructibleAbility.getInstance(), Duration.WhileOnBattlefield),
AnyaMercilessAngelCondition.getInstance(), AnyaMercilessAngelCondition.instance,
"As long as an opponent's life total is less than half his or her starting life total, {this} has indestructible"))); "As long as an opponent's life total is less than half his or her starting life total, {this} has indestructible")));
} }
@ -121,16 +121,9 @@ class AnyaMercilessAngelDynamicValue implements DynamicValue {
} }
} }
class AnyaMercilessAngelCondition implements Condition { enum AnyaMercilessAngelCondition implements Condition {
private static final AnyaMercilessAngelCondition fInstance = new AnyaMercilessAngelCondition();
public static AnyaMercilessAngelCondition getInstance() {
return fInstance;
}
private AnyaMercilessAngelCondition() {}
instance;
@Override @Override
public boolean apply(Game game, Ability source) { public boolean apply(Game game, Ability source) {
return new AnyaMercilessAngelDynamicValue().calculate(game, source, null) > 0; return new AnyaMercilessAngelDynamicValue().calculate(game, source, null) > 0;

View file

@ -84,14 +84,14 @@ public class ArcTrail extends CardImpl {
class ArcTrailEffect extends OneShotEffect { class ArcTrailEffect extends OneShotEffect {
private static final ArcTrailEffect fINSTANCE = new ArcTrailEffect(); private static final ArcTrailEffect instance = new ArcTrailEffect();
private Object readResolve() throws ObjectStreamException { private Object readResolve() throws ObjectStreamException {
return fINSTANCE; return instance;
} }
public static ArcTrailEffect getInstance() { public static ArcTrailEffect getInstance() {
return fINSTANCE; return instance;
} }
private ArcTrailEffect ( ) { private ArcTrailEffect ( ) {
@ -128,7 +128,7 @@ class ArcTrailEffect extends OneShotEffect {
@Override @Override
public Effect copy() { public Effect copy() {
return fINSTANCE; return instance;
} }
} }

View file

@ -113,10 +113,10 @@ class ArchiveTrapWatcher extends Watcher {
class OpponentSearchesLibCondition implements Condition { class OpponentSearchesLibCondition implements Condition {
private static final OpponentSearchesLibCondition fInstance = new OpponentSearchesLibCondition(); private static final OpponentSearchesLibCondition instance = new OpponentSearchesLibCondition();
public static Condition getInstance() { public static Condition getInstance() {
return fInstance; return instance;
} }
@Override @Override

View file

@ -60,7 +60,7 @@ public class ArcticMerfolk extends CardImpl {
// If Arctic Merfolk was kicked, it enters the battlefield with a +1/+1 counter on it. // If Arctic Merfolk was kicked, it enters the battlefield with a +1/+1 counter on it.
this.addAbility(new EntersBattlefieldAbility( this.addAbility(new EntersBattlefieldAbility(
new AddCountersSourceEffect(CounterType.P1P1.createInstance()), new AddCountersSourceEffect(CounterType.P1P1.createInstance()),
KickedCondition.getInstance(),"If Arctic Merfolk was kicked, it enters the battlefield with a +1/+1 counter on it.","")); KickedCondition.instance,"If Arctic Merfolk was kicked, it enters the battlefield with a +1/+1 counter on it.",""));
} }
public ArcticMerfolk(final ArcticMerfolk card) { public ArcticMerfolk(final ArcticMerfolk card) {

View file

@ -57,7 +57,7 @@ public class ArdentRecruit extends CardImpl {
this.power = new MageInt(1); this.power = new MageInt(1);
this.toughness = new MageInt(1); this.toughness = new MageInt(1);
ContinuousEffect boostSource = new BoostSourceEffect(2, 2, Duration.WhileOnBattlefield); ContinuousEffect boostSource = new BoostSourceEffect(2, 2, Duration.WhileOnBattlefield);
ConditionalContinuousEffect effect = new ConditionalContinuousEffect(boostSource, MetalcraftCondition.getInstance(), "Ardent Recruit gets +2/+2 as long as you control three or more artifacts"); ConditionalContinuousEffect effect = new ConditionalContinuousEffect(boostSource, MetalcraftCondition.instance, "Ardent Recruit gets +2/+2 as long as you control three or more artifacts");
Ability ability = new SimpleStaticAbility(Zone.BATTLEFIELD, effect); Ability ability = new SimpleStaticAbility(Zone.BATTLEFIELD, effect);
ability.setAbilityWord(AbilityWord.METALCRAFT); ability.setAbilityWord(AbilityWord.METALCRAFT);
this.addAbility(ability); this.addAbility(ability);

View file

@ -59,7 +59,7 @@ public class ArdentSoldier extends CardImpl {
this.addAbility(VigilanceAbility.getInstance()); this.addAbility(VigilanceAbility.getInstance());
// If Ardent Soldier was kicked, it enters the battlefield with a +1/+1 counter on it. // If Ardent Soldier was kicked, it enters the battlefield with a +1/+1 counter on it.
this.addAbility(new EntersBattlefieldAbility(new AddCountersSourceEffect(CounterType.P1P1.createInstance(1)), this.addAbility(new EntersBattlefieldAbility(new AddCountersSourceEffect(CounterType.P1P1.createInstance(1)),
KickedCondition.getInstance(), "If {this} was kicked, it enters the battlefield with a +1/+1 counter on it.", "")); KickedCondition.instance, "If {this} was kicked, it enters the battlefield with a +1/+1 counter on it.", ""));
} }
public ArdentSoldier(final ArdentSoldier card) { public ArdentSoldier(final ArdentSoldier card) {

View file

@ -66,7 +66,7 @@ public class ArgentSphinx extends CardImpl {
this.addAbility(FlyingAbility.getInstance()); this.addAbility(FlyingAbility.getInstance());
// Metalcraft - {U}: Exile Argent Sphinx. Return it to the battlefield under your control at the beginning of the next end step. Activate this ability only if you control three or more artifacts. // Metalcraft - {U}: Exile Argent Sphinx. Return it to the battlefield under your control at the beginning of the next end step. Activate this ability only if you control three or more artifacts.
Ability ability = new ActivateIfConditionActivatedAbility(Zone.BATTLEFIELD, new ArgentSphinxEffect(), new ManaCostsImpl("{U}"), MetalcraftCondition.getInstance()); Ability ability = new ActivateIfConditionActivatedAbility(Zone.BATTLEFIELD, new ArgentSphinxEffect(), new ManaCostsImpl("{U}"), MetalcraftCondition.instance);
ability.setAbilityWord(AbilityWord.METALCRAFT); ability.setAbilityWord(AbilityWord.METALCRAFT);
this.addAbility(ability); this.addAbility(ability);
} }

View file

@ -51,13 +51,13 @@ public class ArrowStorm extends CardImpl {
// Arrow Storm deals 4 damage to target creature or player. // Arrow Storm deals 4 damage to target creature or player.
this.getSpellAbility().addEffect(new ConditionalOneShotEffect( this.getSpellAbility().addEffect(new ConditionalOneShotEffect(
new DamageTargetEffect(4), new DamageTargetEffect(4),
new InvertCondition(RaidCondition.getInstance()), new InvertCondition(RaidCondition.instance),
"{this} deals 4 damage to target creature or player")); "{this} deals 4 damage to target creature or player"));
this.getSpellAbility().addTarget(new TargetCreatureOrPlayer()); this.getSpellAbility().addTarget(new TargetCreatureOrPlayer());
// Raid - If you attacked with a creature this turn, instead Arrow Storm deals 5 damage to that creature or player and the damage can't be prevented. // Raid - If you attacked with a creature this turn, instead Arrow Storm deals 5 damage to that creature or player and the damage can't be prevented.
this.getSpellAbility().addEffect(new ConditionalOneShotEffect( this.getSpellAbility().addEffect(new ConditionalOneShotEffect(
new DamageTargetEffect(5, false), new DamageTargetEffect(5, false),
RaidCondition.getInstance(), RaidCondition.instance,
"<br/><br/><i>Raid</i> - If you attacked with a creature this turn, instead {this} deals 5 damage to that creature or player and the damage can't be prevented")); "<br/><br/><i>Raid</i> - If you attacked with a creature this turn, instead {this} deals 5 damage to that creature or player and the damage can't be prevented"));
this.getSpellAbility().addWatcher(new PlayerAttackedWatcher()); this.getSpellAbility().addWatcher(new PlayerAttackedWatcher());
} }

View file

@ -70,10 +70,10 @@ public class ArrowVolleyTrap extends CardImpl {
class ArrowVolleyTrapCondition implements Condition { class ArrowVolleyTrapCondition implements Condition {
private static final ArrowVolleyTrapCondition fInstance = new ArrowVolleyTrapCondition(); private static final ArrowVolleyTrapCondition instance = new ArrowVolleyTrapCondition();
public static Condition getInstance() { public static Condition getInstance() {
return fInstance; return instance;
} }
@Override @Override

View file

@ -28,6 +28,7 @@
package mage.cards.a; package mage.cards.a;
import java.util.UUID; import java.util.UUID;
import mage.MageInt; import mage.MageInt;
import mage.abilities.Ability; import mage.abilities.Ability;
import mage.abilities.common.AttacksTriggeredAbility; import mage.abilities.common.AttacksTriggeredAbility;
@ -47,7 +48,6 @@ import mage.target.common.TargetCreaturePermanent;
import mage.watchers.common.LifeLossOtherFromCombatWatcher; import mage.watchers.common.LifeLossOtherFromCombatWatcher;
/** /**
*
* @author Styxo * @author Styxo
*/ */
public class AsajjVentress extends CardImpl { public class AsajjVentress extends CardImpl {
@ -72,7 +72,7 @@ public class AsajjVentress extends CardImpl {
// <i>Hate</i> &mdash; Whenever Asajj Ventress attacks, if an opponent lost life from a source other than combat damage this turn, target creature blocks this turn if able. // <i>Hate</i> &mdash; Whenever Asajj Ventress attacks, if an opponent lost life from a source other than combat damage this turn, target creature blocks this turn if able.
Ability ability = new ConditionalTriggeredAbility( Ability ability = new ConditionalTriggeredAbility(
new AttacksTriggeredAbility(new BlocksIfAbleTargetEffect(Duration.EndOfTurn), false), new AttacksTriggeredAbility(new BlocksIfAbleTargetEffect(Duration.EndOfTurn), false),
HateCondition.getInstance(), HateCondition.instance,
"<i>Hate</i> &mdash; Whenever Asajj Ventress attacks, if an opponent lost life from a source other than combat damage this turn, target creature blocks this turn if able"); "<i>Hate</i> &mdash; Whenever Asajj Ventress attacks, if an opponent lost life from a source other than combat damage this turn, target creature blocks this turn if able");
ability.addTarget(new TargetCreaturePermanent()); ability.addTarget(new TargetCreaturePermanent());
this.addAbility(ability, new LifeLossOtherFromCombatWatcher()); this.addAbility(ability, new LifeLossOtherFromCombatWatcher());

View file

@ -28,6 +28,7 @@
package mage.cards.a; package mage.cards.a;
import java.util.UUID; import java.util.UUID;
import mage.abilities.Ability; import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.common.SkipUntapOptionalAbility; import mage.abilities.common.SkipUntapOptionalAbility;
@ -44,7 +45,6 @@ import mage.constants.Zone;
import mage.target.common.TargetControlledCreaturePermanent; import mage.target.common.TargetControlledCreaturePermanent;
/** /**
*
* @author LoneFox * @author LoneFox
*/ */
public class AshnodsBattleGear extends CardImpl { public class AshnodsBattleGear extends CardImpl {
@ -56,7 +56,7 @@ public class AshnodsBattleGear extends CardImpl {
this.addAbility(new SkipUntapOptionalAbility()); this.addAbility(new SkipUntapOptionalAbility());
// {2}, {tap}: Target creature you control gets +2/-2 for as long as Ashnod's Battle Gear remains tapped. // {2}, {tap}: Target creature you control gets +2/-2 for as long as Ashnod's Battle Gear remains tapped.
Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new ConditionalContinuousEffect( Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new ConditionalContinuousEffect(
new BoostTargetEffect(2, -2, Duration.Custom), SourceTappedCondition.getInstance(), new BoostTargetEffect(2, -2, Duration.Custom), SourceTappedCondition.instance,
"target creature you control gets +2/-2 for as long as {this} remains tapped"), new ManaCostsImpl("{2}")); "target creature you control gets +2/-2 for as long as {this} remains tapped"), new ManaCostsImpl("{2}"));
ability.addCost(new TapSourceCost()); ability.addCost(new TapSourceCost());
ability.addTarget(new TargetControlledCreaturePermanent()); ability.addTarget(new TargetControlledCreaturePermanent());

View file

@ -59,7 +59,7 @@ public class AtarkaBeastbreaker extends CardImpl {
Zone.BATTLEFIELD, Zone.BATTLEFIELD,
new BoostSourceEffect(4,4, Duration.EndOfTurn), new BoostSourceEffect(4,4, Duration.EndOfTurn),
new ManaCostsImpl("{4}{G}"), new ManaCostsImpl("{4}{G}"),
FormidableCondition.getInstance()); FormidableCondition.instance);
ability.setAbilityWord(AbilityWord.FORMIDABLE); ability.setAbilityWord(AbilityWord.FORMIDABLE);
this.addAbility(ability); this.addAbility(ability);
} }

View file

@ -69,7 +69,7 @@ public class AtarkaPummeler extends CardImpl {
Zone.BATTLEFIELD, Zone.BATTLEFIELD,
new GainAbilityAllEffect(new MenaceAbility(), Duration.EndOfTurn, filter), new GainAbilityAllEffect(new MenaceAbility(), Duration.EndOfTurn, filter),
new ManaCostsImpl("{3}{R}{R}"), new ManaCostsImpl("{3}{R}{R}"),
FormidableCondition.getInstance()); FormidableCondition.instance);
ability.setAbilityWord(AbilityWord.FORMIDABLE); ability.setAbilityWord(AbilityWord.FORMIDABLE);
this.addAbility(ability); this.addAbility(ability);

View file

@ -58,7 +58,7 @@ public class AuriokEdgewright extends CardImpl {
this.toughness = new MageInt(2); this.toughness = new MageInt(2);
ContinuousEffect effect = new GainAbilitySourceEffect(DoubleStrikeAbility.getInstance(), Duration.WhileOnBattlefield); ContinuousEffect effect = new GainAbilitySourceEffect(DoubleStrikeAbility.getInstance(), Duration.WhileOnBattlefield);
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new ConditionalContinuousEffect(effect, MetalcraftCondition.getInstance(), effectText))); this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new ConditionalContinuousEffect(effect, MetalcraftCondition.instance, effectText)));
} }
public AuriokEdgewright(final AuriokEdgewright card) { public AuriokEdgewright(final AuriokEdgewright card) {

View file

@ -60,9 +60,9 @@ public class AuriokSunchaser extends CardImpl {
this.toughness = new MageInt(1); this.toughness = new MageInt(1);
ContinuousEffect effect1 = new BoostSourceEffect(2, 2, Duration.WhileOnBattlefield); ContinuousEffect effect1 = new BoostSourceEffect(2, 2, Duration.WhileOnBattlefield);
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new ConditionalContinuousEffect(effect1, MetalcraftCondition.getInstance(), effect1Text))); this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new ConditionalContinuousEffect(effect1, MetalcraftCondition.instance, effect1Text)));
ContinuousEffect effect2 = new GainAbilitySourceEffect(FlyingAbility.getInstance(), Duration.WhileOnBattlefield); ContinuousEffect effect2 = new GainAbilitySourceEffect(FlyingAbility.getInstance(), Duration.WhileOnBattlefield);
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new ConditionalContinuousEffect(effect2, MetalcraftCondition.getInstance(), effect2Text))); this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new ConditionalContinuousEffect(effect2, MetalcraftCondition.instance, effect2Text)));
} }
public AuriokSunchaser(final AuriokSunchaser card) { public AuriokSunchaser(final AuriokSunchaser card) {

View file

@ -59,7 +59,7 @@ public class AutumnalGloom extends CardImpl {
// <i>Delirium</i> &mdash; At the beginning of your end step, if there are four or more card types among cards in your graveyard, transform Autumnal Gloom. // <i>Delirium</i> &mdash; At the beginning of your end step, if there are four or more card types among cards in your graveyard, transform Autumnal Gloom.
this.addAbility(new TransformAbility()); this.addAbility(new TransformAbility());
Ability ability = new BeginningOfEndStepTriggeredAbility(Zone.BATTLEFIELD, new TransformSourceEffect(true), TargetController.YOU, DeliriumCondition.getInstance(), false); Ability ability = new BeginningOfEndStepTriggeredAbility(Zone.BATTLEFIELD, new TransformSourceEffect(true), TargetController.YOU, DeliriumCondition.instance, false);
ability.setAbilityWord(AbilityWord.DELIRIUM); ability.setAbilityWord(AbilityWord.DELIRIUM);
this.addAbility(ability); this.addAbility(ability);
} }

View file

@ -56,9 +56,9 @@ public class BackwoodsSurvivalists extends CardImpl {
this.toughness = new MageInt(3); this.toughness = new MageInt(3);
// <i>Delirium</i> &mdash; Backwoods Survivalists gets +1/+1 and has trample as long as there are four or more card types among cards in your graveyard. // <i>Delirium</i> &mdash; Backwoods Survivalists gets +1/+1 and has trample as long as there are four or more card types among cards in your graveyard.
ConditionalContinuousEffect effect = new ConditionalContinuousEffect(new BoostSourceEffect(1, 1, Duration.WhileOnBattlefield), DeliriumCondition.getInstance(), "<i>Delirium</i> &mdash; {this} gets +1/+1"); ConditionalContinuousEffect effect = new ConditionalContinuousEffect(new BoostSourceEffect(1, 1, Duration.WhileOnBattlefield), DeliriumCondition.instance, "<i>Delirium</i> &mdash; {this} gets +1/+1");
Ability ability = new SimpleStaticAbility(Zone.BATTLEFIELD, effect); Ability ability = new SimpleStaticAbility(Zone.BATTLEFIELD, effect);
ability.addEffect(new ConditionalContinuousEffect(new GainAbilitySourceEffect(TrampleAbility.getInstance()), DeliriumCondition.getInstance(), "and has trample as long as there are four or more card types among cards in your graveyard.")); ability.addEffect(new ConditionalContinuousEffect(new GainAbilitySourceEffect(TrampleAbility.getInstance()), DeliriumCondition.instance, "and has trample as long as there are four or more card types among cards in your graveyard."));
this.addAbility(ability); this.addAbility(ability);
} }

View file

@ -71,10 +71,10 @@ public class BalothCageTrap extends CardImpl {
class BalothCageTrapCondition implements Condition { class BalothCageTrapCondition implements Condition {
private static final BalothCageTrapCondition fInstance = new BalothCageTrapCondition(); private static final BalothCageTrapCondition instance = new BalothCageTrapCondition();
public static Condition getInstance() { public static Condition getInstance() {
return fInstance; return instance;
} }
@Override @Override

View file

@ -64,7 +64,7 @@ public class BaneOfHanweir extends CardImpl {
// At the beginning of each upkeep, if a player cast two or more spells last turn, transform Bane of Hanweir. // At the beginning of each upkeep, if a player cast two or more spells last turn, transform Bane of Hanweir.
TriggeredAbility ability = new BeginningOfUpkeepTriggeredAbility(new TransformSourceEffect(false), TargetController.ANY, false); TriggeredAbility ability = new BeginningOfUpkeepTriggeredAbility(new TransformSourceEffect(false), TargetController.ANY, false);
this.addAbility(new ConditionalTriggeredAbility(ability, TwoOrMoreSpellsWereCastLastTurnCondition.getInstance(), TransformAbility.TWO_OR_MORE_SPELLS_TRANSFORM_RULE)); this.addAbility(new ConditionalTriggeredAbility(ability, TwoOrMoreSpellsWereCastLastTurnCondition.instance, TransformAbility.TWO_OR_MORE_SPELLS_TRANSFORM_RULE));
} }
public BaneOfHanweir(final BaneOfHanweir card) { public BaneOfHanweir(final BaneOfHanweir card) {

View file

@ -64,7 +64,7 @@ public class BarrageOfBoulders extends CardImpl {
Effect effect = new ConditionalRestrictionEffect( Effect effect = new ConditionalRestrictionEffect(
Duration.EndOfTurn, Duration.EndOfTurn,
new CantBlockAllEffect(new FilterCreaturePermanent("creatures"), Duration.EndOfTurn), new CantBlockAllEffect(new FilterCreaturePermanent("creatures"), Duration.EndOfTurn),
new LockedInCondition(FerociousCondition.getInstance()), null); new LockedInCondition(FerociousCondition.instance), null);
effect.setText("<br/><i>Ferocious</i> &mdash; If you control a creature with power 4 or greater, creatures can't block this turn"); effect.setText("<br/><i>Ferocious</i> &mdash; If you control a creature with power 4 or greater, creatures can't block this turn");
this.getSpellAbility().addEffect(effect); this.getSpellAbility().addEffect(effect);
} }

View file

@ -49,7 +49,7 @@ public class BatheInBacta extends CardImpl {
// You gain 6 life. If you lost life from a source other than combat damage this turn, you gain 9 life instead. // You gain 6 life. If you lost life from a source other than combat damage this turn, you gain 9 life instead.
this.getSpellAbility().addEffect(new ConditionalOneShotEffect( this.getSpellAbility().addEffect(new ConditionalOneShotEffect(
new GainLifeEffect(6), new GainLifeEffect(9), new GainLifeEffect(6), new GainLifeEffect(9),
new InvertCondition(HateCondition.getInstance()), new InvertCondition(HateCondition.instance),
"You gain 6 life. If you lost life from a source other than combat damage this turn, you gain 9 life instead")); "You gain 6 life. If you lost life from a source other than combat damage this turn, you gain 9 life instead"));
this.getSpellAbility().addWatcher(new LifeLossOtherFromCombatWatcher()); this.getSpellAbility().addWatcher(new LifeLossOtherFromCombatWatcher());
} }

View file

@ -56,7 +56,7 @@ public class BellowingSaddlebrute extends CardImpl {
// Raid - When Bellowing Saddlebrute enters the battlefield, you lose 4 life unless you attacked with a creature this turn // Raid - When Bellowing Saddlebrute enters the battlefield, you lose 4 life unless you attacked with a creature this turn
this.addAbility(new ConditionalTriggeredAbility( this.addAbility(new ConditionalTriggeredAbility(
new EntersBattlefieldTriggeredAbility(new LoseLifeSourceControllerEffect(4)), new EntersBattlefieldTriggeredAbility(new LoseLifeSourceControllerEffect(4)),
new InvertCondition(RaidCondition.getInstance()), new InvertCondition(RaidCondition.instance),
"<i>Raid</i> - When {this} enters the battlefield, you lose 4 life unless you attacked with a creature this turn" "<i>Raid</i> - When {this} enters the battlefield, you lose 4 life unless you attacked with a creature this turn"
), new PlayerAttackedWatcher()); ), new PlayerAttackedWatcher());
} }

View file

@ -59,7 +59,7 @@ public class BenalishEmissary extends CardImpl {
// When Benalish Emissary enters the battlefield, if it was kicked, destroy target land. // When Benalish Emissary enters the battlefield, if it was kicked, destroy target land.
TriggeredAbility ability = new EntersBattlefieldTriggeredAbility(new DestroyTargetEffect()); TriggeredAbility ability = new EntersBattlefieldTriggeredAbility(new DestroyTargetEffect());
ability.addTarget(new TargetLandPermanent()); ability.addTarget(new TargetLandPermanent());
this.addAbility(new ConditionalTriggeredAbility(ability, KickedCondition.getInstance(), this.addAbility(new ConditionalTriggeredAbility(ability, KickedCondition.instance,
"When {this} enters the battlefield, if it was kicked, destroy target land.")); "When {this} enters the battlefield, if it was kicked, destroy target land."));
} }

View file

@ -60,7 +60,7 @@ public class BenalishLancer extends CardImpl {
// If Benalish Lancer was kicked, it enters the battlefield with two +1/+1 counters on it and with first strike. // If Benalish Lancer was kicked, it enters the battlefield with two +1/+1 counters on it and with first strike.
Ability ability = new EntersBattlefieldAbility(new AddCountersSourceEffect(CounterType.P1P1.createInstance(2)), Ability ability = new EntersBattlefieldAbility(new AddCountersSourceEffect(CounterType.P1P1.createInstance(2)),
KickedCondition.getInstance(), KickedCondition.instance,
"If {this} was kicked, it enters the battlefield with two +1/+1 counters on it and with first strike.", ""); "If {this} was kicked, it enters the battlefield with two +1/+1 counters on it and with first strike.", "");
ability.addEffect(new GainAbilitySourceEffect(FirstStrikeAbility.getInstance(), Duration.WhileOnBattlefield)); ability.addEffect(new GainAbilitySourceEffect(FirstStrikeAbility.getInstance(), Duration.WhileOnBattlefield));
this.addAbility(ability); this.addAbility(ability);

View file

@ -59,7 +59,7 @@ public class BladeTribeBerserkers extends CardImpl {
TriggeredAbility ability = new EntersBattlefieldTriggeredAbility(new BoostSourceEffect(3, 3, Duration.EndOfTurn), false); TriggeredAbility ability = new EntersBattlefieldTriggeredAbility(new BoostSourceEffect(3, 3, Duration.EndOfTurn), false);
ability.addEffect(new GainAbilitySourceEffect(HasteAbility.getInstance(), Duration.EndOfTurn)); ability.addEffect(new GainAbilitySourceEffect(HasteAbility.getInstance(), Duration.EndOfTurn));
this.addAbility(new ConditionalTriggeredAbility(ability, MetalcraftCondition.getInstance(), effectText)); this.addAbility(new ConditionalTriggeredAbility(ability, MetalcraftCondition.instance, effectText));
} }
public BladeTribeBerserkers(final BladeTribeBerserkers card) { public BladeTribeBerserkers(final BladeTribeBerserkers card) {

View file

@ -62,7 +62,7 @@ public class BleakCovenVampires extends CardImpl {
Target target = new TargetPlayer(); Target target = new TargetPlayer();
ability.addTarget(target); ability.addTarget(target);
this.addAbility(new ConditionalTriggeredAbility(ability, MetalcraftCondition.getInstance(), effectText)); this.addAbility(new ConditionalTriggeredAbility(ability, MetalcraftCondition.instance, effectText));
} }
public BleakCovenVampires(final BleakCovenVampires card) { public BleakCovenVampires(final BleakCovenVampires card) {

View file

@ -105,10 +105,10 @@ class TargetMatchesFilterCondition implements Condition {
class TargetPermanentToughnessMinus1Value implements DynamicValue { class TargetPermanentToughnessMinus1Value implements DynamicValue {
private static final TargetPermanentToughnessMinus1Value fINSTANCE = new TargetPermanentToughnessMinus1Value(); private static final TargetPermanentToughnessMinus1Value instance = new TargetPermanentToughnessMinus1Value();
public static TargetPermanentToughnessMinus1Value getInstance() { public static TargetPermanentToughnessMinus1Value getInstance() {
return fINSTANCE; return instance;
} }
@Override @Override

View file

@ -74,7 +74,7 @@ public class BloodTribute extends CardImpl {
// If Blood Tribute was kicked, you gain life equal to the life lost this way. // If Blood Tribute was kicked, you gain life equal to the life lost this way.
Effect effect = new ConditionalOneShotEffect( Effect effect = new ConditionalOneShotEffect(
new BloodTributeGainLifeEffect(), new BloodTributeGainLifeEffect(),
KickedCondition.getInstance(), KickedCondition.instance,
"If {this} was kicked, you gain life equal to the life lost this way"); "If {this} was kicked, you gain life equal to the life lost this way");
this.getSpellAbility().addEffect(effect); this.getSpellAbility().addEffect(effect);
} }

View file

@ -59,7 +59,7 @@ public class BloodhallPriest extends CardImpl {
triggeredAbility.addTarget(new TargetCreatureOrPlayer()); triggeredAbility.addTarget(new TargetCreatureOrPlayer());
this.addAbility(new ConditionalTriggeredAbility( this.addAbility(new ConditionalTriggeredAbility(
triggeredAbility, triggeredAbility,
HellbentCondition.getInstance(), HellbentCondition.instance,
"Whenever {this} enters the battlefield or attacks, if you have no cards in hand, {this} deals 2 damage to target creature or player" "Whenever {this} enters the battlefield or attacks, if you have no cards in hand, {this} deals 2 damage to target creature or player"
)); ));

View file

@ -63,7 +63,7 @@ public class BloodsoakedChampion extends CardImpl {
Zone.GRAVEYARD, Zone.GRAVEYARD,
new ReturnSourceFromGraveyardToBattlefieldEffect(), new ReturnSourceFromGraveyardToBattlefieldEffect(),
new ManaCostsImpl<>("{1}{B}"), new ManaCostsImpl<>("{1}{B}"),
RaidCondition.getInstance(), RaidCondition.instance,
"<i>Raid</i> - {1}{B}: Return {this} from your graveyard to the battlefield. Activate this ability only if you attacked with a creature this turn"); "<i>Raid</i> - {1}{B}: Return {this} from your graveyard to the battlefield. Activate this ability only if you attacked with a creature this turn");
this.addAbility(ability, new PlayerAttackedWatcher()); this.addAbility(ability, new PlayerAttackedWatcher());
} }

View file

@ -54,7 +54,7 @@ public class BogDown extends CardImpl {
this.addAbility(new KickerAbility(new SacrificeTargetCost(new TargetControlledPermanent(2, 2, new FilterControlledLandPermanent("two lands"), true)))); this.addAbility(new KickerAbility(new SacrificeTargetCost(new TargetControlledPermanent(2, 2, new FilterControlledLandPermanent("two lands"), true))));
// Target player discards two cards. If Bog Down was kicked, that player discards three cards instead. // Target player discards two cards. If Bog Down was kicked, that player discards three cards instead.
this.getSpellAbility().addEffect(new ConditionalOneShotEffect(new DiscardTargetEffect(3), this.getSpellAbility().addEffect(new ConditionalOneShotEffect(new DiscardTargetEffect(3),
new DiscardTargetEffect(2), KickedCondition.getInstance(), new DiscardTargetEffect(2), KickedCondition.instance,
"Target player discards two cards. If {this} was kicked, that player discards three cards instead.")); "Target player discards two cards. If {this} was kicked, that player discards three cards instead."));
this.getSpellAbility().addTarget(new TargetPlayer()); this.getSpellAbility().addTarget(new TargetPlayer());
} }

View file

@ -55,10 +55,10 @@ public class BoldDefense extends CardImpl {
// Creatures you control get +1/+1 until end of turn. If Bold Defense was kicked, instead creatures you control get +2/+2 and gain first strike until end of turn. // Creatures you control get +1/+1 until end of turn. If Bold Defense was kicked, instead creatures you control get +2/+2 and gain first strike until end of turn.
this.getSpellAbility().addEffect(new ConditionalContinuousEffect(new BoostControlledEffect(2, 2, Duration.EndOfTurn), this.getSpellAbility().addEffect(new ConditionalContinuousEffect(new BoostControlledEffect(2, 2, Duration.EndOfTurn),
new BoostTargetEffect(1, 1, Duration.EndOfTurn), new LockedInCondition(KickedCondition.getInstance()), new BoostTargetEffect(1, 1, Duration.EndOfTurn), new LockedInCondition(KickedCondition.instance),
"Creatures you control get +1/+1 until end of turn. If {this} was kicked, instead creatures you control get +2/+2")); "Creatures you control get +1/+1 until end of turn. If {this} was kicked, instead creatures you control get +2/+2"));
this.getSpellAbility().addEffect(new ConditionalContinuousEffect(new GainAbilityControlledEffect(FirstStrikeAbility.getInstance(), Duration.EndOfTurn, new FilterCreaturePermanent(), false), this.getSpellAbility().addEffect(new ConditionalContinuousEffect(new GainAbilityControlledEffect(FirstStrikeAbility.getInstance(), Duration.EndOfTurn, new FilterCreaturePermanent(), false),
null, new LockedInCondition(KickedCondition.getInstance()), null, new LockedInCondition(KickedCondition.instance),
"and gain first strike until end of turn")); "and gain first strike until end of turn"));
} }

View file

@ -65,7 +65,7 @@ public class BottomlessVault extends CardImpl {
this.addAbility(new SkipUntapOptionalAbility()); this.addAbility(new SkipUntapOptionalAbility());
// At the beginning of your upkeep, if Bottomless Vault is tapped, put a storage counter on it. // At the beginning of your upkeep, if Bottomless Vault is tapped, put a storage counter on it.
OneShotEffect addStorageCounter = new AddCountersSourceEffect(CounterType.STORAGE.createInstance()); OneShotEffect addStorageCounter = new AddCountersSourceEffect(CounterType.STORAGE.createInstance());
Effect effect = new ConditionalOneShotEffect(addStorageCounter, SourceTappedCondition.getInstance(), "if {this} is tapped, put a storage counter on it"); Effect effect = new ConditionalOneShotEffect(addStorageCounter, SourceTappedCondition.instance, "if {this} is tapped, put a storage counter on it");
this.addAbility(new BeginningOfUpkeepTriggeredAbility(Zone.BATTLEFIELD, effect, TargetController.YOU, false)); this.addAbility(new BeginningOfUpkeepTriggeredAbility(Zone.BATTLEFIELD, effect, TargetController.YOU, false));
// {tap}, Remove any number of storage counters from Bottomless Vault: Add {B} to your mana pool for each storage counter removed this way. // {tap}, Remove any number of storage counters from Bottomless Vault: Add {B} to your mana pool for each storage counter removed this way.
Ability ability = new DynamicManaAbility( Ability ability = new DynamicManaAbility(

View file

@ -59,7 +59,7 @@ public class BrandedHowler extends CardImpl {
// At the beginning of each upkeep, if a player cast two or more spells last turn, transform Branded Howler. // At the beginning of each upkeep, if a player cast two or more spells last turn, transform Branded Howler.
TriggeredAbility ability = new BeginningOfUpkeepTriggeredAbility(new TransformSourceEffect(false), TargetController.ANY, false); TriggeredAbility ability = new BeginningOfUpkeepTriggeredAbility(new TransformSourceEffect(false), TargetController.ANY, false);
this.addAbility(new ConditionalTriggeredAbility(ability, TwoOrMoreSpellsWereCastLastTurnCondition.getInstance(), TransformAbility.TWO_OR_MORE_SPELLS_TRANSFORM_RULE)); this.addAbility(new ConditionalTriggeredAbility(ability, TwoOrMoreSpellsWereCastLastTurnCondition.instance, TransformAbility.TWO_OR_MORE_SPELLS_TRANSFORM_RULE));
} }
public BrandedHowler(final BrandedHowler card) { public BrandedHowler(final BrandedHowler card) {

View file

@ -56,7 +56,7 @@ public class BreakOfDay extends CardImpl {
// Fateful hour - If you have 5 or less life, those creatures also are indestructible this turn. // Fateful hour - If you have 5 or less life, those creatures also are indestructible this turn.
this.getSpellAbility().addEffect(new ConditionalContinuousEffect( this.getSpellAbility().addEffect(new ConditionalContinuousEffect(
new GainAbilityAllEffect(IndestructibleAbility.getInstance(), Duration.EndOfTurn, new FilterControlledCreaturePermanent("creatures you control"), false), new GainAbilityAllEffect(IndestructibleAbility.getInstance(), Duration.EndOfTurn, new FilterControlledCreaturePermanent("creatures you control"), false),
new LockedInCondition(FatefulHourCondition.getInstance()), new LockedInCondition(FatefulHourCondition.instance),
"If you have 5 or less life, those creatures also are indestructible this turn")); "If you have 5 or less life, those creatures also are indestructible this turn"));
} }

View file

@ -61,7 +61,7 @@ public class BreakneckRider extends CardImpl {
// At the beginning of each upkeep, if no spells were cast last turn, transform Breakneck Rider. // At the beginning of each upkeep, if no spells were cast last turn, transform Breakneck Rider.
this.addAbility(new TransformAbility()); this.addAbility(new TransformAbility());
TriggeredAbility ability = new BeginningOfUpkeepTriggeredAbility(new TransformSourceEffect(true), TargetController.ANY, false); TriggeredAbility ability = new BeginningOfUpkeepTriggeredAbility(new TransformSourceEffect(true), TargetController.ANY, false);
this.addAbility(new ConditionalTriggeredAbility(ability, NoSpellsWereCastLastTurnCondition.getInstance(), TransformAbility.NO_SPELLS_TRANSFORM_RULE)); this.addAbility(new ConditionalTriggeredAbility(ability, NoSpellsWereCastLastTurnCondition.instance, TransformAbility.NO_SPELLS_TRANSFORM_RULE));
} }
public BreakneckRider(final BreakneckRider card) { public BreakneckRider(final BreakneckRider card) {

View file

@ -60,7 +60,7 @@ public class BreathOfDarigaaz extends CardImpl {
// Breath of Darigaaz deals 1 damage to each creature without flying and each player. If Breath of Darigaaz was kicked, it deals 4 damage to each creature without flying and each player instead. // Breath of Darigaaz deals 1 damage to each creature without flying and each player. If Breath of Darigaaz was kicked, it deals 4 damage to each creature without flying and each player instead.
this.getSpellAbility().addEffect(new ConditionalOneShotEffect(new DamageEverythingEffect(4, filter), this.getSpellAbility().addEffect(new ConditionalOneShotEffect(new DamageEverythingEffect(4, filter),
new DamageEverythingEffect(1, filter), KickedCondition.getInstance(), new DamageEverythingEffect(1, filter), KickedCondition.instance,
"{this} deals 1 damage to each creature without flying and each player. If {this} was kicked, it deals 4 damage to each creature without flying and each player instead.")); "{this} deals 1 damage to each creature without flying and each player. If {this} was kicked, it deals 4 damage to each creature without flying and each player instead."));
} }

View file

@ -79,10 +79,10 @@ public class BriarbridgePatrol extends CardImpl {
class BriarbridgePatrolCondition implements Condition { class BriarbridgePatrolCondition implements Condition {
private static final BriarbridgePatrolCondition fInstance = new BriarbridgePatrolCondition(); private static final BriarbridgePatrolCondition instance = new BriarbridgePatrolCondition();
public static Condition getInstance() { public static Condition getInstance() {
return fInstance; return instance;
} }
@Override @Override

View file

@ -59,7 +59,7 @@ public class BullRancor extends CardImpl {
// As long as Bull Rancor is monstrous, creatures you control have menace. // As long as Bull Rancor is monstrous, creatures you control have menace.
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new ConditionalContinuousEffect( this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new ConditionalContinuousEffect(
new GainAbilityControlledEffect(new MenaceAbility(), Duration.WhileOnBattlefield), new GainAbilityControlledEffect(new MenaceAbility(), Duration.WhileOnBattlefield),
MonstrousCondition.getInstance(), MonstrousCondition.instance,
"As long as Bull Rancor is monstrous, creatures you control have menace") "As long as Bull Rancor is monstrous, creatures you control have menace")
)); ));
} }

View file

@ -54,7 +54,7 @@ public class BurstLightning extends CardImpl {
// Burst Lightning deals 2 damage to target creature or player. If Burst Lightning was kicked, it deals 4 damage to that creature or player instead. // Burst Lightning deals 2 damage to target creature or player. If Burst Lightning was kicked, it deals 4 damage to that creature or player instead.
this.getSpellAbility().addTarget(new TargetCreatureOrPlayer()); this.getSpellAbility().addTarget(new TargetCreatureOrPlayer());
this.getSpellAbility().addEffect(new ConditionalOneShotEffect(new DamageTargetEffect(4), this.getSpellAbility().addEffect(new ConditionalOneShotEffect(new DamageTargetEffect(4),
new DamageTargetEffect(2), KickedCondition.getInstance(), "{this} deals 2 damage to target creature or player. If {this} was kicked, it deals 4 damage to that creature or player instead")); new DamageTargetEffect(2), KickedCondition.instance, "{this} deals 2 damage to target creature or player. If {this} was kicked, it deals 4 damage to that creature or player instead"));
} }
public BurstLightning(final BurstLightning card) { public BurstLightning(final BurstLightning card) {

View file

@ -51,12 +51,12 @@ public class CacklingFlames extends CardImpl {
// Cackling Flames deals 3 damage to target creature or player. // Cackling Flames deals 3 damage to target creature or player.
this.getSpellAbility().addEffect(new ConditionalOneShotEffect( this.getSpellAbility().addEffect(new ConditionalOneShotEffect(
new DamageTargetEffect(3), new DamageTargetEffect(3),
new InvertCondition(HellbentCondition.getInstance()), new InvertCondition(HellbentCondition.instance),
"{this} deals 3 damage to target creature or player")); "{this} deals 3 damage to target creature or player"));
// Hellbent - Cackling Flames deals 5 damage to that creature or player instead if you have no cards in hand. // Hellbent - Cackling Flames deals 5 damage to that creature or player instead if you have no cards in hand.
this.getSpellAbility().addEffect(new ConditionalOneShotEffect( this.getSpellAbility().addEffect(new ConditionalOneShotEffect(
new DamageTargetEffect(5), new DamageTargetEffect(5),
HellbentCondition.getInstance(), HellbentCondition.instance,
"<br/><br/><i>Hellbent</i> - {this} deals 5 damage to that creature or player instead if you have no cards in hand.")); "<br/><br/><i>Hellbent</i> - {this} deals 5 damage to that creature or player instead if you have no cards in hand."));
this.getSpellAbility().addTarget(new TargetCreatureOrPlayer()); this.getSpellAbility().addTarget(new TargetCreatureOrPlayer());

View file

@ -51,7 +51,7 @@ public class CalculatedDismissal extends CardImpl {
this.getSpellAbility().addTarget(new TargetSpell()); this.getSpellAbility().addTarget(new TargetSpell());
this.getSpellAbility().addEffect(new CounterUnlessPaysEffect(new GenericManaCost(3))); this.getSpellAbility().addEffect(new CounterUnlessPaysEffect(new GenericManaCost(3)));
// <i>Spell mastery</i> &mdash; If there are two or more instant and/or sorcery cards in your graveyard, scry 2. // <i>Spell mastery</i> &mdash; If there are two or more instant and/or sorcery cards in your graveyard, scry 2.
this.getSpellAbility().addEffect(new ConditionalOneShotEffect(new ScryEffect(2), SpellMasteryCondition.getInstance(), this.getSpellAbility().addEffect(new ConditionalOneShotEffect(new ScryEffect(2), SpellMasteryCondition.instance,
"<br><i>Spell mastery</i> &mdash; If there are two or more instant and/or sorcery cards in your graveyard, scry 2")); "<br><i>Spell mastery</i> &mdash; If there are two or more instant and/or sorcery cards in your graveyard, scry 2"));
} }

View file

@ -60,7 +60,7 @@ public class CallForUnity extends CardImpl {
// <i>Revolt</i> &mdash; At the beginning of your end step, if a permanent you controlled left the battlefield this turn, put a unity counter on Call for Unity. // <i>Revolt</i> &mdash; At the beginning of your end step, if a permanent you controlled left the battlefield this turn, put a unity counter on Call for Unity.
TriggeredAbility ability = new BeginningOfYourEndStepTriggeredAbility(new AddCountersSourceEffect(CounterType.UNITY.createInstance(), true), false); TriggeredAbility ability = new BeginningOfYourEndStepTriggeredAbility(new AddCountersSourceEffect(CounterType.UNITY.createInstance(), true), false);
this.addAbility(new ConditionalTriggeredAbility(ability, RevoltCondition.getInstance(), ruleText), new RevoltWatcher()); this.addAbility(new ConditionalTriggeredAbility(ability, RevoltCondition.instance, ruleText), new RevoltWatcher());
// Creatures you control get +1/+1 for each unity counter on Call for Unity. // Creatures you control get +1/+1 for each unity counter on Call for Unity.
Effect effect = new BoostControlledEffect(new CountersSourceCount(CounterType.UNITY), new CountersSourceCount(CounterType.UNITY), Duration.WhileOnBattlefield, Effect effect = new BoostControlledEffect(new CountersSourceCount(CounterType.UNITY), new CountersSourceCount(CounterType.UNITY), Duration.WhileOnBattlefield,

View file

@ -78,7 +78,7 @@ public class CallOfTheFullMoon extends CardImpl {
// At the beginning of each upkeep, if a player cast two or more spells last turn, sacrifice Call of the Full Moon. // At the beginning of each upkeep, if a player cast two or more spells last turn, sacrifice Call of the Full Moon.
TriggeredAbility ability2 = new BeginningOfUpkeepTriggeredAbility(new SacrificeSourceEffect(), TargetController.ANY, false); TriggeredAbility ability2 = new BeginningOfUpkeepTriggeredAbility(new SacrificeSourceEffect(), TargetController.ANY, false);
this.addAbility(new ConditionalTriggeredAbility(ability2, TwoOrMoreSpellsWereCastLastTurnCondition.getInstance(), this.addAbility(new ConditionalTriggeredAbility(ability2, TwoOrMoreSpellsWereCastLastTurnCondition.instance,
"At the beginning of each upkeep, if a player cast two or more spells last turn, sacrifice {this}.")); "At the beginning of each upkeep, if a player cast two or more spells last turn, sacrifice {this}."));
} }

View file

@ -58,7 +58,7 @@ public class CanopySurge extends CardImpl {
this.addAbility(new KickerAbility("{2}")); this.addAbility(new KickerAbility("{2}"));
// Canopy Surge deals 1 damage to each creature with flying and each player. If Canopy Surge was kicked, it deals 4 damage to each creature with flying and each player instead. // Canopy Surge deals 1 damage to each creature with flying and each player. If Canopy Surge was kicked, it deals 4 damage to each creature with flying and each player instead.
this.getSpellAbility().addEffect(new ConditionalOneShotEffect(new DamageEverythingEffect(4, filter), this.getSpellAbility().addEffect(new ConditionalOneShotEffect(new DamageEverythingEffect(4, filter),
new DamageEverythingEffect(1, filter), KickedCondition.getInstance(), new DamageEverythingEffect(1, filter), KickedCondition.instance,
"{this} deals 1 damage to each creature with flying and each player. If {this} was kicked, it deals 4 damage to each creature with flying and each player instead.")); "{this} deals 1 damage to each creature with flying and each player. If {this} was kicked, it deals 4 damage to each creature with flying and each player instead."));
} }

Some files were not shown because too many files have changed in this diff Show more