Merge pull request #2799 from ingmargoudt/master

Introducing Optionals
This commit is contained in:
ingmargoudt 2017-01-20 01:15:47 +01:00 committed by GitHub
commit 41f245cb1f
21 changed files with 411 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;
} }
}); });
} }
@ -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("SESSION CALLBACK EXCEPTION - " + user.getName() + " userId " + userId);
logger.warn(" - method: " + call.getMethod()); logger.warn(" - method: " + call.getMethod());
logger.warn(" - cause: " + getBasicCause(ex).toString()); logger.warn(" - cause: " + getBasicCause(ex).toString());
logger.trace("Stack trace:", ex); logger.trace("Stack trace:", ex);
userLostConnection(); 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,8 +780,7 @@ public class TableController {
// opponent(s) left during sideboarding // opponent(s) left during sideboarding
if (matchPlayer != null) { if (matchPlayer != null) {
if (!matchPlayer.hasQuit()) { if (!matchPlayer.hasQuit()) {
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()) {
@ -797,14 +801,14 @@ public class TableController {
if (!table.isTournamentSubTable()) { if (!table.isTournamentSubTable()) {
user.removeTable(entry.getValue()); user.removeTable(entry.getValue());
} }
} });
}
} }
} }
// free resources no longer needed // free resources no longer needed
match.cleanUpOnMatchEnd(ConfigSettings.getInstance().isSaveGameActivated(), table.isTournament()); match.cleanUpOnMatchEnd(ConfigSettings.getInstance().isSaveGameActivated(), table.isTournament());
} }
} }
}
private synchronized void setupTimeout(int seconds) { private synchronized void setupTimeout(int seconds) {
cancelTimeout(); cancelTimeout();
@ -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 {
@ -77,7 +74,7 @@ public class TableManager {
/** /**
* 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;
@ -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;
} }

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);
logger.debug("User " + user.getName() + " has joined draft " + draft.getId());
draft.getPlayer(playerId).setJoined(); 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)))));
}
} }
} }
@ -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,13 +306,17 @@ 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());
logger.fatal("- userId: " + userId); logger.fatal("- userId: " + userId);
return; return;
} }
if(!user.isPresent(){
logger.fatal("User not found : "+userId);
return;
}
Player player = game.getPlayer(playerId); Player player = game.getPlayer(playerId);
if (player == null) { if (player == null) {
logger.fatal("Player not found - playerId: " + playerId); logger.fatal("Player not found - playerId: " + playerId);
@ -332,7 +331,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 +350,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 +376,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 +396,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 +419,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 +573,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 +600,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,15 +612,14 @@ 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) {
Deck deck; Deck deck;

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));
}
} }
} }
@ -147,6 +138,7 @@ public class GameSessionWatcher {
} }
} }
} }
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);
} }

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();
@ -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();
@ -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());

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);
} });
} }
} }
@ -173,10 +170,10 @@ public class TournamentSession {
} }
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);
}
} }
} }