Introducing Optionals

This commit is contained in:
igoudt 2017-01-14 21:52:40 +01:00
parent 97261fdcca
commit f98afdf4ad
21 changed files with 407 additions and 483 deletions

View file

@ -27,23 +27,20 @@
*/ */
package mage.server; package mage.server;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import mage.cards.repository.CardInfo; import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository; import mage.cards.repository.CardRepository;
import mage.server.exceptions.UserNotFoundException;
import mage.server.util.SystemUtil; import mage.server.util.SystemUtil;
import mage.view.ChatMessage.MessageColor; import mage.view.ChatMessage.MessageColor;
import mage.view.ChatMessage.MessageType; import mage.view.ChatMessage.MessageType;
import mage.view.ChatMessage.SoundToPlay; import mage.view.ChatMessage.SoundToPlay;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
@ -256,26 +253,24 @@ public class ChatManager {
* @param message * @param message
* @param color * @param color
*/ */
public void broadcast(UUID userId, String message, MessageColor color) { public void broadcast(UUID userId, String message, MessageColor color) throws UserNotFoundException {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user-> {
if (user != null) {
for (ChatSession chat : chatSessions.values()) { chatSessions.values()
if (chat.hasUser(userId)) { .stream()
chat.broadcast(user.getName(), message, color, true, MessageType.TALK, null); .filter(chat -> chat.hasUser(userId))
} .forEach(session -> session.broadcast(user.getName(), message, color, true, MessageType.TALK, null));
}
} });
} }
public void sendReconnectMessage(UUID userId) { public void sendReconnectMessage(UUID userId) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user ->
if (user != null) { chatSessions.values()
for (ChatSession chat : chatSessions.values()) { .stream()
if (chat.hasUser(userId)) { .filter(chat -> chat.hasUser(userId))
chat.broadcast(null, user.getName() + " has reconnected", MessageColor.BLUE, true, MessageType.STATUS, null); .forEach(chatSession -> chatSession.broadcast(null, user.getName() + " has reconnected", MessageColor.BLUE, true, MessageType.STATUS, null)));
}
}
}
} }
public void removeUser(UUID userId, DisconnectReason reason) { public void removeUser(UUID userId, DisconnectReason reason) {
@ -291,4 +286,7 @@ public class ChatManager {
chatSessionList.addAll(chatSessions.values()); chatSessionList.addAll(chatSessions.values());
return chatSessionList; return chatSessionList;
} }
} }

View file

@ -28,6 +28,7 @@
package mage.server; package mage.server;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
import mage.server.exceptions.UserNotFoundException;
import mage.view.ChatMessage; import mage.view.ChatMessage;
import mage.view.ChatMessage.MessageColor; import mage.view.ChatMessage.MessageColor;
import mage.view.ChatMessage.MessageType; import mage.view.ChatMessage.MessageType;
@ -38,6 +39,7 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.HashSet; import java.util.HashSet;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -61,13 +63,14 @@ public class ChatSession {
} }
public void join(UUID userId) { public void join(UUID userId) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user-> {
if (user != null && !clients.containsKey(userId)) { if (!clients.containsKey(userId)) {
String userName = user.getName(); String userName = user.getName();
clients.put(userId, userName); clients.put(userId, userName);
broadcast(null, userName + " has joined (" + user.getClientVersion() + ")", MessageColor.BLUE, true, MessageType.STATUS, null); broadcast(null, userName + " has joined (" + user.getClientVersion() + ")", MessageColor.BLUE, true, MessageType.STATUS, null);
logger.trace(userName + " joined chat " + chatId); logger.trace(userName + " joined chat " + chatId);
} }
});
} }
public void kill(UUID userId, DisconnectReason reason) { public void kill(UUID userId, DisconnectReason reason) {
@ -141,9 +144,9 @@ 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()) {
User user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.getInstance().getUser(userId);
if (user != null) { if (user.isPresent()) {
user.fireCallback(clientCallback); user.get().fireCallback(clientCallback);
} else { } else {
if (clientsToRemove == null) { if (clientsToRemove == null) {
clientsToRemove = new HashSet<>(); clientsToRemove = new HashSet<>();

View file

@ -27,18 +27,6 @@
*/ */
package mage.server; package mage.server;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import javax.management.timer.Timer;
import mage.MageException; import mage.MageException;
import mage.cards.decks.DeckCardLists; import mage.cards.decks.DeckCardLists;
import mage.cards.repository.CardInfo; import mage.cards.repository.CardInfo;
@ -61,13 +49,7 @@ import mage.players.net.UserData;
import mage.remote.MageVersionException; import mage.remote.MageVersionException;
import mage.server.draft.CubeFactory; import mage.server.draft.CubeFactory;
import mage.server.draft.DraftManager; import mage.server.draft.DraftManager;
import mage.server.game.DeckValidatorFactory; import mage.server.game.*;
import mage.server.game.GameFactory;
import mage.server.game.GameManager;
import mage.server.game.GamesRoom;
import mage.server.game.GamesRoomManager;
import mage.server.game.PlayerFactory;
import mage.server.game.ReplayManager;
import mage.server.services.impl.FeedbackServiceImpl; import mage.server.services.impl.FeedbackServiceImpl;
import mage.server.tournament.TournamentFactory; import mage.server.tournament.TournamentFactory;
import mage.server.tournament.TournamentManager; import mage.server.tournament.TournamentManager;
@ -75,25 +57,18 @@ import mage.server.util.ConfigSettings;
import mage.server.util.ServerMessagesUtil; import mage.server.util.ServerMessagesUtil;
import mage.server.util.SystemUtil; import mage.server.util.SystemUtil;
import mage.server.util.ThreadExecutor; import mage.server.util.ThreadExecutor;
import mage.utils.ActionWithBooleanResult; import mage.utils.*;
import mage.utils.ActionWithNullNegativeResult; import mage.view.*;
import mage.utils.ActionWithTableViewResult;
import mage.utils.CompressUtil;
import mage.utils.MageVersion;
import mage.view.ChatMessage;
import mage.view.ChatMessage.MessageColor; import mage.view.ChatMessage.MessageColor;
import mage.view.DraftPickView;
import mage.view.GameView;
import mage.view.MatchView;
import mage.view.RoomUsersView;
import mage.view.TableView;
import mage.view.TournamentView;
import mage.view.UserView;
import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import javax.management.timer.Timer;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.ExecutorService;
/** /**
*
* @author BetaSteward_at_googlemail.com, noxx * @author BetaSteward_at_googlemail.com, noxx
*/ */
public class MageServerImpl implements MageServer { public class MageServerImpl implements MageServer {
@ -231,11 +206,12 @@ 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.getInstance().getSession(sessionId).getUserId();
User user = UserManager.getInstance().getUser(userId); Optional<User> _user = UserManager.getInstance().getUser(userId);
if (user == null) { 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;
} }
User user = _user.get();
// check if user can create another table // check if user can create another table
int notStartedTables = user.getNumberOfNotStartedTables(); int notStartedTables = user.getNumberOfNotStartedTables();
if (notStartedTables > 1) { if (notStartedTables > 1) {
@ -267,11 +243,12 @@ public class MageServerImpl implements MageServer {
public TableView execute() throws MageException { public TableView execute() throws MageException {
try { try {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
User user = UserManager.getInstance().getUser(userId); Optional<User> _user = UserManager.getInstance().getUser(userId);
if (user == null) { 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;
} }
User user = _user.get();
// check if user can create another table // check if user can create another table
int notStartedTables = user.getNumberOfNotStartedTables(); int notStartedTables = user.getNumberOfNotStartedTables();
if (notStartedTables > 1) { if (notStartedTables > 1) {
@ -331,8 +308,8 @@ public class MageServerImpl implements MageServer {
logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId);
return false; return false;
} }
boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList, password); return GamesRoomManager.getInstance().getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList, password);
return ret;
} }
}); });
} }
@ -344,8 +321,8 @@ public class MageServerImpl implements MageServer {
public Boolean execute() throws MageException { public Boolean execute() throws MageException {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId(); UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
User user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.getInstance().getUser(userId);
if (user != null) { if (user.isPresent()) {
logger.trace("join tourn. tableId: " + tableId + " " + name); logger.trace("join tourn. tableId: " + tableId + " " + name);
} }
} }
@ -353,8 +330,8 @@ public class MageServerImpl implements MageServer {
logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId); logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId);
return false; return false;
} }
boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill, deckList, password); return GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill, deckList, password);
return ret;
} }
}); });
} }
@ -449,7 +426,7 @@ public class MageServerImpl implements MageServer {
return SessionManager.getInstance().extendUserSession(sessionId, pingInfo); return SessionManager.getInstance().extendUserSession(sessionId, pingInfo);
} }
// @Override // @Override
// public void deregisterClient(final String sessionId) throws MageException { // public void deregisterClient(final String sessionId) throws MageException {
// execute("deregisterClient", sessionId, new Action() { // execute("deregisterClient", sessionId, new Action() {
// @Override // @Override
@ -471,7 +448,7 @@ public class MageServerImpl implements MageServer {
return true; return true;
} }
// @Override // @Override
// public void startChallenge(final String sessionId, final UUID roomId, final UUID tableId, final UUID challengeId) throws MageException { // public void startChallenge(final String sessionId, final UUID roomId, final UUID tableId, final UUID challengeId) throws MageException {
// execute("startChallenge", sessionId, new Action() { // execute("startChallenge", sessionId, new Action() {
// @Override // @Override
@ -580,7 +557,7 @@ public class MageServerImpl implements MageServer {
@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.getInstance().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;
} }
@ -651,10 +628,10 @@ 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, () -> {
User user = SessionManager.getInstance().getUser(sessionId); Optional<User> user = SessionManager.getInstance().getUser(sessionId);
if (user != null) { if (user.isPresent()) {
// logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName()); // logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName());
user.sendPlayerUUID(gameId, data); user.get().sendPlayerUUID(gameId, data);
} else { } else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} }
@ -664,9 +641,9 @@ 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, () -> {
User user = SessionManager.getInstance().getUser(sessionId); Optional<User> user = SessionManager.getInstance().getUser(sessionId);
if (user != null) { if (user.isPresent()) {
user.sendPlayerString(gameId, data); user.get().sendPlayerString(gameId, data);
} else { } else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} }
@ -676,9 +653,9 @@ 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, () -> {
User user = SessionManager.getInstance().getUser(sessionId); Optional<User> user = SessionManager.getInstance().getUser(sessionId);
if (user != null) { if (user.isPresent()) {
user.sendPlayerManaType(gameId, playerId, data); user.get().sendPlayerManaType(gameId, playerId, data);
} else { } else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} }
@ -688,9 +665,9 @@ 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, () -> {
User user = SessionManager.getInstance().getUser(sessionId); Optional<User> user = SessionManager.getInstance().getUser(sessionId);
if (user != null) { if (user.isPresent()) {
user.sendPlayerBoolean(gameId, data); user.get().sendPlayerBoolean(gameId, data);
} else { } else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} }
@ -700,9 +677,9 @@ 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, () -> {
User user = SessionManager.getInstance().getUser(sessionId); Optional<User> user = SessionManager.getInstance().getUser(sessionId);
if (user != null) { if (user.isPresent()) {
user.sendPlayerInteger(gameId, data); user.get().sendPlayerInteger(gameId, data);
} else { } else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId); logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
} }
@ -824,11 +801,10 @@ public class MageServerImpl implements MageServer {
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.getInstance().getSession(sessionId).getUserId();
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> {
if (user != null) {
GameManager.getInstance().stopWatching(gameId, userId); GameManager.getInstance().stopWatching(gameId, userId);
user.removeGameWatchInfo(gameId); user.removeGameWatchInfo(gameId);
} });
}); });
} }

View file

@ -27,16 +27,6 @@
*/ */
package mage.server; package mage.server;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.MBeanServer;
import mage.cards.ExpansionSet; import mage.cards.ExpansionSet;
import mage.cards.Sets; import mage.cards.Sets;
import mage.cards.repository.CardScanner; import mage.cards.repository.CardScanner;
@ -59,14 +49,7 @@ import mage.server.util.config.GamePlugin;
import mage.server.util.config.Plugin; import mage.server.util.config.Plugin;
import mage.utils.MageVersion; import mage.utils.MageVersion;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.jboss.remoting.Client; import org.jboss.remoting.*;
import org.jboss.remoting.ClientDisconnectedException;
import org.jboss.remoting.ConnectionListener;
import org.jboss.remoting.InvocationRequest;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.Remoting;
import org.jboss.remoting.ServerInvocationHandler;
import org.jboss.remoting.ServerInvoker;
import org.jboss.remoting.callback.InvokerCallbackHandler; import org.jboss.remoting.callback.InvokerCallbackHandler;
import org.jboss.remoting.callback.ServerInvokerCallbackHandler; import org.jboss.remoting.callback.ServerInvokerCallbackHandler;
import org.jboss.remoting.transport.Connector; import org.jboss.remoting.transport.Connector;
@ -76,8 +59,14 @@ import org.jboss.remoting.transporter.TransporterClient;
import org.jboss.remoting.transporter.TransporterServer; import org.jboss.remoting.transporter.TransporterServer;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import javax.management.MBeanServer;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.util.*;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class Main { public class Main {
@ -275,10 +264,11 @@ public class Main {
public void handleConnectionException(Throwable throwable, Client client) { public void handleConnectionException(Throwable throwable, Client client) {
Session session = SessionManager.getInstance().getSession(client.getSessionId()); Session session = SessionManager.getInstance().getSession(client.getSessionId());
if (session != null) { if (session != null) {
StringBuilder sessionInfo = new StringBuilder(); StringBuilder sessionInfo = new StringBuilder();
User user = UserManager.getInstance().getUser(session.getUserId()); Optional<User> user = UserManager.getInstance().getUser(session.getUserId());
if (user != null) { if (user.isPresent()) {
sessionInfo.append(user.getName()).append(" [").append(user.getGameInfo()).append("]"); sessionInfo.append(user.get().getName()).append(" [").append(user.get().getGameInfo()).append("]");
} else { } else {
sessionInfo.append("[user missing] "); sessionInfo.append("[user missing] ");
} }
@ -301,7 +291,9 @@ public class Main {
} }
} }
} }
} }
} }
} }

View file

@ -27,11 +27,7 @@
*/ */
package mage.server; package mage.server;
import java.util.Calendar; import java.util.*;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@ -321,10 +317,14 @@ 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());
} }
User user = UserManager.getInstance().getUser(userId); Optional<User> _user = UserManager.getInstance().getUser(userId);
if (user == null || !user.isConnected()) { if (!_user.isPresent()) {
return; //user was already disconnected by other thread return; //user was already disconnected by other thread
} }
User user = _user.get();
if(!user.isConnected()){
return;
}
if (!user.getSessionId().equals(sessionId)) { if (!user.getSessionId().equals(sessionId)) {
// user already reconnected with another instance // user already reconnected with another instance
logger.info("OLD SESSION IGNORED - " + user.getName()); logger.info("OLD SESSION IGNORED - " + user.getName());
@ -371,12 +371,14 @@ public class Session {
call.setMessageId(messageId++); call.setMessageId(messageId++);
callbackHandler.handleCallbackOneway(new Callback(call)); callbackHandler.handleCallbackOneway(new Callback(call));
} catch (HandleCallbackException ex) { } catch (HandleCallbackException ex) {
User user = UserManager.getInstance().getUser(userId); ex.printStackTrace();
logger.warn("SESSION CALLBACK EXCEPTION - " + (user != null ? user.getName() : "") + " userId " + userId); UserManager.getInstance().getUser(userId).ifPresent(user-> {
logger.warn(" - method: " + call.getMethod()); logger.warn("SESSION CALLBACK EXCEPTION - " + (user != null ? user.getName() : "") + " userId " + userId);
logger.warn(" - cause: " + getBasicCause(ex).toString()); logger.warn(" - method: " + call.getMethod());
logger.trace("Stack trace:", ex); logger.warn(" - cause: " + getBasicCause(ex).toString());
userLostConnection(); logger.trace("Stack trace:", ex);
userLostConnection();
});
} }
} }

View file

@ -29,6 +29,7 @@ package mage.server;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import mage.MageException; import mage.MageException;
@ -190,7 +191,7 @@ public class SessionManager {
if (session == null) { if (session == null) {
return null; return null;
} }
return UserManager.getInstance().getUser(session.getUserId()); return UserManager.getInstance().getUser(session.getUserId()).get();
} }
public void endUserSession(String sessionId, String userSessionId) { public void endUserSession(String sessionId, String userSessionId) {
@ -211,12 +212,13 @@ public class SessionManager {
return sessions.containsKey(sessionId); return sessions.containsKey(sessionId);
} }
public User getUser(String sessionId) { public Optional<User> getUser(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.getInstance().getUser(sessions.get(sessionId).getUserId());
} }
return null; logger.error(String.format("Session %s could not be found",sessionId));
return Optional.empty();
} }
public boolean extendUserSession(String sessionId, String pingInfo) { public boolean extendUserSession(String sessionId, String pingInfo) {

View file

@ -27,25 +27,13 @@
*/ */
package mage.server; package mage.server;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import mage.MageException; import mage.MageException;
import mage.cards.decks.Deck; import mage.cards.decks.Deck;
import mage.cards.decks.DeckCardLists; import mage.cards.decks.DeckCardLists;
import mage.cards.decks.InvalidDeckException; import mage.cards.decks.InvalidDeckException;
import mage.constants.RangeOfInfluence; import mage.constants.RangeOfInfluence;
import mage.constants.TableState; import mage.constants.TableState;
import mage.game.Game; import mage.game.*;
import mage.game.GameException;
import mage.game.GameOptions;
import mage.game.Seat;
import mage.game.Table;
import mage.game.draft.Draft; import mage.game.draft.Draft;
import mage.game.draft.DraftPlayer; import mage.game.draft.DraftPlayer;
import mage.game.events.Listener; import mage.game.events.Listener;
@ -72,6 +60,15 @@ import mage.server.util.ThreadExecutor;
import mage.view.ChatMessage; import mage.view.ChatMessage;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
@ -97,9 +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) {
User user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.getInstance().getUser(userId);
// TODO: Handle if user == null // TODO: Handle if user == null
controllerName = user.getName(); if(user.isPresent()) {
controllerName = user.get().getName();
}
else{
controllerName = "undefined";
}
} else { } else {
controllerName = "System"; controllerName = "System";
} }
@ -112,12 +114,12 @@ 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) {
User user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.getInstance().getUser(userId);
if (user == null) { 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]";
} else { } else {
controllerName = user.getName(); controllerName = user.get().getName();
} }
} else { } else {
controllerName = "System"; controllerName = "System";
@ -151,11 +153,12 @@ public class TableController {
if (seat == null) { if (seat == null) {
throw new GameException("No available seats."); throw new GameException("No available seats.");
} }
User user = UserManager.getInstance().getUser(userId); Optional<User> _user = UserManager.getInstance().getUser(userId);
if (user == null) { 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;
} }
User user = _user.get();
// check password // check password
if (!table.getTournament().getOptions().getPassword().isEmpty() && playerType.equals("Human")) { if (!table.getTournament().getOptions().getPassword().isEmpty() && playerType.equals("Human")) {
if (!table.getTournament().getOptions().getPassword().equals(password)) { if (!table.getTournament().getOptions().getPassword().equals(password)) {
@ -247,10 +250,11 @@ public class TableController {
} }
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 {
User user = UserManager.getInstance().getUser(userId); Optional<User> _user = UserManager.getInstance().getUser(userId);
if (user == null) { if (!_user.isPresent()) {
return false; return false;
} }
User user = _user.get();
if (userPlayerMap.containsKey(userId) && playerType.equals("Human")) { if (userPlayerMap.containsKey(userId) && playerType.equals("Human")) {
user.showUserMessage("Join Table", new StringBuilder("You can join a table only one time.").toString()); user.showUserMessage("Join Table", new StringBuilder("You can join a table only one time.").toString());
return false; return false;
@ -398,10 +402,10 @@ 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).removeSideboarding(table.getId()); UserManager.getInstance().getUser(userId).ifPresent(user -> user.removeSideboarding(table.getId()));
} else { } else {
TournamentManager.getInstance().submitDeck(tournament.getId(), playerId, deck); TournamentManager.getInstance().submitDeck(tournament.getId(), playerId, deck);
UserManager.getInstance().getUser(userId).removeConstructing(playerId); UserManager.getInstance().getUser(userId).ifPresent(user -> user.removeConstructing(playerId));
} }
} }
@ -421,7 +425,7 @@ public class TableController {
public boolean watchTable(UUID userId) { public boolean watchTable(UUID userId) {
if (table.isTournament()) { if (table.isTournament()) {
UserManager.getInstance().getUser(userId).ccShowTournament(table.getTournament().getId()); UserManager.getInstance().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()) {
@ -434,7 +438,7 @@ public class TableController {
if (userPlayerMap.get(userId) != null) { if (userPlayerMap.get(userId) != null) {
return false; return false;
} }
return UserManager.getInstance().getUser(userId).ccWatchGame(match.getGame().getId()); return UserManager.getInstance().getUser(userId).get().ccWatchGame(match.getGame().getId());
} }
} }
@ -474,8 +478,7 @@ public class TableController {
logger.error("No tournament object - userId: " + userId + " table: " + table.getId()); logger.error("No tournament object - userId: " + userId + " table: " + table.getId());
return; return;
} }
if (table != null if (this.userId != null && this.userId.equals(userId) // tourn. sub tables have no creator user
&& this.userId != null && this.userId.equals(userId) // tourn. sub tables have no creator user
&& (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
@ -490,11 +493,11 @@ public class TableController {
} else { } else {
match.quitMatch(playerId); match.quitMatch(playerId);
} }
User user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.getInstance().getUser(userId);
if (user != null) { if (!user.isPresent()) {
ChatManager.getInstance().broadcast(chatId, user.getName(), "has left the table", ChatMessage.MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, ChatMessage.SoundToPlay.PlayerLeft); ChatManager.getInstance().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.removeTable(playerId); user.get().removeTable(playerId);
} }
} else { } else {
logger.debug("User not found - userId: " + userId + " tableId:" + table.getId()); logger.debug("User not found - userId: " + userId + " tableId:" + table.getId());
@ -551,9 +554,10 @@ 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 {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().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());
});
} }
match.startMatch(); match.startMatch();
startGame(null); startGame(null);
@ -576,8 +580,9 @@ public class TableController {
StringBuilder opponent = new StringBuilder(); StringBuilder opponent = new StringBuilder();
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) { // no AI players for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) { // 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()) {
User user = UserManager.getInstance().getUser(entry.getKey()); Optional<User> _user = UserManager.getInstance().getUser(entry.getKey());
if (user != null) { if (!_user.isPresent()) {
User user = _user.get();
user.ccGameStarted(match.getGame().getId(), entry.getValue()); user.ccGameStarted(match.getGame().getId(), entry.getValue());
if (creator == null) { if (creator == null) {
@ -634,11 +639,10 @@ public class TableController {
tournament.setStartTime(); tournament.setStartTime();
TournamentManager.getInstance().createTournamentSession(tournament, userPlayerMap, table.getId()); TournamentManager.getInstance().createTournamentSession(tournament, userPlayerMap, table.getId());
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) { for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
User user = UserManager.getInstance().getUser(entry.getKey()); UserManager.getInstance().getUser(entry.getKey()).ifPresent(user -> {
if (user != null) {
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.getInstance().incTournamentsStarted();
} }
@ -653,10 +657,10 @@ public class TableController {
table.initDraft(); table.initDraft();
DraftManager.getInstance().createDraftSession(draft, userPlayerMap, table.getId()); DraftManager.getInstance().createDraftSession(draft, userPlayerMap, table.getId());
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) { for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
User user = UserManager.getInstance().getUser(entry.getKey()); Optional<User> user = UserManager.getInstance().getUser(entry.getKey());
if (user != null) { if (user.isPresent()) {
logger.info(new StringBuilder("User ").append(user.getName()).append(" draft started: ").append(draft.getId()).append(" userId: ").append(user.getId())); logger.info(new StringBuilder("User ").append(user.get().getName()).append(" draft started: ").append(draft.getId()).append(" userId: ").append(user.get().getId()));
user.ccDraftStarted(draft.getId(), entry.getValue()); user.get().ccDraftStarted(draft.getId(), entry.getValue());
} else { } else {
logger.fatal(new StringBuilder("Start draft user not found userId: ").append(entry.getKey())); logger.fatal(new StringBuilder("Start draft user not found userId: ").append(entry.getKey()));
} }
@ -664,12 +668,13 @@ public class TableController {
} }
private void sideboard(UUID playerId, Deck deck) throws MageException { private void sideboard(UUID playerId, Deck deck) throws MageException {
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) { for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
if (entry.getValue().equals(playerId)) { if (entry.getValue().equals(playerId)) {
User user = UserManager.getInstance().getUser(entry.getKey()); Optional<User> user = UserManager.getInstance().getUser(entry.getKey());
int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS); int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS);
if (user != null) { if (user.isPresent()) {
user.ccSideboard(deck, table.getId(), remaining, options.isLimited()); user.get().ccSideboard(deck, table.getId(), remaining, options.isLimited());
} }
break; break;
} }
@ -775,9 +780,8 @@ 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()) {
User user = UserManager.getInstance().getUser(entry.getKey()); UserManager.getInstance().getUser(entry.getKey()).ifPresent(user -> {
if (user != null) { if (table.getState() == TableState.SIDEBOARDING) {
if (table.getState()==TableState.SIDEBOARDING) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (table.isTournamentSubTable()) { if (table.isTournamentSubTable()) {
sb.append("Your tournament match of round "); sb.append("Your tournament match of round ");
@ -797,12 +801,12 @@ public class TableController {
if (!table.isTournamentSubTable()) { if (!table.isTournamentSubTable()) {
user.removeTable(entry.getValue()); user.removeTable(entry.getValue());
} }
} });
} }
} }
// free resources no longer needed
match.cleanUpOnMatchEnd(ConfigSettings.getInstance().isSaveGameActivated(), table.isTournament());
} }
// free resources no longer needed
match.cleanUpOnMatchEnd(ConfigSettings.getInstance().isSaveGameActivated(), table.isTournament());
} }
} }
@ -842,7 +846,7 @@ public class TableController {
} }
public void swapSeats(int seatNum1, int seatNum2) { public void swapSeats(int seatNum1, int seatNum2) {
if (table.getState()==TableState.READY_TO_START) { if (table.getState() == TableState.READY_TO_START) {
if (seatNum1 >= 0 && seatNum2 >= 0 && seatNum1 < table.getSeats().length && seatNum2 < table.getSeats().length) { if (seatNum1 >= 0 && seatNum2 >= 0 && seatNum1 < table.getSeats().length && seatNum2 < table.getSeats().length) {
Player swapPlayer = table.getSeats()[seatNum1].getPlayer(); Player swapPlayer = table.getSeats()[seatNum1].getPlayer();
String swapType = table.getSeats()[seatNum1].getPlayerType(); String swapType = table.getSeats()[seatNum1].getPlayerType();
@ -884,8 +888,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
User user = UserManager.getInstance().getUser(userId); return UserManager.getInstance().getUser(userId).isPresent();
return user != null;
} }
} }
return false; return false;
@ -951,8 +954,8 @@ 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())) {
User user = UserManager.getInstance().getUser(userPlayerEntry.getKey()); Optional<User> user = UserManager.getInstance().getUser(userPlayerEntry.getKey());
if (user == null) { 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());
logger.debug("-- userId:" + userPlayerEntry.getKey()); logger.debug("-- userId:" + userPlayerEntry.getKey());
@ -975,11 +978,10 @@ 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()) {
User user = UserManager.getInstance().getUser(entry.getKey()); UserManager.getInstance().getUser(entry.getKey()).ifPresent(user ->
if (user != null) { user.removeTable(entry.getValue()));
user.removeTable(entry.getValue());
}
} }
} }
ChatManager.getInstance().destroyChatSession(chatId); ChatManager.getInstance().destroyChatSession(chatId);
} }

View file

@ -30,15 +30,13 @@ package mage.server;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import mage.MageException; import mage.MageException;
import mage.cards.decks.Deck; import mage.cards.decks.Deck;
import mage.cards.decks.DeckCardLists; import mage.cards.decks.DeckCardLists;
@ -59,7 +57,6 @@ import mage.server.util.ThreadExecutor;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class TableManager { public class TableManager {
@ -67,21 +64,21 @@ public class TableManager {
protected static final ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor(); protected static final ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor();
// protected static ScheduledExecutorService expireExecutor = ThreadExecutor.getInstance().getExpireExecutor(); // protected static ScheduledExecutorService expireExecutor = ThreadExecutor.getInstance().getExpireExecutor();
private static final TableManager INSTANCE = new TableManager(); private static final TableManager INSTANCE = new TableManager();
private static 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<>();
private final ConcurrentHashMap<UUID, Table> tables = new ConcurrentHashMap<>(); private final ConcurrentHashMap<UUID, Table> tables = new ConcurrentHashMap<>();
/** /**
* Defines how often checking process should be run on server. * Defines how often checking process should be run on server.
* * <p>
* In minutes. * In minutes.
*/ */
private static final int EXPIRE_CHECK_PERIOD = 10; private static final int EXPIRE_CHECK_PERIOD = 10;
public static TableManager getInstance() { public static TableManager getInstance() {
return INSTANCE; return INSTANCE;
} }
@ -90,7 +87,7 @@ public class TableManager {
expireExecutor.scheduleAtFixedRate(() -> { expireExecutor.scheduleAtFixedRate(() -> {
try { try {
checkTableHealthState(); checkTableHealthState();
} catch(Exception ex) { } catch (Exception ex) {
logger.fatal("Check table health state job error:", ex); logger.fatal("Check table health state job error:", ex);
} }
}, EXPIRE_CHECK_PERIOD, EXPIRE_CHECK_PERIOD, TimeUnit.MINUTES); }, EXPIRE_CHECK_PERIOD, EXPIRE_CHECK_PERIOD, TimeUnit.MINUTES);
@ -154,11 +151,11 @@ 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);
} }
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> {
if (user != null) {
user.removeSideboarding(tableId); user.removeSideboarding(tableId);
user.showUserMessage("Submit deck", "Table no longer active"); user.showUserMessage("Submit deck", "Table no longer active");
}
});
// return true so the panel closes // return true so the panel closes
return true; return true;
} }
@ -171,7 +168,7 @@ public class TableManager {
// remove user from all tournament sub tables // remove user from all tournament sub tables
public void userQuitTournamentSubTables(UUID userId) { public void userQuitTournamentSubTables(UUID userId) {
for (TableController controller: controllers.values()) { for (TableController controller : controllers.values()) {
if (controller.getTable() != null) { if (controller.getTable() != null) {
if (controller.getTable().isTournamentSubTable()) { if (controller.getTable().isTournamentSubTable()) {
controller.leaveTable(userId); controller.leaveTable(userId);
@ -184,7 +181,7 @@ public class TableManager {
// remove user from all sub tables of a tournament // remove user from all sub tables of a tournament
public void userQuitTournamentSubTables(UUID tournamentId, UUID userId) { public void userQuitTournamentSubTables(UUID tournamentId, UUID userId) {
for (TableController controller: controllers.values()) { for (TableController controller : controllers.values()) {
if (controller.getTable().isTournamentSubTable() && controller.getTable().getTournament().getId().equals(tournamentId)) { if (controller.getTable().isTournamentSubTable() && controller.getTable().getTournament().getId().equals(tournamentId)) {
if (controller.hasPlayer(userId)) { if (controller.hasPlayer(userId)) {
controller.leaveTable(userId); controller.leaveTable(userId);
@ -231,7 +228,7 @@ public class TableManager {
/** /**
* Starts the Match from a non tournament table * Starts the Match from a non tournament table
* *
* @param userId table owner * @param userId table owner
* @param roomId * @param roomId
* @param tableId * @param tableId
*/ */
@ -239,7 +236,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.getInstance().destroyChatSession(controllers.get(tableId).getChatId());
} }
} }
@ -258,9 +255,9 @@ 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.getInstance().destroyChatSession(controllers.get(tableId).getChatId());
}
} }
}
public void startDraft(UUID tableId, Draft draft) { public void startDraft(UUID tableId, Draft draft) {
if (controllers.containsKey(tableId)) { if (controllers.containsKey(tableId)) {
@ -327,11 +324,11 @@ public class TableManager {
} }
public void removeTable(UUID tableId) { public void removeTable(UUID tableId) {
TableController tableController = controllers.get(tableId); TableController tableController = controllers.get(tableId);
if (tableController != null) { if (tableController != null) {
controllers.remove(tableId); controllers.remove(tableId);
tableController.cleanUp(); // deletes the table chat and references to users tableController.cleanUp(); // deletes the table chat and references to users
Table table = tables.get(tableId); Table table = tables.get(tableId);
tables.remove(tableId); tables.remove(tableId);
Match match = table.getMatch(); Match match = table.getMatch();
@ -340,17 +337,17 @@ public class TableManager {
game = match.getGame(); game = match.getGame();
if (game != null && !game.hasEnded()) { if (game != null && !game.hasEnded()) {
game.end(); game.end();
} }
} }
// 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.getInstance().removeGame(game.getId());
} }
GamesRoomManager.getInstance().removeTable(tableId); GamesRoomManager.getInstance().removeTable(tableId);
} }
} }
} }
@ -358,10 +355,10 @@ public class TableManager {
logger.debug("--- Server state ----------------------------------------------"); logger.debug("--- Server state ----------------------------------------------");
Collection<User> users = UserManager.getInstance().getUsers(); Collection<User> users = UserManager.getInstance().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.getInstance().getSession(user.getSessionId());
String sessionState = "N"; String sessionState = "N";
if (session != null) { if (session!=null) {
if (session.isLocked()) { if (session.isLocked()) {
sessionState = "L"; sessionState = "L";
} else { } else {
@ -371,21 +368,21 @@ public class TableManager {
logger.debug(user.getId() logger.debug(user.getId()
+ " | " + formatter.format(user.getConnectionTime()) + " | " + formatter.format(user.getConnectionTime())
+ " | " + 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.getInstance().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.getInstance().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.getInstance().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 ------------------------------------------");
} }
private void checkTableHealthState() { private void checkTableHealthState() {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
debugServerState(); debugServerState();
@ -395,13 +392,13 @@ public class TableManager {
tableCopy.addAll(tables.values()); tableCopy.addAll(tables.values());
for (Table table : tableCopy) { for (Table table : tableCopy) {
try { try {
if (table.getState()!=TableState.FINISHED) { if (table.getState() != TableState.FINISHED) {
// remove tables and games not valid anymore // remove tables and games not valid anymore
logger.debug(table.getId() + " [" + table.getName()+ "] " + formatter.format(table.getStartTime() == null ? table.getCreateTime() : table.getCreateTime()) +" (" + table.getState().toString() + ") " + (table.isTournament() ? "- Tournament":"")); logger.debug(table.getId() + " [" + table.getName() + "] " + formatter.format(table.getStartTime() == null ? table.getCreateTime() : table.getCreateTime()) + " (" + table.getState().toString() + ") " + (table.isTournament() ? "- Tournament" : ""));
TableController tableController = getController(table.getId()); TableController tableController = getController(table.getId());
if (tableController != null) { if (tableController != null) {
if ((table.isTournament() && !tableController.isTournamentStillValid()) || if ((table.isTournament() && !tableController.isTournamentStillValid()) ||
(!table.isTournament() && !tableController.isMatchTableStillValid())) { (!table.isTournament() && !tableController.isMatchTableStillValid())) {
try { try {
logger.warn("Removing unhealthy tableId " + table.getId()); logger.warn("Removing unhealthy tableId " + table.getId());
removeTable(table.getId()); removeTable(table.getId());

View file

@ -237,10 +237,8 @@ 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); SessionManager.getInstance().getSession(sessionId).fireCallback(call);
if (session != null) {
session.fireCallback(call);
}
} }
} }

View file

@ -27,24 +27,16 @@
*/ */
package mage.server; package mage.server;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import mage.server.User.UserState; import mage.server.User.UserState;
import mage.server.record.UserStats; import mage.server.record.UserStats;
import mage.server.record.UserStatsRepository; import mage.server.record.UserStatsRepository;
import mage.server.util.ThreadExecutor; import mage.server.util.ThreadExecutor;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.util.*;
import java.util.concurrent.*;
/** /**
*
* manages users - if a user is disconnected and 10 minutes have passed with no * manages users - if a user is disconnected and 10 minutes have passed with no
* activity the user is removed * activity the user is removed
* *
@ -81,11 +73,18 @@ public class UserManager {
return user; return user;
} }
public User getUser(UUID userId) { public Optional<User> getUser(UUID userId) {
if (userId != null) { if (users.get(userId) == null) {
LOGGER.error(String.format("User with id %s could not be found", userId));
return Optional.empty();
} else {
return Optional.of(users.get(userId));
}
/* if (userId != null) {
return users.get(userId); return users.get(userId);
} }
return null; return null;
*/
} }
public User getUserByName(String userName) { public User getUserByName(String userName) {

View file

@ -121,9 +121,11 @@ 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).addDraft(playerId, draftSession); UserManager.getInstance().getUser(userId).ifPresent(user-> {
logger.debug("User " + UserManager.getInstance().getUser(userId).getName() + " has joined draft " + draft.getId()); user.addDraft(playerId, draftSession);
draft.getPlayer(playerId).setJoined(); logger.debug("User " + user.getName() + " has joined draft " + draft.getId());
draft.getPlayer(playerId).setJoined();
});
checkStart(); checkStart();
} }

View file

@ -29,11 +29,13 @@
package mage.server.draft; package mage.server.draft;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import mage.game.draft.Draft; import mage.game.draft.Draft;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
import mage.server.User; import mage.server.User;
@ -45,7 +47,6 @@ import mage.view.DraftView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class DraftSession { public class DraftSession {
@ -70,11 +71,11 @@ public class DraftSession {
public boolean init() { public boolean init() {
if (!killed) { if (!killed) {
User user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.getInstance().getUser(userId);
if (user != null) { 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);
user.fireCallback(new ClientCallback("draftInit", draft.getId(), new DraftClientMessage(getDraftPickView(remaining)))); user.get().fireCallback(new ClientCallback("draftInit", draft.getId(), new DraftClientMessage(getDraftPickView(remaining))));
} }
return true; return true;
} }
@ -84,10 +85,10 @@ public class DraftSession {
public void update() { public void update() {
if (!killed) { if (!killed) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance()
if (user != null) { .getUser(userId).
user.fireCallback(new ClientCallback("draftUpdate", draft.getId(), getDraftView())); ifPresent(user -> user.fireCallback(
} new ClientCallback("draftUpdate", draft.getId(), getDraftView())));
} }
} }
@ -95,29 +96,29 @@ public class DraftSession {
// //
public void inform(final String message) { public void inform(final String message) {
if (!killed) { if (!killed) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance()
if (user != null) { .getUser(userId)
user.fireCallback(new ClientCallback("draftInform", draft.getId(), new DraftClientMessage(getDraftView(), message))); .ifPresent(user -> user.fireCallback(new ClientCallback("draftInform", draft.getId(), new DraftClientMessage(getDraftView(), message))));
}
} }
} }
public void draftOver() { public void draftOver() {
if (!killed) { if (!killed) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance()
if (user != null) { .getUser(userId)
user.fireCallback(new ClientCallback("draftOver", draft.getId())); .ifPresent(user -> user.fireCallback(new ClientCallback("draftOver", draft.getId())));
}
} }
} }
public void pickCard(int timeout) { public void pickCard(int timeout) {
if (!killed) { if (!killed) {
setupTimeout(timeout); setupTimeout(timeout);
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance()
if (user != null) { .getUser(userId)
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 +127,7 @@ public class DraftSession {
if (seconds > 0) { if (seconds > 0) {
futureTimeout = timeoutExecutor.schedule( futureTimeout = timeoutExecutor.schedule(
() -> DraftManager.getInstance().timeout(draft.getId(), userId), () -> DraftManager.getInstance().timeout(draft.getId(), userId),
seconds, TimeUnit.SECONDS seconds, TimeUnit.SECONDS
); );
} }
} }
@ -155,10 +156,8 @@ public class DraftSession {
} }
public void removeDraft() { public void removeDraft() {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> user.removeDraft(playerId));
if (user != null) {
user.removeDraft(playerId);
}
} }
private DraftView getDraftView() { private DraftView getDraftView() {

View file

@ -0,0 +1,7 @@
package mage.server.exceptions;
/**
* Created by igoudt on 14-1-2017.
*/
public class UserNotFoundException extends Exception {
}

View file

@ -34,13 +34,8 @@ import java.io.ObjectOutput;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.Serializable; import java.io.Serializable;
import java.util.Collection; import java.util.*;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -49,6 +44,7 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
import mage.MageException; import mage.MageException;
import mage.abilities.Ability; import mage.abilities.Ability;
import mage.cards.Card; import mage.cards.Card;
@ -91,7 +87,6 @@ import mage.view.PermanentView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class GameController implements GameCallback { public class GameController implements GameCallback {
@ -282,7 +277,7 @@ public class GameController implements GameCallback {
* We create a timer that will run every 250 ms individually for a player * We create a timer that will run every 250 ms individually for a player
* decreasing his internal game counter. Later on this counter is used to * decreasing his internal game counter. Later on this counter is used to
* get time left to play the whole match. * get time left to play the whole match.
* * <p>
* What we also do here is passing Action to PriorityTimer that is the * What we also do here is passing Action to PriorityTimer that is the
* action that will be executed once game timer is over. * action that will be executed once game timer is over.
* *
@ -311,7 +306,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);
User user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.getInstance().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 +327,7 @@ public class GameController implements GameCallback {
} else { } else {
joinType = "rejoined"; joinType = "rejoined";
} }
user.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.getInstance().broadcast(chatId, "", game.getPlayer(playerId).getLogName() + " has " + joinType + " the game", MessageColor.ORANGE, true, MessageType.GAME, null);
checkStart(); checkStart();
@ -351,7 +346,7 @@ public class GameController implements GameCallback {
private void sendInfoAboutPlayersNotJoinedYet() { private void sendInfoAboutPlayersNotJoinedYet() {
for (Player player : game.getPlayers().values()) { for (Player player : game.getPlayers().values()) {
if (!player.hasLeft() && player.isHuman()) { if (!player.hasLeft() && player.isHuman()) {
User user = getUserByPlayerId(player.getId()); User user = getUserByPlayerId(player.getId()).get();
if (user != null) { if (user != null) {
if (!user.isConnected()) { if (!user.isConnected()) {
if (gameSessions.get(player.getId()) == null) { if (gameSessions.get(player.getId()) == null) {
@ -377,13 +372,13 @@ public class GameController implements GameCallback {
checkStart(); checkStart();
} }
private 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.getInstance().getUser(entry.getKey());
} }
} }
return null; return Optional.empty();
} }
private void checkStart() { private void checkStart() {
@ -397,9 +392,9 @@ public class GameController implements GameCallback {
private boolean allJoined() { private boolean allJoined() {
for (Player player : game.getPlayers().values()) { for (Player player : game.getPlayers().values()) {
if (!player.hasLeft()) { if (!player.hasLeft()) {
User user = getUserByPlayerId(player.getId()); Optional<User> user = getUserByPlayerId(player.getId());
if (user != null) { if (user.isPresent()) {
if (!user.isConnected()) { if (!user.get().isConnected()) {
return false; return false;
} }
} }
@ -420,22 +415,20 @@ 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;
} }
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> {
if (user != null) {
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.getInstance().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);
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> {
if (user != null) {
ChatManager.getInstance().broadcast(chatId, user.getName(), " has stopped watching", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, null); ChatManager.getInstance().broadcast(chatId, user.getName(), " has stopped watching", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, null);
} });
} }
public void quitMatch(UUID userId) { public void quitMatch(UUID userId) {
@ -576,10 +569,10 @@ public class GameController implements GameCallback {
private int requestPermissionToRollback(UUID userIdRequester, int numberTurns) { private int requestPermissionToRollback(UUID userIdRequester, int numberTurns) {
int requests = 0; int requests = 0;
for (Player player : game.getState().getPlayers().values()) { for (Player player : game.getState().getPlayers().values()) {
User requestedUser = getUserByPlayerId(player.getId()); Optional<User> requestedUser = getUserByPlayerId(player.getId());
if (player.isInGame() && player.isHuman() if (player.isInGame() && player.isHuman()
&& requestedUser != null && requestedUser.isPresent()
&& !requestedUser.getId().equals(userIdRequester)) { && !requestedUser.get().getId().equals(userIdRequester)) {
requests++; requests++;
GameSessionPlayer gameSession = gameSessions.get(player.getId()); GameSessionPlayer gameSession = gameSessions.get(player.getId());
if (gameSession != null) { if (gameSession != null) {
@ -603,10 +596,9 @@ 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
User requester = UserManager.getInstance().getUser(userIdRequester); UserManager.getInstance().getUser(userIdRequester).ifPresent(requester -> {
if (requester != null) {
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!");
} });
} }
} }
} }
@ -616,14 +608,13 @@ public class GameController implements GameCallback {
} }
} else { } else {
// user can already see the cards // user can already see the cards
User requester = UserManager.getInstance().getUser(userIdRequester); UserManager.getInstance().getUser(userIdRequester).ifPresent(requester -> {
if (requester != null) {
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() + "!");
} });
} }
} }
} }
public void cheat(UUID userId, UUID playerId, DeckCardLists deckList) { public void cheat(UUID userId, UUID playerId, DeckCardLists deckList) {

View file

@ -27,15 +27,6 @@
*/ */
package mage.server.game; package mage.server.game;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import mage.cards.Cards; import mage.cards.Cards;
import mage.choices.Choice; import mage.choices.Choice;
import mage.constants.ManaType; import mage.constants.ManaType;
@ -47,17 +38,15 @@ import mage.players.Player;
import mage.server.User; import mage.server.User;
import mage.server.UserManager; import mage.server.UserManager;
import mage.server.util.ThreadExecutor; import mage.server.util.ThreadExecutor;
import mage.view.AbilityPickerView; import mage.view.*;
import mage.view.CardsView;
import mage.view.GameClientMessage;
import mage.view.GameView;
import mage.view.LookedAtView;
import mage.view.SimpleCardsView;
import mage.view.UserRequestMessage;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.io.Serializable;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class GameSessionPlayer extends GameSessionWatcher { public class GameSessionPlayer extends GameSessionWatcher {
@ -80,99 +69,87 @@ 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) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameAsk", game.getId(), new GameClientMessage(getGameView(), question, options)))
if (user != null) { );
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) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> {
if (user != null) {
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)));
} });
} }
} }
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) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameSelect", game.getId(), new GameClientMessage(getGameView(), message, options))));
if (user != null) {
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) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user ->
if (user != null) { user.fireCallback(new ClientCallback("gameChooseAbility", game.getId(), abilities)));
user.fireCallback(new ClientCallback("gameChooseAbility", game.getId(), abilities));
}
} }
} }
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) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user ->
if (user != null) { user.fireCallback(new ClientCallback("gameChoosePile", game.getId(), new GameClientMessage(message, pile1, pile2))));
user.fireCallback(new ClientCallback("gameChoosePile", game.getId(), new GameClientMessage(message, pile1, pile2)));
}
} }
} }
public void chooseChoice(final Choice choice) { public void chooseChoice(final Choice choice) {
if (!killed) { if (!killed) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user ->
if (user != null) { user.fireCallback(new ClientCallback("gameChooseChoice", game.getId(), new GameClientMessage(choice))));
user.fireCallback(new ClientCallback("gameChooseChoice", game.getId(), new GameClientMessage(choice)));
}
} }
} }
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) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user ->
if (user != null) { 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) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user ->
if (user != null) { user.fireCallback(new ClientCallback("gamePlayXMana", game.getId(), new GameClientMessage(getGameView(), message))));
user.fireCallback(new ClientCallback("gamePlayXMana", game.getId(), new GameClientMessage(getGameView(), message)));
}
} }
} }
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) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> {
if (user != null) {
user.fireCallback(new ClientCallback("gameSelectAmount", game.getId(), new GameClientMessage(message, min, max))); user.fireCallback(new ClientCallback("gameSelectAmount", game.getId(), new GameClientMessage(message, min, max)));
} });
} }
} }
public void endGameInfo(Table table) { public void endGameInfo(Table table) {
if (!killed) { if (!killed) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("endGameInfo", game.getId(), getGameEndView(playerId, table))));
if (user != null) {
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) {
User requestingUser = UserManager.getInstance().getUser(requestingUserId); Optional<User> requestingUser = UserManager.getInstance().getUser(requestingUserId);
User requestedUser = UserManager.getInstance().getUser(userId); Optional<User> requestedUser = UserManager.getInstance().getUser(userId);
if (requestedUser != null && requestingUser != null) { if (!requestedUser.isPresent() && !requestingUser.isPresent()) {
String message; String message;
switch (numberTurns) { switch (numberTurns) {
case 0: case 0:
@ -185,30 +162,30 @@ public class GameSessionPlayer extends GameSessionWatcher {
message = "Allow to rollback " + numberTurns + " turns?"; message = "Allow to rollback " + numberTurns + " turns?";
} }
UserRequestMessage userRequestMessage = new UserRequestMessage( UserRequestMessage userRequestMessage = new UserRequestMessage(
"Request by " + requestedUser.getName(), message); "Request by " + requestedUser.get().getName(), message);
userRequestMessage.setRelatedUser(requestingUserId, requestingUser.getName()); userRequestMessage.setRelatedUser(requestingUserId, requestingUser.get().getName());
userRequestMessage.setGameId(game.getId()); userRequestMessage.setGameId(game.getId());
userRequestMessage.setButton1("Accept", PlayerAction.ADD_PERMISSION_TO_ROLLBACK_TURN); userRequestMessage.setButton1("Accept", PlayerAction.ADD_PERMISSION_TO_ROLLBACK_TURN);
userRequestMessage.setButton2("Deny", PlayerAction.DENY_PERMISSON_TO_ROLLBACK_TURN); userRequestMessage.setButton2("Deny", PlayerAction.DENY_PERMISSON_TO_ROLLBACK_TURN);
requestedUser.fireCallback(new ClientCallback("userRequestDialog", game.getId(), userRequestMessage)); requestedUser.get().fireCallback(new ClientCallback("userRequestDialog", game.getId(), userRequestMessage));
} }
} }
} }
public void requestPermissionToSeeHandCards(UUID watcherId) { public void requestPermissionToSeeHandCards(UUID watcherId) {
if (!killed) { if (!killed) {
User watcher = UserManager.getInstance().getUser(watcherId); Optional<User> watcher = UserManager.getInstance().getUser(watcherId);
User user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.getInstance().getUser(userId);
if (user != null && watcher != null) { if (user.isPresent() && watcher.isPresent()) {
UserRequestMessage userRequestMessage = new UserRequestMessage( UserRequestMessage userRequestMessage = new UserRequestMessage(
"User request", "User request",
"Allow user <b>" + watcher.getName() + "</b> for this match to see your hand cards?<br>" "Allow user <b>" + watcher.get().getName() + "</b> for this match to see your hand cards?<br>"
+ "(You can revoke this every time using related popup menu item of your battlefield.)"); + "(You can revoke this every time using related popup menu item of your battlefield.)");
userRequestMessage.setRelatedUser(watcherId, watcher.getName()); userRequestMessage.setRelatedUser(watcherId, watcher.get().getName());
userRequestMessage.setGameId(game.getId()); userRequestMessage.setGameId(game.getId());
userRequestMessage.setButton1("Accept", PlayerAction.ADD_PERMISSION_TO_SEE_HAND_CARDS); userRequestMessage.setButton1("Accept", PlayerAction.ADD_PERMISSION_TO_SEE_HAND_CARDS);
userRequestMessage.setButton2("Reject", null); userRequestMessage.setButton2("Reject", null);
user.fireCallback(new ClientCallback("userRequestDialog", game.getId(), userRequestMessage)); user.get().fireCallback(new ClientCallback("userRequestDialog", game.getId(), userRequestMessage));
} }
} }
} }
@ -267,10 +244,8 @@ public class GameSessionPlayer extends GameSessionWatcher {
} }
public void removeGame() { public void removeGame() {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> user.removeGame(playerId));
if (user != null) {
user.removeGame(playerId);
}
} }
public UUID getGameId() { public UUID getGameId() {

View file

@ -30,7 +30,9 @@ package mage.server.game;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import mage.game.Game; import mage.game.Game;
import mage.game.Table; import mage.game.Table;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
@ -44,7 +46,6 @@ import mage.view.SimpleCardsView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class GameSessionWatcher { public class GameSessionWatcher {
@ -64,9 +65,9 @@ public class GameSessionWatcher {
public boolean init() { public boolean init() {
if (!killed) { if (!killed) {
User user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.getInstance().getUser(userId);
if (user != null) { if (user.isPresent()) {
user.fireCallback(new ClientCallback("gameInit", game.getId(), getGameView())); user.get().fireCallback(new ClientCallback("gameInit", game.getId(), getGameView()));
return true; return true;
} }
} }
@ -75,44 +76,36 @@ public class GameSessionWatcher {
public void update() { public void update() {
if (!killed) { if (!killed) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameUpdate", game.getId(), getGameView())));
if (user != null) {
user.fireCallback(new ClientCallback("gameUpdate", game.getId(), getGameView()));
}
} }
} }
public void inform(final String message) { public void inform(final String message) {
if (!killed) { if (!killed) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameInform", game.getId(), new GameClientMessage(getGameView(), message))));
if (user != null) {
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) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameInformPersonal", game.getId(), new GameClientMessage(getGameView(), message))));
if (user != null) {
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) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> {
if (user != null) {
user.removeGameWatchInfo(game.getId()); user.removeGameWatchInfo(game.getId());
user.fireCallback(new ClientCallback("gameOver", game.getId(), message)); user.fireCallback(new ClientCallback("gameOver", game.getId(), message));
} });
} }
} }
/** /**
* Cleanup if Session ends * Cleanup if Session ends
*
*/ */
public void cleanUp() { public void cleanUp() {
@ -120,10 +113,8 @@ public class GameSessionWatcher {
public void gameError(final String message) { public void gameError(final String message) {
if (!killed) { if (!killed) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameError", game.getId(), message)));
if (user != null) {
user.fireCallback(new ClientCallback("gameError", game.getId(), message));
}
} }
} }
@ -140,13 +131,14 @@ public class GameSessionWatcher {
protected void processWatchedHands(UUID userId, GameView gameView) { protected void processWatchedHands(UUID userId, GameView gameView) {
Map<String, SimpleCardsView> handCards = new HashMap<>(); Map<String, SimpleCardsView> handCards = new HashMap<>();
for (Player player: game.getPlayers().values()) { for (Player player : game.getPlayers().values()) {
if (player.hasUserPermissionToSeeHand(userId)) { if (player.hasUserPermissionToSeeHand(userId)) {
handCards.put(player.getName(), new SimpleCardsView(player.getHand().getCards(game), true)); handCards.put(player.getName(), new SimpleCardsView(player.getHand().getCards(game), true));
gameView.setWatchedHands(handCards); gameView.setWatchedHands(handCards);
} }
} }
} }
public GameEndView getGameEndView(UUID playerId, Table table) { public GameEndView getGameEndView(UUID playerId, Table table) {
return new GameEndView(game.getState(), game, playerId, table); return new GameEndView(game.getState(), game, playerId, table);
} }
@ -154,5 +146,5 @@ public class GameSessionWatcher {
public boolean isPlayer() { public boolean isPlayer() {
return isPlayer; return isPlayer;
} }
} }

View file

@ -133,7 +133,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
} }
} }
users.sort(new UserNameSorter()); 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.getInstance().getNumberActiveGames(),

View file

@ -50,7 +50,7 @@ public class ReplayManager {
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).ccReplayGame(gameId); UserManager.getInstance().getUser(userId).ifPresent(user->user.ccReplayGame(gameId));
} }
public void startReplay(UUID gameId, UUID userId) { public void startReplay(UUID gameId, UUID userId) {

View file

@ -29,6 +29,7 @@
package mage.server.game; package mage.server.game;
import java.util.UUID; import java.util.UUID;
import mage.game.Game; import mage.game.Game;
import mage.game.GameState; import mage.game.GameState;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
@ -37,7 +38,6 @@ import mage.server.UserManager;
import mage.view.GameView; import mage.view.GameView;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class ReplaySession implements GameCallback { public class ReplaySession implements GameCallback {
@ -52,10 +52,9 @@ public class ReplaySession implements GameCallback {
public void replay() { public void replay() {
replay.start(); replay.start();
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user ->
if (user != null) { 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)));
}
} }
public void stop() { public void stop() {
@ -79,22 +78,19 @@ public class ReplaySession implements GameCallback {
@Override @Override
public void gameResult(final String result) { public void gameResult(final String result) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user ->
if (user != null) { 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.getInstance().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 ->
User user = UserManager.getInstance().getUser(userId); user.fireCallback(new ClientCallback("replayUpdate", replay.getGame().getId(), new GameView(state, game, null, null))));
if (user != null) {
user.fireCallback(new ClientCallback("replayUpdate", replay.getGame().getId(), new GameView(state, game, null, null)));
}
} }
} }

View file

@ -27,9 +27,6 @@
*/ */
package mage.server.tournament; package mage.server.tournament;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import mage.MageException; import mage.MageException;
import mage.cards.decks.Deck; import mage.cards.decks.Deck;
import mage.constants.TableState; import mage.constants.TableState;
@ -47,11 +44,7 @@ import mage.game.tournament.MultiplayerRound;
import mage.game.tournament.Tournament; import mage.game.tournament.Tournament;
import mage.game.tournament.TournamentPairing; import mage.game.tournament.TournamentPairing;
import mage.game.tournament.TournamentPlayer; import mage.game.tournament.TournamentPlayer;
import mage.server.ChatManager; import mage.server.*;
import mage.server.TableController;
import mage.server.TableManager;
import mage.server.User;
import mage.server.UserManager;
import mage.server.draft.DraftController; import mage.server.draft.DraftController;
import mage.server.draft.DraftManager; import mage.server.draft.DraftManager;
import mage.server.draft.DraftSession; import mage.server.draft.DraftSession;
@ -63,8 +56,12 @@ import mage.view.ChatMessage.SoundToPlay;
import mage.view.TournamentView; import mage.view.TournamentView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class TournamentController { public class TournamentController {
@ -159,10 +156,9 @@ 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()) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user ->
if (user != null) { logger.debug(user.getName() + " shows tournament panel tournamentId: " + tournament.getId()));
logger.debug(user.getName() + " shows tournament panel tournamentId: " + tournament.getId());
}
} }
return; return;
} }
@ -173,8 +169,9 @@ 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);
User user = UserManager.getInstance().getUser(userId); Optional<User> _user = UserManager.getInstance().getUser(userId);
if (user != null) { if (_user.isPresent()) {
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();
@ -302,7 +299,7 @@ public class TournamentController {
} }
private void initTournament() { private void initTournament() {
if (TableManager.getInstance().getTable(tableId).getState()!=TableState.DUELING) { if (TableManager.getInstance().getTable(tableId).getState() != TableState.DUELING) {
TableManager.getInstance().initTournament(tableId); TableManager.getInstance().initTournament(tableId);
} }
} }
@ -311,7 +308,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)).addConstructing(playerId, tournamentSession); UserManager.getInstance().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);
} }
@ -340,10 +337,9 @@ 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();
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user ->
if (user != null) { sb.append(user.getName()));
sb.append(user.getName());
}
sb.append(" - no deck found for auto submit"); sb.append(" - no deck found for auto submit");
logger.fatal(sb); logger.fatal(sb);
tournamentPlayer.setEliminated(); tournamentPlayer.setEliminated();
@ -385,7 +381,7 @@ public class TournamentController {
// quit active matches of that tournament // quit active matches of that tournament
TableManager.getInstance().userQuitTournamentSubTables(tournament.getId(), userId); TableManager.getInstance().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();
@ -399,7 +395,7 @@ public class TournamentController {
} }
} }
status = TourneyQuitStatus.DURING_DRAFTING; status = TourneyQuitStatus.DURING_DRAFTING;
} else if (tournamentPlayer.getState()==TournamentPlayerState.CONSTRUCTING) { } else if (tournamentPlayer.getState() == TournamentPlayerState.CONSTRUCTING) {
info = "during Construction phase"; info = "during Construction phase";
status = TourneyQuitStatus.DURING_CONSTRUCTION; status = TourneyQuitStatus.DURING_CONSTRUCTION;
} else { } else {
@ -424,17 +420,17 @@ public class TournamentController {
// replace player that quits with draft bot // replace player that quits with draft bot
if (humans > 1) { if (humans > 1) {
String replacePlayerName = "Draftbot"; String replacePlayerName = "Draftbot";
User user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.getInstance().getUser(userId);
TableController tableController = TableManager.getInstance().getController(tableId); TableController tableController = TableManager.getInstance().getController(tableId);
if (tableController != null) { if (tableController != null) {
if (user != null) { if (user.isPresent()) {
replacePlayerName = "Draftbot (" + user.getName() + ")"; replacePlayerName = "Draftbot (" + user.get().getName() + ")";
} }
tableController.replaceDraftPlayer(leavingPlayer.getPlayer(), replacePlayerName, "Computer - draftbot", 5); tableController.replaceDraftPlayer(leavingPlayer.getPlayer(), replacePlayerName, "Computer - draftbot", 5);
if (user != null) { if (user.isPresent()) {
user.removeDraft(leavingPlayer.getPlayer().getId()); user.get().removeDraft(leavingPlayer.getPlayer().getId());
user.removeTable(leavingPlayer.getPlayer().getId()); user.get().removeTable(leavingPlayer.getPlayer().getId());
user.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.getInstance().broadcast(chatId, "", leavingPlayer.getPlayer().getLogName() + " was replaced by draftbot", MessageColor.BLACK, true, MessageType.STATUS, null);
} }
@ -501,8 +497,8 @@ public class TournamentController {
if (tournamentPlayer != null) { if (tournamentPlayer != null) {
if (!tournamentPlayer.hasQuit()) { if (!tournamentPlayer.hasQuit()) {
if (tournamentPlayer.getPlayer().isHuman()) { if (tournamentPlayer.getPlayer().isHuman()) {
User user = UserManager.getInstance().getUser(entry.getKey()); Optional<User> user = UserManager.getInstance().getUser(entry.getKey());
if (user == null) { 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
quit(entry.getKey()); quit(entry.getKey());
@ -523,7 +519,7 @@ public class TournamentController {
} }
} }
} }
if (activePlayers < 2 && tableState!=TableState.WAITING) { if (activePlayers < 2 && tableState != TableState.WAITING) {
logger.debug("Tournament has less than 2 active players - tournamentId: " + tournament.getId() + " state: " + tableState.toString()); logger.debug("Tournament has less than 2 active players - tournamentId: " + tournament.getId() + " state: " + tableState.toString());
return false; return false;
} }

View file

@ -37,13 +37,13 @@ import mage.server.util.ThreadExecutor;
import mage.view.TournamentView; import mage.view.TournamentView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class TournamentSession { public class TournamentSession {
@ -67,9 +67,9 @@ public class TournamentSession {
public boolean init() { public boolean init() {
if (!killed) { if (!killed) {
User user = UserManager.getInstance().getUser(userId); Optional<User> user = UserManager.getInstance().getUser(userId);
if (user != null) { if (user.isPresent()) {
user.fireCallback(new ClientCallback("tournamentInit", tournament.getId(), getTournamentView())); user.get().fireCallback(new ClientCallback("tournamentInit", tournament.getId(), getTournamentView()));
return true; return true;
} }
} }
@ -78,30 +78,27 @@ public class TournamentSession {
public void update() { public void update() {
if (!killed) { if (!killed) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user ->
if (user != null) { user.fireCallback(new ClientCallback("tournamentUpdate", tournament.getId(), getTournamentView())));
user.fireCallback(new ClientCallback("tournamentUpdate", tournament.getId(), getTournamentView()));
}
} }
} }
public void gameOver(final String message) { public void gameOver(final String message) {
if (!killed) { if (!killed) {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user ->
if (user != null) { user.fireCallback(new ClientCallback("tournamentOver", tournament.getId(), message)));
user.fireCallback(new ClientCallback("tournamentOver", tournament.getId(), message));
}
} }
} }
public void construct(int timeout) { public void construct(int timeout) {
if (!killed) { if (!killed) {
setupTimeout(timeout); setupTimeout(timeout);
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user -> {
if (user != null) {
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);
} });
} }
} }
@ -136,7 +133,7 @@ public class TournamentSession {
logger.fatal("TournamentSession error - userId " + userId + " tId " + tournament.getId(), e); logger.fatal("TournamentSession error - userId " + userId + " tId " + tournament.getId(), e);
} }
}, },
seconds, TimeUnit.SECONDS seconds, TimeUnit.SECONDS
); );
} }
} }
@ -165,18 +162,18 @@ public class TournamentSession {
cleanUp(); cleanUp();
removeTournamentForUser(); removeTournamentForUser();
} }
private void cleanUp() { private void cleanUp() {
if (futureTimeout != null && !futureTimeout.isDone()) { if (futureTimeout != null && !futureTimeout.isDone()) {
futureTimeout.cancel(true); futureTimeout.cancel(true);
} }
} }
private void removeTournamentForUser() { private void removeTournamentForUser() {
User user = UserManager.getInstance().getUser(userId); UserManager.getInstance().getUser(userId).ifPresent(user ->
if (user != null) { user.removeTournament(playerId));
user.removeTournament(playerId);
}
} }
} }