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;
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.CardRepository;
import mage.server.exceptions.UserNotFoundException;
import mage.server.util.SystemUtil;
import mage.view.ChatMessage.MessageColor;
import mage.view.ChatMessage.MessageType;
import mage.view.ChatMessage.SoundToPlay;
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
*/
@ -256,26 +253,24 @@ public class ChatManager {
* @param message
* @param color
*/
public void broadcast(UUID userId, String message, MessageColor color) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
for (ChatSession chat : chatSessions.values()) {
if (chat.hasUser(userId)) {
chat.broadcast(user.getName(), message, color, true, MessageType.TALK, null);
}
}
}
public void broadcast(UUID userId, String message, MessageColor color) throws UserNotFoundException {
UserManager.getInstance().getUser(userId).ifPresent(user-> {
chatSessions.values()
.stream()
.filter(chat -> chat.hasUser(userId))
.forEach(session -> session.broadcast(user.getName(), message, color, true, MessageType.TALK, null));
});
}
public void sendReconnectMessage(UUID userId) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
for (ChatSession chat : chatSessions.values()) {
if (chat.hasUser(userId)) {
chat.broadcast(null, user.getName() + " has reconnected", MessageColor.BLUE, true, MessageType.STATUS, null);
}
}
}
UserManager.getInstance().getUser(userId).ifPresent(user ->
chatSessions.values()
.stream()
.filter(chat -> chat.hasUser(userId))
.forEach(chatSession -> chatSession.broadcast(null, user.getName() + " has reconnected", MessageColor.BLUE, true, MessageType.STATUS, null)));
}
public void removeUser(UUID userId, DisconnectReason reason) {
@ -291,4 +286,7 @@ public class ChatManager {
chatSessionList.addAll(chatSessions.values());
return chatSessionList;
}
}

View file

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

View file

@ -27,18 +27,6 @@
*/
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.cards.decks.DeckCardLists;
import mage.cards.repository.CardInfo;
@ -61,13 +49,7 @@ import mage.players.net.UserData;
import mage.remote.MageVersionException;
import mage.server.draft.CubeFactory;
import mage.server.draft.DraftManager;
import mage.server.game.DeckValidatorFactory;
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.game.*;
import mage.server.services.impl.FeedbackServiceImpl;
import mage.server.tournament.TournamentFactory;
import mage.server.tournament.TournamentManager;
@ -75,25 +57,18 @@ import mage.server.util.ConfigSettings;
import mage.server.util.ServerMessagesUtil;
import mage.server.util.SystemUtil;
import mage.server.util.ThreadExecutor;
import mage.utils.ActionWithBooleanResult;
import mage.utils.ActionWithNullNegativeResult;
import mage.utils.ActionWithTableViewResult;
import mage.utils.CompressUtil;
import mage.utils.MageVersion;
import mage.view.ChatMessage;
import mage.utils.*;
import mage.view.*;
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.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
*/
public class MageServerImpl implements MageServer {
@ -231,11 +206,12 @@ public class MageServerImpl implements MageServer {
@Override
public TableView execute() throws MageException {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
User user = UserManager.getInstance().getUser(userId);
if (user == null) {
Optional<User> _user = UserManager.getInstance().getUser(userId);
if (!_user.isPresent()) {
logger.error("User for session not found. session = " + sessionId);
return null;
}
User user = _user.get();
// check if user can create another table
int notStartedTables = user.getNumberOfNotStartedTables();
if (notStartedTables > 1) {
@ -267,11 +243,12 @@ public class MageServerImpl implements MageServer {
public TableView execute() throws MageException {
try {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
User user = UserManager.getInstance().getUser(userId);
if (user == null) {
Optional<User> _user = UserManager.getInstance().getUser(userId);
if (!_user.isPresent()) {
logger.error("User for session not found. session = " + sessionId);
return null;
}
User user = _user.get();
// check if user can create another table
int notStartedTables = user.getNumberOfNotStartedTables();
if (notStartedTables > 1) {
@ -331,8 +308,8 @@ public class MageServerImpl implements MageServer {
logger.fatal("Got no userId from sessionId" + sessionId + " tableId" + tableId);
return false;
}
boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList, password);
return ret;
return GamesRoomManager.getInstance().getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList, password);
}
});
}
@ -344,8 +321,8 @@ public class MageServerImpl implements MageServer {
public Boolean execute() throws MageException {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
if (logger.isTraceEnabled()) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
Optional<User> user = UserManager.getInstance().getUser(userId);
if (user.isPresent()) {
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);
return false;
}
boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill, deckList, password);
return ret;
return GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill, deckList, password);
}
});
}
@ -449,7 +426,7 @@ public class MageServerImpl implements MageServer {
return SessionManager.getInstance().extendUserSession(sessionId, pingInfo);
}
// @Override
// @Override
// public void deregisterClient(final String sessionId) throws MageException {
// execute("deregisterClient", sessionId, new Action() {
// @Override
@ -471,7 +448,7 @@ public class MageServerImpl implements MageServer {
return true;
}
// @Override
// @Override
// public void startChallenge(final String sessionId, final UUID roomId, final UUID tableId, final UUID challengeId) throws MageException {
// execute("startChallenge", sessionId, new Action() {
// @Override
@ -580,7 +557,7 @@ public class MageServerImpl implements MageServer {
@Override
public boolean leaveTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
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
return false;
}
@ -651,10 +628,10 @@ public class MageServerImpl implements MageServer {
@Override
public void sendPlayerUUID(final UUID gameId, final String sessionId, final UUID data) throws MageException {
execute("sendPlayerUUID", sessionId, () -> {
User user = SessionManager.getInstance().getUser(sessionId);
if (user != null) {
Optional<User> user = SessionManager.getInstance().getUser(sessionId);
if (user.isPresent()) {
// logger.warn("sendPlayerUUID gameId=" + gameId + " sessionId=" + sessionId + " username=" + user.getName());
user.sendPlayerUUID(gameId, data);
user.get().sendPlayerUUID(gameId, data);
} else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
}
@ -664,9 +641,9 @@ public class MageServerImpl implements MageServer {
@Override
public void sendPlayerString(final UUID gameId, final String sessionId, final String data) throws MageException {
execute("sendPlayerString", sessionId, () -> {
User user = SessionManager.getInstance().getUser(sessionId);
if (user != null) {
user.sendPlayerString(gameId, data);
Optional<User> user = SessionManager.getInstance().getUser(sessionId);
if (user.isPresent()) {
user.get().sendPlayerString(gameId, data);
} else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
}
@ -676,9 +653,9 @@ public class MageServerImpl implements MageServer {
@Override
public void sendPlayerManaType(final UUID gameId, final UUID playerId, final String sessionId, final ManaType data) throws MageException {
execute("sendPlayerManaType", sessionId, () -> {
User user = SessionManager.getInstance().getUser(sessionId);
if (user != null) {
user.sendPlayerManaType(gameId, playerId, data);
Optional<User> user = SessionManager.getInstance().getUser(sessionId);
if (user.isPresent()) {
user.get().sendPlayerManaType(gameId, playerId, data);
} else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
}
@ -688,9 +665,9 @@ public class MageServerImpl implements MageServer {
@Override
public void sendPlayerBoolean(final UUID gameId, final String sessionId, final Boolean data) throws MageException {
execute("sendPlayerBoolean", sessionId, () -> {
User user = SessionManager.getInstance().getUser(sessionId);
if (user != null) {
user.sendPlayerBoolean(gameId, data);
Optional<User> user = SessionManager.getInstance().getUser(sessionId);
if (user.isPresent()) {
user.get().sendPlayerBoolean(gameId, data);
} else {
logger.warn("Your session expired: gameId=" + gameId + ", sessionId=" + sessionId);
}
@ -700,9 +677,9 @@ public class MageServerImpl implements MageServer {
@Override
public void sendPlayerInteger(final UUID gameId, final String sessionId, final Integer data) throws MageException {
execute("sendPlayerInteger", sessionId, () -> {
User user = SessionManager.getInstance().getUser(sessionId);
if (user != null) {
user.sendPlayerInteger(gameId, data);
Optional<User> user = SessionManager.getInstance().getUser(sessionId);
if (user.isPresent()) {
user.get().sendPlayerInteger(gameId, data);
} else {
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 {
execute("stopWatching", sessionId, () -> {
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
UserManager.getInstance().getUser(userId).ifPresent(user -> {
GameManager.getInstance().stopWatching(gameId, userId);
user.removeGameWatchInfo(gameId);
}
});
});
}

View file

@ -27,16 +27,6 @@
*/
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.Sets;
import mage.cards.repository.CardScanner;
@ -59,14 +49,7 @@ import mage.server.util.config.GamePlugin;
import mage.server.util.config.Plugin;
import mage.utils.MageVersion;
import org.apache.log4j.Logger;
import org.jboss.remoting.Client;
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.*;
import org.jboss.remoting.callback.InvokerCallbackHandler;
import org.jboss.remoting.callback.ServerInvokerCallbackHandler;
import org.jboss.remoting.transport.Connector;
@ -76,8 +59,14 @@ import org.jboss.remoting.transporter.TransporterClient;
import org.jboss.remoting.transporter.TransporterServer;
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
*/
public class Main {
@ -275,10 +264,11 @@ public class Main {
public void handleConnectionException(Throwable throwable, Client client) {
Session session = SessionManager.getInstance().getSession(client.getSessionId());
if (session != null) {
StringBuilder sessionInfo = new StringBuilder();
User user = UserManager.getInstance().getUser(session.getUserId());
if (user != null) {
sessionInfo.append(user.getName()).append(" [").append(user.getGameInfo()).append("]");
Optional<User> user = UserManager.getInstance().getUser(session.getUserId());
if (user.isPresent()) {
sessionInfo.append(user.get().getName()).append(" [").append(user.get().getGameInfo()).append("]");
} else {
sessionInfo.append("[user missing] ");
}
@ -301,7 +291,9 @@ public class Main {
}
}
}
}
}
}

View file

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

View file

@ -29,6 +29,7 @@ package mage.server;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import mage.MageException;
@ -190,7 +191,7 @@ public class SessionManager {
if (session == null) {
return null;
}
return UserManager.getInstance().getUser(session.getUserId());
return UserManager.getInstance().getUser(session.getUserId()).get();
}
public void endUserSession(String sessionId, String userSessionId) {
@ -211,12 +212,13 @@ public class SessionManager {
return sessions.containsKey(sessionId);
}
public User getUser(String sessionId) {
public Optional<User> getUser(String sessionId) {
Session session = sessions.get(sessionId);
if (session != null) {
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) {

View file

@ -27,25 +27,13 @@
*/
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.cards.decks.Deck;
import mage.cards.decks.DeckCardLists;
import mage.cards.decks.InvalidDeckException;
import mage.constants.RangeOfInfluence;
import mage.constants.TableState;
import mage.game.Game;
import mage.game.GameException;
import mage.game.GameOptions;
import mage.game.Seat;
import mage.game.Table;
import mage.game.*;
import mage.game.draft.Draft;
import mage.game.draft.DraftPlayer;
import mage.game.events.Listener;
@ -72,6 +60,15 @@ import mage.server.util.ThreadExecutor;
import mage.view.ChatMessage;
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
*/
@ -97,9 +94,14 @@ public class TableController {
this.options = options;
match = GameFactory.getInstance().createMatch(options.getGameType(), options);
if (userId != null) {
User user = UserManager.getInstance().getUser(userId);
Optional<User> user = UserManager.getInstance().getUser(userId);
// TODO: Handle if user == null
controllerName = user.getName();
if(user.isPresent()) {
controllerName = user.get().getName();
}
else{
controllerName = "undefined";
}
} else {
controllerName = "System";
}
@ -112,12 +114,12 @@ public class TableController {
this.userId = userId;
tournament = TournamentFactory.getInstance().createTournament(options.getTournamentType(), options);
if (userId != null) {
User user = UserManager.getInstance().getUser(userId);
if (user == null) {
Optional<User> user = UserManager.getInstance().getUser(userId);
if (!user.isPresent()) {
logger.fatal(new StringBuilder("User for userId ").append(userId).append(" could not be retrieved from UserManager").toString());
controllerName = "[unknown]";
} else {
controllerName = user.getName();
controllerName = user.get().getName();
}
} else {
controllerName = "System";
@ -151,11 +153,12 @@ public class TableController {
if (seat == null) {
throw new GameException("No available seats.");
}
User user = UserManager.getInstance().getUser(userId);
if (user == null) {
Optional<User> _user = UserManager.getInstance().getUser(userId);
if (!_user.isPresent()) {
logger.fatal(new StringBuilder("couldn't get user ").append(name).append(" for join tournament userId = ").append(userId).toString());
return false;
}
User user = _user.get();
// check password
if (!table.getTournament().getOptions().getPassword().isEmpty() && playerType.equals("Human")) {
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 {
User user = UserManager.getInstance().getUser(userId);
if (user == null) {
Optional<User> _user = UserManager.getInstance().getUser(userId);
if (!_user.isPresent()) {
return false;
}
User user = _user.get();
if (userPlayerMap.containsKey(userId) && playerType.equals("Human")) {
user.showUserMessage("Join Table", new StringBuilder("You can join a table only one time.").toString());
return false;
@ -398,10 +402,10 @@ public class TableController {
private void submitDeck(UUID userId, UUID playerId, Deck deck) {
if (table.getState() == TableState.SIDEBOARDING) {
match.submitDeck(playerId, deck);
UserManager.getInstance().getUser(userId).removeSideboarding(table.getId());
UserManager.getInstance().getUser(userId).ifPresent(user -> user.removeSideboarding(table.getId()));
} else {
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) {
if (table.isTournament()) {
UserManager.getInstance().getUser(userId).ccShowTournament(table.getTournament().getId());
UserManager.getInstance().getUser(userId).ifPresent(user -> user.ccShowTournament(table.getTournament().getId()));
return true;
} else {
if (table.isTournamentSubTable() && !table.getTournament().getOptions().isWatchingAllowed()) {
@ -434,7 +438,7 @@ public class TableController {
if (userPlayerMap.get(userId) != null) {
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());
return;
}
if (table != null
&& this.userId != null && this.userId.equals(userId) // tourn. sub tables have no creator user
if (this.userId != null && this.userId.equals(userId) // tourn. sub tables have no creator user
&& (table.getState() == TableState.WAITING
|| table.getState() == TableState.READY_TO_START)) {
// table not started yet and user is the owner, remove the table
@ -490,11 +493,11 @@ public class TableController {
} else {
match.quitMatch(playerId);
}
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
ChatManager.getInstance().broadcast(chatId, user.getName(), "has left the table", ChatMessage.MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, ChatMessage.SoundToPlay.PlayerLeft);
Optional<User> user = UserManager.getInstance().getUser(userId);
if (!user.isPresent()) {
ChatManager.getInstance().broadcast(chatId, user.get().getName(), "has left the table", ChatMessage.MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, ChatMessage.SoundToPlay.PlayerLeft);
if (!table.isTournamentSubTable()) {
user.removeTable(playerId);
user.get().removeTable(playerId);
}
} else {
logger.debug("User not found - userId: " + userId + " tableId:" + table.getId());
@ -551,9 +554,10 @@ public class TableController {
if (table.isTournamentSubTable()) {
logger.info("Tourn. match started id:" + match.getId() + " tournId: " + table.getTournament().getId());
} else {
User user = UserManager.getInstance().getUser(userId);
logger.info("MATCH started [" + match.getName() + "] " + match.getId() + "(" + user.getName() + ")");
logger.debug("- " + match.getOptions().getGameType() + " - " + match.getOptions().getDeckType());
UserManager.getInstance().getUser(userId).ifPresent(user -> {
logger.info("MATCH started [" + match.getName() + "] " + match.getId() + "(" + user.getName() + ")");
logger.debug("- " + match.getOptions().getGameType() + " - " + match.getOptions().getDeckType());
});
}
match.startMatch();
startGame(null);
@ -576,8 +580,9 @@ public class TableController {
StringBuilder opponent = new StringBuilder();
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) { // no AI players
if (match.getPlayer(entry.getValue()) != null && !match.getPlayer(entry.getValue()).hasQuit()) {
User user = UserManager.getInstance().getUser(entry.getKey());
if (user != null) {
Optional<User> _user = UserManager.getInstance().getUser(entry.getKey());
if (!_user.isPresent()) {
User user = _user.get();
user.ccGameStarted(match.getGame().getId(), entry.getValue());
if (creator == null) {
@ -634,11 +639,10 @@ public class TableController {
tournament.setStartTime();
TournamentManager.getInstance().createTournamentSession(tournament, userPlayerMap, table.getId());
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
User user = UserManager.getInstance().getUser(entry.getKey());
if (user != null) {
UserManager.getInstance().getUser(entry.getKey()).ifPresent(user -> {
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());
}
});
}
ServerMessagesUtil.getInstance().incTournamentsStarted();
}
@ -653,10 +657,10 @@ public class TableController {
table.initDraft();
DraftManager.getInstance().createDraftSession(draft, userPlayerMap, table.getId());
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
User user = UserManager.getInstance().getUser(entry.getKey());
if (user != null) {
logger.info(new StringBuilder("User ").append(user.getName()).append(" draft started: ").append(draft.getId()).append(" userId: ").append(user.getId()));
user.ccDraftStarted(draft.getId(), entry.getValue());
Optional<User> user = UserManager.getInstance().getUser(entry.getKey());
if (user.isPresent()) {
logger.info(new StringBuilder("User ").append(user.get().getName()).append(" draft started: ").append(draft.getId()).append(" userId: ").append(user.get().getId()));
user.get().ccDraftStarted(draft.getId(), entry.getValue());
} else {
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 {
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
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);
if (user != null) {
user.ccSideboard(deck, table.getId(), remaining, options.isLimited());
if (user.isPresent()) {
user.get().ccSideboard(deck, table.getId(), remaining, options.isLimited());
}
break;
}
@ -775,9 +780,8 @@ public class TableController {
// opponent(s) left during sideboarding
if (matchPlayer != null) {
if (!matchPlayer.hasQuit()) {
User user = UserManager.getInstance().getUser(entry.getKey());
if (user != null) {
if (table.getState()==TableState.SIDEBOARDING) {
UserManager.getInstance().getUser(entry.getKey()).ifPresent(user -> {
if (table.getState() == TableState.SIDEBOARDING) {
StringBuilder sb = new StringBuilder();
if (table.isTournamentSubTable()) {
sb.append("Your tournament match of round ");
@ -797,12 +801,12 @@ public class TableController {
if (!table.isTournamentSubTable()) {
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) {
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) {
Player swapPlayer = table.getSeats()[seatNum1].getPlayer();
String swapType = table.getSeats()[seatNum1].getPlayerType();
@ -884,8 +888,7 @@ public class TableController {
}
} else {
// check if table creator is still a valid user, if not remove table
User user = UserManager.getInstance().getUser(userId);
return user != null;
return UserManager.getInstance().getUser(userId).isPresent();
}
}
return false;
@ -951,8 +954,8 @@ public class TableController {
|| table.getState() == TableState.READY_TO_START)
|| !match.isDoneSideboarding()
|| (!matchPlayer.hasQuit() && match.getGame() != null && matchPlayer.getPlayer().isInGame())) {
User user = UserManager.getInstance().getUser(userPlayerEntry.getKey());
if (user == null) {
Optional<User> user = UserManager.getInstance().getUser(userPlayerEntry.getKey());
if (!user.isPresent()) {
logger.debug("- Active user of match is missing: " + matchPlayer.getName());
logger.debug("-- matchId:" + match.getId());
logger.debug("-- userId:" + userPlayerEntry.getKey());
@ -975,11 +978,10 @@ public class TableController {
void cleanUp() {
if (!table.isTournamentSubTable()) {
for (Map.Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
User user = UserManager.getInstance().getUser(entry.getKey());
if (user != null) {
user.removeTable(entry.getValue());
}
UserManager.getInstance().getUser(entry.getKey()).ifPresent(user ->
user.removeTable(entry.getValue()));
}
}
ChatManager.getInstance().destroyChatSession(chatId);
}

View file

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

View file

@ -237,10 +237,8 @@ public class User {
public void fireCallback(final ClientCallback call) {
if (isConnected()) {
Session session = SessionManager.getInstance().getSession(sessionId);
if (session != null) {
session.fireCallback(call);
}
SessionManager.getInstance().getSession(sessionId).fireCallback(call);
}
}

View file

@ -27,24 +27,16 @@
*/
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.record.UserStats;
import mage.server.record.UserStatsRepository;
import mage.server.util.ThreadExecutor;
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
* activity the user is removed
*
@ -81,11 +73,18 @@ public class UserManager {
return user;
}
public User getUser(UUID userId) {
if (userId != null) {
public Optional<User> getUser(UUID userId) {
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 null;
*/
}
public User getUserByName(String userName) {

View file

@ -121,9 +121,11 @@ public class DraftController {
UUID playerId = userPlayerMap.get(userId);
DraftSession draftSession = new DraftSession(draft, userId, playerId);
draftSessions.put(playerId, draftSession);
UserManager.getInstance().getUser(userId).addDraft(playerId, draftSession);
logger.debug("User " + UserManager.getInstance().getUser(userId).getName() + " has joined draft " + draft.getId());
draft.getPlayer(playerId).setJoined();
UserManager.getInstance().getUser(userId).ifPresent(user-> {
user.addDraft(playerId, draftSession);
logger.debug("User " + user.getName() + " has joined draft " + draft.getId());
draft.getPlayer(playerId).setJoined();
});
checkStart();
}

View file

@ -29,11 +29,13 @@
package mage.server.draft;
import java.rmi.RemoteException;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import mage.game.draft.Draft;
import mage.interfaces.callback.ClientCallback;
import mage.server.User;
@ -45,7 +47,6 @@ import mage.view.DraftView;
import org.apache.log4j.Logger;
/**
*
* @author BetaSteward_at_googlemail.com
*/
public class DraftSession {
@ -70,11 +71,11 @@ public class DraftSession {
public boolean init() {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
Optional<User> user = UserManager.getInstance().getUser(userId);
if (user.isPresent()) {
if (futureTimeout != null && !futureTimeout.isDone()) {
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;
}
@ -84,10 +85,10 @@ public class DraftSession {
public void update() {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.fireCallback(new ClientCallback("draftUpdate", draft.getId(), getDraftView()));
}
UserManager.getInstance()
.getUser(userId).
ifPresent(user -> user.fireCallback(
new ClientCallback("draftUpdate", draft.getId(), getDraftView())));
}
}
@ -95,29 +96,29 @@ public class DraftSession {
//
public void inform(final String message) {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.fireCallback(new ClientCallback("draftInform", draft.getId(), new DraftClientMessage(getDraftView(), message)));
}
UserManager.getInstance()
.getUser(userId)
.ifPresent(user -> user.fireCallback(new ClientCallback("draftInform", draft.getId(), new DraftClientMessage(getDraftView(), message))));
}
}
public void draftOver() {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.fireCallback(new ClientCallback("draftOver", draft.getId()));
}
UserManager.getInstance()
.getUser(userId)
.ifPresent(user -> user.fireCallback(new ClientCallback("draftOver", draft.getId())));
}
}
public void pickCard(int timeout) {
if (!killed) {
setupTimeout(timeout);
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.fireCallback(new ClientCallback("draftPick", draft.getId(), new DraftClientMessage(getDraftPickView(timeout))));
}
UserManager.getInstance()
.getUser(userId)
.ifPresent(user -> user.fireCallback(new ClientCallback("draftPick", draft.getId(), new DraftClientMessage(getDraftPickView(timeout)))));
}
}
@ -126,7 +127,7 @@ public class DraftSession {
if (seconds > 0) {
futureTimeout = timeoutExecutor.schedule(
() -> DraftManager.getInstance().timeout(draft.getId(), userId),
seconds, TimeUnit.SECONDS
seconds, TimeUnit.SECONDS
);
}
}
@ -155,10 +156,8 @@ public class DraftSession {
}
public void removeDraft() {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.removeDraft(playerId);
}
UserManager.getInstance().getUser(userId).ifPresent(user -> user.removeDraft(playerId));
}
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.OutputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ -49,6 +44,7 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;
import mage.MageException;
import mage.abilities.Ability;
import mage.cards.Card;
@ -91,7 +87,6 @@ import mage.view.PermanentView;
import org.apache.log4j.Logger;
/**
*
* @author BetaSteward_at_googlemail.com
*/
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
* decreasing his internal game counter. Later on this counter is used to
* get time left to play the whole match.
*
* <p>
* What we also do here is passing Action to PriorityTimer that is the
* action that will be executed once game timer is over.
*
@ -311,13 +306,17 @@ public class GameController implements GameCallback {
public void join(UUID userId) {
UUID playerId = userPlayerMap.get(userId);
User user = UserManager.getInstance().getUser(userId);
Optional<User> user = UserManager.getInstance().getUser(userId);
if (userId == null || playerId == null) {
logger.fatal("Join game failed!");
logger.fatal("- gameId: " + game.getId());
logger.fatal("- userId: " + userId);
return;
}
if(!user.isPresent(){
logger.fatal("User not found : "+userId);
return;
}
Player player = game.getPlayer(playerId);
if (player == null) {
logger.fatal("Player not found - playerId: " + playerId);
@ -332,7 +331,7 @@ public class GameController implements GameCallback {
} else {
joinType = "rejoined";
}
user.addGame(playerId, gameSession);
user.get().addGame(playerId, gameSession);
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);
checkStart();
@ -351,7 +350,7 @@ public class GameController implements GameCallback {
private void sendInfoAboutPlayersNotJoinedYet() {
for (Player player : game.getPlayers().values()) {
if (!player.hasLeft() && player.isHuman()) {
User user = getUserByPlayerId(player.getId());
User user = getUserByPlayerId(player.getId()).get();
if (user != null) {
if (!user.isConnected()) {
if (gameSessions.get(player.getId()) == null) {
@ -377,13 +376,13 @@ public class GameController implements GameCallback {
checkStart();
}
private User getUserByPlayerId(UUID playerId) {
private Optional<User> getUserByPlayerId(UUID playerId) {
for (Map.Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
if (entry.getValue().equals(playerId)) {
return UserManager.getInstance().getUser(entry.getKey());
}
}
return null;
return Optional.empty();
}
private void checkStart() {
@ -397,9 +396,9 @@ public class GameController implements GameCallback {
private boolean allJoined() {
for (Player player : game.getPlayers().values()) {
if (!player.hasLeft()) {
User user = getUserByPlayerId(player.getId());
if (user != null) {
if (!user.isConnected()) {
Optional<User> user = getUserByPlayerId(player.getId());
if (user.isPresent()) {
if (!user.get().isConnected()) {
return false;
}
}
@ -420,22 +419,20 @@ public class GameController implements GameCallback {
// You can't watch a game if you already watch it
return;
}
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
UserManager.getInstance().getUser(userId).ifPresent(user -> {
GameSessionWatcher gameWatcher = new GameSessionWatcher(userId, game, false);
watchers.put(userId, gameWatcher);
gameWatcher.init();
user.addGameWatchInfo(game.getId());
ChatManager.getInstance().broadcast(chatId, user.getName(), " has started watching", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, null);
}
});
}
public void stopWatching(UUID userId) {
watchers.remove(userId);
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
UserManager.getInstance().getUser(userId).ifPresent(user -> {
ChatManager.getInstance().broadcast(chatId, user.getName(), " has stopped watching", MessageColor.BLUE, true, ChatMessage.MessageType.STATUS, null);
}
});
}
public void quitMatch(UUID userId) {
@ -576,10 +573,10 @@ public class GameController implements GameCallback {
private int requestPermissionToRollback(UUID userIdRequester, int numberTurns) {
int requests = 0;
for (Player player : game.getState().getPlayers().values()) {
User requestedUser = getUserByPlayerId(player.getId());
Optional<User> requestedUser = getUserByPlayerId(player.getId());
if (player.isInGame() && player.isHuman()
&& requestedUser != null
&& !requestedUser.getId().equals(userIdRequester)) {
&& requestedUser.isPresent()
&& !requestedUser.get().getId().equals(userIdRequester)) {
requests++;
GameSessionPlayer gameSession = gameSessions.get(player.getId());
if (gameSession != null) {
@ -603,10 +600,9 @@ public class GameController implements GameCallback {
gameSession.requestPermissionToSeeHandCards(userIdRequester);
} else {
// player does not allow the request
User requester = UserManager.getInstance().getUser(userIdRequester);
if (requester != null) {
UserManager.getInstance().getUser(userIdRequester).ifPresent(requester -> {
requester.showUserMessage("Request to show hand cards", "Player " + grantingPlayer.getName() + " does not allow to request to show hand cards!");
}
});
}
}
}
@ -616,14 +612,13 @@ public class GameController implements GameCallback {
}
} else {
// user can already see the cards
User requester = UserManager.getInstance().getUser(userIdRequester);
if (requester != null) {
UserManager.getInstance().getUser(userIdRequester).ifPresent(requester -> {
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) {

View file

@ -27,15 +27,6 @@
*/
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.choices.Choice;
import mage.constants.ManaType;
@ -47,17 +38,15 @@ import mage.players.Player;
import mage.server.User;
import mage.server.UserManager;
import mage.server.util.ThreadExecutor;
import mage.view.AbilityPickerView;
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 mage.view.*;
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
*/
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) {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.fireCallback(new ClientCallback("gameAsk", game.getId(), new GameClientMessage(getGameView(), question, options)));
}
UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameAsk", game.getId(), new GameClientMessage(getGameView(), question, options)))
);
}
}
public void target(final String question, final CardsView cardView, final Set<UUID> targets, final boolean required, final Map<String, Serializable> options) {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
UserManager.getInstance().getUser(userId).ifPresent(user -> {
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) {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.fireCallback(new ClientCallback("gameSelect", game.getId(), new GameClientMessage(getGameView(), message, options)));
}
UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("gameSelect", game.getId(), new GameClientMessage(getGameView(), message, options))));
}
;
}
public void chooseAbility(final AbilityPickerView abilities) {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.fireCallback(new ClientCallback("gameChooseAbility", game.getId(), abilities));
}
UserManager.getInstance().getUser(userId).ifPresent(user ->
user.fireCallback(new ClientCallback("gameChooseAbility", game.getId(), abilities)));
}
}
public void choosePile(final String message, final CardsView pile1, final CardsView pile2) {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.fireCallback(new ClientCallback("gameChoosePile", game.getId(), new GameClientMessage(message, pile1, pile2)));
}
UserManager.getInstance().getUser(userId).ifPresent(user ->
user.fireCallback(new ClientCallback("gameChoosePile", game.getId(), new GameClientMessage(message, pile1, pile2))));
}
}
public void chooseChoice(final Choice choice) {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.fireCallback(new ClientCallback("gameChooseChoice", game.getId(), new GameClientMessage(choice)));
}
UserManager.getInstance().getUser(userId).ifPresent(user ->
user.fireCallback(new ClientCallback("gameChooseChoice", game.getId(), new GameClientMessage(choice))));
}
}
public void playMana(final String message, final Map<String, Serializable> options) {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.fireCallback(new ClientCallback("gamePlayMana", game.getId(), new GameClientMessage(getGameView(), message, options)));
}
UserManager.getInstance().getUser(userId).ifPresent(user ->
user.fireCallback(new ClientCallback("gamePlayMana", game.getId(), new GameClientMessage(getGameView(), message, options))));
}
}
public void playXMana(final String message) {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.fireCallback(new ClientCallback("gamePlayXMana", game.getId(), new GameClientMessage(getGameView(), message)));
}
UserManager.getInstance().getUser(userId).ifPresent(user ->
user.fireCallback(new ClientCallback("gamePlayXMana", game.getId(), new GameClientMessage(getGameView(), message))));
}
}
public void getAmount(final String message, final int min, final int max) {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
UserManager.getInstance().getUser(userId).ifPresent(user -> {
user.fireCallback(new ClientCallback("gameSelectAmount", game.getId(), new GameClientMessage(message, min, max)));
}
});
}
}
public void endGameInfo(Table table) {
if (!killed) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.fireCallback(new ClientCallback("endGameInfo", game.getId(), getGameEndView(playerId, table)));
}
UserManager.getInstance().getUser(userId).ifPresent(user -> user.fireCallback(new ClientCallback("endGameInfo", game.getId(), getGameEndView(playerId, table))));
}
}
public void requestPermissionToRollbackTurn(UUID requestingUserId, int numberTurns) {
if (!killed) {
User requestingUser = UserManager.getInstance().getUser(requestingUserId);
User requestedUser = UserManager.getInstance().getUser(userId);
if (requestedUser != null && requestingUser != null) {
Optional<User> requestingUser = UserManager.getInstance().getUser(requestingUserId);
Optional<User> requestedUser = UserManager.getInstance().getUser(userId);
if (!requestedUser.isPresent() && !requestingUser.isPresent()) {
String message;
switch (numberTurns) {
case 0:
@ -185,30 +162,30 @@ public class GameSessionPlayer extends GameSessionWatcher {
message = "Allow to rollback " + numberTurns + " turns?";
}
UserRequestMessage userRequestMessage = new UserRequestMessage(
"Request by " + requestedUser.getName(), message);
userRequestMessage.setRelatedUser(requestingUserId, requestingUser.getName());
"Request by " + requestedUser.get().getName(), message);
userRequestMessage.setRelatedUser(requestingUserId, requestingUser.get().getName());
userRequestMessage.setGameId(game.getId());
userRequestMessage.setButton1("Accept", PlayerAction.ADD_PERMISSION_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) {
if (!killed) {
User watcher = UserManager.getInstance().getUser(watcherId);
User user = UserManager.getInstance().getUser(userId);
if (user != null && watcher != null) {
Optional<User> watcher = UserManager.getInstance().getUser(watcherId);
Optional<User> user = UserManager.getInstance().getUser(userId);
if (user.isPresent() && watcher.isPresent()) {
UserRequestMessage userRequestMessage = new UserRequestMessage(
"User request",
"Allow user <b>" + watcher.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.)");
userRequestMessage.setRelatedUser(watcherId, watcher.getName());
"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.)");
userRequestMessage.setRelatedUser(watcherId, watcher.get().getName());
userRequestMessage.setGameId(game.getId());
userRequestMessage.setButton1("Accept", PlayerAction.ADD_PERMISSION_TO_SEE_HAND_CARDS);
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() {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
user.removeGame(playerId);
}
UserManager.getInstance().getUser(userId).ifPresent(user -> user.removeGame(playerId));
}
public UUID getGameId() {

View file

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

View file

@ -50,7 +50,7 @@ public class ReplayManager {
public void replayGame(UUID gameId, UUID userId) {
ReplaySession replaySession = new ReplaySession(gameId, userId);
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) {

View file

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

View file

@ -27,9 +27,6 @@
*/
package mage.server.tournament;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import mage.MageException;
import mage.cards.decks.Deck;
import mage.constants.TableState;
@ -47,11 +44,7 @@ import mage.game.tournament.MultiplayerRound;
import mage.game.tournament.Tournament;
import mage.game.tournament.TournamentPairing;
import mage.game.tournament.TournamentPlayer;
import mage.server.ChatManager;
import mage.server.TableController;
import mage.server.TableManager;
import mage.server.User;
import mage.server.UserManager;
import mage.server.*;
import mage.server.draft.DraftController;
import mage.server.draft.DraftManager;
import mage.server.draft.DraftSession;
@ -63,8 +56,12 @@ import mage.view.ChatMessage.SoundToPlay;
import mage.view.TournamentView;
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
*/
public class TournamentController {
@ -159,10 +156,9 @@ public class TournamentController {
UUID playerId = userPlayerMap.get(userId);
if (playerId == null) {
if (logger.isDebugEnabled()) {
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
logger.debug(user.getName() + " shows tournament panel tournamentId: " + tournament.getId());
}
UserManager.getInstance().getUser(userId).ifPresent(user ->
logger.debug(user.getName() + " shows tournament panel tournamentId: " + tournament.getId()));
}
return;
}
@ -173,8 +169,9 @@ public class TournamentController {
// first join of player
TournamentSession tournamentSession = new TournamentSession(tournament, userId, tableId, playerId);
tournamentSessions.put(playerId, tournamentSession);
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
Optional<User> _user = UserManager.getInstance().getUser(userId);
if (_user.isPresent()) {
User user = _user.get();
user.addTournament(playerId, tournament.getId());
TournamentPlayer player = tournament.getPlayer(playerId);
player.setJoined();
@ -302,7 +299,7 @@ public class TournamentController {
}
private void initTournament() {
if (TableManager.getInstance().getTable(tableId).getState()!=TableState.DUELING) {
if (TableManager.getInstance().getTable(tableId).getState() != TableState.DUELING) {
TableManager.getInstance().initTournament(tableId);
}
}
@ -311,7 +308,7 @@ public class TournamentController {
if (tournamentSessions.containsKey(playerId)) {
TournamentSession tournamentSession = tournamentSessions.get(playerId);
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);
player.setState(TournamentPlayerState.CONSTRUCTING);
}
@ -340,10 +337,9 @@ public class TournamentController {
tournament.autoSubmit(userPlayerMap.get(userId), tournamentPlayer.generateDeck());
} else {
StringBuilder sb = new StringBuilder();
User user = UserManager.getInstance().getUser(userId);
if (user != null) {
sb.append(user.getName());
}
UserManager.getInstance().getUser(userId).ifPresent(user ->
sb.append(user.getName()));
sb.append(" - no deck found for auto submit");
logger.fatal(sb);
tournamentPlayer.setEliminated();
@ -385,7 +381,7 @@ public class TournamentController {
// quit active matches of that tournament
TableManager.getInstance().userQuitTournamentSubTables(tournament.getId(), userId);
status = TourneyQuitStatus.DURING_ROUND;
} else if (tournamentPlayer.getState()==TournamentPlayerState.DRAFTING) {
} else if (tournamentPlayer.getState() == TournamentPlayerState.DRAFTING) {
info = "during Draft phase";
if (!checkToReplaceDraftPlayerByAi(userId, tournamentPlayer)) {
this.abortDraftTournament();
@ -399,7 +395,7 @@ public class TournamentController {
}
}
status = TourneyQuitStatus.DURING_DRAFTING;
} else if (tournamentPlayer.getState()==TournamentPlayerState.CONSTRUCTING) {
} else if (tournamentPlayer.getState() == TournamentPlayerState.CONSTRUCTING) {
info = "during Construction phase";
status = TourneyQuitStatus.DURING_CONSTRUCTION;
} else {
@ -424,17 +420,17 @@ public class TournamentController {
// replace player that quits with draft bot
if (humans > 1) {
String replacePlayerName = "Draftbot";
User user = UserManager.getInstance().getUser(userId);
Optional<User> user = UserManager.getInstance().getUser(userId);
TableController tableController = TableManager.getInstance().getController(tableId);
if (tableController != null) {
if (user != null) {
replacePlayerName = "Draftbot (" + user.getName() + ")";
if (user.isPresent()) {
replacePlayerName = "Draftbot (" + user.get().getName() + ")";
}
tableController.replaceDraftPlayer(leavingPlayer.getPlayer(), replacePlayerName, "Computer - draftbot", 5);
if (user != null) {
user.removeDraft(leavingPlayer.getPlayer().getId());
user.removeTable(leavingPlayer.getPlayer().getId());
user.removeTournament(leavingPlayer.getPlayer().getId());
if (user.isPresent()) {
user.get().removeDraft(leavingPlayer.getPlayer().getId());
user.get().removeTable(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);
}
@ -501,8 +497,8 @@ public class TournamentController {
if (tournamentPlayer != null) {
if (!tournamentPlayer.hasQuit()) {
if (tournamentPlayer.getPlayer().isHuman()) {
User user = UserManager.getInstance().getUser(entry.getKey());
if (user == null) {
Optional<User> user = UserManager.getInstance().getUser(entry.getKey());
if (!user.isPresent()) {
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
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());
return false;
}

View file

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