mirror of
https://github.com/magefree/mage.git
synced 2025-12-23 20:11:59 -08:00
[refactoring][minor] Replaced all tabs with four spaces.
This commit is contained in:
parent
e646e4768d
commit
239a4fb100
2891 changed files with 79411 additions and 79411 deletions
|
|
@ -39,59 +39,59 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||
*/
|
||||
public class ChatManager {
|
||||
|
||||
private final static ChatManager INSTANCE = new ChatManager();
|
||||
private final static ChatManager INSTANCE = new ChatManager();
|
||||
|
||||
public static ChatManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static ChatManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private ChatManager() {}
|
||||
private ChatManager() {}
|
||||
|
||||
private ConcurrentHashMap<UUID, ChatSession> chatSessions = new ConcurrentHashMap<UUID, ChatSession>();
|
||||
private ConcurrentHashMap<UUID, ChatSession> chatSessions = new ConcurrentHashMap<UUID, ChatSession>();
|
||||
|
||||
public UUID createChatSession() {
|
||||
ChatSession chatSession = new ChatSession();
|
||||
chatSessions.put(chatSession.getChatId(), chatSession);
|
||||
return chatSession.getChatId();
|
||||
}
|
||||
public UUID createChatSession() {
|
||||
ChatSession chatSession = new ChatSession();
|
||||
chatSessions.put(chatSession.getChatId(), chatSession);
|
||||
return chatSession.getChatId();
|
||||
}
|
||||
|
||||
public void joinChat(UUID chatId, UUID userId) {
|
||||
chatSessions.get(chatId).join(userId);
|
||||
}
|
||||
public void joinChat(UUID chatId, UUID userId) {
|
||||
chatSessions.get(chatId).join(userId);
|
||||
}
|
||||
|
||||
public void leaveChat(UUID chatId, UUID userId) {
|
||||
chatSessions.get(chatId).kill(userId);
|
||||
}
|
||||
public void leaveChat(UUID chatId, UUID userId) {
|
||||
chatSessions.get(chatId).kill(userId);
|
||||
}
|
||||
|
||||
public void destroyChatSession(UUID chatId) {
|
||||
chatSessions.remove(chatId);
|
||||
}
|
||||
public void destroyChatSession(UUID chatId) {
|
||||
chatSessions.remove(chatId);
|
||||
}
|
||||
|
||||
public void broadcast(UUID chatId, String userName, String message, MessageColor color) {
|
||||
chatSessions.get(chatId).broadcast(userName, message, color);
|
||||
}
|
||||
public void broadcast(UUID chatId, String userName, String message, MessageColor color) {
|
||||
chatSessions.get(chatId).broadcast(userName, message, color);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* use mainly for announcing that a user connection was lost or that a user has reconnected
|
||||
*
|
||||
* @param userId
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
*
|
||||
* use mainly for announcing that a user connection was lost or that a user has reconnected
|
||||
*
|
||||
* @param userId
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void removeUser(UUID userId) {
|
||||
for (ChatSession chat: chatSessions.values()) {
|
||||
chat.kill(userId);
|
||||
}
|
||||
}
|
||||
public void removeUser(UUID userId) {
|
||||
for (ChatSession chat: chatSessions.values()) {
|
||||
chat.kill(userId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,58 +45,58 @@ import org.apache.log4j.Logger;
|
|||
*/
|
||||
public class ChatSession {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(ChatSession.class);
|
||||
private ConcurrentHashMap<UUID, String> clients = new ConcurrentHashMap<UUID, String>();
|
||||
private UUID chatId;
|
||||
private DateFormat timeFormatter = SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT);
|
||||
private final static Logger logger = Logger.getLogger(ChatSession.class);
|
||||
private ConcurrentHashMap<UUID, String> clients = new ConcurrentHashMap<UUID, String>();
|
||||
private UUID chatId;
|
||||
private DateFormat timeFormatter = SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT);
|
||||
|
||||
public ChatSession() {
|
||||
chatId = UUID.randomUUID();
|
||||
}
|
||||
public ChatSession() {
|
||||
chatId = UUID.randomUUID();
|
||||
}
|
||||
|
||||
public void join(UUID userId) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
String userName = user.getName();
|
||||
clients.put(userId, userName);
|
||||
broadcast(userName, " has joined", MessageColor.BLACK);
|
||||
logger.info(userName + " joined chat " + chatId);
|
||||
}
|
||||
}
|
||||
public void join(UUID userId) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
String userName = user.getName();
|
||||
clients.put(userId, userName);
|
||||
broadcast(userName, " has joined", MessageColor.BLACK);
|
||||
logger.info(userName + " joined chat " + chatId);
|
||||
}
|
||||
}
|
||||
|
||||
public void kill(UUID userId) {
|
||||
if (userId != null && clients.containsKey(userId)) {
|
||||
String userName = clients.get(userId);
|
||||
clients.remove(userId);
|
||||
broadcast(userName, " has left", MessageColor.BLACK);
|
||||
logger.info(userName + " has left chat " + chatId);
|
||||
}
|
||||
}
|
||||
public void kill(UUID userId) {
|
||||
if (userId != null && clients.containsKey(userId)) {
|
||||
String userName = clients.get(userId);
|
||||
clients.remove(userId);
|
||||
broadcast(userName, " has left", MessageColor.BLACK);
|
||||
logger.info(userName + " has left chat " + chatId);
|
||||
}
|
||||
}
|
||||
|
||||
public void broadcast(String userName, String message, MessageColor color) {
|
||||
Calendar cal = new GregorianCalendar();
|
||||
final String msg = message;
|
||||
final String time = timeFormatter.format(cal.getTime());
|
||||
final String username = userName;
|
||||
logger.debug("Broadcasting '" + msg + "' for " + chatId);
|
||||
for (UUID userId: clients.keySet()) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null)
|
||||
user.fireCallback(new ClientCallback("chatMessage", chatId, new ChatMessage(username, msg, time, color)));
|
||||
else
|
||||
kill(userId);
|
||||
}
|
||||
}
|
||||
public void broadcast(String userName, String message, MessageColor color) {
|
||||
Calendar cal = new GregorianCalendar();
|
||||
final String msg = message;
|
||||
final String time = timeFormatter.format(cal.getTime());
|
||||
final String username = userName;
|
||||
logger.debug("Broadcasting '" + msg + "' for " + chatId);
|
||||
for (UUID userId: clients.keySet()) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null)
|
||||
user.fireCallback(new ClientCallback("chatMessage", chatId, new ChatMessage(username, msg, time, color)));
|
||||
else
|
||||
kill(userId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the chatId
|
||||
*/
|
||||
public UUID getChatId() {
|
||||
return chatId;
|
||||
}
|
||||
/**
|
||||
* @return the chatId
|
||||
*/
|
||||
public UUID getChatId() {
|
||||
return chatId;
|
||||
}
|
||||
|
||||
public boolean hasUser(UUID userId) {
|
||||
return clients.containsKey(userId);
|
||||
}
|
||||
public boolean hasUser(UUID userId) {
|
||||
return clients.containsKey(userId);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -66,61 +66,61 @@ import java.util.concurrent.ExecutorService;
|
|||
*/
|
||||
public class MageServerImpl implements MageServer {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(MageServerImpl.class);
|
||||
private static ExecutorService callExecutor = ThreadExecutor.getInstance().getCallExecutor();
|
||||
private final static Logger logger = Logger.getLogger(MageServerImpl.class);
|
||||
private static ExecutorService callExecutor = ThreadExecutor.getInstance().getCallExecutor();
|
||||
|
||||
private String password;
|
||||
private boolean testMode;
|
||||
private String password;
|
||||
private boolean testMode;
|
||||
|
||||
public MageServerImpl(String password, boolean testMode) {
|
||||
this.password = password;
|
||||
this.testMode = testMode;
|
||||
ServerMessagesUtil.getInstance().getMessages();
|
||||
}
|
||||
public MageServerImpl(String password, boolean testMode) {
|
||||
this.password = password;
|
||||
this.testMode = testMode;
|
||||
ServerMessagesUtil.getInstance().getMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean registerClient(String userName, String sessionId, MageVersion version) throws MageException {
|
||||
try {
|
||||
if (version.compareTo(Main.getVersion()) != 0) {
|
||||
logger.info("MageVersionException: userName=" + userName + ", version=" + version);
|
||||
@Override
|
||||
public boolean registerClient(String userName, String sessionId, MageVersion version) throws MageException {
|
||||
try {
|
||||
if (version.compareTo(Main.getVersion()) != 0) {
|
||||
logger.info("MageVersionException: userName=" + userName + ", version=" + version);
|
||||
LogServiceImpl.instance.log(LogKeys.KEY_WRONG_VERSION, userName, version.toString(), Main.getVersion().toString(), sessionId);
|
||||
throw new MageVersionException(version, Main.getVersion());
|
||||
}
|
||||
return SessionManager.getInstance().registerUser(sessionId, userName);
|
||||
} catch (Exception ex) {
|
||||
throw new MageVersionException(version, Main.getVersion());
|
||||
}
|
||||
return SessionManager.getInstance().registerUser(sessionId, userName);
|
||||
} catch (Exception ex) {
|
||||
if (ex instanceof MageVersionException)
|
||||
throw (MageVersionException)ex;
|
||||
handleException(ex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
handleException(ex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setUserData(final String userName, final String sessionId, final UserDataView userDataView) throws MageException {
|
||||
@Override
|
||||
public boolean setUserData(final String userName, final String sessionId, final UserDataView userDataView) throws MageException {
|
||||
return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() {
|
||||
public Boolean execute() throws MageException {
|
||||
return SessionManager.getInstance().setUserData(userName, sessionId, userDataView);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean registerAdmin(String password, String sessionId, MageVersion version) throws MageException {
|
||||
try {
|
||||
if (version.compareTo(Main.getVersion()) != 0)
|
||||
throw new MageException("Wrong client version " + version + ", expecting version " + Main.getVersion());
|
||||
if (!password.equals(this.password))
|
||||
throw new MageException("Wrong password");
|
||||
return SessionManager.getInstance().registerAdmin(sessionId);
|
||||
} catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public boolean registerAdmin(String password, String sessionId, MageVersion version) throws MageException {
|
||||
try {
|
||||
if (version.compareTo(Main.getVersion()) != 0)
|
||||
throw new MageException("Wrong client version " + version + ", expecting version " + Main.getVersion());
|
||||
if (!password.equals(this.password))
|
||||
throw new MageException("Wrong password");
|
||||
return SessionManager.getInstance().registerAdmin(sessionId);
|
||||
} catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableView createTable(final String sessionId, final UUID roomId, final MatchOptions options) throws MageException {
|
||||
return executeWithResult("createTable", sessionId, new ActionWithTableViewResult() {
|
||||
@Override
|
||||
public TableView createTable(final String sessionId, final UUID roomId, final MatchOptions options) throws MageException {
|
||||
return executeWithResult("createTable", sessionId, new ActionWithTableViewResult() {
|
||||
public TableView execute() throws MageException {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
TableView table = GamesRoomManager.getInstance().getRoom(roomId).createTable(userId, options);
|
||||
|
|
@ -129,10 +129,10 @@ public class MageServerImpl implements MageServer {
|
|||
return table;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableView createTournamentTable(final String sessionId, final UUID roomId, final TournamentOptions options) throws MageException {
|
||||
@Override
|
||||
public TableView createTournamentTable(final String sessionId, final UUID roomId, final TournamentOptions options) throws MageException {
|
||||
return executeWithResult("createTournamentTable", sessionId, new ActionWithTableViewResult() {
|
||||
public TableView execute() throws MageException {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
|
|
@ -142,21 +142,21 @@ public class MageServerImpl implements MageServer {
|
|||
return table;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
|
||||
@Override
|
||||
public void removeTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
|
||||
execute("removeTable", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
TableManager.getInstance().removeTable(userId, tableId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean joinTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill, final DeckCardLists deckList) throws MageException, GameException {
|
||||
return executeWithResult("joinTable", sessionId, new ActionWithBooleanResult() {
|
||||
@Override
|
||||
public boolean joinTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill, final DeckCardLists deckList) throws MageException, GameException {
|
||||
return executeWithResult("joinTable", sessionId, new ActionWithBooleanResult() {
|
||||
public Boolean execute() throws MageException {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTable(userId, tableId, name, playerType, skill, deckList);
|
||||
|
|
@ -164,11 +164,11 @@ public class MageServerImpl implements MageServer {
|
|||
return ret;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean joinTournamentTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill) throws MageException, GameException {
|
||||
return executeWithResult("joinTournamentTable", sessionId, new ActionWithBooleanResult() {
|
||||
@Override
|
||||
public boolean joinTournamentTable(final String sessionId, final UUID roomId, final UUID tableId, final String name, final String playerType, final int skill) throws MageException, GameException {
|
||||
return executeWithResult("joinTournamentTable", sessionId, new ActionWithBooleanResult() {
|
||||
public Boolean execute() throws MageException {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
boolean ret = GamesRoomManager.getInstance().getRoom(roomId).joinTournamentTable(userId, tableId, name, playerType, skill);
|
||||
|
|
@ -176,106 +176,106 @@ public class MageServerImpl implements MageServer {
|
|||
return ret;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean submitDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) throws MageException, GameException {
|
||||
@Override
|
||||
public boolean submitDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) throws MageException, GameException {
|
||||
return executeWithResult("submitDeck", sessionId, new ActionWithBooleanResult() {
|
||||
public Boolean execute() throws MageException {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
boolean ret = TableManager.getInstance().submitDeck(userId, tableId, deckList);
|
||||
logger.info("Session " + sessionId + " submitted deck");
|
||||
return ret;
|
||||
boolean ret = TableManager.getInstance().submitDeck(userId, tableId, deckList);
|
||||
logger.info("Session " + sessionId + " submitted deck");
|
||||
return ret;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) throws MageException, GameException {
|
||||
execute("updateDeck", sessionId, new Action() {
|
||||
@Override
|
||||
public void updateDeck(final String sessionId, final UUID tableId, final DeckCardLists deckList) throws MageException, GameException {
|
||||
execute("updateDeck", sessionId, new Action() {
|
||||
public void execute() throws MageException {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
TableManager.getInstance().updateDeck(userId, tableId, deckList);
|
||||
logger.debug("Session " + sessionId + " updated deck");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
//FIXME: why no sessionId here???
|
||||
public List<TableView> getTables(UUID roomId) throws MageException {
|
||||
public List<TableView> getTables(UUID roomId) throws MageException {
|
||||
try {
|
||||
return GamesRoomManager.getInstance().getRoom(roomId).getTables();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
//FIXME: why no sessionId here???
|
||||
public List<MatchView> getFinishedMatches(UUID roomId) throws MageException {
|
||||
try {
|
||||
return GamesRoomManager.getInstance().getRoom(roomId).getFinished();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return GamesRoomManager.getInstance().getRoom(roomId).getTables();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
//FIXME: why no sessionId here???
|
||||
public List<String> getConnectedPlayers(UUID roomId) throws MageException {
|
||||
try {
|
||||
return GamesRoomManager.getInstance().getRoom(roomId).getPlayers();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public List<MatchView> getFinishedMatches(UUID roomId) throws MageException {
|
||||
try {
|
||||
return GamesRoomManager.getInstance().getRoom(roomId).getFinished();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
//FIXME: why no sessionId here???
|
||||
public TableView getTable(UUID roomId, UUID tableId) throws MageException {
|
||||
try {
|
||||
return GamesRoomManager.getInstance().getRoom(roomId).getTable(tableId);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<String> getConnectedPlayers(UUID roomId) throws MageException {
|
||||
try {
|
||||
return GamesRoomManager.getInstance().getRoom(roomId).getPlayers();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
//FIXME: why no sessionId here???
|
||||
public TableView getTable(UUID roomId, UUID tableId) throws MageException {
|
||||
try {
|
||||
return GamesRoomManager.getInstance().getRoom(roomId).getTable(tableId);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean ping(String sessionId) {
|
||||
return SessionManager.getInstance().extendUserSession(sessionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deregisterClient(final String sessionId) throws MageException {
|
||||
execute("deregisterClient", sessionId, new Action() {
|
||||
@Override
|
||||
public void deregisterClient(final String sessionId) throws MageException {
|
||||
execute("deregisterClient", sessionId, new Action() {
|
||||
public void execute() {
|
||||
SessionManager.getInstance().disconnect(sessionId, true);
|
||||
logger.info("Client deregistered ...");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startMatch(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
|
||||
@Override
|
||||
public void startMatch(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
|
||||
execute("startMatch", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
TableManager.getInstance().startMatch(userId, roomId, tableId);
|
||||
TableManager.getInstance().startMatch(userId, roomId, tableId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startChallenge(final String sessionId, final UUID roomId, final UUID tableId, final UUID challengeId) throws MageException {
|
||||
@Override
|
||||
public void startChallenge(final String sessionId, final UUID roomId, final UUID tableId, final UUID challengeId) throws MageException {
|
||||
execute("startChallenge", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
|
|
@ -284,185 +284,185 @@ public class MageServerImpl implements MageServer {
|
|||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startTournament(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
|
||||
@Override
|
||||
public void startTournament(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
|
||||
execute("startTournament", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
TableManager.getInstance().startTournament(userId, roomId, tableId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
//FIXME: why no sessionId here???
|
||||
public TournamentView getTournament(UUID tournamentId) throws MageException {
|
||||
try {
|
||||
return TournamentManager.getInstance().getTournamentView(tournamentId);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public TournamentView getTournament(UUID tournamentId) throws MageException {
|
||||
try {
|
||||
return TournamentManager.getInstance().getTournamentView(tournamentId);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
//FIXME: why no sessionId here???
|
||||
public void sendChatMessage(final UUID chatId, final String userName, final String message) throws MageException {
|
||||
try {
|
||||
callExecutor.execute(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
ChatManager.getInstance().broadcast(chatId, userName, message, MessageColor.BLUE);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
}
|
||||
public void sendChatMessage(final UUID chatId, final String userName, final String message) throws MageException {
|
||||
try {
|
||||
callExecutor.execute(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
ChatManager.getInstance().broadcast(chatId, userName, message, MessageColor.BLUE);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void joinChat(final UUID chatId, final String sessionId, final String userName) throws MageException {
|
||||
@Override
|
||||
public void joinChat(final UUID chatId, final String sessionId, final String userName) throws MageException {
|
||||
execute("joinChat", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
ChatManager.getInstance().joinChat(chatId, userId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void leaveChat(final UUID chatId, final String sessionId) throws MageException {
|
||||
@Override
|
||||
public void leaveChat(final UUID chatId, final String sessionId) throws MageException {
|
||||
execute("leaveChat", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
ChatManager.getInstance().leaveChat(chatId, userId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
//FIXME: why no sessionId here???
|
||||
public UUID getMainRoomId() throws MageException {
|
||||
try {
|
||||
return GamesRoomManager.getInstance().getMainRoomId();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public UUID getMainRoomId() throws MageException {
|
||||
try {
|
||||
return GamesRoomManager.getInstance().getMainRoomId();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
//FIXME: why no sessionId here???
|
||||
public UUID getRoomChatId(UUID roomId) throws MageException {
|
||||
try {
|
||||
return GamesRoomManager.getInstance().getRoom(roomId).getChatId();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public UUID getRoomChatId(UUID roomId) throws MageException {
|
||||
try {
|
||||
return GamesRoomManager.getInstance().getRoom(roomId).getChatId();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTableOwner(final String sessionId, UUID roomId, final UUID tableId) throws MageException {
|
||||
return executeWithResult("isTableOwner", sessionId, new ActionWithBooleanResult() {
|
||||
@Override
|
||||
public boolean isTableOwner(final String sessionId, UUID roomId, final UUID tableId) throws MageException {
|
||||
return executeWithResult("isTableOwner", sessionId, new ActionWithBooleanResult() {
|
||||
public Boolean execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
return TableManager.getInstance().isTableOwner(tableId, userId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void swapSeats(final String sessionId, final UUID roomId, final UUID tableId, final int seatNum1, final int seatNum2) throws MageException {
|
||||
@Override
|
||||
public void swapSeats(final String sessionId, final UUID roomId, final UUID tableId, final int seatNum1, final int seatNum2) throws MageException {
|
||||
execute("swapSeats", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
TableManager.getInstance().swapSeats(tableId, userId, seatNum1, seatNum2);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void leaveTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
|
||||
@Override
|
||||
public void leaveTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
|
||||
execute("leaveTable", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
GamesRoomManager.getInstance().getRoom(roomId).leaveTable(userId, tableId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
//FIXME: why no sessionId here???
|
||||
public UUID getTableChatId(UUID tableId) throws MageException {
|
||||
try {
|
||||
return TableManager.getInstance().getChatId(tableId);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public UUID getTableChatId(UUID tableId) throws MageException {
|
||||
try {
|
||||
return TableManager.getInstance().getChatId(tableId);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void joinGame(final UUID gameId, final String sessionId) throws MageException {
|
||||
@Override
|
||||
public void joinGame(final UUID gameId, final String sessionId) throws MageException {
|
||||
execute("joinGame", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
GameManager.getInstance().joinGame(gameId, userId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void joinDraft(final UUID draftId, final String sessionId) throws MageException {
|
||||
@Override
|
||||
public void joinDraft(final UUID draftId, final String sessionId) throws MageException {
|
||||
execute("joinDraft", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
DraftManager.getInstance().joinDraft(draftId, userId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void joinTournament(final UUID tournamentId, final String sessionId) throws MageException {
|
||||
@Override
|
||||
public void joinTournament(final UUID tournamentId, final String sessionId) throws MageException {
|
||||
execute("joinTournament", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
TournamentManager.getInstance().joinTournament(tournamentId, userId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
//FIXME: why no sessionId here???
|
||||
public UUID getGameChatId(UUID gameId) throws MageException {
|
||||
try {
|
||||
return GameManager.getInstance().getChatId(gameId);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public UUID getGameChatId(UUID gameId) throws MageException {
|
||||
try {
|
||||
return GameManager.getInstance().getChatId(gameId);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
//FIXME: why no sessionId here???
|
||||
public UUID getTournamentChatId(UUID tournamentId) throws MageException {
|
||||
try {
|
||||
return TournamentManager.getInstance().getChatId(tournamentId);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public UUID getTournamentChatId(UUID tournamentId) throws MageException {
|
||||
try {
|
||||
return TournamentManager.getInstance().getChatId(tournamentId);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendPlayerUUID(final UUID gameId, final String sessionId, final UUID data) throws MageException {
|
||||
|
|
@ -474,7 +474,7 @@ public class MageServerImpl implements MageServer {
|
|||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
public void sendPlayerString(final UUID gameId, final String sessionId, final String data) throws MageException {
|
||||
execute("sendPlayerString", sessionId, new Action() {
|
||||
public void execute() {
|
||||
|
|
@ -482,20 +482,20 @@ public class MageServerImpl implements MageServer {
|
|||
user.sendPlayerString(gameId, data);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendPlayerBoolean(final UUID gameId, final String sessionId, final Boolean data) throws MageException {
|
||||
@Override
|
||||
public void sendPlayerBoolean(final UUID gameId, final String sessionId, final Boolean data) throws MageException {
|
||||
execute("sendPlayerBoolean", sessionId, new Action() {
|
||||
public void execute() {
|
||||
User user = SessionManager.getInstance().getUser(sessionId);
|
||||
user.sendPlayerBoolean(gameId, data);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendPlayerInteger(final UUID gameId, final String sessionId, final Integer data) throws MageException {
|
||||
@Override
|
||||
public void sendPlayerInteger(final UUID gameId, final String sessionId, final Integer data) throws MageException {
|
||||
execute("sendPlayerInteger", sessionId, new Action() {
|
||||
public void execute() {
|
||||
User user = SessionManager.getInstance().getUser(sessionId);
|
||||
|
|
@ -504,15 +504,15 @@ public class MageServerImpl implements MageServer {
|
|||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public DraftPickView sendCardPick(final UUID draftId, final String sessionId, final UUID cardPick) throws MageException {
|
||||
return executeWithResult("sendCardPick", sessionId, new ActionWithNullNegativeResult<DraftPickView>() {
|
||||
@Override
|
||||
public DraftPickView sendCardPick(final UUID draftId, final String sessionId, final UUID cardPick) throws MageException {
|
||||
return executeWithResult("sendCardPick", sessionId, new ActionWithNullNegativeResult<DraftPickView>() {
|
||||
public DraftPickView execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
return DraftManager.getInstance().sendCardPick(draftId, userId, cardPick);
|
||||
return DraftManager.getInstance().sendCardPick(draftId, userId, cardPick);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void concedeGame(final UUID gameId, final String sessionId) throws MageException {
|
||||
|
|
@ -524,15 +524,15 @@ public class MageServerImpl implements MageServer {
|
|||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean watchTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
|
||||
return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() {
|
||||
@Override
|
||||
public boolean watchTable(final String sessionId, final UUID roomId, final UUID tableId) throws MageException {
|
||||
return executeWithResult("setUserData", sessionId, new ActionWithBooleanResult() {
|
||||
public Boolean execute() throws MageException {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
return GamesRoomManager.getInstance().getRoom(roomId).watchTable(userId, tableId);
|
||||
return GamesRoomManager.getInstance().getRoom(roomId).watchTable(userId, tableId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void watchGame(final UUID gameId, final String sessionId) throws MageException {
|
||||
|
|
@ -554,15 +554,15 @@ public class MageServerImpl implements MageServer {
|
|||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void replayGame(final UUID gameId, final String sessionId) throws MageException {
|
||||
@Override
|
||||
public void replayGame(final UUID gameId, final String sessionId) throws MageException {
|
||||
execute("replayGame", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
ReplayManager.getInstance().replayGame(gameId, userId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startReplay(final UUID gameId, final String sessionId) throws MageException {
|
||||
|
|
@ -574,17 +574,17 @@ public class MageServerImpl implements MageServer {
|
|||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopReplay(final UUID gameId, final String sessionId) throws MageException {
|
||||
@Override
|
||||
public void stopReplay(final UUID gameId, final String sessionId) throws MageException {
|
||||
execute("stopReplay", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
ReplayManager.getInstance().stopReplay(gameId, userId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
public void nextPlay(final UUID gameId, final String sessionId) throws MageException {
|
||||
execute("nextPlay", sessionId, new Action() {
|
||||
public void execute() {
|
||||
|
|
@ -594,15 +594,15 @@ public class MageServerImpl implements MageServer {
|
|||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void previousPlay(final UUID gameId, final String sessionId) throws MageException {
|
||||
@Override
|
||||
public void previousPlay(final UUID gameId, final String sessionId) throws MageException {
|
||||
execute("previousPlay", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
ReplayManager.getInstance().previousPlay(gameId, userId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void skipForward(final UUID gameId, final String sessionId, final int moves) throws MageException {
|
||||
|
|
@ -616,21 +616,21 @@ public class MageServerImpl implements MageServer {
|
|||
|
||||
@Override
|
||||
//TODO: check how often it is used
|
||||
public ServerState getServerState() throws MageException {
|
||||
try {
|
||||
return new ServerState(
|
||||
GameFactory.getInstance().getGameTypes(),
|
||||
TournamentFactory.getInstance().getTournamentTypes(),
|
||||
PlayerFactory.getInstance().getPlayerTypes().toArray(new String[0]),
|
||||
DeckValidatorFactory.getInstance().getDeckTypes().toArray(new String[0]),
|
||||
testMode,
|
||||
Main.getVersion());
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public ServerState getServerState() throws MageException {
|
||||
try {
|
||||
return new ServerState(
|
||||
GameFactory.getInstance().getGameTypes(),
|
||||
TournamentFactory.getInstance().getTournamentTypes(),
|
||||
PlayerFactory.getInstance().getPlayerTypes().toArray(new String[0]),
|
||||
DeckValidatorFactory.getInstance().getDeckTypes().toArray(new String[0]),
|
||||
testMode,
|
||||
Main.getVersion());
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cheat(final UUID gameId, final String sessionId, final UUID playerId, final DeckCardLists deckList) throws MageException {
|
||||
|
|
@ -645,7 +645,7 @@ public class MageServerImpl implements MageServer {
|
|||
}
|
||||
|
||||
@Override
|
||||
public boolean cheat(final UUID gameId, final String sessionId, final UUID playerId, final String cardName) throws MageException {
|
||||
public boolean cheat(final UUID gameId, final String sessionId, final UUID playerId, final String cardName) throws MageException {
|
||||
return executeWithResult("cheatOne", sessionId, new ActionWithBooleanResult() {
|
||||
public Boolean execute() {
|
||||
if (testMode) {
|
||||
|
|
@ -655,16 +655,16 @@ public class MageServerImpl implements MageServer {
|
|||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void handleException(Exception ex) throws MageException {
|
||||
logger.fatal("", ex);
|
||||
throw new MageException("Server error: " + ex.getMessage());
|
||||
}
|
||||
public void handleException(Exception ex) throws MageException {
|
||||
logger.fatal("", ex);
|
||||
throw new MageException("Server error: " + ex.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
public GameView getGameView(final UUID gameId, final String sessionId, final UUID playerId) throws MageException {
|
||||
return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult<GameView>() {
|
||||
return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult<GameView>() {
|
||||
public GameView execute() throws MageException {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
return GameManager.getInstance().getGameView(gameId, userId, playerId);
|
||||
|
|
@ -672,8 +672,8 @@ public class MageServerImpl implements MageServer {
|
|||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UserView> getUsers(String sessionId) throws MageException {
|
||||
@Override
|
||||
public List<UserView> getUsers(String sessionId) throws MageException {
|
||||
return executeWithResult("getUsers", sessionId, new ActionWithNullNegativeResult<List<UserView>>() {
|
||||
public List<UserView> execute() throws MageException {
|
||||
List<UserView> users = new ArrayList<UserView>();
|
||||
|
|
@ -683,35 +683,35 @@ public class MageServerImpl implements MageServer {
|
|||
return users;
|
||||
}
|
||||
}, true);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnectUser(final String sessionId, final String userSessionId) throws MageException {
|
||||
@Override
|
||||
public void disconnectUser(final String sessionId, final String userSessionId) throws MageException {
|
||||
execute("disconnectUser", sessionId, new Action() {
|
||||
public void execute() {
|
||||
SessionManager.getInstance().disconnectUser(sessionId, userSessionId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTable(final String sessionId, final UUID tableId) throws MageException {
|
||||
@Override
|
||||
public void removeTable(final String sessionId, final UUID tableId) throws MageException {
|
||||
execute("removeTable", sessionId, new Action() {
|
||||
public void execute() {
|
||||
UUID userId = SessionManager.getInstance().getSession(sessionId).getUserId();
|
||||
TableManager.getInstance().removeTable(userId, tableId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getServerMessagesCompressed(String sessionId) throws MageException {
|
||||
return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult<Object>() {
|
||||
@Override
|
||||
public Object getServerMessagesCompressed(String sessionId) throws MageException {
|
||||
return executeWithResult("getGameView", sessionId, new ActionWithNullNegativeResult<Object>() {
|
||||
public Object execute() throws MageException {
|
||||
return CompressUtil.compress(ServerMessagesUtil.getInstance().getMessages());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendFeedbackMessage(final String sessionId, final String username, final String title, final String type, final String message, final String email) throws MageException {
|
||||
|
|
@ -754,11 +754,11 @@ public class MageServerImpl implements MageServer {
|
|||
|
||||
protected void execute(final String actionName, final String sessionId, final Action action) throws MageException {
|
||||
if (SessionManager.getInstance().isValidSession(sessionId)) {
|
||||
try {
|
||||
callExecutor.execute(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
callExecutor.execute(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (SessionManager.getInstance().isValidSession(sessionId)) {
|
||||
try {
|
||||
action.execute();
|
||||
|
|
@ -768,14 +768,14 @@ public class MageServerImpl implements MageServer {
|
|||
} else {
|
||||
LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION_INTERNAL, actionName, sessionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
} else {
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
} else {
|
||||
LogServiceImpl.instance.log(LogKeys.KEY_NOT_VALID_SESSION, actionName, sessionId);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -66,51 +66,51 @@ import java.util.Map;
|
|||
*/
|
||||
public class Main {
|
||||
|
||||
private static Logger logger = Logger.getLogger(Main.class);
|
||||
private static Logger logger = Logger.getLogger(Main.class);
|
||||
|
||||
private final static String testModeArg = "-testMode=";
|
||||
private final static String adminPasswordArg = "-adminPassword=";
|
||||
private final static String pluginFolder = "plugins";
|
||||
private static MageVersion version = new MageVersion(0, 8, 6, "r5");
|
||||
private final static String testModeArg = "-testMode=";
|
||||
private final static String adminPasswordArg = "-adminPassword=";
|
||||
private final static String pluginFolder = "plugins";
|
||||
private static MageVersion version = new MageVersion(0, 8, 6, "r5");
|
||||
|
||||
public static PluginClassLoader classLoader = new PluginClassLoader();
|
||||
public static TransporterServer server;
|
||||
protected static boolean testMode;
|
||||
public static PluginClassLoader classLoader = new PluginClassLoader();
|
||||
public static TransporterServer server;
|
||||
protected static boolean testMode;
|
||||
/**
|
||||
* @param args the command line arguments
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
|
||||
logger.info("Starting MAGE server version " + version);
|
||||
logger.info("Logging level: " + logger.getEffectiveLevel());
|
||||
deleteSavedGames();
|
||||
ConfigSettings config = ConfigSettings.getInstance();
|
||||
for (GamePlugin plugin: config.getGameTypes()) {
|
||||
GameFactory.getInstance().addGameType(plugin.getName(), loadGameType(plugin), loadPlugin(plugin));
|
||||
}
|
||||
for (GamePlugin plugin: config.getTournamentTypes()) {
|
||||
TournamentFactory.getInstance().addTournamentType(plugin.getName(), loadTournamentType(plugin), loadPlugin(plugin));
|
||||
}
|
||||
for (Plugin plugin: config.getPlayerTypes()) {
|
||||
PlayerFactory.getInstance().addPlayerType(plugin.getName(), loadPlugin(plugin));
|
||||
}
|
||||
for (Plugin plugin: config.getDeckTypes()) {
|
||||
DeckValidatorFactory.getInstance().addDeckType(plugin.getName(), loadPlugin(plugin));
|
||||
}
|
||||
String adminPassword = "";
|
||||
for (String arg: args) {
|
||||
if (arg.startsWith(testModeArg)) {
|
||||
testMode = Boolean.valueOf(arg.replace(testModeArg, ""));
|
||||
}
|
||||
else if (arg.startsWith(adminPasswordArg)) {
|
||||
adminPassword = arg.replace(adminPasswordArg, "");
|
||||
}
|
||||
}
|
||||
Connection connection = new Connection();
|
||||
connection.setHost(config.getServerAddress());
|
||||
connection.setPort(config.getPort());
|
||||
try {
|
||||
InvokerLocator serverLocator = new InvokerLocator(connection.getURI());
|
||||
logger.info("Starting MAGE server version " + version);
|
||||
logger.info("Logging level: " + logger.getEffectiveLevel());
|
||||
deleteSavedGames();
|
||||
ConfigSettings config = ConfigSettings.getInstance();
|
||||
for (GamePlugin plugin: config.getGameTypes()) {
|
||||
GameFactory.getInstance().addGameType(plugin.getName(), loadGameType(plugin), loadPlugin(plugin));
|
||||
}
|
||||
for (GamePlugin plugin: config.getTournamentTypes()) {
|
||||
TournamentFactory.getInstance().addTournamentType(plugin.getName(), loadTournamentType(plugin), loadPlugin(plugin));
|
||||
}
|
||||
for (Plugin plugin: config.getPlayerTypes()) {
|
||||
PlayerFactory.getInstance().addPlayerType(plugin.getName(), loadPlugin(plugin));
|
||||
}
|
||||
for (Plugin plugin: config.getDeckTypes()) {
|
||||
DeckValidatorFactory.getInstance().addDeckType(plugin.getName(), loadPlugin(plugin));
|
||||
}
|
||||
String adminPassword = "";
|
||||
for (String arg: args) {
|
||||
if (arg.startsWith(testModeArg)) {
|
||||
testMode = Boolean.valueOf(arg.replace(testModeArg, ""));
|
||||
}
|
||||
else if (arg.startsWith(adminPasswordArg)) {
|
||||
adminPassword = arg.replace(adminPasswordArg, "");
|
||||
}
|
||||
}
|
||||
Connection connection = new Connection();
|
||||
connection.setHost(config.getServerAddress());
|
||||
connection.setPort(config.getPort());
|
||||
try {
|
||||
InvokerLocator serverLocator = new InvokerLocator(connection.getURI());
|
||||
if (!isAlreadyRunning(serverLocator)) {
|
||||
server = new MageTransporterServer(serverLocator, new MageServerImpl(adminPassword, testMode), MageServer.class.getName(), new MageServerInvocationHandler());
|
||||
server.start();
|
||||
|
|
@ -122,11 +122,11 @@ public class Main {
|
|||
else {
|
||||
logger.fatal("Unable to start MAGE server - another server is already started");
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
logger.fatal("Failed to start server - " + connection.toString(), ex);
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("Failed to start server - " + connection.toString(), ex);
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
logger.fatal("Failed to start server - " + connection.toString(), ex);
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("Failed to start server - " + connection.toString(), ex);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -136,8 +136,8 @@ public class Main {
|
|||
|
||||
static boolean isAlreadyRunning(InvokerLocator serverLocator) {
|
||||
Map<String, String> metadata = new HashMap<String, String>();
|
||||
metadata.put(SocketWrapper.WRITE_TIMEOUT, "2000");
|
||||
metadata.put("generalizeSocketException", "true");
|
||||
metadata.put(SocketWrapper.WRITE_TIMEOUT, "2000");
|
||||
metadata.put("generalizeSocketException", "true");
|
||||
try {
|
||||
MageServer testServer = (MageServer) TransporterClient.createTransporterClient(serverLocator.getLocatorURI(), MageServer.class, metadata);
|
||||
if (testServer != null) {
|
||||
|
|
@ -149,64 +149,64 @@ public class Main {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static class ClientConnectionListener implements ConnectionListener {
|
||||
@Override
|
||||
public void handleConnectionException(Throwable throwable, Client client) {
|
||||
Session session = SessionManager.getInstance().getSession(client.getSessionId());
|
||||
if (session != null) {
|
||||
String sessionName;
|
||||
User user = UserManager.getInstance().getUser(session.getUserId());
|
||||
if (user != null)
|
||||
sessionName = user.getName() + " at " + session.getHost();
|
||||
else
|
||||
sessionName = session.getHost();
|
||||
if (throwable instanceof ClientDisconnectedException) {
|
||||
SessionManager.getInstance().disconnect(client.getSessionId(), false);
|
||||
logger.info("client disconnected - " + sessionName);
|
||||
}
|
||||
else {
|
||||
SessionManager.getInstance().disconnect(client.getSessionId(), false);
|
||||
logger.info("connection to client lost - " + sessionName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static class MageTransporterServer extends TransporterServer {
|
||||
|
||||
protected Connector connector;
|
||||
|
||||
public MageTransporterServer(InvokerLocator locator, Object target, String subsystem, MageServerInvocationHandler callback) throws Exception {
|
||||
super(locator, target, subsystem);
|
||||
connector.addInvocationHandler("callback", callback);
|
||||
connector.setLeasePeriod(5000);
|
||||
connector.addConnectionListener(new ClientConnectionListener());
|
||||
}
|
||||
|
||||
public Connector getConnector() throws Exception {
|
||||
return connector;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Connector getConnector(InvokerLocator locator, Map config, Element xmlConfig) throws Exception {
|
||||
Connector c = super.getConnector(locator, config, xmlConfig);
|
||||
this.connector = c;
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
static class MageServerInvocationHandler implements ServerInvocationHandler {
|
||||
static class ClientConnectionListener implements ConnectionListener {
|
||||
@Override
|
||||
public void handleConnectionException(Throwable throwable, Client client) {
|
||||
Session session = SessionManager.getInstance().getSession(client.getSessionId());
|
||||
if (session != null) {
|
||||
String sessionName;
|
||||
User user = UserManager.getInstance().getUser(session.getUserId());
|
||||
if (user != null)
|
||||
sessionName = user.getName() + " at " + session.getHost();
|
||||
else
|
||||
sessionName = session.getHost();
|
||||
if (throwable instanceof ClientDisconnectedException) {
|
||||
SessionManager.getInstance().disconnect(client.getSessionId(), false);
|
||||
logger.info("client disconnected - " + sessionName);
|
||||
}
|
||||
else {
|
||||
SessionManager.getInstance().disconnect(client.getSessionId(), false);
|
||||
logger.info("connection to client lost - " + sessionName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMBeanServer(MBeanServer server) {}
|
||||
static class MageTransporterServer extends TransporterServer {
|
||||
|
||||
@Override
|
||||
public void setInvoker(ServerInvoker invoker) {}
|
||||
protected Connector connector;
|
||||
|
||||
@Override
|
||||
public Object invoke(final InvocationRequest invocation) throws Throwable {
|
||||
String sessionId = invocation.getSessionId();
|
||||
public MageTransporterServer(InvokerLocator locator, Object target, String subsystem, MageServerInvocationHandler callback) throws Exception {
|
||||
super(locator, target, subsystem);
|
||||
connector.addInvocationHandler("callback", callback);
|
||||
connector.setLeasePeriod(5000);
|
||||
connector.addConnectionListener(new ClientConnectionListener());
|
||||
}
|
||||
|
||||
public Connector getConnector() throws Exception {
|
||||
return connector;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Connector getConnector(InvokerLocator locator, Map config, Element xmlConfig) throws Exception {
|
||||
Connector c = super.getConnector(locator, config, xmlConfig);
|
||||
this.connector = c;
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
static class MageServerInvocationHandler implements ServerInvocationHandler {
|
||||
|
||||
@Override
|
||||
public void setMBeanServer(MBeanServer server) {}
|
||||
|
||||
@Override
|
||||
public void setInvoker(ServerInvoker invoker) {}
|
||||
|
||||
@Override
|
||||
public Object invoke(final InvocationRequest invocation) throws Throwable {
|
||||
String sessionId = invocation.getSessionId();
|
||||
Map map = invocation.getRequestPayload();
|
||||
String host;
|
||||
if (map != null) {
|
||||
|
|
@ -216,92 +216,92 @@ public class Main {
|
|||
host = "localhost";
|
||||
}
|
||||
SessionManager.getInstance().getSession(sessionId).setHost(host);
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addListener(InvokerCallbackHandler callbackHandler) {
|
||||
ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler;
|
||||
try {
|
||||
String sessionId = handler.getClientSessionId();
|
||||
SessionManager.getInstance().createSession(sessionId, callbackHandler);
|
||||
} catch (Throwable ex) {
|
||||
logger.fatal("", ex);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void addListener(InvokerCallbackHandler callbackHandler) {
|
||||
ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler;
|
||||
try {
|
||||
String sessionId = handler.getClientSessionId();
|
||||
SessionManager.getInstance().createSession(sessionId, callbackHandler);
|
||||
} catch (Throwable ex) {
|
||||
logger.fatal("", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeListener(InvokerCallbackHandler callbackHandler) {
|
||||
logger.fatal("removeListener called");
|
||||
// ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler;
|
||||
// String sessionId = handler.getCallbackClient().getSessionId();
|
||||
// SessionManager.getInstance().disconnect(sessionId);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static Class<?> loadPlugin(Plugin plugin) {
|
||||
try {
|
||||
classLoader.addURL(new File(pluginFolder + "/" + plugin.getJar()).toURI().toURL());
|
||||
logger.info("Loading plugin: " + plugin.getClassName());
|
||||
return Class.forName(plugin.getClassName(), true, classLoader);
|
||||
} catch (ClassNotFoundException ex) {
|
||||
logger.warn("Plugin not Found:" + plugin.getJar() + " - check plugin folder");
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("Error loading plugin " + plugin.getJar(), ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public void removeListener(InvokerCallbackHandler callbackHandler) {
|
||||
logger.fatal("removeListener called");
|
||||
// ServerInvokerCallbackHandler handler = (ServerInvokerCallbackHandler) callbackHandler;
|
||||
// String sessionId = handler.getCallbackClient().getSessionId();
|
||||
// SessionManager.getInstance().disconnect(sessionId);
|
||||
}
|
||||
|
||||
private static MatchType loadGameType(GamePlugin plugin) {
|
||||
try {
|
||||
classLoader.addURL(new File(pluginFolder + "/" + plugin.getJar()).toURI().toURL());
|
||||
logger.info("Loading game type: " + plugin.getClassName());
|
||||
return (MatchType) Class.forName(plugin.getTypeName(), true, classLoader).newInstance();
|
||||
} catch (ClassNotFoundException ex) {
|
||||
logger.warn("Game type not found:" + plugin.getJar() + " - check plugin folder");
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("Error loading game type " + plugin.getJar(), ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static TournamentType loadTournamentType(GamePlugin plugin) {
|
||||
try {
|
||||
classLoader.addURL(new File(pluginFolder + "/" + plugin.getJar()).toURI().toURL());
|
||||
logger.info("Loading tournament type: " + plugin.getClassName());
|
||||
return (TournamentType) Class.forName(plugin.getTypeName(), true, classLoader).newInstance();
|
||||
} catch (ClassNotFoundException ex) {
|
||||
logger.warn("Tournament type not found:" + plugin.getJar() + " - check plugin folder");
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("Error loading game type " + plugin.getJar(), ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
private static Class<?> loadPlugin(Plugin plugin) {
|
||||
try {
|
||||
classLoader.addURL(new File(pluginFolder + "/" + plugin.getJar()).toURI().toURL());
|
||||
logger.info("Loading plugin: " + plugin.getClassName());
|
||||
return Class.forName(plugin.getClassName(), true, classLoader);
|
||||
} catch (ClassNotFoundException ex) {
|
||||
logger.warn("Plugin not Found:" + plugin.getJar() + " - check plugin folder");
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("Error loading plugin " + plugin.getJar(), ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void deleteSavedGames() {
|
||||
File directory = new File("saved/");
|
||||
if (!directory.exists())
|
||||
directory.mkdirs();
|
||||
File[] files = directory.listFiles(
|
||||
new FilenameFilter() {
|
||||
@Override
|
||||
public boolean accept(File dir, String name) {
|
||||
return name.endsWith(".game");
|
||||
}
|
||||
}
|
||||
);
|
||||
for (File file : files)
|
||||
{
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
private static MatchType loadGameType(GamePlugin plugin) {
|
||||
try {
|
||||
classLoader.addURL(new File(pluginFolder + "/" + plugin.getJar()).toURI().toURL());
|
||||
logger.info("Loading game type: " + plugin.getClassName());
|
||||
return (MatchType) Class.forName(plugin.getTypeName(), true, classLoader).newInstance();
|
||||
} catch (ClassNotFoundException ex) {
|
||||
logger.warn("Game type not found:" + plugin.getJar() + " - check plugin folder");
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("Error loading game type " + plugin.getJar(), ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static MageVersion getVersion() {
|
||||
return version;
|
||||
}
|
||||
private static TournamentType loadTournamentType(GamePlugin plugin) {
|
||||
try {
|
||||
classLoader.addURL(new File(pluginFolder + "/" + plugin.getJar()).toURI().toURL());
|
||||
logger.info("Loading tournament type: " + plugin.getClassName());
|
||||
return (TournamentType) Class.forName(plugin.getTypeName(), true, classLoader).newInstance();
|
||||
} catch (ClassNotFoundException ex) {
|
||||
logger.warn("Tournament type not found:" + plugin.getJar() + " - check plugin folder");
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("Error loading game type " + plugin.getJar(), ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean isTestMode() {
|
||||
return testMode;
|
||||
}
|
||||
private static void deleteSavedGames() {
|
||||
File directory = new File("saved/");
|
||||
if (!directory.exists())
|
||||
directory.mkdirs();
|
||||
File[] files = directory.listFiles(
|
||||
new FilenameFilter() {
|
||||
@Override
|
||||
public boolean accept(File dir, String name) {
|
||||
return name.endsWith(".game");
|
||||
}
|
||||
}
|
||||
);
|
||||
for (File file : files)
|
||||
{
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
|
||||
public static MageVersion getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public static boolean isTestMode() {
|
||||
return testMode;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,6 +36,6 @@ import java.util.UUID;
|
|||
* @author BetaSteward_at_googlemail.com
|
||||
*/
|
||||
public interface Room extends Remote {
|
||||
public UUID getChatId();
|
||||
public UUID getRoomId();
|
||||
public UUID getChatId();
|
||||
public UUID getRoomId();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,29 +36,29 @@ import java.util.UUID;
|
|||
*/
|
||||
public abstract class RoomImpl implements Room {
|
||||
|
||||
private UUID chatId;
|
||||
private UUID roomId;
|
||||
private UUID chatId;
|
||||
private UUID roomId;
|
||||
|
||||
public RoomImpl() {
|
||||
roomId = UUID.randomUUID();
|
||||
chatId = ChatManager.getInstance().createChatSession();
|
||||
}
|
||||
public RoomImpl() {
|
||||
roomId = UUID.randomUUID();
|
||||
chatId = ChatManager.getInstance().createChatSession();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the chatId
|
||||
*/
|
||||
@Override
|
||||
public UUID getChatId() {
|
||||
return chatId;
|
||||
}
|
||||
/**
|
||||
* @return the chatId
|
||||
*/
|
||||
@Override
|
||||
public UUID getChatId() {
|
||||
return chatId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the roomId
|
||||
*/
|
||||
@Override
|
||||
public UUID getRoomId() {
|
||||
return roomId;
|
||||
}
|
||||
/**
|
||||
* @return the roomId
|
||||
*/
|
||||
@Override
|
||||
public UUID getRoomId() {
|
||||
return roomId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -48,137 +48,137 @@ import java.util.UUID;
|
|||
*/
|
||||
public class Session {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(Session.class);
|
||||
private final static Logger logger = Logger.getLogger(Session.class);
|
||||
|
||||
private String sessionId;
|
||||
private UUID userId;
|
||||
private String host;
|
||||
private int messageId = 0;
|
||||
private Date timeConnected;
|
||||
private boolean isAdmin = false;
|
||||
private AsynchInvokerCallbackHandler callbackHandler;
|
||||
private String sessionId;
|
||||
private UUID userId;
|
||||
private String host;
|
||||
private int messageId = 0;
|
||||
private Date timeConnected;
|
||||
private boolean isAdmin = false;
|
||||
private AsynchInvokerCallbackHandler callbackHandler;
|
||||
|
||||
public Session(String sessionId, InvokerCallbackHandler callbackHandler) {
|
||||
this.sessionId = sessionId;
|
||||
this.callbackHandler = (AsynchInvokerCallbackHandler) callbackHandler;
|
||||
this.isAdmin = false;
|
||||
this.timeConnected = new Date();
|
||||
}
|
||||
|
||||
public void registerUser(String userName) throws MageException {
|
||||
this.isAdmin = false;
|
||||
if (userName.equals("Admin"))
|
||||
throw new MageException("User name already in use");
|
||||
User user = UserManager.getInstance().createUser(userName, host);
|
||||
if (user == null) { // user already exists
|
||||
user = UserManager.getInstance().findUser(userName);
|
||||
if (user.getHost().equals(host)) {
|
||||
if (user.getSessionId().isEmpty())
|
||||
logger.info("Reconnecting session for " + userName);
|
||||
else {
|
||||
//throw new MageException("This machine is already connected");
|
||||
public Session(String sessionId, InvokerCallbackHandler callbackHandler) {
|
||||
this.sessionId = sessionId;
|
||||
this.callbackHandler = (AsynchInvokerCallbackHandler) callbackHandler;
|
||||
this.isAdmin = false;
|
||||
this.timeConnected = new Date();
|
||||
}
|
||||
|
||||
public void registerUser(String userName) throws MageException {
|
||||
this.isAdmin = false;
|
||||
if (userName.equals("Admin"))
|
||||
throw new MageException("User name already in use");
|
||||
User user = UserManager.getInstance().createUser(userName, host);
|
||||
if (user == null) { // user already exists
|
||||
user = UserManager.getInstance().findUser(userName);
|
||||
if (user.getHost().equals(host)) {
|
||||
if (user.getSessionId().isEmpty())
|
||||
logger.info("Reconnecting session for " + userName);
|
||||
else {
|
||||
//throw new MageException("This machine is already connected");
|
||||
//disconnect previous one
|
||||
logger.info("Disconnecting another user instance: " + userName);
|
||||
UserManager.getInstance().disconnect(user.getId());
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new MageException("User name already in use");
|
||||
}
|
||||
}
|
||||
if (!UserManager.getInstance().connectToSession(sessionId, user.getId()))
|
||||
throw new MageException("Error connecting");
|
||||
this.userId = user.getId();
|
||||
}
|
||||
|
||||
public void registerAdmin() {
|
||||
this.isAdmin = true;
|
||||
User user = UserManager.getInstance().createUser("Admin", host);
|
||||
}
|
||||
else {
|
||||
throw new MageException("User name already in use");
|
||||
}
|
||||
}
|
||||
if (!UserManager.getInstance().connectToSession(sessionId, user.getId()))
|
||||
throw new MageException("Error connecting");
|
||||
this.userId = user.getId();
|
||||
}
|
||||
|
||||
public void registerAdmin() {
|
||||
this.isAdmin = true;
|
||||
User user = UserManager.getInstance().createUser("Admin", host);
|
||||
if (user == null) {
|
||||
user = UserManager.getInstance().findUser("Admin");
|
||||
}
|
||||
user.setUserData(new UserData(UserGroup.ADMIN, 0));
|
||||
this.userId = user.getId();
|
||||
}
|
||||
user.setUserData(new UserData(UserGroup.ADMIN, 0));
|
||||
this.userId = user.getId();
|
||||
}
|
||||
|
||||
public boolean setUserData(String userName, UserDataView userDataView) {
|
||||
User user = UserManager.getInstance().findUser(userName);
|
||||
if (user != null) {
|
||||
UserData userData = new UserData(UserGroup.PLAYER, userDataView.getAvatarId());
|
||||
updateAvatar(userName, userData);
|
||||
user.setUserData(userData);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public boolean setUserData(String userName, UserDataView userDataView) {
|
||||
User user = UserManager.getInstance().findUser(userName);
|
||||
if (user != null) {
|
||||
UserData userData = new UserData(UserGroup.PLAYER, userDataView.getAvatarId());
|
||||
updateAvatar(userName, userData);
|
||||
user.setUserData(userData);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void updateAvatar(String userName, UserData userData) {
|
||||
//TODO: move to separate class
|
||||
//TODO: add for checking for private key
|
||||
if (userName.equals("nantuko")) {
|
||||
userData.setAvatarId(1000);
|
||||
} else if (userName.equals("i_no_k")) {
|
||||
userData.setAvatarId(1002);
|
||||
} else if (userName.equals("Askael")) {
|
||||
userData.setAvatarId(1004);
|
||||
} else if (userName.equals("North")) {
|
||||
userData.setAvatarId(1006);
|
||||
} else if (userName.equals("BetaSteward")) {
|
||||
userData.setAvatarId(1008);
|
||||
} else if (userName.equals("Arching")) {
|
||||
userData.setAvatarId(1010);
|
||||
} else if (userName.equals("loki")) {
|
||||
userData.setAvatarId(1012);
|
||||
} else if (userName.equals("Alive")) {
|
||||
userData.setAvatarId(1014);
|
||||
} else if (userName.equals("Rahan")) {
|
||||
userData.setAvatarId(1016);
|
||||
} else if (userName.equals("Ayrat")) {
|
||||
userData.setAvatarId(1018);
|
||||
}
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
private void updateAvatar(String userName, UserData userData) {
|
||||
//TODO: move to separate class
|
||||
//TODO: add for checking for private key
|
||||
if (userName.equals("nantuko")) {
|
||||
userData.setAvatarId(1000);
|
||||
} else if (userName.equals("i_no_k")) {
|
||||
userData.setAvatarId(1002);
|
||||
} else if (userName.equals("Askael")) {
|
||||
userData.setAvatarId(1004);
|
||||
} else if (userName.equals("North")) {
|
||||
userData.setAvatarId(1006);
|
||||
} else if (userName.equals("BetaSteward")) {
|
||||
userData.setAvatarId(1008);
|
||||
} else if (userName.equals("Arching")) {
|
||||
userData.setAvatarId(1010);
|
||||
} else if (userName.equals("loki")) {
|
||||
userData.setAvatarId(1012);
|
||||
} else if (userName.equals("Alive")) {
|
||||
userData.setAvatarId(1014);
|
||||
} else if (userName.equals("Rahan")) {
|
||||
userData.setAvatarId(1016);
|
||||
} else if (userName.equals("Ayrat")) {
|
||||
userData.setAvatarId(1018);
|
||||
}
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
logger.info("session disconnected for user " + userId);
|
||||
UserManager.getInstance().disconnect(userId);
|
||||
}
|
||||
|
||||
public void kill() {
|
||||
UserManager.getInstance().disconnect(userId);
|
||||
}
|
||||
|
||||
public void kill() {
|
||||
logger.info("session killed for user " + userId);
|
||||
UserManager.getInstance().removeUser(userId);
|
||||
}
|
||||
|
||||
synchronized void fireCallback(final ClientCallback call) {
|
||||
try {
|
||||
call.setMessageId(messageId++);
|
||||
callbackHandler.handleCallbackOneway(new Callback(call));
|
||||
} catch (HandleCallbackException ex) {
|
||||
logger.fatal("Session fireCallback error: " + ex.getMessage(), ex);
|
||||
disconnect();
|
||||
}
|
||||
}
|
||||
UserManager.getInstance().removeUser(userId);
|
||||
}
|
||||
|
||||
public UUID getUserId() {
|
||||
return userId;
|
||||
}
|
||||
synchronized void fireCallback(final ClientCallback call) {
|
||||
try {
|
||||
call.setMessageId(messageId++);
|
||||
callbackHandler.handleCallbackOneway(new Callback(call));
|
||||
} catch (HandleCallbackException ex) {
|
||||
logger.fatal("Session fireCallback error: " + ex.getMessage(), ex);
|
||||
disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isAdmin() {
|
||||
return isAdmin;
|
||||
}
|
||||
public UUID getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
public Date getConnectionTime() {
|
||||
return timeConnected;
|
||||
}
|
||||
public boolean isAdmin() {
|
||||
return isAdmin;
|
||||
}
|
||||
|
||||
void setHost(String hostAddress) {
|
||||
this.host = hostAddress;
|
||||
}
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
public Date getConnectionTime() {
|
||||
return timeConnected;
|
||||
}
|
||||
|
||||
void setHost(String hostAddress) {
|
||||
this.host = hostAddress;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,107 +45,107 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||
*/
|
||||
public class SessionManager {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(SessionManager.class);
|
||||
private final static SessionManager INSTANCE = new SessionManager();
|
||||
private final static Logger logger = Logger.getLogger(SessionManager.class);
|
||||
private final static SessionManager INSTANCE = new SessionManager();
|
||||
|
||||
public static SessionManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static SessionManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<String, Session>();
|
||||
private ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<String, Session>();
|
||||
|
||||
public Session getSession(String sessionId) {
|
||||
if (sessions == null || sessionId == null) return null;
|
||||
return sessions.get(sessionId);
|
||||
}
|
||||
public Session getSession(String sessionId) {
|
||||
if (sessions == null || sessionId == null) return null;
|
||||
return sessions.get(sessionId);
|
||||
}
|
||||
|
||||
public void createSession(String sessionId, InvokerCallbackHandler callbackHandler) {
|
||||
Session session = new Session(sessionId, callbackHandler);
|
||||
sessions.put(sessionId, session);
|
||||
}
|
||||
|
||||
public boolean registerUser(String sessionId, String userName) throws MageException {
|
||||
Session session = sessions.get(sessionId);
|
||||
if (session != null) {
|
||||
session.registerUser(userName);
|
||||
public void createSession(String sessionId, InvokerCallbackHandler callbackHandler) {
|
||||
Session session = new Session(sessionId, callbackHandler);
|
||||
sessions.put(sessionId, session);
|
||||
}
|
||||
|
||||
public boolean registerUser(String sessionId, String userName) throws MageException {
|
||||
Session session = sessions.get(sessionId);
|
||||
if (session != null) {
|
||||
session.registerUser(userName);
|
||||
LogServiceImpl.instance.log(LogKeys.KEY_USER_CONNECTED, userName, session.getHost(), sessionId);
|
||||
logger.info("User " + userName + " connected from " + session.getHost() + " sessionId: " + sessionId);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean registerAdmin(String sessionId) {
|
||||
Session session = sessions.get(sessionId);
|
||||
if (session != null) {
|
||||
session.registerAdmin();
|
||||
LogServiceImpl.instance.log(LogKeys.KEY_ADMIN_CONNECTED, "Admin", session.getHost(), sessionId);
|
||||
logger.info("Admin connected from " + session.getHost());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
logger.info("User " + userName + " connected from " + session.getHost() + " sessionId: " + sessionId);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean setUserData(String userName, String sessionId, UserDataView userDataView) throws MageException {
|
||||
Session session = sessions.get(sessionId);
|
||||
if (session != null) {
|
||||
session.setUserData(userName, userDataView);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public synchronized void disconnect(String sessionId, boolean voluntary) {
|
||||
Session session = sessions.get(sessionId);
|
||||
sessions.remove(sessionId);
|
||||
if (session != null) {
|
||||
if (voluntary) {
|
||||
session.kill();
|
||||
public boolean registerAdmin(String sessionId) {
|
||||
Session session = sessions.get(sessionId);
|
||||
if (session != null) {
|
||||
session.registerAdmin();
|
||||
LogServiceImpl.instance.log(LogKeys.KEY_ADMIN_CONNECTED, "Admin", session.getHost(), sessionId);
|
||||
logger.info("Admin connected from " + session.getHost());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean setUserData(String userName, String sessionId, UserDataView userDataView) throws MageException {
|
||||
Session session = sessions.get(sessionId);
|
||||
if (session != null) {
|
||||
session.setUserData(userName, userDataView);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public synchronized void disconnect(String sessionId, boolean voluntary) {
|
||||
Session session = sessions.get(sessionId);
|
||||
sessions.remove(sessionId);
|
||||
if (session != null) {
|
||||
if (voluntary) {
|
||||
session.kill();
|
||||
LogServiceImpl.instance.log(LogKeys.KEY_SESSION_KILLED, sessionId);
|
||||
} else {
|
||||
session.disconnect();
|
||||
session.disconnect();
|
||||
LogServiceImpl.instance.log(LogKeys.KEY_SESSION_DISCONNECTED, sessionId);
|
||||
}
|
||||
} else {
|
||||
} else {
|
||||
logger.info("could not find session with id " + sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Session> getSessions() {
|
||||
Map<String, Session> map = new HashMap<String, Session>();
|
||||
for (Map.Entry<String, Session> entry : sessions.entrySet()) {
|
||||
map.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
}
|
||||
|
||||
public void disconnectUser(String sessionId, String userSessionId) {
|
||||
if (isAdmin(sessionId)) {
|
||||
disconnect(userSessionId, true);
|
||||
public Map<String, Session> getSessions() {
|
||||
Map<String, Session> map = new HashMap<String, Session>();
|
||||
for (Map.Entry<String, Session> entry : sessions.entrySet()) {
|
||||
map.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
public void disconnectUser(String sessionId, String userSessionId) {
|
||||
if (isAdmin(sessionId)) {
|
||||
disconnect(userSessionId, true);
|
||||
LogServiceImpl.instance.log(LogKeys.KEY_SESSION_DISCONNECTED_BY_ADMIN, sessionId, userSessionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isAdmin(String sessionId) {
|
||||
Session admin = sessions.get(sessionId);
|
||||
if (admin != null) {
|
||||
return admin.isAdmin();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public boolean isAdmin(String sessionId) {
|
||||
Session admin = sessions.get(sessionId);
|
||||
if (admin != null) {
|
||||
return admin.isAdmin();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isValidSession(String sessionId) {
|
||||
if (sessions.containsKey(sessionId))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
public boolean isValidSession(String sessionId) {
|
||||
if (sessions.containsKey(sessionId))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public User getUser(String sessionId) {
|
||||
if (sessions.containsKey(sessionId)) {
|
||||
return UserManager.getInstance().getUser(sessions.get(sessionId).getUserId());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public User getUser(String sessionId) {
|
||||
if (sessions.containsKey(sessionId)) {
|
||||
return UserManager.getInstance().getUser(sessions.get(sessionId).getUserId());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean extendUserSession(String sessionId) {
|
||||
if (sessions.containsKey(sessionId)) {
|
||||
|
|
|
|||
|
|
@ -72,274 +72,274 @@ import java.util.concurrent.TimeUnit;
|
|||
*/
|
||||
public class TableController {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(TableController.class);
|
||||
private final static Logger logger = Logger.getLogger(TableController.class);
|
||||
|
||||
private UUID userId;
|
||||
private UUID chatId;
|
||||
private String controllerName;
|
||||
private Table table;
|
||||
private Match match;
|
||||
private MatchOptions options;
|
||||
private Tournament tournament;
|
||||
private ConcurrentHashMap<UUID, UUID> userPlayerMap = new ConcurrentHashMap<UUID, UUID>();
|
||||
|
||||
private ScheduledFuture<?> futureTimeout;
|
||||
protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor();
|
||||
private UUID userId;
|
||||
private UUID chatId;
|
||||
private String controllerName;
|
||||
private Table table;
|
||||
private Match match;
|
||||
private MatchOptions options;
|
||||
private Tournament tournament;
|
||||
private ConcurrentHashMap<UUID, UUID> userPlayerMap = new ConcurrentHashMap<UUID, UUID>();
|
||||
|
||||
public TableController(UUID roomId, UUID userId, MatchOptions options) {
|
||||
this.userId = userId;
|
||||
chatId = ChatManager.getInstance().createChatSession();
|
||||
this.options = options;
|
||||
match = GameFactory.getInstance().createMatch(options.getGameType(), options);
|
||||
if (userId != null) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
controllerName = user.getName();
|
||||
}
|
||||
else
|
||||
controllerName = "System";
|
||||
table = new Table(roomId, options.getGameType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getDeckType()), options.getPlayerTypes(), match);
|
||||
init();
|
||||
}
|
||||
private ScheduledFuture<?> futureTimeout;
|
||||
protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor();
|
||||
|
||||
public TableController(UUID roomId, UUID userId, TournamentOptions options) {
|
||||
this.userId = userId;
|
||||
chatId = ChatManager.getInstance().createChatSession();
|
||||
tournament = TournamentFactory.getInstance().createTournament(options.getTournamentType(), options);
|
||||
if (userId != null) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
controllerName = user.getName();
|
||||
}
|
||||
else
|
||||
controllerName = "System";
|
||||
table = new Table(roomId, options.getTournamentType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getMatchOptions().getDeckType()), options.getPlayerTypes(), tournament);
|
||||
}
|
||||
public TableController(UUID roomId, UUID userId, MatchOptions options) {
|
||||
this.userId = userId;
|
||||
chatId = ChatManager.getInstance().createChatSession();
|
||||
this.options = options;
|
||||
match = GameFactory.getInstance().createMatch(options.getGameType(), options);
|
||||
if (userId != null) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
controllerName = user.getName();
|
||||
}
|
||||
else
|
||||
controllerName = "System";
|
||||
table = new Table(roomId, options.getGameType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getDeckType()), options.getPlayerTypes(), match);
|
||||
init();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
match.addTableEventListener(
|
||||
new Listener<TableEvent> () {
|
||||
@Override
|
||||
public void event(TableEvent event) {
|
||||
try {
|
||||
switch (event.getEventType()) {
|
||||
case SIDEBOARD:
|
||||
sideboard(event.getPlayerId(), event.getDeck());
|
||||
break;
|
||||
}
|
||||
} catch (MageException ex) {
|
||||
logger.fatal("Table event listener error", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
public TableController(UUID roomId, UUID userId, TournamentOptions options) {
|
||||
this.userId = userId;
|
||||
chatId = ChatManager.getInstance().createChatSession();
|
||||
tournament = TournamentFactory.getInstance().createTournament(options.getTournamentType(), options);
|
||||
if (userId != null) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
controllerName = user.getName();
|
||||
}
|
||||
else
|
||||
controllerName = "System";
|
||||
table = new Table(roomId, options.getTournamentType(), options.getName(), controllerName, DeckValidatorFactory.getInstance().createDeckValidator(options.getMatchOptions().getDeckType()), options.getPlayerTypes(), tournament);
|
||||
}
|
||||
|
||||
public synchronized boolean joinTournament(UUID userId, String name, String playerType, int skill) throws GameException {
|
||||
if (table.getState() != TableState.WAITING) {
|
||||
return false;
|
||||
}
|
||||
Seat seat = table.getNextAvailableSeat(playerType);
|
||||
if (seat == null) {
|
||||
throw new GameException("No available seats.");
|
||||
}
|
||||
Player player = createPlayer(name, seat.getPlayerType(), skill);
|
||||
tournament.addPlayer(player, seat.getPlayerType());
|
||||
table.joinTable(player, seat);
|
||||
private void init() {
|
||||
match.addTableEventListener(
|
||||
new Listener<TableEvent> () {
|
||||
@Override
|
||||
public void event(TableEvent event) {
|
||||
try {
|
||||
switch (event.getEventType()) {
|
||||
case SIDEBOARD:
|
||||
sideboard(event.getPlayerId(), event.getDeck());
|
||||
break;
|
||||
}
|
||||
} catch (MageException ex) {
|
||||
logger.fatal("Table event listener error", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public synchronized boolean joinTournament(UUID userId, String name, String playerType, int skill) throws GameException {
|
||||
if (table.getState() != TableState.WAITING) {
|
||||
return false;
|
||||
}
|
||||
Seat seat = table.getNextAvailableSeat(playerType);
|
||||
if (seat == null) {
|
||||
throw new GameException("No available seats.");
|
||||
}
|
||||
Player player = createPlayer(name, seat.getPlayerType(), skill);
|
||||
tournament.addPlayer(player, seat.getPlayerType());
|
||||
table.joinTable(player, seat);
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
user.addTable(player.getId(), table);
|
||||
user.joinedTable(table.getRoomId(), table.getId(), true);
|
||||
logger.info("player joined " + player.getId());
|
||||
//only add human players to sessionPlayerMap
|
||||
if (seat.getPlayer().isHuman()) {
|
||||
userPlayerMap.put(userId, player.getId());
|
||||
}
|
||||
logger.info("player joined " + player.getId());
|
||||
//only add human players to sessionPlayerMap
|
||||
if (seat.getPlayer().isHuman()) {
|
||||
userPlayerMap.put(userId, player.getId());
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public synchronized boolean joinTable(UUID userId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException {
|
||||
if (table.getState() != TableState.WAITING) {
|
||||
return false;
|
||||
}
|
||||
Seat seat = table.getNextAvailableSeat(playerType);
|
||||
if (seat == null) {
|
||||
throw new GameException("No available seats.");
|
||||
}
|
||||
Deck deck = Deck.load(deckList);
|
||||
if (!Main.isTestMode() && !table.getValidator().validate(deck)) {
|
||||
throw new InvalidDeckException(name + " has an invalid deck for this format", table.getValidator().getInvalid());
|
||||
}
|
||||
|
||||
Player player = createPlayer(name, seat.getPlayerType(), skill);
|
||||
match.addPlayer(player, deck);
|
||||
table.joinTable(player, seat);
|
||||
public synchronized boolean joinTable(UUID userId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException {
|
||||
if (table.getState() != TableState.WAITING) {
|
||||
return false;
|
||||
}
|
||||
Seat seat = table.getNextAvailableSeat(playerType);
|
||||
if (seat == null) {
|
||||
throw new GameException("No available seats.");
|
||||
}
|
||||
Deck deck = Deck.load(deckList);
|
||||
if (!Main.isTestMode() && !table.getValidator().validate(deck)) {
|
||||
throw new InvalidDeckException(name + " has an invalid deck for this format", table.getValidator().getInvalid());
|
||||
}
|
||||
|
||||
Player player = createPlayer(name, seat.getPlayerType(), skill);
|
||||
match.addPlayer(player, deck);
|
||||
table.joinTable(player, seat);
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
user.addTable(player.getId(), table);
|
||||
user.joinedTable(table.getRoomId(), table.getId(), false);
|
||||
logger.info("player joined " + player.getId());
|
||||
//only add human players to sessionPlayerMap
|
||||
if (seat.getPlayer().isHuman()) {
|
||||
userPlayerMap.put(userId, player.getId());
|
||||
}
|
||||
logger.info("player joined " + player.getId());
|
||||
//only add human players to sessionPlayerMap
|
||||
if (seat.getPlayer().isHuman()) {
|
||||
userPlayerMap.put(userId, player.getId());
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void addPlayer(UUID userId, Player player, String playerType, Deck deck) throws GameException {
|
||||
if (table.getState() != TableState.WAITING) {
|
||||
return;
|
||||
}
|
||||
Seat seat = table.getNextAvailableSeat(playerType);
|
||||
if (seat == null) {
|
||||
throw new GameException("No available seats.");
|
||||
}
|
||||
match.addPlayer(player, deck);
|
||||
table.joinTable(player, seat);
|
||||
if (player.isHuman()) {
|
||||
userPlayerMap.put(userId, player.getId());
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized boolean submitDeck(UUID userId, DeckCardLists deckList) throws MageException {
|
||||
UUID playerId = userPlayerMap.get(userId);
|
||||
if (table.getState() != TableState.SIDEBOARDING && table.getState() != TableState.CONSTRUCTING) {
|
||||
return false;
|
||||
}
|
||||
Deck deck = Deck.load(deckList);
|
||||
if (!Main.isTestMode() && !table.getValidator().validate(deck)) {
|
||||
throw new InvalidDeckException("Invalid deck for this format", table.getValidator().getInvalid());
|
||||
}
|
||||
submitDeck(userId, playerId, deck);
|
||||
return true;
|
||||
}
|
||||
public void addPlayer(UUID userId, Player player, String playerType, Deck deck) throws GameException {
|
||||
if (table.getState() != TableState.WAITING) {
|
||||
return;
|
||||
}
|
||||
Seat seat = table.getNextAvailableSeat(playerType);
|
||||
if (seat == null) {
|
||||
throw new GameException("No available seats.");
|
||||
}
|
||||
match.addPlayer(player, deck);
|
||||
table.joinTable(player, seat);
|
||||
if (player.isHuman()) {
|
||||
userPlayerMap.put(userId, player.getId());
|
||||
}
|
||||
}
|
||||
|
||||
public void updateDeck(UUID userId, DeckCardLists deckList) throws MageException {
|
||||
UUID playerId = userPlayerMap.get(userId);
|
||||
if (table.getState() != TableState.SIDEBOARDING && table.getState() != TableState.CONSTRUCTING) {
|
||||
return;
|
||||
}
|
||||
Deck deck = Deck.load(deckList);
|
||||
updateDeck(userId, playerId, deck);
|
||||
}
|
||||
public synchronized boolean submitDeck(UUID userId, DeckCardLists deckList) throws MageException {
|
||||
UUID playerId = userPlayerMap.get(userId);
|
||||
if (table.getState() != TableState.SIDEBOARDING && table.getState() != TableState.CONSTRUCTING) {
|
||||
return false;
|
||||
}
|
||||
Deck deck = Deck.load(deckList);
|
||||
if (!Main.isTestMode() && !table.getValidator().validate(deck)) {
|
||||
throw new InvalidDeckException("Invalid deck for this format", table.getValidator().getInvalid());
|
||||
}
|
||||
submitDeck(userId, playerId, deck);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void updateDeck(UUID userId, DeckCardLists deckList) throws MageException {
|
||||
UUID playerId = userPlayerMap.get(userId);
|
||||
if (table.getState() != TableState.SIDEBOARDING && table.getState() != TableState.CONSTRUCTING) {
|
||||
return;
|
||||
}
|
||||
Deck deck = Deck.load(deckList);
|
||||
updateDeck(userId, playerId, deck);
|
||||
}
|
||||
|
||||
private void submitDeck(UUID userId, UUID playerId, Deck deck) {
|
||||
if (table.getState() == TableState.SIDEBOARDING) {
|
||||
match.submitDeck(playerId, deck);
|
||||
if (table.getState() == TableState.SIDEBOARDING) {
|
||||
match.submitDeck(playerId, deck);
|
||||
UserManager.getInstance().getUser(userId).removeSideboarding(table.getId());
|
||||
}
|
||||
else {
|
||||
TournamentManager.getInstance().submitDeck(tournament.getId(), playerId, deck);
|
||||
}
|
||||
else {
|
||||
TournamentManager.getInstance().submitDeck(tournament.getId(), playerId, deck);
|
||||
UserManager.getInstance().getUser(userId).removeConstructing(table.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void updateDeck(UUID userId, UUID playerId, Deck deck) {
|
||||
if (table.getState() == TableState.SIDEBOARDING) {
|
||||
match.updateDeck(playerId, deck);
|
||||
}
|
||||
else {
|
||||
TournamentManager.getInstance().updateDeck(tournament.getId(), playerId, deck);
|
||||
}
|
||||
}
|
||||
if (table.getState() == TableState.SIDEBOARDING) {
|
||||
match.updateDeck(playerId, deck);
|
||||
}
|
||||
else {
|
||||
TournamentManager.getInstance().updateDeck(tournament.getId(), playerId, deck);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean watchTable(UUID userId) {
|
||||
if (table.getState() != TableState.DUELING) {
|
||||
return false;
|
||||
}
|
||||
UserManager.getInstance().getUser(userId).watchGame(match.getGame().getId());
|
||||
return true;
|
||||
}
|
||||
if (table.getState() != TableState.DUELING) {
|
||||
return false;
|
||||
}
|
||||
UserManager.getInstance().getUser(userId).watchGame(match.getGame().getId());
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean replayTable(UUID userId) {
|
||||
if (table.getState() != TableState.FINISHED) {
|
||||
return false;
|
||||
}
|
||||
ReplayManager.getInstance().replayGame(table.getId(), userId);
|
||||
return true;
|
||||
}
|
||||
public boolean replayTable(UUID userId) {
|
||||
if (table.getState() != TableState.FINISHED) {
|
||||
return false;
|
||||
}
|
||||
ReplayManager.getInstance().replayGame(table.getId(), userId);
|
||||
return true;
|
||||
}
|
||||
|
||||
private Player createPlayer(String name, String playerType, int skill) {
|
||||
Player player;
|
||||
if (options == null) {
|
||||
player = PlayerFactory.getInstance().createPlayer(playerType, name, RangeOfInfluence.ALL, skill);
|
||||
}
|
||||
else {
|
||||
player = PlayerFactory.getInstance().createPlayer(playerType, name, options.getRange(), skill);
|
||||
}
|
||||
private Player createPlayer(String name, String playerType, int skill) {
|
||||
Player player;
|
||||
if (options == null) {
|
||||
player = PlayerFactory.getInstance().createPlayer(playerType, name, RangeOfInfluence.ALL, skill);
|
||||
}
|
||||
else {
|
||||
player = PlayerFactory.getInstance().createPlayer(playerType, name, options.getRange(), skill);
|
||||
}
|
||||
if (player != null)
|
||||
logger.info("Player created " + player.getId());
|
||||
return player;
|
||||
}
|
||||
return player;
|
||||
}
|
||||
|
||||
public void kill(UUID userId) {
|
||||
leaveTable(userId);
|
||||
userPlayerMap.remove(userId);
|
||||
}
|
||||
|
||||
public synchronized void leaveTable(UUID userId) {
|
||||
if (table.getState() == TableState.WAITING || table.getState() == TableState.STARTING)
|
||||
table.leaveTable(userPlayerMap.get(userId));
|
||||
}
|
||||
public void kill(UUID userId) {
|
||||
leaveTable(userId);
|
||||
userPlayerMap.remove(userId);
|
||||
}
|
||||
|
||||
public synchronized void startMatch(UUID userId) {
|
||||
if (userId.equals(this.userId)) {
|
||||
startMatch();
|
||||
}
|
||||
}
|
||||
public synchronized void leaveTable(UUID userId) {
|
||||
if (table.getState() == TableState.WAITING || table.getState() == TableState.STARTING)
|
||||
table.leaveTable(userPlayerMap.get(userId));
|
||||
}
|
||||
|
||||
public synchronized void startChallenge(UUID userId, UUID challengeId) {
|
||||
if (userId.equals(this.userId)) {
|
||||
try {
|
||||
match.startMatch();
|
||||
match.startGame();
|
||||
table.initGame();
|
||||
GameOptions options = new GameOptions();
|
||||
options.testMode = true;
|
||||
// match.getGame().setGameOptions(options);
|
||||
GameManager.getInstance().createGameSession(match.getGame(), userPlayerMap, table.getId(), null);
|
||||
ChallengeManager.getInstance().prepareChallenge(getPlayerId(), match);
|
||||
for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
|
||||
UserManager.getInstance().getUser(entry.getKey()).gameStarted(match.getGame().getId(), entry.getValue());
|
||||
}
|
||||
} catch (GameException ex) {
|
||||
logger.fatal(null, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
public synchronized void startMatch(UUID userId) {
|
||||
if (userId.equals(this.userId)) {
|
||||
startMatch();
|
||||
}
|
||||
}
|
||||
|
||||
private UUID getPlayerId() throws GameException {
|
||||
UUID playerId = null;
|
||||
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
|
||||
playerId = entry.getValue();
|
||||
break;
|
||||
}
|
||||
if (playerId == null)
|
||||
throw new GameException("Couldn't find a player in challenge mode.");
|
||||
return playerId;
|
||||
}
|
||||
public synchronized void startChallenge(UUID userId, UUID challengeId) {
|
||||
if (userId.equals(this.userId)) {
|
||||
try {
|
||||
match.startMatch();
|
||||
match.startGame();
|
||||
table.initGame();
|
||||
GameOptions options = new GameOptions();
|
||||
options.testMode = true;
|
||||
// match.getGame().setGameOptions(options);
|
||||
GameManager.getInstance().createGameSession(match.getGame(), userPlayerMap, table.getId(), null);
|
||||
ChallengeManager.getInstance().prepareChallenge(getPlayerId(), match);
|
||||
for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
|
||||
UserManager.getInstance().getUser(entry.getKey()).gameStarted(match.getGame().getId(), entry.getValue());
|
||||
}
|
||||
} catch (GameException ex) {
|
||||
logger.fatal(null, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void startMatch() {
|
||||
if (table.getState() == TableState.STARTING) {
|
||||
try {
|
||||
match.startMatch();
|
||||
startGame(null);
|
||||
} catch (GameException ex) {
|
||||
logger.fatal("Error starting match ", ex);
|
||||
match.endGame();
|
||||
}
|
||||
}
|
||||
}
|
||||
private UUID getPlayerId() throws GameException {
|
||||
UUID playerId = null;
|
||||
for (Entry<UUID, UUID> entry : userPlayerMap.entrySet()) {
|
||||
playerId = entry.getValue();
|
||||
break;
|
||||
}
|
||||
if (playerId == null)
|
||||
throw new GameException("Couldn't find a player in challenge mode.");
|
||||
return playerId;
|
||||
}
|
||||
|
||||
private void startGame(UUID choosingPlayerId) throws GameException {
|
||||
try {
|
||||
match.startGame();
|
||||
table.initGame();
|
||||
GameManager.getInstance().createGameSession(match.getGame(), userPlayerMap, table.getId(), choosingPlayerId);
|
||||
public synchronized void startMatch() {
|
||||
if (table.getState() == TableState.STARTING) {
|
||||
try {
|
||||
match.startMatch();
|
||||
startGame(null);
|
||||
} catch (GameException ex) {
|
||||
logger.fatal("Error starting match ", ex);
|
||||
match.endGame();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void startGame(UUID choosingPlayerId) throws GameException {
|
||||
try {
|
||||
match.startGame();
|
||||
table.initGame();
|
||||
GameManager.getInstance().createGameSession(match.getGame(), userPlayerMap, table.getId(), choosingPlayerId);
|
||||
String creator = null;
|
||||
String opponent = null;
|
||||
for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
|
||||
User user = UserManager.getInstance().getUser(entry.getKey());
|
||||
if (user != null) {
|
||||
user.gameStarted(match.getGame().getId(), entry.getValue());
|
||||
for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
|
||||
User user = UserManager.getInstance().getUser(entry.getKey());
|
||||
if (user != null) {
|
||||
user.gameStarted(match.getGame().getId(), entry.getValue());
|
||||
if (creator == null) {
|
||||
creator = user.getName();
|
||||
} else {
|
||||
|
|
@ -347,121 +347,121 @@ public class TableController {
|
|||
opponent = user.getName();
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
TableManager.getInstance().removeTable(table.getId());
|
||||
GameManager.getInstance().removeGame(match.getGame().getId());
|
||||
logger.warn("Unable to find player " + entry.getKey());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
TableManager.getInstance().removeTable(table.getId());
|
||||
GameManager.getInstance().removeGame(match.getGame().getId());
|
||||
logger.warn("Unable to find player " + entry.getKey());
|
||||
break;
|
||||
}
|
||||
}
|
||||
ServerMessagesUtil.getInstance().incGamesStarted();
|
||||
|
||||
// log about game started
|
||||
LogServiceImpl.instance.log(LogKeys.KEY_GAME_STARTED, String.valueOf(userPlayerMap.size()), creator, opponent);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
logger.fatal("Error starting game", ex);
|
||||
TableManager.getInstance().removeTable(table.getId());
|
||||
GameManager.getInstance().removeGame(match.getGame().getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex) {
|
||||
logger.fatal("Error starting game", ex);
|
||||
TableManager.getInstance().removeTable(table.getId());
|
||||
GameManager.getInstance().removeGame(match.getGame().getId());
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void startTournament(UUID userId) {
|
||||
try {
|
||||
if (userId.equals(this.userId) && table.getState() == TableState.STARTING) {
|
||||
TournamentManager.getInstance().createTournamentSession(tournament, userPlayerMap, table.getId());
|
||||
for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
|
||||
User user = UserManager.getInstance().getUser(entry.getKey());
|
||||
user.tournamentStarted(tournament.getId(), entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex) {
|
||||
logger.fatal("Error starting tournament", ex);
|
||||
TableManager.getInstance().removeTable(table.getId());
|
||||
TournamentManager.getInstance().kill(tournament.getId(), userId);
|
||||
}
|
||||
}
|
||||
public synchronized void startTournament(UUID userId) {
|
||||
try {
|
||||
if (userId.equals(this.userId) && table.getState() == TableState.STARTING) {
|
||||
TournamentManager.getInstance().createTournamentSession(tournament, userPlayerMap, table.getId());
|
||||
for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
|
||||
User user = UserManager.getInstance().getUser(entry.getKey());
|
||||
user.tournamentStarted(tournament.getId(), entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex) {
|
||||
logger.fatal("Error starting tournament", ex);
|
||||
TableManager.getInstance().removeTable(table.getId());
|
||||
TournamentManager.getInstance().kill(tournament.getId(), userId);
|
||||
}
|
||||
}
|
||||
|
||||
public void startDraft(Draft draft) {
|
||||
table.initDraft();
|
||||
DraftManager.getInstance().createDraftSession(draft, userPlayerMap, table.getId());
|
||||
for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
|
||||
UserManager.getInstance().getUser(entry.getKey()).draftStarted(draft.getId(), entry.getValue());
|
||||
}
|
||||
}
|
||||
public void startDraft(Draft draft) {
|
||||
table.initDraft();
|
||||
DraftManager.getInstance().createDraftSession(draft, userPlayerMap, table.getId());
|
||||
for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
|
||||
UserManager.getInstance().getUser(entry.getKey()).draftStarted(draft.getId(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
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());
|
||||
int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS);
|
||||
if (user != null)
|
||||
user.sideboard(deck, table.getId(), remaining, options.isLimited());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
user.sideboard(deck, table.getId(), remaining, options.isLimited());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int getRemainingTime() {
|
||||
return (int) futureTimeout.getDelay(TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
public void construct() {
|
||||
table.construct();
|
||||
}
|
||||
|
||||
|
||||
public void construct() {
|
||||
table.construct();
|
||||
}
|
||||
|
||||
public MatchOptions getOptions() {
|
||||
return options;
|
||||
}
|
||||
|
||||
public void endGame() {
|
||||
UUID choosingPlayerId = match.getChooser();
|
||||
match.endGame();
|
||||
table.endGame();
|
||||
public void endGame() {
|
||||
UUID choosingPlayerId = match.getChooser();
|
||||
match.endGame();
|
||||
table.endGame();
|
||||
//if (!match.getGame().isSimulation())
|
||||
//GameManager.getInstance().saveGame(match.getGame().getId());
|
||||
GameManager.getInstance().removeGame(match.getGame().getId());
|
||||
try {
|
||||
if (!match.isMatchOver()) {
|
||||
table.sideboard();
|
||||
GameManager.getInstance().removeGame(match.getGame().getId());
|
||||
try {
|
||||
if (!match.isMatchOver()) {
|
||||
table.sideboard();
|
||||
setupTimeout(Match.SIDEBOARD_TIME);
|
||||
match.sideboard();
|
||||
match.sideboard();
|
||||
cancelTimeout();
|
||||
startGame(choosingPlayerId);
|
||||
}
|
||||
else {
|
||||
GamesRoomManager.getInstance().removeTable(table.getId());
|
||||
startGame(choosingPlayerId);
|
||||
}
|
||||
else {
|
||||
GamesRoomManager.getInstance().removeTable(table.getId());
|
||||
match.getGames().clear();
|
||||
match = null;
|
||||
table = null;
|
||||
}
|
||||
} catch (GameException ex) {
|
||||
logger.fatal(null, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (GameException ex) {
|
||||
logger.fatal(null, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void setupTimeout(int seconds) {
|
||||
cancelTimeout();
|
||||
if (seconds > 0) {
|
||||
futureTimeout = timeoutExecutor.schedule(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
autoSideboard();
|
||||
}
|
||||
},
|
||||
seconds, TimeUnit.SECONDS
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void cancelTimeout() {
|
||||
if (futureTimeout != null) {
|
||||
futureTimeout.cancel(false);
|
||||
}
|
||||
}
|
||||
private synchronized void setupTimeout(int seconds) {
|
||||
cancelTimeout();
|
||||
if (seconds > 0) {
|
||||
futureTimeout = timeoutExecutor.schedule(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
autoSideboard();
|
||||
}
|
||||
},
|
||||
seconds, TimeUnit.SECONDS
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void cancelTimeout() {
|
||||
if (futureTimeout != null) {
|
||||
futureTimeout.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void autoSideboard() {
|
||||
for (MatchPlayer player: match.getPlayers()) {
|
||||
|
|
@ -469,47 +469,47 @@ public class TableController {
|
|||
match.submitDeck(player.getPlayer().getId(), player.generateDeck());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void endDraft(Draft draft) {
|
||||
for (DraftPlayer player: draft.getPlayers()) {
|
||||
tournament.getPlayer(player.getPlayer().getId()).setDeck(player.getDeck());
|
||||
}
|
||||
tournament.nextStep();
|
||||
}
|
||||
for (DraftPlayer player: draft.getPlayers()) {
|
||||
tournament.getPlayer(player.getPlayer().getId()).setDeck(player.getDeck());
|
||||
}
|
||||
tournament.nextStep();
|
||||
}
|
||||
|
||||
public void endTournament(Tournament tournament) {
|
||||
//TODO: implement this
|
||||
}
|
||||
public void endTournament(Tournament tournament) {
|
||||
//TODO: implement this
|
||||
}
|
||||
|
||||
public void swapSeats(int seatNum1, int seatNum2) {
|
||||
if (table.getState() == TableState.STARTING) {
|
||||
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();
|
||||
table.getSeats()[seatNum1].setPlayer(table.getSeats()[seatNum2].getPlayer());
|
||||
table.getSeats()[seatNum1].setPlayerType(table.getSeats()[seatNum2].getPlayerType());
|
||||
table.getSeats()[seatNum2].setPlayer(swapPlayer);
|
||||
table.getSeats()[seatNum2].setPlayerType(swapType);
|
||||
}
|
||||
}
|
||||
}
|
||||
public void swapSeats(int seatNum1, int seatNum2) {
|
||||
if (table.getState() == TableState.STARTING) {
|
||||
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();
|
||||
table.getSeats()[seatNum1].setPlayer(table.getSeats()[seatNum2].getPlayer());
|
||||
table.getSeats()[seatNum1].setPlayerType(table.getSeats()[seatNum2].getPlayerType());
|
||||
table.getSeats()[seatNum2].setPlayer(swapPlayer);
|
||||
table.getSeats()[seatNum2].setPlayerType(swapType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isOwner(UUID userId) {
|
||||
public boolean isOwner(UUID userId) {
|
||||
if (userId == null)
|
||||
return false;
|
||||
return userId.equals(this.userId);
|
||||
}
|
||||
return userId.equals(this.userId);
|
||||
}
|
||||
|
||||
public Table getTable() {
|
||||
return table;
|
||||
}
|
||||
public Table getTable() {
|
||||
return table;
|
||||
}
|
||||
|
||||
public UUID getChatId() {
|
||||
return chatId;
|
||||
}
|
||||
public UUID getChatId() {
|
||||
return chatId;
|
||||
}
|
||||
|
||||
public Match getMatch() {
|
||||
return match;
|
||||
}
|
||||
public Match getMatch() {
|
||||
return match;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -50,186 +50,186 @@ import mage.server.game.GamesRoomManager;
|
|||
*/
|
||||
public class TableManager {
|
||||
|
||||
private final static TableManager INSTANCE = new TableManager();
|
||||
//private final static Logger logger = Logger.getLogger(TableManager.class);
|
||||
private final static TableManager INSTANCE = new TableManager();
|
||||
//private final static Logger logger = Logger.getLogger(TableManager.class);
|
||||
|
||||
private ConcurrentHashMap<UUID, TableController> controllers = new ConcurrentHashMap<UUID, TableController>();
|
||||
private ConcurrentHashMap<UUID, Table> tables = new ConcurrentHashMap<UUID, Table>();
|
||||
private ConcurrentHashMap<UUID, TableController> controllers = new ConcurrentHashMap<UUID, TableController>();
|
||||
private ConcurrentHashMap<UUID, Table> tables = new ConcurrentHashMap<UUID, Table>();
|
||||
|
||||
public static TableManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static TableManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public Table createTable(UUID roomId, UUID userId, MatchOptions options) {
|
||||
TableController tableController = new TableController(roomId, userId, options);
|
||||
controllers.put(tableController.getTable().getId(), tableController);
|
||||
tables.put(tableController.getTable().getId(), tableController.getTable());
|
||||
return tableController.getTable();
|
||||
}
|
||||
public Table createTable(UUID roomId, UUID userId, MatchOptions options) {
|
||||
TableController tableController = new TableController(roomId, userId, options);
|
||||
controllers.put(tableController.getTable().getId(), tableController);
|
||||
tables.put(tableController.getTable().getId(), tableController.getTable());
|
||||
return tableController.getTable();
|
||||
}
|
||||
|
||||
public Table createTable(UUID roomId, MatchOptions options) {
|
||||
TableController tableController = new TableController(roomId, null, options);
|
||||
controllers.put(tableController.getTable().getId(), tableController);
|
||||
tables.put(tableController.getTable().getId(), tableController.getTable());
|
||||
return tableController.getTable();
|
||||
}
|
||||
public Table createTable(UUID roomId, MatchOptions options) {
|
||||
TableController tableController = new TableController(roomId, null, options);
|
||||
controllers.put(tableController.getTable().getId(), tableController);
|
||||
tables.put(tableController.getTable().getId(), tableController.getTable());
|
||||
return tableController.getTable();
|
||||
}
|
||||
|
||||
public Table createTournamentTable(UUID roomId, UUID userId, TournamentOptions options) {
|
||||
TableController tableController = new TableController(roomId, userId, options);
|
||||
controllers.put(tableController.getTable().getId(), tableController);
|
||||
tables.put(tableController.getTable().getId(), tableController.getTable());
|
||||
return tableController.getTable();
|
||||
}
|
||||
public Table createTournamentTable(UUID roomId, UUID userId, TournamentOptions options) {
|
||||
TableController tableController = new TableController(roomId, userId, options);
|
||||
controllers.put(tableController.getTable().getId(), tableController);
|
||||
tables.put(tableController.getTable().getId(), tableController.getTable());
|
||||
return tableController.getTable();
|
||||
}
|
||||
|
||||
public Table getTable(UUID tableId) {
|
||||
return tables.get(tableId);
|
||||
}
|
||||
public Table getTable(UUID tableId) {
|
||||
return tables.get(tableId);
|
||||
}
|
||||
|
||||
public Match getMatch(UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).getMatch();
|
||||
return null;
|
||||
}
|
||||
public Match getMatch(UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).getMatch();
|
||||
return null;
|
||||
}
|
||||
|
||||
public Collection<Table> getTables() {
|
||||
return tables.values();
|
||||
}
|
||||
public Collection<Table> getTables() {
|
||||
return tables.values();
|
||||
}
|
||||
|
||||
public TableController getController(UUID tableId) {
|
||||
return controllers.get(tableId);
|
||||
}
|
||||
|
||||
public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).joinTable(userId, name, playerType, skill, deckList);
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean joinTournament(UUID userId, UUID tableId, String name, String playerType, int skill) throws GameException {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).joinTournament(userId, name, playerType, skill);
|
||||
return false;
|
||||
}
|
||||
public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).joinTable(userId, name, playerType, skill, deckList);
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean submitDeck(UUID userId, UUID tableId, DeckCardLists deckList) throws MageException {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).submitDeck(userId, deckList);
|
||||
return false;
|
||||
}
|
||||
public boolean joinTournament(UUID userId, UUID tableId, String name, String playerType, int skill) throws GameException {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).joinTournament(userId, name, playerType, skill);
|
||||
return false;
|
||||
}
|
||||
|
||||
public void updateDeck(UUID userId, UUID tableId, DeckCardLists deckList) throws MageException {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).updateDeck(userId, deckList);
|
||||
}
|
||||
public boolean submitDeck(UUID userId, UUID tableId, DeckCardLists deckList) throws MageException {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).submitDeck(userId, deckList);
|
||||
return false;
|
||||
}
|
||||
|
||||
public void updateDeck(UUID userId, UUID tableId, DeckCardLists deckList) throws MageException {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).updateDeck(userId, deckList);
|
||||
}
|
||||
|
||||
public void removeSession(UUID userId) {
|
||||
for (TableController controller: controllers.values()) {
|
||||
controller.kill(userId);
|
||||
}
|
||||
}
|
||||
for (TableController controller: controllers.values()) {
|
||||
controller.kill(userId);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isTableOwner(UUID tableId, UUID userId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).isOwner(userId);
|
||||
return false;
|
||||
}
|
||||
public boolean isTableOwner(UUID tableId, UUID userId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).isOwner(userId);
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean removeTable(UUID userId, UUID tableId) {
|
||||
if (isTableOwner(tableId, userId) || UserManager.getInstance().isAdmin(userId)) {
|
||||
removeTable(tableId);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public boolean removeTable(UUID userId, UUID tableId) {
|
||||
if (isTableOwner(tableId, userId) || UserManager.getInstance().isAdmin(userId)) {
|
||||
removeTable(tableId);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void leaveTable(UUID userId, UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).leaveTable(userId);
|
||||
}
|
||||
public void leaveTable(UUID userId, UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).leaveTable(userId);
|
||||
}
|
||||
|
||||
public UUID getChatId(UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).getChatId();
|
||||
return null;
|
||||
}
|
||||
public UUID getChatId(UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).getChatId();
|
||||
return null;
|
||||
}
|
||||
|
||||
public void startMatch(UUID userId, UUID roomId, UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).startMatch(userId);
|
||||
}
|
||||
public void startMatch(UUID userId, UUID roomId, UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).startMatch(userId);
|
||||
}
|
||||
|
||||
public void startMatch(UUID roomId, UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).startMatch();
|
||||
}
|
||||
public void startMatch(UUID roomId, UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).startMatch();
|
||||
}
|
||||
|
||||
public void startChallenge(UUID userId, UUID roomId, UUID tableId, UUID challengeId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).startChallenge(userId, challengeId);
|
||||
}
|
||||
public void startChallenge(UUID userId, UUID roomId, UUID tableId, UUID challengeId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).startChallenge(userId, challengeId);
|
||||
}
|
||||
|
||||
public void startTournament(UUID userId, UUID roomId, UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).startTournament(userId);
|
||||
}
|
||||
public void startTournament(UUID userId, UUID roomId, UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).startTournament(userId);
|
||||
}
|
||||
|
||||
public void startDraft(UUID tableId, Draft draft) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).startDraft(draft);
|
||||
}
|
||||
public void startDraft(UUID tableId, Draft draft) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).startDraft(draft);
|
||||
}
|
||||
|
||||
public boolean watchTable(UUID userId, UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).watchTable(userId);
|
||||
return false;
|
||||
}
|
||||
public boolean watchTable(UUID userId, UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).watchTable(userId);
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean replayTable(UUID userId, UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).replayTable(userId);
|
||||
return false;
|
||||
}
|
||||
public boolean replayTable(UUID userId, UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
return controllers.get(tableId).replayTable(userId);
|
||||
return false;
|
||||
}
|
||||
|
||||
public void endGame(UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).endGame();
|
||||
}
|
||||
public void endGame(UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).endGame();
|
||||
}
|
||||
|
||||
public void endDraft(UUID tableId, Draft draft) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).endDraft(draft);
|
||||
}
|
||||
public void endDraft(UUID tableId, Draft draft) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).endDraft(draft);
|
||||
}
|
||||
|
||||
public void endTournament(UUID tableId, Tournament tournament) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).endTournament(tournament);
|
||||
}
|
||||
public void endTournament(UUID tableId, Tournament tournament) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).endTournament(tournament);
|
||||
}
|
||||
|
||||
public void swapSeats(UUID tableId, UUID userId, int seatNum1, int seatNum2) {
|
||||
if (controllers.containsKey(tableId) && isTableOwner(tableId, userId)) {
|
||||
controllers.get(tableId).swapSeats(seatNum1, seatNum2);
|
||||
}
|
||||
}
|
||||
public void swapSeats(UUID tableId, UUID userId, int seatNum1, int seatNum2) {
|
||||
if (controllers.containsKey(tableId) && isTableOwner(tableId, userId)) {
|
||||
controllers.get(tableId).swapSeats(seatNum1, seatNum2);
|
||||
}
|
||||
}
|
||||
|
||||
public void construct(UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).construct();
|
||||
}
|
||||
public void construct(UUID tableId) {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).construct();
|
||||
}
|
||||
|
||||
public void addPlayer(UUID userId, UUID tableId, Player player, String playerType, Deck deck) throws GameException {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).addPlayer(userId, player, playerType, deck);
|
||||
}
|
||||
public void addPlayer(UUID userId, UUID tableId, Player player, String playerType, Deck deck) throws GameException {
|
||||
if (controllers.containsKey(tableId))
|
||||
controllers.get(tableId).addPlayer(userId, player, playerType, deck);
|
||||
}
|
||||
|
||||
public void removeTable(UUID tableId) {
|
||||
if (tables.containsKey(tableId)) {
|
||||
Table table = tables.get(tableId);
|
||||
controllers.remove(tableId);
|
||||
tables.remove(tableId);
|
||||
GamesRoomManager.getInstance().removeTable(tableId);
|
||||
if (table.getMatch() != null && table.getMatch().getGame() != null)
|
||||
table.getMatch().getGame().end();
|
||||
}
|
||||
}
|
||||
public void removeTable(UUID tableId) {
|
||||
if (tables.containsKey(tableId)) {
|
||||
Table table = tables.get(tableId);
|
||||
controllers.remove(tableId);
|
||||
tables.remove(tableId);
|
||||
GamesRoomManager.getInstance().removeTable(tableId);
|
||||
if (table.getMatch() != null && table.getMatch().getGame() != null)
|
||||
table.getMatch().getGame().end();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -50,161 +50,161 @@ import java.util.UUID;
|
|||
*/
|
||||
public class User {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(User.class);
|
||||
private final static Logger logger = Logger.getLogger(User.class);
|
||||
|
||||
public enum UserState {
|
||||
Created, Connected, Disconnected, Reconnected;
|
||||
}
|
||||
|
||||
private UUID userId = UUID.randomUUID();
|
||||
private String userName;
|
||||
private String sessionId = "";
|
||||
private String host;
|
||||
private Date connectionTime = new Date();
|
||||
private Date lastActivity = new Date();
|
||||
private UserState userState;
|
||||
Created, Connected, Disconnected, Reconnected;
|
||||
}
|
||||
|
||||
private UUID userId = UUID.randomUUID();
|
||||
private String userName;
|
||||
private String sessionId = "";
|
||||
private String host;
|
||||
private Date connectionTime = new Date();
|
||||
private Date lastActivity = new Date();
|
||||
private UserState userState;
|
||||
private Map<UUID, Table> tables = new HashMap<UUID, Table>();
|
||||
private Map<UUID, GameSession> gameSessions = new HashMap<UUID, GameSession>();
|
||||
private Map<UUID, DraftSession> draftSessions = new HashMap<UUID, DraftSession>();
|
||||
private Map<UUID, TournamentSession> tournamentSessions = new HashMap<UUID, TournamentSession>();
|
||||
private Map<UUID, GameSession> gameSessions = new HashMap<UUID, GameSession>();
|
||||
private Map<UUID, DraftSession> draftSessions = new HashMap<UUID, DraftSession>();
|
||||
private Map<UUID, TournamentSession> tournamentSessions = new HashMap<UUID, TournamentSession>();
|
||||
private Map<UUID, TournamentSession> constructing = new HashMap<UUID, TournamentSession>();
|
||||
private Map<UUID, Deck> sideboarding = new HashMap<UUID, Deck>();
|
||||
|
||||
private UserData userData;
|
||||
|
||||
public User(String userName, String host) {
|
||||
this.userName = userName;
|
||||
this.host = host;
|
||||
this.userState = UserState.Created;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
public UUID getId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
public String getSessionId() {
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
public void setSessionId(String sessionId) {
|
||||
this.sessionId = sessionId;
|
||||
if (sessionId.isEmpty()) {
|
||||
userState = UserState.Disconnected;
|
||||
private UserData userData;
|
||||
|
||||
public User(String userName, String host) {
|
||||
this.userName = userName;
|
||||
this.host = host;
|
||||
this.userState = UserState.Created;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
public UUID getId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
public String getSessionId() {
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
public void setSessionId(String sessionId) {
|
||||
this.sessionId = sessionId;
|
||||
if (sessionId.isEmpty()) {
|
||||
userState = UserState.Disconnected;
|
||||
logger.info("User " + userName + " disconnected");
|
||||
} else if (userState == UserState.Created) {
|
||||
userState = UserState.Connected;
|
||||
userState = UserState.Connected;
|
||||
logger.info("User " + userName + " created");
|
||||
} else {
|
||||
userState = UserState.Reconnected;
|
||||
reconnect();
|
||||
userState = UserState.Reconnected;
|
||||
reconnect();
|
||||
logger.info("User " + userName + " reconnected");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isConnected() {
|
||||
return userState == UserState.Connected || userState == UserState.Reconnected;
|
||||
}
|
||||
|
||||
public Date getConnectionTime() {
|
||||
return connectionTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void fireCallback(final ClientCallback call) {
|
||||
if (isConnected()) {
|
||||
Session session = SessionManager.getInstance().getSession(sessionId);
|
||||
public boolean isConnected() {
|
||||
return userState == UserState.Connected || userState == UserState.Reconnected;
|
||||
}
|
||||
|
||||
public Date getConnectionTime() {
|
||||
return connectionTime;
|
||||
}
|
||||
|
||||
public synchronized void fireCallback(final ClientCallback call) {
|
||||
if (isConnected()) {
|
||||
Session session = SessionManager.getInstance().getSession(sessionId);
|
||||
if (session != null)
|
||||
session.fireCallback(call);
|
||||
}
|
||||
}
|
||||
session.fireCallback(call);
|
||||
}
|
||||
}
|
||||
|
||||
public void joinedTable(final UUID roomId, final UUID tableId, boolean isTournament) {
|
||||
fireCallback(new ClientCallback("joinedTable", tableId, new TableClientMessage(roomId, tableId, isTournament)));
|
||||
}
|
||||
public void joinedTable(final UUID roomId, final UUID tableId, boolean isTournament) {
|
||||
fireCallback(new ClientCallback("joinedTable", tableId, new TableClientMessage(roomId, tableId, isTournament)));
|
||||
}
|
||||
|
||||
public void gameStarted(final UUID gameId, final UUID playerId) {
|
||||
fireCallback(new ClientCallback("startGame", gameId, new TableClientMessage(gameId, playerId)));
|
||||
}
|
||||
public void gameStarted(final UUID gameId, final UUID playerId) {
|
||||
fireCallback(new ClientCallback("startGame", gameId, new TableClientMessage(gameId, playerId)));
|
||||
}
|
||||
|
||||
public void draftStarted(final UUID draftId, final UUID playerId) {
|
||||
fireCallback(new ClientCallback("startDraft", draftId, new TableClientMessage(draftId, playerId)));
|
||||
}
|
||||
public void draftStarted(final UUID draftId, final UUID playerId) {
|
||||
fireCallback(new ClientCallback("startDraft", draftId, new TableClientMessage(draftId, playerId)));
|
||||
}
|
||||
|
||||
public void tournamentStarted(final UUID tournamentId, final UUID playerId) {
|
||||
fireCallback(new ClientCallback("startTournament", tournamentId, new TableClientMessage(tournamentId, playerId)));
|
||||
}
|
||||
public void tournamentStarted(final UUID tournamentId, final UUID playerId) {
|
||||
fireCallback(new ClientCallback("startTournament", tournamentId, new TableClientMessage(tournamentId, playerId)));
|
||||
}
|
||||
|
||||
public void sideboard(final Deck deck, final UUID tableId, final int time, boolean limited) {
|
||||
fireCallback(new ClientCallback("sideboard", tableId, new TableClientMessage(deck, tableId, time, limited)));
|
||||
public void sideboard(final Deck deck, final UUID tableId, final int time, boolean limited) {
|
||||
fireCallback(new ClientCallback("sideboard", tableId, new TableClientMessage(deck, tableId, time, limited)));
|
||||
sideboarding.put(tableId, deck);
|
||||
}
|
||||
}
|
||||
|
||||
public void construct(final Deck deck, final UUID tableId, final int time) {
|
||||
fireCallback(new ClientCallback("construct", tableId, new TableClientMessage(deck, tableId, time)));
|
||||
}
|
||||
public void construct(final Deck deck, final UUID tableId, final int time) {
|
||||
fireCallback(new ClientCallback("construct", tableId, new TableClientMessage(deck, tableId, time)));
|
||||
}
|
||||
|
||||
public void watchGame(final UUID gameId) {
|
||||
fireCallback(new ClientCallback("watchGame", gameId));
|
||||
}
|
||||
public void watchGame(final UUID gameId) {
|
||||
fireCallback(new ClientCallback("watchGame", gameId));
|
||||
}
|
||||
|
||||
public void replayGame(final UUID gameId) {
|
||||
fireCallback(new ClientCallback("replayGame", gameId));
|
||||
}
|
||||
public void replayGame(final UUID gameId) {
|
||||
fireCallback(new ClientCallback("replayGame", gameId));
|
||||
}
|
||||
|
||||
public void sendPlayerUUID(final UUID gameId, final UUID data) {
|
||||
lastActivity = new Date();
|
||||
GameManager.getInstance().sendPlayerUUID(gameId, userId, data);
|
||||
}
|
||||
public void sendPlayerUUID(final UUID gameId, final UUID data) {
|
||||
lastActivity = new Date();
|
||||
GameManager.getInstance().sendPlayerUUID(gameId, userId, data);
|
||||
}
|
||||
|
||||
public void sendPlayerString(final UUID gameId, final String data) {
|
||||
lastActivity = new Date();
|
||||
GameManager.getInstance().sendPlayerString(gameId, userId, data);
|
||||
}
|
||||
public void sendPlayerString(final UUID gameId, final String data) {
|
||||
lastActivity = new Date();
|
||||
GameManager.getInstance().sendPlayerString(gameId, userId, data);
|
||||
}
|
||||
|
||||
public void sendPlayerBoolean(final UUID gameId, final Boolean data) {
|
||||
lastActivity = new Date();
|
||||
GameManager.getInstance().sendPlayerBoolean(gameId, userId, data);
|
||||
}
|
||||
public void sendPlayerBoolean(final UUID gameId, final Boolean data) {
|
||||
lastActivity = new Date();
|
||||
GameManager.getInstance().sendPlayerBoolean(gameId, userId, data);
|
||||
}
|
||||
|
||||
public void sendPlayerInteger(final UUID gameId, final Integer data) {
|
||||
lastActivity = new Date();
|
||||
GameManager.getInstance().sendPlayerInteger(gameId, userId, data);
|
||||
}
|
||||
|
||||
public void sendPlayerInteger(final UUID gameId, final Integer data) {
|
||||
lastActivity = new Date();
|
||||
GameManager.getInstance().sendPlayerInteger(gameId, userId, data);
|
||||
}
|
||||
|
||||
public void updateLastActivity() {
|
||||
lastActivity = new Date();
|
||||
}
|
||||
|
||||
public boolean isExpired(Date expired) {
|
||||
return /*userState == UserState.Disconnected && */ lastActivity.before(expired);
|
||||
}
|
||||
|
||||
private void reconnect() {
|
||||
for (Entry<UUID, Table> entry: tables.entrySet()) {
|
||||
public boolean isExpired(Date expired) {
|
||||
return /*userState == UserState.Disconnected && */ lastActivity.before(expired);
|
||||
}
|
||||
|
||||
private void reconnect() {
|
||||
for (Entry<UUID, Table> entry: tables.entrySet()) {
|
||||
joinedTable(entry.getValue().getRoomId(), entry.getValue().getId(), entry.getValue().isTournament());
|
||||
}
|
||||
for (Entry<UUID, TournamentSession> entry: tournamentSessions.entrySet()) {
|
||||
tournamentStarted(entry.getValue().getTournamentId(), entry.getKey());
|
||||
entry.getValue().init();
|
||||
entry.getValue().update();
|
||||
}
|
||||
for (Entry<UUID, GameSession> entry: gameSessions.entrySet()) {
|
||||
gameStarted(entry.getValue().getGameId(), entry.getKey());
|
||||
entry.getValue().init();
|
||||
GameManager.getInstance().sendPlayerString(entry.getValue().getGameId(), userId, "");
|
||||
}
|
||||
for (Entry<UUID, DraftSession> entry: draftSessions.entrySet()) {
|
||||
draftStarted(entry.getValue().getDraftId(), entry.getKey());
|
||||
entry.getValue().init();
|
||||
entry.getValue().update();
|
||||
}
|
||||
}
|
||||
for (Entry<UUID, TournamentSession> entry: tournamentSessions.entrySet()) {
|
||||
tournamentStarted(entry.getValue().getTournamentId(), entry.getKey());
|
||||
entry.getValue().init();
|
||||
entry.getValue().update();
|
||||
}
|
||||
for (Entry<UUID, GameSession> entry: gameSessions.entrySet()) {
|
||||
gameStarted(entry.getValue().getGameId(), entry.getKey());
|
||||
entry.getValue().init();
|
||||
GameManager.getInstance().sendPlayerString(entry.getValue().getGameId(), userId, "");
|
||||
}
|
||||
for (Entry<UUID, DraftSession> entry: draftSessions.entrySet()) {
|
||||
draftStarted(entry.getValue().getDraftId(), entry.getKey());
|
||||
entry.getValue().init();
|
||||
entry.getValue().update();
|
||||
}
|
||||
for (Entry<UUID, TournamentSession> entry: constructing.entrySet()) {
|
||||
entry.getValue().construct(0);
|
||||
}
|
||||
|
|
@ -212,36 +212,36 @@ public class User {
|
|||
TableController controller = TableManager.getInstance().getController(entry.getKey());
|
||||
sideboard(entry.getValue(), entry.getKey(), controller.getRemainingTime(), controller.getOptions().isLimited());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void addGame(UUID playerId, GameSession gameSession) {
|
||||
gameSessions.put(playerId, gameSession);
|
||||
}
|
||||
|
||||
public void removeGame(UUID playerId) {
|
||||
gameSessions.remove(playerId);
|
||||
}
|
||||
|
||||
public void addDraft(UUID playerId, DraftSession draftSession) {
|
||||
draftSessions.put(playerId, draftSession);
|
||||
}
|
||||
|
||||
public void removeDraft(UUID playerId) {
|
||||
draftSessions.remove(playerId);
|
||||
}
|
||||
|
||||
public void addTournament(UUID playerId, TournamentSession tournamentSession) {
|
||||
tournamentSessions.put(playerId, tournamentSession);
|
||||
}
|
||||
|
||||
public void removeTournament(UUID playerId) {
|
||||
tournamentSessions.remove(playerId);
|
||||
}
|
||||
|
||||
public void addGame(UUID playerId, GameSession gameSession) {
|
||||
gameSessions.put(playerId, gameSession);
|
||||
}
|
||||
|
||||
public void removeGame(UUID playerId) {
|
||||
gameSessions.remove(playerId);
|
||||
}
|
||||
|
||||
public void addDraft(UUID playerId, DraftSession draftSession) {
|
||||
draftSessions.put(playerId, draftSession);
|
||||
}
|
||||
|
||||
public void removeDraft(UUID playerId) {
|
||||
draftSessions.remove(playerId);
|
||||
}
|
||||
|
||||
public void addTournament(UUID playerId, TournamentSession tournamentSession) {
|
||||
tournamentSessions.put(playerId, tournamentSession);
|
||||
}
|
||||
|
||||
public void removeTournament(UUID playerId) {
|
||||
tournamentSessions.remove(playerId);
|
||||
}
|
||||
|
||||
public void addTable(UUID playerId, Table table) {
|
||||
tables.put(playerId, table);
|
||||
}
|
||||
|
||||
|
||||
public void removeTable(UUID playerId) {
|
||||
tables.remove(playerId);
|
||||
}
|
||||
|
|
@ -249,39 +249,39 @@ public class User {
|
|||
public void addConstructing(UUID playerId, TournamentSession tournamentSession) {
|
||||
constructing.put(playerId, tournamentSession);
|
||||
}
|
||||
|
||||
|
||||
public void removeConstructing(UUID playerId) {
|
||||
constructing.remove(playerId);
|
||||
}
|
||||
|
||||
|
||||
public void removeSideboarding(UUID tableId) {
|
||||
sideboarding.remove(tableId);
|
||||
}
|
||||
|
||||
public void kill() {
|
||||
for (GameSession session: gameSessions.values()) {
|
||||
session.kill();
|
||||
}
|
||||
for (DraftSession session: draftSessions.values()) {
|
||||
session.setKilled();
|
||||
}
|
||||
for (TournamentSession session: tournamentSessions.values()) {
|
||||
session.setKilled();
|
||||
}
|
||||
for (Entry<UUID, Table> entry: tables.entrySet()) {
|
||||
entry.getValue().leaveTable(entry.getKey());
|
||||
for (GameSession session: gameSessions.values()) {
|
||||
session.kill();
|
||||
}
|
||||
for (DraftSession session: draftSessions.values()) {
|
||||
session.setKilled();
|
||||
}
|
||||
for (TournamentSession session: tournamentSessions.values()) {
|
||||
session.setKilled();
|
||||
}
|
||||
for (Entry<UUID, Table> entry: tables.entrySet()) {
|
||||
entry.getValue().leaveTable(entry.getKey());
|
||||
if (TableManager.getInstance().isTableOwner(entry.getValue().getId(), userId)) {
|
||||
TableManager.getInstance().removeTable(userId, entry.getValue().getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setUserData(UserData userData) {
|
||||
this.userData = userData;
|
||||
}
|
||||
public void setUserData(UserData userData) {
|
||||
this.userData = userData;
|
||||
}
|
||||
|
||||
public UserData getUserData() {
|
||||
return this.userData;
|
||||
}
|
||||
public UserData getUserData() {
|
||||
return this.userData;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,59 +47,59 @@ import java.util.concurrent.TimeUnit;
|
|||
*/
|
||||
public class UserManager {
|
||||
|
||||
protected static ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
protected static ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
|
||||
private final static UserManager INSTANCE = new UserManager();
|
||||
private final static Logger logger = Logger.getLogger(UserManager.class);
|
||||
private final static UserManager INSTANCE = new UserManager();
|
||||
private final static Logger logger = Logger.getLogger(UserManager.class);
|
||||
|
||||
public static UserManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static UserManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private UserManager() {
|
||||
expireExecutor.scheduleAtFixedRate(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
checkExpired();
|
||||
}
|
||||
}, 60, 60, TimeUnit.SECONDS);
|
||||
}
|
||||
private UserManager() {
|
||||
expireExecutor.scheduleAtFixedRate(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
checkExpired();
|
||||
}
|
||||
}, 60, 60, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private ConcurrentHashMap<UUID, User> users = new ConcurrentHashMap<UUID, User>();
|
||||
private ConcurrentHashMap<UUID, User> users = new ConcurrentHashMap<UUID, User>();
|
||||
|
||||
public User createUser(String userName, String host) {
|
||||
if (findUser(userName) != null)
|
||||
return null; //user already exists
|
||||
User user = new User(userName, host);
|
||||
users.put(user.getId(), user);
|
||||
return user;
|
||||
}
|
||||
|
||||
public User getUser(UUID userId) {
|
||||
return users.get(userId);
|
||||
}
|
||||
|
||||
public User findUser(String userName) {
|
||||
for (User user: users.values()) {
|
||||
if (user.getName().equals(userName))
|
||||
return user;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Collection<User> getUsers() {
|
||||
return users.values();
|
||||
}
|
||||
|
||||
public boolean connectToSession(String sessionId, UUID userId) {
|
||||
if (users.containsKey(userId)) {
|
||||
users.get(userId).setSessionId(sessionId);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void disconnect(UUID userId) {
|
||||
public User createUser(String userName, String host) {
|
||||
if (findUser(userName) != null)
|
||||
return null; //user already exists
|
||||
User user = new User(userName, host);
|
||||
users.put(user.getId(), user);
|
||||
return user;
|
||||
}
|
||||
|
||||
public User getUser(UUID userId) {
|
||||
return users.get(userId);
|
||||
}
|
||||
|
||||
public User findUser(String userName) {
|
||||
for (User user: users.values()) {
|
||||
if (user.getName().equals(userName))
|
||||
return user;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Collection<User> getUsers() {
|
||||
return users.values();
|
||||
}
|
||||
|
||||
public boolean connectToSession(String sessionId, UUID userId) {
|
||||
if (users.containsKey(userId)) {
|
||||
users.get(userId).setSessionId(sessionId);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void disconnect(UUID userId) {
|
||||
if (userId != null) {
|
||||
ChatManager.getInstance().removeUser(userId);
|
||||
if (users.containsKey(userId)) {
|
||||
|
|
@ -108,24 +108,24 @@ public class UserManager {
|
|||
ChatManager.getInstance().broadcast(userId, "has lost connection", MessageColor.BLACK);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isAdmin(UUID userId) {
|
||||
if (users.containsKey(userId)) {
|
||||
return users.get(userId).getName().equals("Admin");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void removeUser(UUID userId) {
|
||||
if (users.containsKey(userId)) {
|
||||
public boolean isAdmin(UUID userId) {
|
||||
if (users.containsKey(userId)) {
|
||||
return users.get(userId).getName().equals("Admin");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void removeUser(UUID userId) {
|
||||
if (users.containsKey(userId)) {
|
||||
logger.info("user removed" + userId);
|
||||
users.get(userId).setSessionId("");
|
||||
ChatManager.getInstance().broadcast(userId, "has disconnected", MessageColor.BLACK);
|
||||
users.get(userId).kill();
|
||||
users.remove(userId);
|
||||
}
|
||||
}
|
||||
users.get(userId).setSessionId("");
|
||||
ChatManager.getInstance().broadcast(userId, "has disconnected", MessageColor.BLACK);
|
||||
users.get(userId).kill();
|
||||
users.remove(userId);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean extendUserSession(UUID userId) {
|
||||
if (users.containsKey(userId)) {
|
||||
|
|
@ -134,17 +134,17 @@ public class UserManager {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void checkExpired() {
|
||||
Calendar expired = Calendar.getInstance();
|
||||
expired.add(Calendar.MINUTE, -3) ;
|
||||
for (User user: users.values()) {
|
||||
if (user.isExpired(expired.getTime())) {
|
||||
|
||||
private void checkExpired() {
|
||||
Calendar expired = Calendar.getInstance();
|
||||
expired.add(Calendar.MINUTE, -3) ;
|
||||
for (User user: users.values()) {
|
||||
if (user.isExpired(expired.getTime())) {
|
||||
logger.info(user.getName() + " session expired " + user.getId());
|
||||
user.kill();
|
||||
users.remove(user.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
user.kill();
|
||||
users.remove(user.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,15 +13,15 @@ import java.util.UUID;
|
|||
*/
|
||||
public class ChallengeManager {
|
||||
|
||||
public static final ChallengeManager fInstance = new ChallengeManager();
|
||||
public static final ChallengeManager fInstance = new ChallengeManager();
|
||||
|
||||
public static ChallengeManager getInstance() {
|
||||
return fInstance;
|
||||
}
|
||||
public static ChallengeManager getInstance() {
|
||||
return fInstance;
|
||||
}
|
||||
|
||||
public void prepareChallenge(UUID playerId, Match match) {
|
||||
Map<Constants.Zone, String> commands = new HashMap<Constants.Zone, String>();
|
||||
commands.put(Constants.Zone.OUTSIDE, "life:3");
|
||||
match.getGame().cheat(playerId, commands);
|
||||
}
|
||||
public void prepareChallenge(UUID playerId, Match match) {
|
||||
Map<Constants.Zone, String> commands = new HashMap<Constants.Zone, String>();
|
||||
commands.put(Constants.Zone.OUTSIDE, "life:3");
|
||||
match.getGame().cheat(playerId, commands);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -51,163 +51,163 @@ import org.apache.log4j.Logger;
|
|||
*/
|
||||
public class DraftController {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(GameController.class);
|
||||
public static final String INIT_FILE_PATH = "config" + File.separator + "init.txt";
|
||||
private final static Logger logger = Logger.getLogger(GameController.class);
|
||||
public static final String INIT_FILE_PATH = "config" + File.separator + "init.txt";
|
||||
|
||||
private ConcurrentHashMap<UUID, DraftSession> draftSessions = new ConcurrentHashMap<UUID, DraftSession>();
|
||||
private ConcurrentHashMap<UUID, UUID> userPlayerMap;
|
||||
private UUID draftSessionId;
|
||||
private Draft draft;
|
||||
private UUID tableId;
|
||||
private ConcurrentHashMap<UUID, DraftSession> draftSessions = new ConcurrentHashMap<UUID, DraftSession>();
|
||||
private ConcurrentHashMap<UUID, UUID> userPlayerMap;
|
||||
private UUID draftSessionId;
|
||||
private Draft draft;
|
||||
private UUID tableId;
|
||||
|
||||
public DraftController(Draft draft, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {
|
||||
draftSessionId = UUID.randomUUID();
|
||||
this.userPlayerMap = userPlayerMap;
|
||||
this.draft = draft;
|
||||
this.tableId = tableId;
|
||||
init();
|
||||
}
|
||||
public DraftController(Draft draft, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {
|
||||
draftSessionId = UUID.randomUUID();
|
||||
this.userPlayerMap = userPlayerMap;
|
||||
this.draft = draft;
|
||||
this.tableId = tableId;
|
||||
init();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
draft.addTableEventListener(
|
||||
new Listener<TableEvent> () {
|
||||
@Override
|
||||
public void event(TableEvent event) {
|
||||
try {
|
||||
switch (event.getEventType()) {
|
||||
case UPDATE:
|
||||
updateDraft();
|
||||
break;
|
||||
case END:
|
||||
endDraft();
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (MageException ex) {
|
||||
logger.fatal("Table event listener error", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
draft.addPlayerQueryEventListener(
|
||||
new Listener<PlayerQueryEvent> () {
|
||||
@Override
|
||||
public void event(PlayerQueryEvent event) {
|
||||
try {
|
||||
switch (event.getQueryType()) {
|
||||
case PICK_CARD:
|
||||
pickCard(event.getPlayerId(), event.getMax());
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (MageException ex) {
|
||||
logger.fatal("Table event listener error", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
for (DraftPlayer player: draft.getPlayers()) {
|
||||
if (!player.getPlayer().isHuman()) {
|
||||
player.setJoined();
|
||||
logger.info("player " + player.getPlayer().getId() + " has joined draft " + draft.getId());
|
||||
}
|
||||
}
|
||||
checkStart();
|
||||
}
|
||||
private void init() {
|
||||
draft.addTableEventListener(
|
||||
new Listener<TableEvent> () {
|
||||
@Override
|
||||
public void event(TableEvent event) {
|
||||
try {
|
||||
switch (event.getEventType()) {
|
||||
case UPDATE:
|
||||
updateDraft();
|
||||
break;
|
||||
case END:
|
||||
endDraft();
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (MageException ex) {
|
||||
logger.fatal("Table event listener error", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
draft.addPlayerQueryEventListener(
|
||||
new Listener<PlayerQueryEvent> () {
|
||||
@Override
|
||||
public void event(PlayerQueryEvent event) {
|
||||
try {
|
||||
switch (event.getQueryType()) {
|
||||
case PICK_CARD:
|
||||
pickCard(event.getPlayerId(), event.getMax());
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (MageException ex) {
|
||||
logger.fatal("Table event listener error", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
for (DraftPlayer player: draft.getPlayers()) {
|
||||
if (!player.getPlayer().isHuman()) {
|
||||
player.setJoined();
|
||||
logger.info("player " + player.getPlayer().getId() + " has joined draft " + draft.getId());
|
||||
}
|
||||
}
|
||||
checkStart();
|
||||
}
|
||||
|
||||
private UUID getPlayerId(UUID userId) {
|
||||
return userPlayerMap.get(userId);
|
||||
}
|
||||
private UUID getPlayerId(UUID userId) {
|
||||
return userPlayerMap.get(userId);
|
||||
}
|
||||
|
||||
public void join(UUID userId) {
|
||||
UUID playerId = userPlayerMap.get(userId);
|
||||
DraftSession draftSession = new DraftSession(draft, userId, playerId);
|
||||
draftSessions.put(playerId, draftSession);
|
||||
UserManager.getInstance().getUser(userId).addDraft(playerId, draftSession);
|
||||
logger.info("User " + UserManager.getInstance().getUser(userId).getName() + " has joined draft " + draft.getId());
|
||||
draft.getPlayer(playerId).setJoined();
|
||||
checkStart();
|
||||
}
|
||||
public void join(UUID userId) {
|
||||
UUID playerId = userPlayerMap.get(userId);
|
||||
DraftSession draftSession = new DraftSession(draft, userId, playerId);
|
||||
draftSessions.put(playerId, draftSession);
|
||||
UserManager.getInstance().getUser(userId).addDraft(playerId, draftSession);
|
||||
logger.info("User " + UserManager.getInstance().getUser(userId).getName() + " has joined draft " + draft.getId());
|
||||
draft.getPlayer(playerId).setJoined();
|
||||
checkStart();
|
||||
}
|
||||
|
||||
private synchronized void startDraft() {
|
||||
for (final Entry<UUID, DraftSession> entry: draftSessions.entrySet()) {
|
||||
if (!entry.getValue().init()) {
|
||||
logger.fatal("Unable to initialize client");
|
||||
//TODO: generate client error message
|
||||
return;
|
||||
}
|
||||
}
|
||||
draft.start();
|
||||
}
|
||||
private synchronized void startDraft() {
|
||||
for (final Entry<UUID, DraftSession> entry: draftSessions.entrySet()) {
|
||||
if (!entry.getValue().init()) {
|
||||
logger.fatal("Unable to initialize client");
|
||||
//TODO: generate client error message
|
||||
return;
|
||||
}
|
||||
}
|
||||
draft.start();
|
||||
}
|
||||
|
||||
private void checkStart() {
|
||||
if (allJoined()) {
|
||||
ThreadExecutor.getInstance().getCallExecutor().execute(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
startDraft();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
private void checkStart() {
|
||||
if (allJoined()) {
|
||||
ThreadExecutor.getInstance().getCallExecutor().execute(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
startDraft();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private boolean allJoined() {
|
||||
if (!draft.allJoined())
|
||||
return false;
|
||||
for (DraftPlayer player: draft.getPlayers()) {
|
||||
if (player.getPlayer().isHuman() && draftSessions.get(player.getPlayer().getId()) == null) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
private boolean allJoined() {
|
||||
if (!draft.allJoined())
|
||||
return false;
|
||||
for (DraftPlayer player: draft.getPlayers()) {
|
||||
if (player.getPlayer().isHuman() && draftSessions.get(player.getPlayer().getId()) == null) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void leave(UUID userId) {
|
||||
draft.leave(getPlayerId(userId));
|
||||
}
|
||||
private void leave(UUID userId) {
|
||||
draft.leave(getPlayerId(userId));
|
||||
}
|
||||
|
||||
private void endDraft() throws MageException {
|
||||
for (final DraftSession draftSession: draftSessions.values()) {
|
||||
draftSession.draftOver();
|
||||
draftSession.removeDraft();
|
||||
}
|
||||
TableManager.getInstance().endDraft(tableId, draft);
|
||||
}
|
||||
private void endDraft() throws MageException {
|
||||
for (final DraftSession draftSession: draftSessions.values()) {
|
||||
draftSession.draftOver();
|
||||
draftSession.removeDraft();
|
||||
}
|
||||
TableManager.getInstance().endDraft(tableId, draft);
|
||||
}
|
||||
|
||||
public void kill(UUID userId) {
|
||||
if (userPlayerMap.containsKey(userId)) {
|
||||
draftSessions.get(userPlayerMap.get(userId)).setKilled();
|
||||
draftSessions.remove(userPlayerMap.get(userId));
|
||||
leave(userId);
|
||||
userPlayerMap.remove(userId);
|
||||
}
|
||||
}
|
||||
public void kill(UUID userId) {
|
||||
if (userPlayerMap.containsKey(userId)) {
|
||||
draftSessions.get(userPlayerMap.get(userId)).setKilled();
|
||||
draftSessions.remove(userPlayerMap.get(userId));
|
||||
leave(userId);
|
||||
userPlayerMap.remove(userId);
|
||||
}
|
||||
}
|
||||
|
||||
public void timeout(UUID userId) {
|
||||
if (userPlayerMap.containsKey(userId)) {
|
||||
draft.autoPick(userPlayerMap.get(userId));
|
||||
logger.info("Draft pick timeout - autopick for player: " + userPlayerMap.get(userId));
|
||||
}
|
||||
}
|
||||
public void timeout(UUID userId) {
|
||||
if (userPlayerMap.containsKey(userId)) {
|
||||
draft.autoPick(userPlayerMap.get(userId));
|
||||
logger.info("Draft pick timeout - autopick for player: " + userPlayerMap.get(userId));
|
||||
}
|
||||
}
|
||||
|
||||
public UUID getSessionId() {
|
||||
return this.draftSessionId;
|
||||
}
|
||||
public UUID getSessionId() {
|
||||
return this.draftSessionId;
|
||||
}
|
||||
|
||||
public DraftPickView sendCardPick(UUID userId, UUID cardId) {
|
||||
return draftSessions.get(userPlayerMap.get(userId)).sendCardPick(cardId);
|
||||
}
|
||||
public DraftPickView sendCardPick(UUID userId, UUID cardId) {
|
||||
return draftSessions.get(userPlayerMap.get(userId)).sendCardPick(cardId);
|
||||
}
|
||||
|
||||
private synchronized void updateDraft() throws MageException {
|
||||
for (final Entry<UUID, DraftSession> entry: draftSessions.entrySet()) {
|
||||
entry.getValue().update();
|
||||
}
|
||||
}
|
||||
private synchronized void updateDraft() throws MageException {
|
||||
for (final Entry<UUID, DraftSession> entry: draftSessions.entrySet()) {
|
||||
entry.getValue().update();
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void pickCard(UUID playerId, int timeout) throws MageException {
|
||||
if (draftSessions.containsKey(playerId))
|
||||
draftSessions.get(playerId).pickCard(timeout);
|
||||
}
|
||||
private synchronized void pickCard(UUID playerId, int timeout) throws MageException {
|
||||
if (draftSessions.containsKey(playerId))
|
||||
draftSessions.get(playerId).pickCard(timeout);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,50 +38,50 @@ import mage.view.DraftPickView;
|
|||
* @author BetaSteward_at_googlemail.com
|
||||
*/
|
||||
public class DraftManager {
|
||||
private final static DraftManager INSTANCE = new DraftManager();
|
||||
private final static DraftManager INSTANCE = new DraftManager();
|
||||
|
||||
public static DraftManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static DraftManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private DraftManager() {}
|
||||
private DraftManager() {}
|
||||
|
||||
private ConcurrentHashMap<UUID, DraftController> draftControllers = new ConcurrentHashMap<UUID, DraftController>();
|
||||
private ConcurrentHashMap<UUID, DraftController> draftControllers = new ConcurrentHashMap<UUID, DraftController>();
|
||||
|
||||
public UUID createDraftSession(Draft draft, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {
|
||||
DraftController draftController = new DraftController(draft, userPlayerMap, tableId);
|
||||
draftControllers.put(draft.getId(), draftController);
|
||||
return draftController.getSessionId();
|
||||
}
|
||||
public UUID createDraftSession(Draft draft, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {
|
||||
DraftController draftController = new DraftController(draft, userPlayerMap, tableId);
|
||||
draftControllers.put(draft.getId(), draftController);
|
||||
return draftController.getSessionId();
|
||||
}
|
||||
|
||||
public void joinDraft(UUID draftId, UUID userId) {
|
||||
draftControllers.get(draftId).join(userId);
|
||||
}
|
||||
public void joinDraft(UUID draftId, UUID userId) {
|
||||
draftControllers.get(draftId).join(userId);
|
||||
}
|
||||
|
||||
public void destroyChatSession(UUID gameId) {
|
||||
draftControllers.remove(gameId);
|
||||
}
|
||||
public void destroyChatSession(UUID gameId) {
|
||||
draftControllers.remove(gameId);
|
||||
}
|
||||
|
||||
public DraftPickView sendCardPick(UUID draftId, UUID userId, UUID cardId) {
|
||||
return draftControllers.get(draftId).sendCardPick(userId, cardId);
|
||||
}
|
||||
public DraftPickView sendCardPick(UUID draftId, UUID userId, UUID cardId) {
|
||||
return draftControllers.get(draftId).sendCardPick(userId, cardId);
|
||||
}
|
||||
|
||||
public void removeSession(UUID userId) {
|
||||
for (DraftController controller: draftControllers.values()) {
|
||||
controller.kill(userId);
|
||||
}
|
||||
}
|
||||
public void removeSession(UUID userId) {
|
||||
for (DraftController controller: draftControllers.values()) {
|
||||
controller.kill(userId);
|
||||
}
|
||||
}
|
||||
|
||||
public void kill(UUID draftId, UUID userId) {
|
||||
draftControllers.get(draftId).kill(userId);
|
||||
}
|
||||
public void kill(UUID draftId, UUID userId) {
|
||||
draftControllers.get(draftId).kill(userId);
|
||||
}
|
||||
|
||||
public void timeout(UUID gameId, UUID userId) {
|
||||
draftControllers.get(gameId).timeout(userId);
|
||||
}
|
||||
public void timeout(UUID gameId, UUID userId) {
|
||||
draftControllers.get(gameId).timeout(userId);
|
||||
}
|
||||
|
||||
public void removeDraft(UUID draftId) {
|
||||
draftControllers.remove(draftId);
|
||||
}
|
||||
public void removeDraft(UUID draftId) {
|
||||
draftControllers.remove(draftId);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -49,126 +49,126 @@ import org.apache.log4j.Logger;
|
|||
*/
|
||||
public class DraftSession {
|
||||
|
||||
protected final static Logger logger = Logger.getLogger(DraftSession.class);
|
||||
protected final static Logger logger = Logger.getLogger(DraftSession.class);
|
||||
|
||||
protected UUID userId;
|
||||
protected UUID playerId;
|
||||
protected Draft draft;
|
||||
protected boolean killed = false;
|
||||
protected UUID userId;
|
||||
protected UUID playerId;
|
||||
protected Draft draft;
|
||||
protected boolean killed = false;
|
||||
|
||||
private ScheduledFuture<?> futureTimeout;
|
||||
protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor();
|
||||
private ScheduledFuture<?> futureTimeout;
|
||||
protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor();
|
||||
|
||||
public DraftSession(Draft draft, UUID userId, UUID playerId) {
|
||||
this.userId = userId;
|
||||
this.draft = draft;
|
||||
this.playerId = playerId;
|
||||
}
|
||||
public DraftSession(Draft draft, UUID userId, UUID playerId) {
|
||||
this.userId = userId;
|
||||
this.draft = draft;
|
||||
this.playerId = playerId;
|
||||
}
|
||||
|
||||
public boolean init() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
if (futureTimeout != null && !futureTimeout.isDone()) {
|
||||
int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS);
|
||||
user.fireCallback(new ClientCallback("draftInit", draft.getId(), new DraftClientMessage(getDraftPickView(remaining))));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public boolean init() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
if (futureTimeout != null && !futureTimeout.isDone()) {
|
||||
int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS);
|
||||
user.fireCallback(new ClientCallback("draftInit", draft.getId(), new DraftClientMessage(getDraftPickView(remaining))));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void update() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("draftUpdate", draft.getId(), getDraftView()));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void update() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("draftUpdate", draft.getId(), getDraftView()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void draftOver() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("draftOver", draft.getId()));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void draftOver() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
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))));
|
||||
}
|
||||
}
|
||||
}
|
||||
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))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void setupTimeout(int seconds) {
|
||||
cancelTimeout();
|
||||
if (seconds > 0) {
|
||||
futureTimeout = timeoutExecutor.schedule(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
DraftManager.getInstance().timeout(draft.getId(), userId);
|
||||
}
|
||||
},
|
||||
seconds, TimeUnit.SECONDS
|
||||
);
|
||||
}
|
||||
}
|
||||
private synchronized void setupTimeout(int seconds) {
|
||||
cancelTimeout();
|
||||
if (seconds > 0) {
|
||||
futureTimeout = timeoutExecutor.schedule(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
DraftManager.getInstance().timeout(draft.getId(), userId);
|
||||
}
|
||||
},
|
||||
seconds, TimeUnit.SECONDS
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void cancelTimeout() {
|
||||
if (futureTimeout != null) {
|
||||
futureTimeout.cancel(false);
|
||||
}
|
||||
}
|
||||
private synchronized void cancelTimeout() {
|
||||
if (futureTimeout != null) {
|
||||
futureTimeout.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
protected void handleRemoteException(RemoteException ex) {
|
||||
logger.fatal("DraftSession error ", ex);
|
||||
DraftManager.getInstance().kill(draft.getId(), userId);
|
||||
}
|
||||
protected void handleRemoteException(RemoteException ex) {
|
||||
logger.fatal("DraftSession error ", ex);
|
||||
DraftManager.getInstance().kill(draft.getId(), userId);
|
||||
}
|
||||
|
||||
public void setKilled() {
|
||||
killed = true;
|
||||
}
|
||||
public void setKilled() {
|
||||
killed = true;
|
||||
}
|
||||
|
||||
public DraftPickView sendCardPick(UUID cardId) {
|
||||
cancelTimeout();
|
||||
if (draft.addPick(playerId, cardId))
|
||||
return getDraftPickView(0);
|
||||
return null;
|
||||
}
|
||||
public DraftPickView sendCardPick(UUID cardId) {
|
||||
cancelTimeout();
|
||||
if (draft.addPick(playerId, cardId))
|
||||
return getDraftPickView(0);
|
||||
return null;
|
||||
}
|
||||
|
||||
public void removeDraft() {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null)
|
||||
user.removeDraft(playerId);
|
||||
}
|
||||
public void removeDraft() {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null)
|
||||
user.removeDraft(playerId);
|
||||
}
|
||||
|
||||
private DraftView getDraftView() {
|
||||
return new DraftView(draft);
|
||||
}
|
||||
private DraftView getDraftView() {
|
||||
return new DraftView(draft);
|
||||
}
|
||||
|
||||
private DraftPickView getDraftPickView(int timeout) {
|
||||
return new DraftPickView(draft.getPlayer(playerId), timeout);
|
||||
}
|
||||
private DraftPickView getDraftPickView(int timeout) {
|
||||
return new DraftPickView(draft.getPlayer(playerId), timeout);
|
||||
}
|
||||
|
||||
public UUID getDraftId() {
|
||||
return draft.getId();
|
||||
}
|
||||
public UUID getDraftId() {
|
||||
return draft.getId();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,40 +41,40 @@ import org.apache.log4j.Logger;
|
|||
*/
|
||||
public class DeckValidatorFactory {
|
||||
|
||||
private final static DeckValidatorFactory INSTANCE = new DeckValidatorFactory();
|
||||
private final static Logger logger = Logger.getLogger(DeckValidatorFactory.class);
|
||||
private final static DeckValidatorFactory INSTANCE = new DeckValidatorFactory();
|
||||
private final static Logger logger = Logger.getLogger(DeckValidatorFactory.class);
|
||||
|
||||
private Map<String, Class> deckTypes = new HashMap<String, Class>();
|
||||
private Map<String, Class> deckTypes = new HashMap<String, Class>();
|
||||
|
||||
public static DeckValidatorFactory getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static DeckValidatorFactory getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private DeckValidatorFactory() {}
|
||||
private DeckValidatorFactory() {}
|
||||
|
||||
public DeckValidator createDeckValidator(String deckType) {
|
||||
public DeckValidator createDeckValidator(String deckType) {
|
||||
|
||||
DeckValidator validator;
|
||||
Constructor<?> con;
|
||||
try {
|
||||
con = deckTypes.get(deckType).getConstructor(new Class[]{});
|
||||
validator = (DeckValidator)con.newInstance(new Object[] {});
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("DeckValidatorFactory error", ex);
|
||||
return null;
|
||||
}
|
||||
logger.info("Deck validator created: " + validator.getName());
|
||||
DeckValidator validator;
|
||||
Constructor<?> con;
|
||||
try {
|
||||
con = deckTypes.get(deckType).getConstructor(new Class[]{});
|
||||
validator = (DeckValidator)con.newInstance(new Object[] {});
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("DeckValidatorFactory error", ex);
|
||||
return null;
|
||||
}
|
||||
logger.info("Deck validator created: " + validator.getName());
|
||||
|
||||
return validator;
|
||||
}
|
||||
return validator;
|
||||
}
|
||||
|
||||
public Set<String> getDeckTypes() {
|
||||
return deckTypes.keySet();
|
||||
}
|
||||
public Set<String> getDeckTypes() {
|
||||
return deckTypes.keySet();
|
||||
}
|
||||
|
||||
public void addDeckType(String name, Class deckType) {
|
||||
if (deckType != null)
|
||||
this.deckTypes.put(name, deckType);
|
||||
}
|
||||
public void addDeckType(String name, Class deckType) {
|
||||
if (deckType != null)
|
||||
this.deckTypes.put(name, deckType);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,6 +36,6 @@ import mage.MageException;
|
|||
*/
|
||||
public interface GameCallback {
|
||||
|
||||
public void gameResult(String result) throws MageException;
|
||||
|
||||
public void gameResult(String result) throws MageException;
|
||||
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -45,46 +45,46 @@ import org.apache.log4j.Logger;
|
|||
*/
|
||||
public class GameFactory {
|
||||
|
||||
private final static GameFactory INSTANCE = new GameFactory();
|
||||
private final static Logger logger = Logger.getLogger(GameFactory.class);
|
||||
private final static GameFactory INSTANCE = new GameFactory();
|
||||
private final static Logger logger = Logger.getLogger(GameFactory.class);
|
||||
|
||||
private Map<String, Class<Match>> games = new HashMap<String, Class<Match>>();
|
||||
private Map<String, MatchType> gameTypes = new HashMap<String, MatchType>();
|
||||
private List<GameTypeView> gameTypeViews = new ArrayList<GameTypeView>();
|
||||
private Map<String, Class<Match>> games = new HashMap<String, Class<Match>>();
|
||||
private Map<String, MatchType> gameTypes = new HashMap<String, MatchType>();
|
||||
private List<GameTypeView> gameTypeViews = new ArrayList<GameTypeView>();
|
||||
|
||||
|
||||
public static GameFactory getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static GameFactory getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private GameFactory() {}
|
||||
private GameFactory() {}
|
||||
|
||||
public Match createMatch(String gameType, MatchOptions options) {
|
||||
public Match createMatch(String gameType, MatchOptions options) {
|
||||
|
||||
Match match;
|
||||
Constructor<Match> con;
|
||||
try {
|
||||
con = games.get(gameType).getConstructor(new Class[]{MatchOptions.class});
|
||||
match = con.newInstance(new Object[] {options});
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("Error creating match - " + gameType, ex);
|
||||
return null;
|
||||
}
|
||||
logger.info("Game created: " + gameType); // + game.getId().toString());
|
||||
Match match;
|
||||
Constructor<Match> con;
|
||||
try {
|
||||
con = games.get(gameType).getConstructor(new Class[]{MatchOptions.class});
|
||||
match = con.newInstance(new Object[] {options});
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("Error creating match - " + gameType, ex);
|
||||
return null;
|
||||
}
|
||||
logger.info("Game created: " + gameType); // + game.getId().toString());
|
||||
|
||||
return match;
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
public List<GameTypeView> getGameTypes() {
|
||||
return gameTypeViews;
|
||||
}
|
||||
public List<GameTypeView> getGameTypes() {
|
||||
return gameTypeViews;
|
||||
}
|
||||
|
||||
public void addGameType(String name, MatchType matchType, Class game) {
|
||||
if (game != null) {
|
||||
this.games.put(name, game);
|
||||
this.gameTypes.put(name, matchType);
|
||||
this.gameTypeViews.add(new GameTypeView(matchType));
|
||||
}
|
||||
}
|
||||
public void addGameType(String name, MatchType matchType, Class game) {
|
||||
if (game != null) {
|
||||
this.games.put(name, game);
|
||||
this.gameTypes.put(name, matchType);
|
||||
this.gameTypeViews.add(new GameTypeView(matchType));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,112 +39,112 @@ import mage.view.GameView;
|
|||
* @author BetaSteward_at_googlemail.com
|
||||
*/
|
||||
public class GameManager {
|
||||
private final static GameManager INSTANCE = new GameManager();
|
||||
private final static GameManager INSTANCE = new GameManager();
|
||||
|
||||
public static GameManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static GameManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private GameManager() {}
|
||||
private GameManager() {}
|
||||
|
||||
private ConcurrentHashMap<UUID, GameController> gameControllers = new ConcurrentHashMap<UUID, GameController>();
|
||||
private ConcurrentHashMap<UUID, GameController> gameControllers = new ConcurrentHashMap<UUID, GameController>();
|
||||
|
||||
public UUID createGameSession(Game game, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId, UUID choosingPlayerId) {
|
||||
GameController gameController = new GameController(game, userPlayerMap, tableId, choosingPlayerId);
|
||||
gameControllers.put(game.getId(), gameController);
|
||||
return gameController.getSessionId();
|
||||
}
|
||||
public UUID createGameSession(Game game, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId, UUID choosingPlayerId) {
|
||||
GameController gameController = new GameController(game, userPlayerMap, tableId, choosingPlayerId);
|
||||
gameControllers.put(game.getId(), gameController);
|
||||
return gameController.getSessionId();
|
||||
}
|
||||
|
||||
public void joinGame(UUID gameId, UUID userId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).join(userId);
|
||||
}
|
||||
public void joinGame(UUID gameId, UUID userId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).join(userId);
|
||||
}
|
||||
|
||||
public void destroyChatSession(UUID gameId) {
|
||||
gameControllers.remove(gameId);
|
||||
}
|
||||
public void destroyChatSession(UUID gameId) {
|
||||
gameControllers.remove(gameId);
|
||||
}
|
||||
|
||||
public UUID getChatId(UUID gameId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
return gameControllers.get(gameId).getChatId();
|
||||
return null;
|
||||
}
|
||||
public UUID getChatId(UUID gameId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
return gameControllers.get(gameId).getChatId();
|
||||
return null;
|
||||
}
|
||||
|
||||
public void sendPlayerUUID(UUID gameId, UUID userId, UUID data) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).sendPlayerUUID(userId, data);
|
||||
}
|
||||
public void sendPlayerUUID(UUID gameId, UUID userId, UUID data) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).sendPlayerUUID(userId, data);
|
||||
}
|
||||
|
||||
public void sendPlayerString(UUID gameId, UUID userId, String data) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).sendPlayerString(userId, data);
|
||||
}
|
||||
public void sendPlayerString(UUID gameId, UUID userId, String data) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).sendPlayerString(userId, data);
|
||||
}
|
||||
|
||||
public void sendPlayerBoolean(UUID gameId, UUID userId, Boolean data) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).sendPlayerBoolean(userId, data);
|
||||
}
|
||||
public void sendPlayerBoolean(UUID gameId, UUID userId, Boolean data) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).sendPlayerBoolean(userId, data);
|
||||
}
|
||||
|
||||
public void sendPlayerInteger(UUID gameId, UUID userId, Integer data) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).sendPlayerInteger(userId, data);
|
||||
}
|
||||
public void sendPlayerInteger(UUID gameId, UUID userId, Integer data) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).sendPlayerInteger(userId, data);
|
||||
}
|
||||
|
||||
public void concedeGame(UUID gameId, UUID userId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).concede(userId);
|
||||
}
|
||||
public void concedeGame(UUID gameId, UUID userId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).concede(userId);
|
||||
}
|
||||
|
||||
public void watchGame(UUID gameId, UUID userId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).watch(userId);
|
||||
}
|
||||
public void watchGame(UUID gameId, UUID userId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).watch(userId);
|
||||
}
|
||||
|
||||
public void stopWatching(UUID gameId, UUID userId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).stopWatching(userId);
|
||||
}
|
||||
public void stopWatching(UUID gameId, UUID userId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).stopWatching(userId);
|
||||
}
|
||||
|
||||
public void removeSession(UUID userId) {
|
||||
for (GameController controller: gameControllers.values()) {
|
||||
controller.kill(userId);
|
||||
}
|
||||
}
|
||||
public void removeSession(UUID userId) {
|
||||
for (GameController controller: gameControllers.values()) {
|
||||
controller.kill(userId);
|
||||
}
|
||||
}
|
||||
|
||||
public void kill(UUID gameId, UUID userId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).kill(userId);
|
||||
}
|
||||
public void kill(UUID gameId, UUID userId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).kill(userId);
|
||||
}
|
||||
|
||||
public void cheat(UUID gameId, UUID userId, UUID playerId, DeckCardLists deckList) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).cheat(userId, playerId, deckList);
|
||||
}
|
||||
public void cheat(UUID gameId, UUID userId, UUID playerId, DeckCardLists deckList) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).cheat(userId, playerId, deckList);
|
||||
}
|
||||
|
||||
public boolean cheat(UUID gameId, UUID userId, UUID playerId, String cardName) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
return gameControllers.get(gameId).cheat(userId, playerId, cardName);
|
||||
return false;
|
||||
}
|
||||
if (gameControllers.containsKey(gameId))
|
||||
return gameControllers.get(gameId).cheat(userId, playerId, cardName);
|
||||
return false;
|
||||
}
|
||||
|
||||
public void timeout(UUID gameId, UUID userId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).timeout(userId);
|
||||
}
|
||||
public void timeout(UUID gameId, UUID userId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).timeout(userId);
|
||||
}
|
||||
|
||||
public void removeGame(UUID gameId) {
|
||||
gameControllers.remove(gameId);
|
||||
}
|
||||
public void removeGame(UUID gameId) {
|
||||
gameControllers.remove(gameId);
|
||||
}
|
||||
|
||||
public void saveGame(UUID gameId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).saveGame();
|
||||
}
|
||||
public void saveGame(UUID gameId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
gameControllers.get(gameId).saveGame();
|
||||
}
|
||||
|
||||
public GameView getGameView(UUID gameId, UUID userId, UUID playerId) {
|
||||
if (gameControllers.containsKey(gameId))
|
||||
return gameControllers.get(gameId).getGameView(playerId);
|
||||
return null;
|
||||
if (gameControllers.containsKey(gameId))
|
||||
return gameControllers.get(gameId).getGameView(playerId);
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,61 +46,61 @@ import org.apache.log4j.Logger;
|
|||
*/
|
||||
public class GameReplay {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(GameReplay.class);
|
||||
private final static Logger logger = Logger.getLogger(GameReplay.class);
|
||||
|
||||
private GameStates savedGame;
|
||||
private Game game;
|
||||
private int stateIndex;
|
||||
private GameStates savedGame;
|
||||
private Game game;
|
||||
private int stateIndex;
|
||||
|
||||
public GameReplay(UUID gameId) {
|
||||
this.game = loadGame(gameId);
|
||||
this.savedGame = game.getGameStates();
|
||||
}
|
||||
public GameReplay(UUID gameId) {
|
||||
this.game = loadGame(gameId);
|
||||
this.savedGame = game.getGameStates();
|
||||
}
|
||||
|
||||
public void start() {
|
||||
this.stateIndex = 0;
|
||||
}
|
||||
public void start() {
|
||||
this.stateIndex = 0;
|
||||
}
|
||||
|
||||
public GameState next() {
|
||||
if (this.stateIndex < savedGame.getSize()) {
|
||||
return savedGame.get(stateIndex++);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public GameState next() {
|
||||
if (this.stateIndex < savedGame.getSize()) {
|
||||
return savedGame.get(stateIndex++);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public GameState previous() {
|
||||
if (this.stateIndex > 0) {
|
||||
return savedGame.get(--stateIndex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public GameState previous() {
|
||||
if (this.stateIndex > 0) {
|
||||
return savedGame.get(--stateIndex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Game getGame() {
|
||||
return this.game;
|
||||
}
|
||||
public Game getGame() {
|
||||
return this.game;
|
||||
}
|
||||
|
||||
private Game loadGame(UUID gameId) {
|
||||
try{
|
||||
InputStream file = new FileInputStream("saved/" + gameId.toString() + ".game");
|
||||
InputStream buffer = new BufferedInputStream(file);
|
||||
ObjectInput input = new CopierObjectInputStream(Main.classLoader, new GZIPInputStream(buffer));
|
||||
try {
|
||||
Game loadGame = (Game)input.readObject();
|
||||
GameStates states = (GameStates)input.readObject();
|
||||
loadGame.loadGameStates(states);
|
||||
return loadGame;
|
||||
}
|
||||
finally {
|
||||
input.close();
|
||||
}
|
||||
}
|
||||
catch(ClassNotFoundException ex) {
|
||||
logger.fatal("Cannot load game. Class not found.", ex);
|
||||
}
|
||||
catch(IOException ex) {
|
||||
logger.fatal("Cannot load game:" + gameId, ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
private Game loadGame(UUID gameId) {
|
||||
try{
|
||||
InputStream file = new FileInputStream("saved/" + gameId.toString() + ".game");
|
||||
InputStream buffer = new BufferedInputStream(file);
|
||||
ObjectInput input = new CopierObjectInputStream(Main.classLoader, new GZIPInputStream(buffer));
|
||||
try {
|
||||
Game loadGame = (Game)input.readObject();
|
||||
GameStates states = (GameStates)input.readObject();
|
||||
loadGame.loadGameStates(states);
|
||||
return loadGame;
|
||||
}
|
||||
finally {
|
||||
input.close();
|
||||
}
|
||||
}
|
||||
catch(ClassNotFoundException ex) {
|
||||
logger.fatal("Cannot load game. Class not found.", ex);
|
||||
}
|
||||
catch(IOException ex) {
|
||||
logger.fatal("Cannot load game:" + gameId, ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,206 +56,206 @@ import mage.view.SimpleCardsView;
|
|||
*/
|
||||
public class GameSession extends GameWatcher {
|
||||
|
||||
private UUID playerId;
|
||||
private UUID playerId;
|
||||
private boolean useTimeout;
|
||||
|
||||
private ScheduledFuture<?> futureTimeout;
|
||||
protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor();
|
||||
private ScheduledFuture<?> futureTimeout;
|
||||
protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor();
|
||||
|
||||
private UserData userData;
|
||||
private UserData userData;
|
||||
|
||||
public GameSession(Game game, UUID userId, UUID playerId, boolean useTimeout) {
|
||||
super(userId, game);
|
||||
this.playerId = playerId;
|
||||
public GameSession(Game game, UUID userId, UUID playerId, boolean useTimeout) {
|
||||
super(userId, game);
|
||||
this.playerId = playerId;
|
||||
this.useTimeout = useTimeout;
|
||||
}
|
||||
}
|
||||
|
||||
public void ask(final String question) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameAsk", game.getId(), new GameClientMessage(getGameView(), question)));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void ask(final String question) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameAsk", game.getId(), new GameClientMessage(getGameView(), question)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void target(final String question, final CardsView cardView, final Set<UUID> targets, final boolean required, final Map<String, Serializable> options) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameTarget", game.getId(), new GameClientMessage(getGameView(), question, cardView, targets, required, options)));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void target(final String question, final CardsView cardView, final Set<UUID> targets, final boolean required, final Map<String, Serializable> options) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameTarget", game.getId(), new GameClientMessage(getGameView(), question, cardView, targets, required, options)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void select(final String message) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameSelect", game.getId(), new GameClientMessage(getGameView(), message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void select(final String message) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameSelect", game.getId(), new GameClientMessage(getGameView(), message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void chooseAbility(final AbilityPickerView abilities) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameChooseAbility", game.getId(), abilities));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void chooseAbility(final AbilityPickerView abilities) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameChooseAbility", game.getId(), abilities));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void choosePile(final String message, final CardsView pile1, final CardsView pile2) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
public void choosePile(final String message, final CardsView pile1, final CardsView pile2) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
List<CardsView> piles = new ArrayList<CardsView>();
|
||||
piles.add(pile1);
|
||||
piles.add(pile2);
|
||||
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 choose(final String message, final Set<String> choices) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameChoose", game.getId(), new GameClientMessage(choices.toArray(new String[0]), message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void choose(final String message, final Set<String> choices) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameChoose", game.getId(), new GameClientMessage(choices.toArray(new String[0]), message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void playMana(final String message) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gamePlayMana", game.getId(), new GameClientMessage(getGameView(), message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void playMana(final String message) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gamePlayMana", game.getId(), new GameClientMessage(getGameView(), message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void playXMana(final String message) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gamePlayXMana", game.getId(), new GameClientMessage(getGameView(), message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void playXMana(final String message) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
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) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameSelectAmount", game.getId(), new GameClientMessage(message, min, max)));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void getAmount(final String message, final int min, final int max) {
|
||||
if (!killed) {
|
||||
setupTimeout();
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameSelectAmount", game.getId(), new GameClientMessage(message, min, max)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void revealCards(final String name, final CardsView cardView) {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameReveal", game.getId(), new GameClientMessage(cardView, name)));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void revealCards(final String name, final CardsView cardView) {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameReveal", game.getId(), new GameClientMessage(cardView, name)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void setupTimeout() {
|
||||
private synchronized void setupTimeout() {
|
||||
if (!useTimeout)
|
||||
return;
|
||||
cancelTimeout();
|
||||
futureTimeout = timeoutExecutor.schedule(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
GameManager.getInstance().timeout(game.getId(), userId);
|
||||
}
|
||||
},
|
||||
ConfigSettings.getInstance().getMaxSecondsIdle(), TimeUnit.SECONDS
|
||||
);
|
||||
}
|
||||
cancelTimeout();
|
||||
futureTimeout = timeoutExecutor.schedule(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
GameManager.getInstance().timeout(game.getId(), userId);
|
||||
}
|
||||
},
|
||||
ConfigSettings.getInstance().getMaxSecondsIdle(), TimeUnit.SECONDS
|
||||
);
|
||||
}
|
||||
|
||||
private synchronized void cancelTimeout() {
|
||||
if (futureTimeout != null) {
|
||||
futureTimeout.cancel(false);
|
||||
}
|
||||
}
|
||||
private synchronized void cancelTimeout() {
|
||||
if (futureTimeout != null) {
|
||||
futureTimeout.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
public void sendPlayerUUID(UUID data) {
|
||||
cancelTimeout();
|
||||
game.getPlayer(playerId).setResponseUUID(data);
|
||||
}
|
||||
public void sendPlayerUUID(UUID data) {
|
||||
cancelTimeout();
|
||||
game.getPlayer(playerId).setResponseUUID(data);
|
||||
}
|
||||
|
||||
public void sendPlayerString(String data) {
|
||||
cancelTimeout();
|
||||
game.getPlayer(playerId).setResponseString(data);
|
||||
}
|
||||
public void sendPlayerString(String data) {
|
||||
cancelTimeout();
|
||||
game.getPlayer(playerId).setResponseString(data);
|
||||
}
|
||||
|
||||
public void sendPlayerBoolean(Boolean data) {
|
||||
cancelTimeout();
|
||||
game.getPlayer(playerId).setResponseBoolean(data);
|
||||
}
|
||||
public void sendPlayerBoolean(Boolean data) {
|
||||
cancelTimeout();
|
||||
game.getPlayer(playerId).setResponseBoolean(data);
|
||||
}
|
||||
|
||||
public void sendPlayerInteger(Integer data) {
|
||||
cancelTimeout();
|
||||
game.getPlayer(playerId).setResponseInteger(data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GameView getGameView() {
|
||||
Player player = game.getPlayer(playerId);
|
||||
player.setUserData(this.userData);
|
||||
GameView gameView = new GameView(game.getState(), game);
|
||||
gameView.setHand(new SimpleCardsView(player.getHand().getCards(game)));
|
||||
public void sendPlayerInteger(Integer data) {
|
||||
cancelTimeout();
|
||||
game.getPlayer(playerId).setResponseInteger(data);
|
||||
}
|
||||
|
||||
if (player.getPlayersUnderYourControl().size() > 0) {
|
||||
Map<String, SimpleCardsView> handCards = new HashMap<String, SimpleCardsView>();
|
||||
for (UUID playerId : player.getPlayersUnderYourControl()) {
|
||||
Player opponent = game.getPlayer(playerId);
|
||||
handCards.put(opponent.getName(), new SimpleCardsView(opponent.getHand().getCards(game)));
|
||||
}
|
||||
gameView.setOpponentHands(handCards);
|
||||
}
|
||||
@Override
|
||||
public GameView getGameView() {
|
||||
Player player = game.getPlayer(playerId);
|
||||
player.setUserData(this.userData);
|
||||
GameView gameView = new GameView(game.getState(), game);
|
||||
gameView.setHand(new SimpleCardsView(player.getHand().getCards(game)));
|
||||
|
||||
//TODO: should player who controls another player's turn be able to look at all these cards?
|
||||
if (player.getPlayersUnderYourControl().size() > 0) {
|
||||
Map<String, SimpleCardsView> handCards = new HashMap<String, SimpleCardsView>();
|
||||
for (UUID playerId : player.getPlayersUnderYourControl()) {
|
||||
Player opponent = game.getPlayer(playerId);
|
||||
handCards.put(opponent.getName(), new SimpleCardsView(opponent.getHand().getCards(game)));
|
||||
}
|
||||
gameView.setOpponentHands(handCards);
|
||||
}
|
||||
|
||||
List<LookedAtView> list = new ArrayList<LookedAtView>();
|
||||
for (Entry<String, Cards> entry : game.getState().getLookedAt(playerId).entrySet()) {
|
||||
list.add(new LookedAtView(entry.getKey(), entry.getValue(), game));
|
||||
}
|
||||
gameView.setLookedAt(list);
|
||||
//TODO: should player who controls another player's turn be able to look at all these cards?
|
||||
|
||||
List<LookedAtView> list = new ArrayList<LookedAtView>();
|
||||
for (Entry<String, Cards> entry : game.getState().getLookedAt(playerId).entrySet()) {
|
||||
list.add(new LookedAtView(entry.getKey(), entry.getValue(), game));
|
||||
}
|
||||
gameView.setLookedAt(list);
|
||||
game.getState().clearLookedAt();
|
||||
|
||||
return gameView;
|
||||
}
|
||||
return gameView;
|
||||
}
|
||||
|
||||
public void removeGame() {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null)
|
||||
user.removeGame(playerId);
|
||||
}
|
||||
public void removeGame() {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null)
|
||||
user.removeGame(playerId);
|
||||
}
|
||||
|
||||
public UUID getGameId() {
|
||||
return game.getId();
|
||||
}
|
||||
|
||||
public void kill() {
|
||||
game.quit(playerId);
|
||||
}
|
||||
public UUID getGameId() {
|
||||
return game.getId();
|
||||
}
|
||||
|
||||
public void setUserData(UserData userData) {
|
||||
this.userData = userData;
|
||||
}
|
||||
public void kill() {
|
||||
game.quit(playerId);
|
||||
}
|
||||
|
||||
public void setUserData(UserData userData) {
|
||||
this.userData = userData;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,75 +44,75 @@ import org.apache.log4j.Logger;
|
|||
*/
|
||||
public class GameWatcher {
|
||||
|
||||
protected final static Logger logger = Logger.getLogger(GameWatcher.class);
|
||||
protected final static Logger logger = Logger.getLogger(GameWatcher.class);
|
||||
|
||||
protected UUID userId;
|
||||
protected Game game;
|
||||
protected boolean killed = false;
|
||||
protected UUID userId;
|
||||
protected Game game;
|
||||
protected boolean killed = false;
|
||||
|
||||
public GameWatcher(UUID userId, Game game) {
|
||||
this.userId = userId;
|
||||
this.game = game;
|
||||
}
|
||||
public GameWatcher(UUID userId, Game game) {
|
||||
this.userId = userId;
|
||||
this.game = game;
|
||||
}
|
||||
|
||||
public boolean init() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameInit", game.getId(), getGameView()));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public boolean init() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameInit", game.getId(), getGameView()));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void update() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameUpdate", game.getId(), getGameView()));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void update() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void gameOver(final String message) {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameOver", game.getId(), message));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void gameOver(final String message) {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("gameOver", game.getId(), message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void handleRemoteException(RemoteException ex) {
|
||||
logger.fatal("GameWatcher error", ex);
|
||||
GameManager.getInstance().kill(game.getId(), userId);
|
||||
}
|
||||
|
||||
public void setKilled() {
|
||||
killed = true;
|
||||
}
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public GameView getGameView() {
|
||||
return new GameView(game.getState(), game);
|
||||
}
|
||||
protected void handleRemoteException(RemoteException ex) {
|
||||
logger.fatal("GameWatcher error", ex);
|
||||
GameManager.getInstance().kill(game.getId(), userId);
|
||||
}
|
||||
|
||||
public void setKilled() {
|
||||
killed = true;
|
||||
}
|
||||
|
||||
public GameView getGameView() {
|
||||
return new GameView(game.getState(), game);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,28 +40,28 @@ import java.util.concurrent.Callable;
|
|||
*/
|
||||
public class GameWorker implements Callable {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(GameWorker.class);
|
||||
private final static Logger logger = Logger.getLogger(GameWorker.class);
|
||||
|
||||
private GameCallback result;
|
||||
private Game game;
|
||||
private UUID choosingPlayerId;
|
||||
private GameCallback result;
|
||||
private Game game;
|
||||
private UUID choosingPlayerId;
|
||||
|
||||
public GameWorker(Game game, UUID choosingPlayerId, GameCallback result) {
|
||||
this.game = game;
|
||||
this.choosingPlayerId = choosingPlayerId;
|
||||
this.result = result;
|
||||
}
|
||||
public GameWorker(Game game, UUID choosingPlayerId, GameCallback result) {
|
||||
this.game = game;
|
||||
this.choosingPlayerId = choosingPlayerId;
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object call() {
|
||||
try {
|
||||
game.start(choosingPlayerId);
|
||||
game.fireUpdatePlayersEvent();
|
||||
result.gameResult(game.getWinner());
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("GameWorker error ", ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public Object call() {
|
||||
try {
|
||||
game.start(choosingPlayerId);
|
||||
game.fireUpdatePlayersEvent();
|
||||
result.gameResult(game.getWinner());
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("GameWorker error ", ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,17 +45,17 @@ import mage.view.TableView;
|
|||
*/
|
||||
public interface GamesRoom extends Room {
|
||||
|
||||
public List<TableView> getTables();
|
||||
public List<TableView> getTables();
|
||||
public List<MatchView> getFinished();
|
||||
public List<String> getPlayers();
|
||||
public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException;
|
||||
public boolean joinTournamentTable(UUID userId, UUID tableId, String name, String playerType, int skill) throws GameException;
|
||||
public TableView createTable(UUID userId, MatchOptions options);
|
||||
public TableView createTournamentTable(UUID userId, TournamentOptions options);
|
||||
public void removeTable(UUID userId, UUID tableId);
|
||||
public void removeTable(UUID tableId);
|
||||
public TableView getTable(UUID tableId);
|
||||
public void leaveTable(UUID userId, UUID tableId);
|
||||
public boolean watchTable(UUID userId, UUID tableId) throws MageException;
|
||||
public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException;
|
||||
public boolean joinTournamentTable(UUID userId, UUID tableId, String name, String playerType, int skill) throws GameException;
|
||||
public TableView createTable(UUID userId, MatchOptions options);
|
||||
public TableView createTournamentTable(UUID userId, TournamentOptions options);
|
||||
public void removeTable(UUID userId, UUID tableId);
|
||||
public void removeTable(UUID tableId);
|
||||
public TableView getTable(UUID tableId);
|
||||
public void leaveTable(UUID userId, UUID tableId);
|
||||
public boolean watchTable(UUID userId, UUID tableId) throws MageException;
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -60,116 +60,116 @@ import org.apache.log4j.Logger;
|
|||
*/
|
||||
public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(GamesRoomImpl.class);
|
||||
|
||||
private static ScheduledExecutorService updateExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
private final static Logger logger = Logger.getLogger(GamesRoomImpl.class);
|
||||
|
||||
private static ScheduledExecutorService updateExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
private static List<TableView> tableView = new ArrayList<TableView>();
|
||||
private static List<MatchView> matchView = new ArrayList<MatchView>();
|
||||
private static List<String> playersView = new ArrayList<String>();
|
||||
|
||||
private ConcurrentHashMap<UUID, Table> tables = new ConcurrentHashMap<UUID, Table>();
|
||||
|
||||
public GamesRoomImpl() {
|
||||
updateExecutor.scheduleAtFixedRate(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
update();
|
||||
}
|
||||
}, 2, 2, TimeUnit.SECONDS);
|
||||
}
|
||||
private ConcurrentHashMap<UUID, Table> tables = new ConcurrentHashMap<UUID, Table>();
|
||||
|
||||
public GamesRoomImpl() {
|
||||
updateExecutor.scheduleAtFixedRate(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
update();
|
||||
}
|
||||
}, 2, 2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TableView> getTables() {
|
||||
return tableView;
|
||||
}
|
||||
public List<TableView> getTables() {
|
||||
return tableView;
|
||||
}
|
||||
|
||||
private void update() {
|
||||
ArrayList<TableView> tableList = new ArrayList<TableView>();
|
||||
ArrayList<MatchView> matchList = new ArrayList<MatchView>();
|
||||
private void update() {
|
||||
ArrayList<TableView> tableList = new ArrayList<TableView>();
|
||||
ArrayList<MatchView> matchList = new ArrayList<MatchView>();
|
||||
List<Table> t = new ArrayList<Table>(tables.values());
|
||||
Collections.sort(t, new TimestampSorter());
|
||||
for (Table table: t) {
|
||||
for (Table table: t) {
|
||||
if (table.getState() != TableState.FINISHED) {
|
||||
tableList.add(new TableView(table));
|
||||
}
|
||||
else if (matchList.size() < 50) {
|
||||
matchList.add(new MatchView(table.getMatch()));
|
||||
}
|
||||
}
|
||||
tableView = tableList;
|
||||
matchView = matchList;
|
||||
}
|
||||
tableView = tableList;
|
||||
matchView = matchList;
|
||||
List<String> players = new ArrayList<String>();
|
||||
for (User user : UserManager.getInstance().getUsers()) {
|
||||
players.add(user.getName());
|
||||
}
|
||||
playersView = players;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MatchView> getFinished() {
|
||||
return matchView;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException {
|
||||
if (tables.containsKey(tableId)) {
|
||||
return TableManager.getInstance().joinTable(userId, tableId, name, playerType, skill, deckList);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public List<MatchView> getFinished() {
|
||||
return matchView;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableView createTable(UUID userId, MatchOptions options) {
|
||||
Table table = TableManager.getInstance().createTable(this.getRoomId(), userId, options);
|
||||
tables.put(table.getId(), table);
|
||||
return new TableView(table);
|
||||
}
|
||||
@Override
|
||||
public boolean joinTable(UUID userId, UUID tableId, String name, String playerType, int skill, DeckCardLists deckList) throws MageException {
|
||||
if (tables.containsKey(tableId)) {
|
||||
return TableManager.getInstance().joinTable(userId, tableId, name, playerType, skill, deckList);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean joinTournamentTable(UUID userId, UUID tableId, String name, String playerType, int skill) throws GameException {
|
||||
if (tables.containsKey(tableId)) {
|
||||
return TableManager.getInstance().joinTournament(userId, tableId, name, playerType, skill);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public TableView createTable(UUID userId, MatchOptions options) {
|
||||
Table table = TableManager.getInstance().createTable(this.getRoomId(), userId, options);
|
||||
tables.put(table.getId(), table);
|
||||
return new TableView(table);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableView createTournamentTable(UUID userId, TournamentOptions options) {
|
||||
Table table = TableManager.getInstance().createTournamentTable(this.getRoomId(), userId, options);
|
||||
tables.put(table.getId(), table);
|
||||
return new TableView(table);
|
||||
}
|
||||
@Override
|
||||
public boolean joinTournamentTable(UUID userId, UUID tableId, String name, String playerType, int skill) throws GameException {
|
||||
if (tables.containsKey(tableId)) {
|
||||
return TableManager.getInstance().joinTournament(userId, tableId, name, playerType, skill);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableView getTable(UUID tableId) {
|
||||
if (tables.containsKey(tableId))
|
||||
return new TableView(tables.get(tableId));
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public TableView createTournamentTable(UUID userId, TournamentOptions options) {
|
||||
Table table = TableManager.getInstance().createTournamentTable(this.getRoomId(), userId, options);
|
||||
tables.put(table.getId(), table);
|
||||
return new TableView(table);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTable(UUID userId, UUID tableId) {
|
||||
tables.remove(tableId);
|
||||
}
|
||||
@Override
|
||||
public TableView getTable(UUID tableId) {
|
||||
if (tables.containsKey(tableId))
|
||||
return new TableView(tables.get(tableId));
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTable(UUID tableId) {
|
||||
tables.remove(tableId);
|
||||
if (logger.isDebugEnabled())
|
||||
logger.debug("Table removed: " + tableId);
|
||||
}
|
||||
@Override
|
||||
public void removeTable(UUID userId, UUID tableId) {
|
||||
tables.remove(tableId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void leaveTable(UUID userId, UUID tableId) {
|
||||
TableManager.getInstance().leaveTable(userId, tableId);
|
||||
}
|
||||
@Override
|
||||
public void removeTable(UUID tableId) {
|
||||
tables.remove(tableId);
|
||||
if (logger.isDebugEnabled())
|
||||
logger.debug("Table removed: " + tableId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean watchTable(UUID userId, UUID tableId) throws MageException {
|
||||
return TableManager.getInstance().watchTable(userId, tableId);
|
||||
}
|
||||
@Override
|
||||
public void leaveTable(UUID userId, UUID tableId) {
|
||||
TableManager.getInstance().leaveTable(userId, tableId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean watchTable(UUID userId, UUID tableId) throws MageException {
|
||||
return TableManager.getInstance().watchTable(userId, tableId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getPlayers() {
|
||||
|
|
@ -179,8 +179,8 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
|
|||
}
|
||||
|
||||
class TimestampSorter implements Comparator<Table> {
|
||||
@Override
|
||||
public int compare(Table one, Table two) {
|
||||
return one.getCreateTime().compareTo(two.getCreateTime());
|
||||
}
|
||||
@Override
|
||||
public int compare(Table one, Table two) {
|
||||
return one.getCreateTime().compareTo(two.getCreateTime());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,40 +37,40 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||
*/
|
||||
public class GamesRoomManager {
|
||||
|
||||
private final static GamesRoomManager INSTANCE = new GamesRoomManager();
|
||||
// private final static Logger logger = Logger.getLogger(GamesRoomManager.class);
|
||||
private final static GamesRoomManager INSTANCE = new GamesRoomManager();
|
||||
// private final static Logger logger = Logger.getLogger(GamesRoomManager.class);
|
||||
|
||||
private ConcurrentHashMap<UUID, GamesRoom> rooms = new ConcurrentHashMap<UUID, GamesRoom>();
|
||||
private UUID mainRoomId;
|
||||
private ConcurrentHashMap<UUID, GamesRoom> rooms = new ConcurrentHashMap<UUID, GamesRoom>();
|
||||
private UUID mainRoomId;
|
||||
|
||||
public static GamesRoomManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static GamesRoomManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private GamesRoomManager() {
|
||||
GamesRoom mainRoom = new GamesRoomImpl();
|
||||
mainRoomId = mainRoom.getRoomId();
|
||||
rooms.put(mainRoomId, mainRoom);
|
||||
}
|
||||
private GamesRoomManager() {
|
||||
GamesRoom mainRoom = new GamesRoomImpl();
|
||||
mainRoomId = mainRoom.getRoomId();
|
||||
rooms.put(mainRoomId, mainRoom);
|
||||
}
|
||||
|
||||
public UUID createRoom() {
|
||||
GamesRoom room = new GamesRoomImpl();
|
||||
rooms.put(room.getRoomId(), room);
|
||||
return room.getRoomId();
|
||||
}
|
||||
public UUID createRoom() {
|
||||
GamesRoom room = new GamesRoomImpl();
|
||||
rooms.put(room.getRoomId(), room);
|
||||
return room.getRoomId();
|
||||
}
|
||||
|
||||
public UUID getMainRoomId() {
|
||||
return mainRoomId;
|
||||
}
|
||||
public UUID getMainRoomId() {
|
||||
return mainRoomId;
|
||||
}
|
||||
|
||||
public GamesRoom getRoom(UUID roomId) {
|
||||
return rooms.get(roomId);
|
||||
}
|
||||
|
||||
public void removeTable(UUID tableId) {
|
||||
for (GamesRoom room: rooms.values()) {
|
||||
room.removeTable(tableId);
|
||||
}
|
||||
}
|
||||
public GamesRoom getRoom(UUID roomId) {
|
||||
return rooms.get(roomId);
|
||||
}
|
||||
|
||||
public void removeTable(UUID tableId) {
|
||||
for (GamesRoom room: rooms.values()) {
|
||||
room.removeTable(tableId);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,21 +42,21 @@ import org.apache.log4j.Logger;
|
|||
*/
|
||||
public class PlayerFactory {
|
||||
|
||||
private final static PlayerFactory INSTANCE = new PlayerFactory();
|
||||
private final static Logger logger = Logger.getLogger(PlayerFactory.class);
|
||||
private final static PlayerFactory INSTANCE = new PlayerFactory();
|
||||
private final static Logger logger = Logger.getLogger(PlayerFactory.class);
|
||||
|
||||
private Map<String, Class> playerTypes = new LinkedHashMap<String, Class>();
|
||||
private Map<String, Class> playerTypes = new LinkedHashMap<String, Class>();
|
||||
|
||||
public static PlayerFactory getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static PlayerFactory getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private PlayerFactory() {}
|
||||
private PlayerFactory() {}
|
||||
|
||||
public Player createPlayer(String playerType, String name, RangeOfInfluence range, int skill) {
|
||||
Player player;
|
||||
Constructor<?> con;
|
||||
try {
|
||||
public Player createPlayer(String playerType, String name, RangeOfInfluence range, int skill) {
|
||||
Player player;
|
||||
Constructor<?> con;
|
||||
try {
|
||||
Class playerTypeClass = playerTypes.get(playerType);
|
||||
if (playerTypeClass != null) {
|
||||
con = playerTypeClass.getConstructor(new Class[]{String.class, RangeOfInfluence.class, int.class});
|
||||
|
|
@ -67,19 +67,19 @@ public class PlayerFactory {
|
|||
else {
|
||||
logger.fatal("Unknown player type: " + playerType);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("PlayerFactory error ", ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("PlayerFactory error ", ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Set<String> getPlayerTypes() {
|
||||
return playerTypes.keySet();
|
||||
}
|
||||
public Set<String> getPlayerTypes() {
|
||||
return playerTypes.keySet();
|
||||
}
|
||||
|
||||
public void addPlayerType(String name, Class playerType) {
|
||||
if (playerType != null)
|
||||
this.playerTypes.put(name, playerType);
|
||||
}
|
||||
public void addPlayerType(String name, Class playerType) {
|
||||
if (playerType != null)
|
||||
this.playerTypes.put(name, playerType);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,41 +37,41 @@ import mage.server.UserManager;
|
|||
* @author BetaSteward_at_googlemail.com
|
||||
*/
|
||||
public class ReplayManager {
|
||||
private final static ReplayManager INSTANCE = new ReplayManager();
|
||||
private final static ReplayManager INSTANCE = new ReplayManager();
|
||||
|
||||
public static ReplayManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static ReplayManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private ReplayManager() {}
|
||||
private ReplayManager() {}
|
||||
|
||||
private ConcurrentHashMap<String, ReplaySession> replaySessions = new ConcurrentHashMap<String, ReplaySession>();
|
||||
private ConcurrentHashMap<String, ReplaySession> replaySessions = new ConcurrentHashMap<String, ReplaySession>();
|
||||
|
||||
public void replayGame(UUID gameId, UUID userId) {
|
||||
ReplaySession replaySession = new ReplaySession(gameId, userId);
|
||||
replaySessions.put(gameId.toString() + userId.toString(), replaySession);
|
||||
UserManager.getInstance().getUser(userId).replayGame(gameId);
|
||||
}
|
||||
public void replayGame(UUID gameId, UUID userId) {
|
||||
ReplaySession replaySession = new ReplaySession(gameId, userId);
|
||||
replaySessions.put(gameId.toString() + userId.toString(), replaySession);
|
||||
UserManager.getInstance().getUser(userId).replayGame(gameId);
|
||||
}
|
||||
|
||||
public void startReplay(UUID gameId, UUID userId) {
|
||||
replaySessions.get(gameId.toString() + userId.toString()).replay();
|
||||
}
|
||||
public void startReplay(UUID gameId, UUID userId) {
|
||||
replaySessions.get(gameId.toString() + userId.toString()).replay();
|
||||
}
|
||||
|
||||
public void stopReplay(UUID gameId, UUID userId) {
|
||||
replaySessions.get(gameId.toString() + userId.toString()).stop();
|
||||
}
|
||||
public void stopReplay(UUID gameId, UUID userId) {
|
||||
replaySessions.get(gameId.toString() + userId.toString()).stop();
|
||||
}
|
||||
|
||||
public void nextPlay(UUID gameId, UUID userId) {
|
||||
replaySessions.get(gameId.toString() + userId.toString()).next();
|
||||
}
|
||||
public void nextPlay(UUID gameId, UUID userId) {
|
||||
replaySessions.get(gameId.toString() + userId.toString()).next();
|
||||
}
|
||||
|
||||
public void previousPlay(UUID gameId, UUID userId) {
|
||||
replaySessions.get(gameId.toString() + userId.toString()).previous();
|
||||
}
|
||||
|
||||
public void skipForward(UUID gameId, UUID userId, int moves) {
|
||||
replaySessions.get(gameId.toString() + userId.toString()).next(moves);
|
||||
}
|
||||
public void previousPlay(UUID gameId, UUID userId) {
|
||||
replaySessions.get(gameId.toString() + userId.toString()).previous();
|
||||
}
|
||||
|
||||
public void skipForward(UUID gameId, UUID userId, int moves) {
|
||||
replaySessions.get(gameId.toString() + userId.toString()).next(moves);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,60 +43,60 @@ import org.apache.log4j.Logger;
|
|||
*/
|
||||
public class ReplaySession implements GameCallback {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(ReplaySession.class);
|
||||
private GameReplay replay;
|
||||
protected UUID userId;
|
||||
private final static Logger logger = Logger.getLogger(ReplaySession.class);
|
||||
private GameReplay replay;
|
||||
protected UUID userId;
|
||||
|
||||
ReplaySession(UUID gameId, UUID userId) {
|
||||
this.replay = new GameReplay(gameId);
|
||||
this.userId = userId;
|
||||
}
|
||||
ReplaySession(UUID gameId, UUID userId) {
|
||||
this.replay = new GameReplay(gameId);
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
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())));
|
||||
}
|
||||
}
|
||||
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())));
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
gameResult("stopped replay");
|
||||
}
|
||||
public void stop() {
|
||||
gameResult("stopped replay");
|
||||
}
|
||||
|
||||
public synchronized void next() {
|
||||
updateGame(replay.next(), replay.getGame());
|
||||
}
|
||||
public synchronized void next() {
|
||||
updateGame(replay.next(), replay.getGame());
|
||||
}
|
||||
|
||||
public synchronized void next(int moves) {
|
||||
public synchronized void next(int moves) {
|
||||
for (int i = 0; i < moves; i++) {
|
||||
replay.next();
|
||||
}
|
||||
updateGame(replay.next(), replay.getGame());
|
||||
}
|
||||
updateGame(replay.next(), replay.getGame());
|
||||
}
|
||||
|
||||
public synchronized void previous() {
|
||||
updateGame(replay.previous(), replay.getGame());
|
||||
}
|
||||
updateGame(replay.previous(), replay.getGame());
|
||||
}
|
||||
|
||||
@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));
|
||||
}
|
||||
}
|
||||
@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));
|
||||
}
|
||||
}
|
||||
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -58,218 +58,218 @@ import org.apache.log4j.Logger;
|
|||
*/
|
||||
public class TournamentController {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(TournamentController.class);
|
||||
private final static Logger logger = Logger.getLogger(TournamentController.class);
|
||||
|
||||
private UUID chatId;
|
||||
private UUID tableId;
|
||||
private boolean started = false;
|
||||
private Tournament tournament;
|
||||
private ConcurrentHashMap<UUID, UUID> userPlayerMap = new ConcurrentHashMap<UUID, UUID>();
|
||||
private ConcurrentHashMap<UUID, TournamentSession> tournamentSessions = new ConcurrentHashMap<UUID, TournamentSession>();
|
||||
private UUID chatId;
|
||||
private UUID tableId;
|
||||
private boolean started = false;
|
||||
private Tournament tournament;
|
||||
private ConcurrentHashMap<UUID, UUID> userPlayerMap = new ConcurrentHashMap<UUID, UUID>();
|
||||
private ConcurrentHashMap<UUID, TournamentSession> tournamentSessions = new ConcurrentHashMap<UUID, TournamentSession>();
|
||||
|
||||
public TournamentController(Tournament tournament, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {
|
||||
this.userPlayerMap = userPlayerMap;
|
||||
chatId = ChatManager.getInstance().createChatSession();
|
||||
this.tournament = tournament;
|
||||
this.tableId = tableId;
|
||||
init();
|
||||
}
|
||||
public TournamentController(Tournament tournament, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {
|
||||
this.userPlayerMap = userPlayerMap;
|
||||
chatId = ChatManager.getInstance().createChatSession();
|
||||
this.tournament = tournament;
|
||||
this.tableId = tableId;
|
||||
init();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
tournament.addTableEventListener(
|
||||
new Listener<TableEvent> () {
|
||||
@Override
|
||||
public void event(TableEvent event) {
|
||||
switch (event.getEventType()) {
|
||||
case INFO:
|
||||
ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK);
|
||||
logger.debug(tournament.getId() + " " + event.getMessage());
|
||||
break;
|
||||
case START_DRAFT:
|
||||
startDraft(event.getDraft());
|
||||
break;
|
||||
case START_MATCH:
|
||||
startMatch(event.getPair(), event.getMatchOptions());
|
||||
break;
|
||||
// case SUBMIT_DECK:
|
||||
// submitDeck(event.getPlayerId(), event.getDeck());
|
||||
// break;
|
||||
case CONSTRUCT:
|
||||
construct();
|
||||
break;
|
||||
case END:
|
||||
endTournament();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
tournament.addPlayerQueryEventListener(
|
||||
new Listener<PlayerQueryEvent> () {
|
||||
@Override
|
||||
public void event(PlayerQueryEvent event) {
|
||||
try {
|
||||
switch (event.getQueryType()) {
|
||||
case CONSTRUCT:
|
||||
construct(event.getPlayerId(), event.getMax());
|
||||
break;
|
||||
}
|
||||
} catch (MageException ex) {
|
||||
logger.fatal("Player event listener error", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
for (TournamentPlayer player: tournament.getPlayers()) {
|
||||
if (!player.getPlayer().isHuman()) {
|
||||
player.setJoined();
|
||||
logger.info("player " + player.getPlayer().getId() + " has joined tournament " + tournament.getId());
|
||||
ChatManager.getInstance().broadcast(chatId, "", player.getPlayer().getName() + " has joined the tournament", MessageColor.BLACK);
|
||||
}
|
||||
}
|
||||
checkStart();
|
||||
}
|
||||
private void init() {
|
||||
tournament.addTableEventListener(
|
||||
new Listener<TableEvent> () {
|
||||
@Override
|
||||
public void event(TableEvent event) {
|
||||
switch (event.getEventType()) {
|
||||
case INFO:
|
||||
ChatManager.getInstance().broadcast(chatId, "", event.getMessage(), MessageColor.BLACK);
|
||||
logger.debug(tournament.getId() + " " + event.getMessage());
|
||||
break;
|
||||
case START_DRAFT:
|
||||
startDraft(event.getDraft());
|
||||
break;
|
||||
case START_MATCH:
|
||||
startMatch(event.getPair(), event.getMatchOptions());
|
||||
break;
|
||||
// case SUBMIT_DECK:
|
||||
// submitDeck(event.getPlayerId(), event.getDeck());
|
||||
// break;
|
||||
case CONSTRUCT:
|
||||
construct();
|
||||
break;
|
||||
case END:
|
||||
endTournament();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
tournament.addPlayerQueryEventListener(
|
||||
new Listener<PlayerQueryEvent> () {
|
||||
@Override
|
||||
public void event(PlayerQueryEvent event) {
|
||||
try {
|
||||
switch (event.getQueryType()) {
|
||||
case CONSTRUCT:
|
||||
construct(event.getPlayerId(), event.getMax());
|
||||
break;
|
||||
}
|
||||
} catch (MageException ex) {
|
||||
logger.fatal("Player event listener error", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
for (TournamentPlayer player: tournament.getPlayers()) {
|
||||
if (!player.getPlayer().isHuman()) {
|
||||
player.setJoined();
|
||||
logger.info("player " + player.getPlayer().getId() + " has joined tournament " + tournament.getId());
|
||||
ChatManager.getInstance().broadcast(chatId, "", player.getPlayer().getName() + " has joined the tournament", MessageColor.BLACK);
|
||||
}
|
||||
}
|
||||
checkStart();
|
||||
}
|
||||
|
||||
public synchronized void join(UUID userId) {
|
||||
UUID playerId = userPlayerMap.get(userId);
|
||||
TournamentSession tournamentSession = new TournamentSession(tournament, userId, tableId, playerId);
|
||||
tournamentSessions.put(playerId, tournamentSession);
|
||||
UserManager.getInstance().getUser(userId).addTournament(playerId, tournamentSession);
|
||||
TournamentPlayer player = tournament.getPlayer(playerId);
|
||||
player.setJoined();
|
||||
logger.info("player " + playerId + " has joined tournament " + tournament.getId());
|
||||
ChatManager.getInstance().broadcast(chatId, "", player.getPlayer().getName() + " has joined the tournament", MessageColor.BLACK);
|
||||
checkStart();
|
||||
}
|
||||
public synchronized void join(UUID userId) {
|
||||
UUID playerId = userPlayerMap.get(userId);
|
||||
TournamentSession tournamentSession = new TournamentSession(tournament, userId, tableId, playerId);
|
||||
tournamentSessions.put(playerId, tournamentSession);
|
||||
UserManager.getInstance().getUser(userId).addTournament(playerId, tournamentSession);
|
||||
TournamentPlayer player = tournament.getPlayer(playerId);
|
||||
player.setJoined();
|
||||
logger.info("player " + playerId + " has joined tournament " + tournament.getId());
|
||||
ChatManager.getInstance().broadcast(chatId, "", player.getPlayer().getName() + " has joined the tournament", MessageColor.BLACK);
|
||||
checkStart();
|
||||
}
|
||||
|
||||
private void checkStart() {
|
||||
if (!started && allJoined()) {
|
||||
ThreadExecutor.getInstance().getCallExecutor().execute(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
startTournament();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
private void checkStart() {
|
||||
if (!started && allJoined()) {
|
||||
ThreadExecutor.getInstance().getCallExecutor().execute(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
startTournament();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private boolean allJoined() {
|
||||
if (!tournament.allJoined())
|
||||
return false;
|
||||
for (TournamentPlayer player: tournament.getPlayers()) {
|
||||
if (player.getPlayer().isHuman() && tournamentSessions.get(player.getPlayer().getId()) == null) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
private boolean allJoined() {
|
||||
if (!tournament.allJoined())
|
||||
return false;
|
||||
for (TournamentPlayer player: tournament.getPlayers()) {
|
||||
if (player.getPlayer().isHuman() && tournamentSessions.get(player.getPlayer().getId()) == null) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private synchronized void startTournament() {
|
||||
for (final Entry<UUID, TournamentSession> entry: tournamentSessions.entrySet()) {
|
||||
if (!entry.getValue().init()) {
|
||||
logger.fatal("Unable to initialize client");
|
||||
//TODO: generate client error message
|
||||
return;
|
||||
}
|
||||
}
|
||||
started = true;
|
||||
tournament.nextStep();
|
||||
}
|
||||
private synchronized void startTournament() {
|
||||
for (final Entry<UUID, TournamentSession> entry: tournamentSessions.entrySet()) {
|
||||
if (!entry.getValue().init()) {
|
||||
logger.fatal("Unable to initialize client");
|
||||
//TODO: generate client error message
|
||||
return;
|
||||
}
|
||||
}
|
||||
started = true;
|
||||
tournament.nextStep();
|
||||
}
|
||||
|
||||
private void endTournament() {
|
||||
for (final TournamentSession tournamentSession: tournamentSessions.values()) {
|
||||
tournamentSession.tournamentOver();
|
||||
tournamentSession.removeTournament();
|
||||
}
|
||||
TableManager.getInstance().endTournament(tableId, tournament);
|
||||
}
|
||||
private void endTournament() {
|
||||
for (final TournamentSession tournamentSession: tournamentSessions.values()) {
|
||||
tournamentSession.tournamentOver();
|
||||
tournamentSession.removeTournament();
|
||||
}
|
||||
TableManager.getInstance().endTournament(tableId, tournament);
|
||||
}
|
||||
|
||||
private void startMatch(TournamentPairing pair, MatchOptions matchOptions) {
|
||||
try {
|
||||
TableManager tableManager = TableManager.getInstance();
|
||||
Table table = tableManager.createTable(GamesRoomManager.getInstance().getMainRoomId(), matchOptions);
|
||||
TournamentPlayer player1 = pair.getPlayer1();
|
||||
TournamentPlayer player2 = pair.getPlayer2();
|
||||
tableManager.addPlayer(getPlayerSessionId(player1.getPlayer().getId()), table.getId(), player1.getPlayer(), player1.getPlayerType(), player1.getDeck());
|
||||
tableManager.addPlayer(getPlayerSessionId(player2.getPlayer().getId()), table.getId(), player2.getPlayer(), player2.getPlayerType(), player2.getDeck());
|
||||
tableManager.startMatch(null, table.getId());
|
||||
pair.setMatch(tableManager.getMatch(table.getId()));
|
||||
} catch (GameException ex) {
|
||||
logger.fatal("TournamentController startMatch error", ex);
|
||||
}
|
||||
}
|
||||
private void startMatch(TournamentPairing pair, MatchOptions matchOptions) {
|
||||
try {
|
||||
TableManager tableManager = TableManager.getInstance();
|
||||
Table table = tableManager.createTable(GamesRoomManager.getInstance().getMainRoomId(), matchOptions);
|
||||
TournamentPlayer player1 = pair.getPlayer1();
|
||||
TournamentPlayer player2 = pair.getPlayer2();
|
||||
tableManager.addPlayer(getPlayerSessionId(player1.getPlayer().getId()), table.getId(), player1.getPlayer(), player1.getPlayerType(), player1.getDeck());
|
||||
tableManager.addPlayer(getPlayerSessionId(player2.getPlayer().getId()), table.getId(), player2.getPlayer(), player2.getPlayerType(), player2.getDeck());
|
||||
tableManager.startMatch(null, table.getId());
|
||||
pair.setMatch(tableManager.getMatch(table.getId()));
|
||||
} catch (GameException ex) {
|
||||
logger.fatal("TournamentController startMatch error", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void startDraft(Draft draft) {
|
||||
TableManager.getInstance().startDraft(tableId, draft);
|
||||
}
|
||||
private void startDraft(Draft draft) {
|
||||
TableManager.getInstance().startDraft(tableId, draft);
|
||||
}
|
||||
|
||||
private void construct() {
|
||||
TableManager.getInstance().construct(tableId);
|
||||
}
|
||||
private void construct() {
|
||||
TableManager.getInstance().construct(tableId);
|
||||
}
|
||||
|
||||
private void construct(UUID playerId, int timeout) throws MageException {
|
||||
if (tournamentSessions.containsKey(playerId)) {
|
||||
private void construct(UUID playerId, int timeout) throws MageException {
|
||||
if (tournamentSessions.containsKey(playerId)) {
|
||||
TournamentSession tournamentSession = tournamentSessions.get(playerId);
|
||||
tournamentSession.construct(timeout);
|
||||
tournamentSession.construct(timeout);
|
||||
UserManager.getInstance().getUser(getPlayerSessionId(playerId)).addConstructing(playerId, tournamentSession);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void submitDeck(UUID playerId, Deck deck) {
|
||||
if (tournamentSessions.containsKey(playerId)) {
|
||||
tournamentSessions.get(playerId).submitDeck(deck);
|
||||
public void submitDeck(UUID playerId, Deck deck) {
|
||||
if (tournamentSessions.containsKey(playerId)) {
|
||||
tournamentSessions.get(playerId).submitDeck(deck);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void updateDeck(UUID playerId, Deck deck) {
|
||||
if (tournamentSessions.containsKey(playerId)) {
|
||||
tournamentSessions.get(playerId).updateDeck(deck);
|
||||
public void updateDeck(UUID playerId, Deck deck) {
|
||||
if (tournamentSessions.containsKey(playerId)) {
|
||||
tournamentSessions.get(playerId).updateDeck(deck);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void timeout(UUID userId) {
|
||||
if (userPlayerMap.containsKey(userId)) {
|
||||
TournamentPlayer player = tournament.getPlayer(userPlayerMap.get(userId));
|
||||
tournament.autoSubmit(userPlayerMap.get(userId), player.generateDeck());
|
||||
}
|
||||
}
|
||||
if (userPlayerMap.containsKey(userId)) {
|
||||
TournamentPlayer player = tournament.getPlayer(userPlayerMap.get(userId));
|
||||
tournament.autoSubmit(userPlayerMap.get(userId), player.generateDeck());
|
||||
}
|
||||
}
|
||||
|
||||
// public UUID getSessionId() {
|
||||
// return this.sessionId;
|
||||
// }
|
||||
// public UUID getSessionId() {
|
||||
// return this.sessionId;
|
||||
// }
|
||||
|
||||
public UUID getChatId() {
|
||||
return chatId;
|
||||
}
|
||||
public UUID getChatId() {
|
||||
return chatId;
|
||||
}
|
||||
|
||||
public void kill(UUID userId) {
|
||||
if (userPlayerMap.containsKey(userId)) {
|
||||
tournamentSessions.get(userPlayerMap.get(userId)).setKilled();
|
||||
tournamentSessions.remove(userPlayerMap.get(userId));
|
||||
leave(userId);
|
||||
userPlayerMap.remove(userId);
|
||||
}
|
||||
}
|
||||
public void kill(UUID userId) {
|
||||
if (userPlayerMap.containsKey(userId)) {
|
||||
tournamentSessions.get(userPlayerMap.get(userId)).setKilled();
|
||||
tournamentSessions.remove(userPlayerMap.get(userId));
|
||||
leave(userId);
|
||||
userPlayerMap.remove(userId);
|
||||
}
|
||||
}
|
||||
|
||||
private void leave(UUID userId) {
|
||||
tournament.leave(getPlayerId(userId));
|
||||
}
|
||||
private void leave(UUID userId) {
|
||||
tournament.leave(getPlayerId(userId));
|
||||
}
|
||||
|
||||
private UUID getPlayerId(UUID userId) {
|
||||
return userPlayerMap.get(userId);
|
||||
}
|
||||
private UUID getPlayerId(UUID userId) {
|
||||
return userPlayerMap.get(userId);
|
||||
}
|
||||
|
||||
private UUID getPlayerSessionId(UUID playerId) {
|
||||
for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
|
||||
if (entry.getValue().equals(playerId))
|
||||
return entry.getKey();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
private UUID getPlayerSessionId(UUID playerId) {
|
||||
for (Entry<UUID, UUID> entry: userPlayerMap.entrySet()) {
|
||||
if (entry.getValue().equals(playerId))
|
||||
return entry.getKey();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public TournamentView getTournamentView() {
|
||||
return new TournamentView(tournament);
|
||||
}
|
||||
public TournamentView getTournamentView() {
|
||||
return new TournamentView(tournament);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,49 +45,49 @@ import org.apache.log4j.Logger;
|
|||
* @author BetaSteward_at_googlemail.com
|
||||
*/
|
||||
public class TournamentFactory {
|
||||
private final static TournamentFactory INSTANCE = new TournamentFactory();
|
||||
private final static Logger logger = Logger.getLogger(TournamentFactory.class);
|
||||
private final static TournamentFactory INSTANCE = new TournamentFactory();
|
||||
private final static Logger logger = Logger.getLogger(TournamentFactory.class);
|
||||
|
||||
private Map<String, Class<Tournament>> tournaments = new HashMap<String, Class<Tournament>>();
|
||||
private Map<String, TournamentType> tournamentTypes = new HashMap<String, TournamentType>();
|
||||
private List<TournamentTypeView> tournamentTypeViews = new ArrayList<TournamentTypeView>();
|
||||
private Map<String, Class<Tournament>> tournaments = new HashMap<String, Class<Tournament>>();
|
||||
private Map<String, TournamentType> tournamentTypes = new HashMap<String, TournamentType>();
|
||||
private List<TournamentTypeView> tournamentTypeViews = new ArrayList<TournamentTypeView>();
|
||||
|
||||
public static TournamentFactory getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static TournamentFactory getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private TournamentFactory() {}
|
||||
private TournamentFactory() {}
|
||||
|
||||
public Tournament createTournament(String tournamentType, TournamentOptions options) {
|
||||
public Tournament createTournament(String tournamentType, TournamentOptions options) {
|
||||
|
||||
Tournament tournament;
|
||||
Constructor<Tournament> con;
|
||||
try {
|
||||
con = tournaments.get(tournamentType).getConstructor(new Class[]{TournamentOptions.class});
|
||||
tournament = con.newInstance(new Object[] {options});
|
||||
for (String setCode: options.getLimitedOptions().getSetCodes()) {
|
||||
tournament.getSets().add(Sets.findSet(setCode));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("TournamentFactory error ", ex);
|
||||
return null;
|
||||
}
|
||||
logger.info("Tournament created: " + tournamentType); // + game.getId().toString());
|
||||
Tournament tournament;
|
||||
Constructor<Tournament> con;
|
||||
try {
|
||||
con = tournaments.get(tournamentType).getConstructor(new Class[]{TournamentOptions.class});
|
||||
tournament = con.newInstance(new Object[] {options});
|
||||
for (String setCode: options.getLimitedOptions().getSetCodes()) {
|
||||
tournament.getSets().add(Sets.findSet(setCode));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("TournamentFactory error ", ex);
|
||||
return null;
|
||||
}
|
||||
logger.info("Tournament created: " + tournamentType); // + game.getId().toString());
|
||||
|
||||
return tournament;
|
||||
}
|
||||
return tournament;
|
||||
}
|
||||
|
||||
public List<TournamentTypeView> getTournamentTypes() {
|
||||
return tournamentTypeViews;
|
||||
}
|
||||
public List<TournamentTypeView> getTournamentTypes() {
|
||||
return tournamentTypeViews;
|
||||
}
|
||||
|
||||
|
||||
public void addTournamentType(String name, TournamentType tournamentType, Class tournament) {
|
||||
if (tournament != null) {
|
||||
this.tournaments.put(name, tournament);
|
||||
this.tournamentTypes.put(name, tournamentType);
|
||||
this.tournamentTypeViews.add(new TournamentTypeView(tournamentType));
|
||||
}
|
||||
}
|
||||
public void addTournamentType(String name, TournamentType tournamentType, Class tournament) {
|
||||
if (tournament != null) {
|
||||
this.tournaments.put(name, tournament);
|
||||
this.tournamentTypes.put(name, tournamentType);
|
||||
this.tournamentTypeViews.add(new TournamentTypeView(tournamentType));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -40,45 +40,45 @@ import mage.view.TournamentView;
|
|||
*/
|
||||
public class TournamentManager {
|
||||
|
||||
private final static TournamentManager INSTANCE = new TournamentManager();
|
||||
private final static TournamentManager INSTANCE = new TournamentManager();
|
||||
|
||||
private ConcurrentHashMap<UUID, TournamentController> controllers = new ConcurrentHashMap<UUID, TournamentController>();
|
||||
private ConcurrentHashMap<UUID, TournamentController> controllers = new ConcurrentHashMap<UUID, TournamentController>();
|
||||
|
||||
public static TournamentManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static TournamentManager getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public void createTournamentSession(Tournament tournament, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {
|
||||
TournamentController tournamentController = new TournamentController(tournament, userPlayerMap, tableId);
|
||||
controllers.put(tournament.getId(), tournamentController);
|
||||
}
|
||||
public void createTournamentSession(Tournament tournament, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId) {
|
||||
TournamentController tournamentController = new TournamentController(tournament, userPlayerMap, tableId);
|
||||
controllers.put(tournament.getId(), tournamentController);
|
||||
}
|
||||
|
||||
public void joinTournament(UUID tournamentId, UUID userId) {
|
||||
controllers.get(tournamentId).join(userId);
|
||||
}
|
||||
public void joinTournament(UUID tournamentId, UUID userId) {
|
||||
controllers.get(tournamentId).join(userId);
|
||||
}
|
||||
|
||||
public void kill(UUID tournamentId, UUID userId) {
|
||||
controllers.get(tournamentId).kill(userId);
|
||||
}
|
||||
public void kill(UUID tournamentId, UUID userId) {
|
||||
controllers.get(tournamentId).kill(userId);
|
||||
}
|
||||
|
||||
public void timeout(UUID tournamentId, UUID userId) {
|
||||
controllers.get(tournamentId).timeout(userId);
|
||||
}
|
||||
public void timeout(UUID tournamentId, UUID userId) {
|
||||
controllers.get(tournamentId).timeout(userId);
|
||||
}
|
||||
|
||||
public void submitDeck(UUID tournamentId, UUID playerId, Deck deck) {
|
||||
controllers.get(tournamentId).submitDeck(playerId, deck);
|
||||
}
|
||||
public void submitDeck(UUID tournamentId, UUID playerId, Deck deck) {
|
||||
controllers.get(tournamentId).submitDeck(playerId, deck);
|
||||
}
|
||||
|
||||
public void updateDeck(UUID tournamentId, UUID playerId, Deck deck) {
|
||||
controllers.get(tournamentId).updateDeck(playerId, deck);
|
||||
}
|
||||
public void updateDeck(UUID tournamentId, UUID playerId, Deck deck) {
|
||||
controllers.get(tournamentId).updateDeck(playerId, deck);
|
||||
}
|
||||
|
||||
public TournamentView getTournamentView(UUID tournamentId) {
|
||||
return controllers.get(tournamentId).getTournamentView();
|
||||
}
|
||||
return controllers.get(tournamentId).getTournamentView();
|
||||
}
|
||||
|
||||
public UUID getChatId(UUID tournamentId) {
|
||||
return controllers.get(tournamentId).getChatId();
|
||||
}
|
||||
public UUID getChatId(UUID tournamentId) {
|
||||
return controllers.get(tournamentId).getChatId();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,121 +47,121 @@ import org.apache.log4j.Logger;
|
|||
* @author BetaSteward_at_googlemail.com
|
||||
*/
|
||||
public class TournamentSession {
|
||||
protected final static Logger logger = Logger.getLogger(TournamentSession.class);
|
||||
protected final static Logger logger = Logger.getLogger(TournamentSession.class);
|
||||
|
||||
protected UUID userId;
|
||||
protected UUID playerId;
|
||||
protected UUID tableId;
|
||||
protected Tournament tournament;
|
||||
protected boolean killed = false;
|
||||
protected UUID userId;
|
||||
protected UUID playerId;
|
||||
protected UUID tableId;
|
||||
protected Tournament tournament;
|
||||
protected boolean killed = false;
|
||||
|
||||
private ScheduledFuture<?> futureTimeout;
|
||||
protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor();
|
||||
private ScheduledFuture<?> futureTimeout;
|
||||
protected static ScheduledExecutorService timeoutExecutor = ThreadExecutor.getInstance().getTimeoutExecutor();
|
||||
|
||||
public TournamentSession(Tournament tournament, UUID userId, UUID tableId, UUID playerId) {
|
||||
this.userId = userId;
|
||||
this.tournament = tournament;
|
||||
this.playerId = playerId;
|
||||
this.tableId = tableId;
|
||||
}
|
||||
public TournamentSession(Tournament tournament, UUID userId, UUID tableId, UUID playerId) {
|
||||
this.userId = userId;
|
||||
this.tournament = tournament;
|
||||
this.playerId = playerId;
|
||||
this.tableId = tableId;
|
||||
}
|
||||
|
||||
public boolean init() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("tournamentInit", tournament.getId(), getTournamentView()));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public boolean init() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("tournamentInit", tournament.getId(), getTournamentView()));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void update() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
user.fireCallback(new ClientCallback("tournamentUpdate", tournament.getId(), getTournamentView()));
|
||||
}
|
||||
}
|
||||
}
|
||||
public void update() {
|
||||
if (!killed) {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void construct(int timeout) {
|
||||
if (!killed) {
|
||||
setupTimeout(timeout);
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
public void construct(int timeout) {
|
||||
if (!killed) {
|
||||
setupTimeout(timeout);
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null) {
|
||||
int remaining = (int) futureTimeout.getDelay(TimeUnit.SECONDS);
|
||||
user.construct(tournament.getPlayer(playerId).getDeck(), tableId, remaining);
|
||||
}
|
||||
}
|
||||
}
|
||||
user.construct(tournament.getPlayer(playerId).getDeck(), tableId, remaining);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void submitDeck(Deck deck) {
|
||||
cancelTimeout();
|
||||
tournament.submitDeck(playerId, deck);
|
||||
}
|
||||
public void submitDeck(Deck deck) {
|
||||
cancelTimeout();
|
||||
tournament.submitDeck(playerId, deck);
|
||||
}
|
||||
|
||||
public void updateDeck(Deck deck) {
|
||||
tournament.updateDeck(playerId, deck);
|
||||
}
|
||||
public void updateDeck(Deck deck) {
|
||||
tournament.updateDeck(playerId, deck);
|
||||
}
|
||||
|
||||
protected void handleRemoteException(RemoteException ex) {
|
||||
logger.fatal("TournamentSession error ", ex);
|
||||
TournamentManager.getInstance().kill(tournament.getId(), userId);
|
||||
}
|
||||
logger.fatal("TournamentSession error ", ex);
|
||||
TournamentManager.getInstance().kill(tournament.getId(), userId);
|
||||
}
|
||||
|
||||
public void setKilled() {
|
||||
killed = true;
|
||||
}
|
||||
public void setKilled() {
|
||||
killed = true;
|
||||
}
|
||||
|
||||
private synchronized void setupTimeout(int seconds) {
|
||||
private synchronized void setupTimeout(int seconds) {
|
||||
if (futureTimeout != null && !futureTimeout.isDone())
|
||||
return;
|
||||
cancelTimeout();
|
||||
if (seconds > 0) {
|
||||
futureTimeout = timeoutExecutor.schedule(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
TournamentManager.getInstance().timeout(tournament.getId(), userId);
|
||||
}
|
||||
},
|
||||
seconds, TimeUnit.SECONDS
|
||||
);
|
||||
}
|
||||
}
|
||||
cancelTimeout();
|
||||
if (seconds > 0) {
|
||||
futureTimeout = timeoutExecutor.schedule(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
TournamentManager.getInstance().timeout(tournament.getId(), userId);
|
||||
}
|
||||
},
|
||||
seconds, TimeUnit.SECONDS
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void cancelTimeout() {
|
||||
if (futureTimeout != null) {
|
||||
futureTimeout.cancel(false);
|
||||
}
|
||||
}
|
||||
private synchronized void cancelTimeout() {
|
||||
if (futureTimeout != null) {
|
||||
futureTimeout.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeTournament() {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null)
|
||||
user.removeTournament(playerId);
|
||||
}
|
||||
|
||||
private TournamentView getTournamentView() {
|
||||
return new TournamentView(tournament);
|
||||
}
|
||||
public void removeTournament() {
|
||||
User user = UserManager.getInstance().getUser(userId);
|
||||
if (user != null)
|
||||
user.removeTournament(playerId);
|
||||
}
|
||||
|
||||
public UUID getTournamentId() {
|
||||
return tournament.getId();
|
||||
}
|
||||
private TournamentView getTournamentView() {
|
||||
return new TournamentView(tournament);
|
||||
}
|
||||
|
||||
void tournamentOver() {
|
||||
//TODO: implement this
|
||||
}
|
||||
public UUID getTournamentId() {
|
||||
return tournament.getId();
|
||||
}
|
||||
|
||||
void tournamentOver() {
|
||||
//TODO: implement this
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,24 +38,24 @@ import org.apache.log4j.Logger;
|
|||
*/
|
||||
public class Config {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(Config.class);
|
||||
private final static Logger logger = Logger.getLogger(Config.class);
|
||||
|
||||
static {
|
||||
Properties p = new Properties();
|
||||
try {
|
||||
p.load(Config.class.getResourceAsStream("resources/config.properties"));
|
||||
} catch (IOException ex) {
|
||||
logger.fatal("Config error", ex);
|
||||
}
|
||||
port = Integer.parseInt(p.getProperty("port"));
|
||||
remoteServer = p.getProperty("remote-server");
|
||||
maxGameThreads = Integer.parseInt(p.getProperty("max-game-threads"));
|
||||
maxSecondsIdle = Integer.parseInt(p.getProperty("max-seconds-idle"));
|
||||
}
|
||||
static {
|
||||
Properties p = new Properties();
|
||||
try {
|
||||
p.load(Config.class.getResourceAsStream("resources/config.properties"));
|
||||
} catch (IOException ex) {
|
||||
logger.fatal("Config error", ex);
|
||||
}
|
||||
port = Integer.parseInt(p.getProperty("port"));
|
||||
remoteServer = p.getProperty("remote-server");
|
||||
maxGameThreads = Integer.parseInt(p.getProperty("max-game-threads"));
|
||||
maxSecondsIdle = Integer.parseInt(p.getProperty("max-seconds-idle"));
|
||||
}
|
||||
|
||||
public static final String remoteServer;
|
||||
public static final int port;
|
||||
public static final int maxGameThreads;
|
||||
public static final int maxSecondsIdle;
|
||||
public static final String remoteServer;
|
||||
public static final int port;
|
||||
public static final int maxGameThreads;
|
||||
public static final int maxSecondsIdle;
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,59 +44,59 @@ import org.apache.log4j.Logger;
|
|||
*/
|
||||
public class ConfigSettings {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(ConfigSettings.class);
|
||||
private final static ConfigSettings INSTANCE = new ConfigSettings();
|
||||
|
||||
private Config config;
|
||||
private final static Logger logger = Logger.getLogger(ConfigSettings.class);
|
||||
private final static ConfigSettings INSTANCE = new ConfigSettings();
|
||||
|
||||
public static ConfigSettings getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
private Config config;
|
||||
|
||||
private ConfigSettings() {
|
||||
try {
|
||||
JAXBContext jaxbContext = JAXBContext.newInstance("mage.server.util.config");
|
||||
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
|
||||
config = (Config) unmarshaller.unmarshal(new File("config/config.xml"));
|
||||
} catch (JAXBException ex) {
|
||||
logger.fatal("ConfigSettings error", ex);
|
||||
}
|
||||
}
|
||||
public static ConfigSettings getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public String getServerAddress() {
|
||||
return config.getServer().getServerAddress();
|
||||
}
|
||||
private ConfigSettings() {
|
||||
try {
|
||||
JAXBContext jaxbContext = JAXBContext.newInstance("mage.server.util.config");
|
||||
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
|
||||
config = (Config) unmarshaller.unmarshal(new File("config/config.xml"));
|
||||
} catch (JAXBException ex) {
|
||||
logger.fatal("ConfigSettings error", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public String getServerName() {
|
||||
return config.getServer().getServerName();
|
||||
}
|
||||
public String getServerAddress() {
|
||||
return config.getServer().getServerAddress();
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return config.getServer().getPort().intValue();
|
||||
}
|
||||
public String getServerName() {
|
||||
return config.getServer().getServerName();
|
||||
}
|
||||
|
||||
public int getMaxGameThreads() {
|
||||
return config.getServer().getMaxGameThreads().intValue();
|
||||
}
|
||||
public int getPort() {
|
||||
return config.getServer().getPort().intValue();
|
||||
}
|
||||
|
||||
public int getMaxSecondsIdle() {
|
||||
return config.getServer().getMaxSecondsIdle().intValue();
|
||||
}
|
||||
public int getMaxGameThreads() {
|
||||
return config.getServer().getMaxGameThreads().intValue();
|
||||
}
|
||||
|
||||
public List<Plugin> getPlayerTypes() {
|
||||
return config.getPlayerTypes().getPlayerType();
|
||||
}
|
||||
public int getMaxSecondsIdle() {
|
||||
return config.getServer().getMaxSecondsIdle().intValue();
|
||||
}
|
||||
|
||||
public List<GamePlugin> getGameTypes() {
|
||||
return config.getGameTypes().getGameType();
|
||||
}
|
||||
public List<Plugin> getPlayerTypes() {
|
||||
return config.getPlayerTypes().getPlayerType();
|
||||
}
|
||||
|
||||
public List<GamePlugin> getTournamentTypes() {
|
||||
return config.getTournamentTypes().getTournamentType();
|
||||
}
|
||||
public List<GamePlugin> getGameTypes() {
|
||||
return config.getGameTypes().getGameType();
|
||||
}
|
||||
|
||||
public List<Plugin> getDeckTypes() {
|
||||
return config.getDeckTypes().getDeckType();
|
||||
}
|
||||
public List<GamePlugin> getTournamentTypes() {
|
||||
return config.getTournamentTypes().getTournamentType();
|
||||
}
|
||||
|
||||
public List<Plugin> getDeckTypes() {
|
||||
return config.getDeckTypes().getDeckType();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,37 +40,37 @@ import java.net.URLClassLoader;
|
|||
*/
|
||||
public class PluginClassLoader extends URLClassLoader {
|
||||
|
||||
public PluginClassLoader(){
|
||||
super(new URL[0], PluginClassLoader.class.getClassLoader());
|
||||
}
|
||||
public PluginClassLoader(){
|
||||
super(new URL[0], PluginClassLoader.class.getClassLoader());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addURL(URL url) {
|
||||
super.addURL(url);
|
||||
}
|
||||
@Override
|
||||
public void addURL(URL url) {
|
||||
super.addURL(url);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> loadClass(String name) throws ClassNotFoundException {
|
||||
// First check whether it's already been loaded, if so use it
|
||||
Class loadedClass = findLoadedClass(name);
|
||||
@Override
|
||||
public Class<?> loadClass(String name) throws ClassNotFoundException {
|
||||
// First check whether it's already been loaded, if so use it
|
||||
Class loadedClass = findLoadedClass(name);
|
||||
|
||||
// Not loaded, try to load it
|
||||
if (loadedClass == null) {
|
||||
try {
|
||||
// Ignore parent delegation and just try to load locally
|
||||
loadedClass = findClass(name);
|
||||
} catch (ClassNotFoundException e) {
|
||||
// Swallow exception - does not exist locally
|
||||
}
|
||||
// Not loaded, try to load it
|
||||
if (loadedClass == null) {
|
||||
try {
|
||||
// Ignore parent delegation and just try to load locally
|
||||
loadedClass = findClass(name);
|
||||
} catch (ClassNotFoundException e) {
|
||||
// Swallow exception - does not exist locally
|
||||
}
|
||||
|
||||
// If not found locally, use normal parent delegation in URLClassloader
|
||||
if (loadedClass == null) {
|
||||
// throws ClassNotFoundException if not found in delegation hierarchy at all
|
||||
loadedClass = super.loadClass(name);
|
||||
}
|
||||
}
|
||||
// will never return null (ClassNotFoundException will be thrown)
|
||||
return loadedClass;
|
||||
// If not found locally, use normal parent delegation in URLClassloader
|
||||
if (loadedClass == null) {
|
||||
// throws ClassNotFoundException if not found in delegation hierarchy at all
|
||||
loadedClass = super.loadClass(name);
|
||||
}
|
||||
}
|
||||
// will never return null (ClassNotFoundException will be thrown)
|
||||
return loadedClass;
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ public class ServerMessagesUtil {
|
|||
|
||||
private static final Logger log = Logger.getLogger(ServerMessagesUtil.class);
|
||||
private static final String SERVER_MSG_TXT_FILE = "server.msg.txt";
|
||||
private static ScheduledExecutorService updateExecutor;
|
||||
private static ScheduledExecutorService updateExecutor;
|
||||
|
||||
private List<String> messages = new ArrayList<String>();
|
||||
private ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
|
|
@ -72,12 +72,12 @@ public class ServerMessagesUtil {
|
|||
|
||||
public ServerMessagesUtil() {
|
||||
updateExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
updateExecutor.scheduleAtFixedRate(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
reloadMessages();
|
||||
}
|
||||
}, 5, 5 * 60, TimeUnit.SECONDS);
|
||||
updateExecutor.scheduleAtFixedRate(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
reloadMessages();
|
||||
}
|
||||
}, 5, 5 * 60, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
public static ServerMessagesUtil getInstance() {
|
||||
|
|
|
|||
|
|
@ -12,13 +12,13 @@ import java.util.UUID;
|
|||
*/
|
||||
public class Splitter {
|
||||
|
||||
public static List<UUID> split(Game game, UUID playerId) {
|
||||
List<UUID> players = new ArrayList<UUID>();
|
||||
//players.add(playerId); // add original player
|
||||
Player player = game.getPlayer(playerId);
|
||||
if (player != null && player.getTurnControlledBy() != null) {
|
||||
players.add(player.getTurnControlledBy());
|
||||
}
|
||||
return players;
|
||||
}
|
||||
public static List<UUID> split(Game game, UUID playerId) {
|
||||
List<UUID> players = new ArrayList<UUID>();
|
||||
//players.add(playerId); // add original player
|
||||
Player player = game.getPlayer(playerId);
|
||||
if (player != null && player.getTurnControlledBy() != null) {
|
||||
players.add(player.getTurnControlledBy());
|
||||
}
|
||||
return players;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,117 +18,117 @@ import java.util.regex.Pattern;
|
|||
*/
|
||||
public class SystemUtil {
|
||||
|
||||
private static final String INIT_FILE_PATH = "config" + File.separator + "init.txt";
|
||||
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(SystemUtil.class);
|
||||
private static final String INIT_FILE_PATH = "config" + File.separator + "init.txt";
|
||||
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(SystemUtil.class);
|
||||
|
||||
/**
|
||||
* Replaces cards in player's hands by specified in config/init.txt.<br/>
|
||||
* <br/>
|
||||
* <b>Implementation note:</b><br/>
|
||||
* 1. Read init.txt line by line<br/>
|
||||
* 2. Parse line using the following format: line ::= <zone>:<nickname>:<card name>:<amount><br/>
|
||||
* 3. If zone equals to 'hand', add card to player's library<br/>
|
||||
* 3a. Then swap added card with any card in player's hand<br/>
|
||||
* 3b. Parse next line (go to 2.), If EOF go to 4.<br/>
|
||||
* 4. Log message to all players that cards were added (to prevent unfair play).<br/>
|
||||
* 5. Exit<br/>
|
||||
*/
|
||||
public static void addCardsForTesting(Game game) {
|
||||
try {
|
||||
File f = new File(INIT_FILE_PATH);
|
||||
Pattern pattern = Pattern.compile("([a-zA-Z]*):([\\w]*):([a-zA-Z ,\\-.!'\\d]*):([\\d]*)");
|
||||
if (!f.exists()) {
|
||||
logger.warn("Couldn't find init file: " + INIT_FILE_PATH);
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Replaces cards in player's hands by specified in config/init.txt.<br/>
|
||||
* <br/>
|
||||
* <b>Implementation note:</b><br/>
|
||||
* 1. Read init.txt line by line<br/>
|
||||
* 2. Parse line using the following format: line ::= <zone>:<nickname>:<card name>:<amount><br/>
|
||||
* 3. If zone equals to 'hand', add card to player's library<br/>
|
||||
* 3a. Then swap added card with any card in player's hand<br/>
|
||||
* 3b. Parse next line (go to 2.), If EOF go to 4.<br/>
|
||||
* 4. Log message to all players that cards were added (to prevent unfair play).<br/>
|
||||
* 5. Exit<br/>
|
||||
*/
|
||||
public static void addCardsForTesting(Game game) {
|
||||
try {
|
||||
File f = new File(INIT_FILE_PATH);
|
||||
Pattern pattern = Pattern.compile("([a-zA-Z]*):([\\w]*):([a-zA-Z ,\\-.!'\\d]*):([\\d]*)");
|
||||
if (!f.exists()) {
|
||||
logger.warn("Couldn't find init file: " + INIT_FILE_PATH);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info("Parsing init.txt... ");
|
||||
logger.info("Parsing init.txt... ");
|
||||
|
||||
Scanner scanner = new Scanner(f);
|
||||
try {
|
||||
while (scanner.hasNextLine()) {
|
||||
String line = scanner.nextLine().trim();
|
||||
if (line.trim().length() == 0 || line.startsWith("#")) continue;
|
||||
Matcher m = pattern.matcher(line);
|
||||
if (m.matches()) {
|
||||
Scanner scanner = new Scanner(f);
|
||||
try {
|
||||
while (scanner.hasNextLine()) {
|
||||
String line = scanner.nextLine().trim();
|
||||
if (line.trim().length() == 0 || line.startsWith("#")) continue;
|
||||
Matcher m = pattern.matcher(line);
|
||||
if (m.matches()) {
|
||||
|
||||
String zone = m.group(1);
|
||||
String nickname = m.group(2);
|
||||
String zone = m.group(1);
|
||||
String nickname = m.group(2);
|
||||
|
||||
Player player = findPlayer(game, nickname);
|
||||
if (player != null) {
|
||||
Constants.Zone gameZone;
|
||||
if ("hand".equalsIgnoreCase(zone)) {
|
||||
gameZone = Constants.Zone.HAND;
|
||||
} else if ("battlefield".equalsIgnoreCase(zone)) {
|
||||
gameZone = Constants.Zone.BATTLEFIELD;
|
||||
} else if ("graveyard".equalsIgnoreCase(zone)) {
|
||||
gameZone = Constants.Zone.GRAVEYARD;
|
||||
} else if ("library".equalsIgnoreCase(zone)) {
|
||||
gameZone = Constants.Zone.LIBRARY;
|
||||
} else {
|
||||
continue; // go parse next line
|
||||
}
|
||||
Player player = findPlayer(game, nickname);
|
||||
if (player != null) {
|
||||
Constants.Zone gameZone;
|
||||
if ("hand".equalsIgnoreCase(zone)) {
|
||||
gameZone = Constants.Zone.HAND;
|
||||
} else if ("battlefield".equalsIgnoreCase(zone)) {
|
||||
gameZone = Constants.Zone.BATTLEFIELD;
|
||||
} else if ("graveyard".equalsIgnoreCase(zone)) {
|
||||
gameZone = Constants.Zone.GRAVEYARD;
|
||||
} else if ("library".equalsIgnoreCase(zone)) {
|
||||
gameZone = Constants.Zone.LIBRARY;
|
||||
} else {
|
||||
continue; // go parse next line
|
||||
}
|
||||
|
||||
String cardName = m.group(3);
|
||||
Integer amount = Integer.parseInt(m.group(4));
|
||||
for (int i = 0; i < amount; i++) {
|
||||
Card card = Sets.findCard(cardName, true);
|
||||
if (card != null) {
|
||||
Set<Card> cards = new HashSet<Card>();
|
||||
cards.add(card);
|
||||
game.loadCards(cards, player.getId());
|
||||
swapWithAnyCard(game, player, card, gameZone);
|
||||
} else {
|
||||
logger.fatal("Couldn't find a card: " + cardName);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.warn("Was skipped: " + line);
|
||||
}
|
||||
} else {
|
||||
logger.warn("Init string wasn't parsed: " + line);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally {
|
||||
scanner.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.fatal("", e);
|
||||
}
|
||||
}
|
||||
String cardName = m.group(3);
|
||||
Integer amount = Integer.parseInt(m.group(4));
|
||||
for (int i = 0; i < amount; i++) {
|
||||
Card card = Sets.findCard(cardName, true);
|
||||
if (card != null) {
|
||||
Set<Card> cards = new HashSet<Card>();
|
||||
cards.add(card);
|
||||
game.loadCards(cards, player.getId());
|
||||
swapWithAnyCard(game, player, card, gameZone);
|
||||
} else {
|
||||
logger.fatal("Couldn't find a card: " + cardName);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.warn("Was skipped: " + line);
|
||||
}
|
||||
} else {
|
||||
logger.warn("Init string wasn't parsed: " + line);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally {
|
||||
scanner.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.fatal("", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Swap cards between specified card from library and any hand card.
|
||||
*
|
||||
* @param game
|
||||
* @param card Card to put to player's hand
|
||||
*/
|
||||
private static void swapWithAnyCard(Game game, Player player, Card card, Constants.Zone zone) {
|
||||
if (zone.equals(Constants.Zone.BATTLEFIELD)) {
|
||||
card.putOntoBattlefield(game, Constants.Zone.OUTSIDE, null, player.getId());
|
||||
} else if (zone.equals(Constants.Zone.LIBRARY)) {
|
||||
/**
|
||||
* Swap cards between specified card from library and any hand card.
|
||||
*
|
||||
* @param game
|
||||
* @param card Card to put to player's hand
|
||||
*/
|
||||
private static void swapWithAnyCard(Game game, Player player, Card card, Constants.Zone zone) {
|
||||
if (zone.equals(Constants.Zone.BATTLEFIELD)) {
|
||||
card.putOntoBattlefield(game, Constants.Zone.OUTSIDE, null, player.getId());
|
||||
} else if (zone.equals(Constants.Zone.LIBRARY)) {
|
||||
game.setZone(card.getId(), Constants.Zone.LIBRARY);
|
||||
player.getLibrary().putOnTop(card, game);
|
||||
} else {
|
||||
card.moveToZone(zone, null, game, false);
|
||||
}
|
||||
logger.info("Added card to player's " + zone.toString() + ": " + card.getName() +", player = " + player.getName());
|
||||
}
|
||||
card.moveToZone(zone, null, game, false);
|
||||
}
|
||||
logger.info("Added card to player's " + zone.toString() + ": " + card.getName() +", player = " + player.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Find player by name.
|
||||
*
|
||||
* @param game
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
private static Player findPlayer(Game game, String name) {
|
||||
for (Player player: game.getPlayers().values()) {
|
||||
if (player.getName().equals(name))
|
||||
return player;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Find player by name.
|
||||
*
|
||||
* @param game
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
private static Player findPlayer(Game game, String name) {
|
||||
for (Player player: game.getPlayers().values()) {
|
||||
if (player.getName().equals(name))
|
||||
return player;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,37 +36,37 @@ import java.util.concurrent.*;
|
|||
*/
|
||||
public class ThreadExecutor {
|
||||
|
||||
private static final ExecutorService callExecutor = Executors.newCachedThreadPool();
|
||||
private static final ExecutorService gameExecutor = Executors.newFixedThreadPool(ConfigSettings.getInstance().getMaxGameThreads());
|
||||
private static final ScheduledExecutorService timeoutExecutor = Executors.newScheduledThreadPool(5);
|
||||
private static final ExecutorService callExecutor = Executors.newCachedThreadPool();
|
||||
private static final ExecutorService gameExecutor = Executors.newFixedThreadPool(ConfigSettings.getInstance().getMaxGameThreads());
|
||||
private static final ScheduledExecutorService timeoutExecutor = Executors.newScheduledThreadPool(5);
|
||||
|
||||
static {
|
||||
((ThreadPoolExecutor)callExecutor).setKeepAliveTime(60, TimeUnit.SECONDS);
|
||||
((ThreadPoolExecutor)callExecutor).allowCoreThreadTimeOut(true);
|
||||
((ThreadPoolExecutor)gameExecutor).setKeepAliveTime(60, TimeUnit.SECONDS);
|
||||
((ThreadPoolExecutor)gameExecutor).allowCoreThreadTimeOut(true);
|
||||
((ThreadPoolExecutor)timeoutExecutor).setKeepAliveTime(60, TimeUnit.SECONDS);
|
||||
((ThreadPoolExecutor)timeoutExecutor).allowCoreThreadTimeOut(true);
|
||||
}
|
||||
static {
|
||||
((ThreadPoolExecutor)callExecutor).setKeepAliveTime(60, TimeUnit.SECONDS);
|
||||
((ThreadPoolExecutor)callExecutor).allowCoreThreadTimeOut(true);
|
||||
((ThreadPoolExecutor)gameExecutor).setKeepAliveTime(60, TimeUnit.SECONDS);
|
||||
((ThreadPoolExecutor)gameExecutor).allowCoreThreadTimeOut(true);
|
||||
((ThreadPoolExecutor)timeoutExecutor).setKeepAliveTime(60, TimeUnit.SECONDS);
|
||||
((ThreadPoolExecutor)timeoutExecutor).allowCoreThreadTimeOut(true);
|
||||
}
|
||||
|
||||
private final static ThreadExecutor INSTANCE = new ThreadExecutor();
|
||||
private final static ThreadExecutor INSTANCE = new ThreadExecutor();
|
||||
|
||||
public static ThreadExecutor getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
public static ThreadExecutor getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private ThreadExecutor() {}
|
||||
private ThreadExecutor() {}
|
||||
|
||||
public ExecutorService getCallExecutor() {
|
||||
return callExecutor;
|
||||
}
|
||||
public ExecutorService getCallExecutor() {
|
||||
return callExecutor;
|
||||
}
|
||||
|
||||
public ExecutorService getGameExecutor() {
|
||||
return gameExecutor;
|
||||
}
|
||||
public ExecutorService getGameExecutor() {
|
||||
return gameExecutor;
|
||||
}
|
||||
|
||||
public ScheduledExecutorService getTimeoutExecutor() {
|
||||
return timeoutExecutor;
|
||||
}
|
||||
public ScheduledExecutorService getTimeoutExecutor() {
|
||||
return timeoutExecutor;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,15 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../Config.xsd">
|
||||
<server serverAddress="0.0.0.0" serverName="mage-server" port="17171" maxGameThreads="10" maxSecondsIdle="600"/>
|
||||
<playerTypes>
|
||||
<playerType name="Human" jar="Mage.Player.Human.jar" className="mage.player.human.HumanPlayer"/>
|
||||
<playerType name="Computer - default" jar="Mage.Player.AI.jar" className="mage.player.ai.ComputerPlayer"/>
|
||||
</playerTypes>
|
||||
<gameTypes>
|
||||
<gameType name="Two Player Duel" jar="Mage.Game.TwoPlayerDuel.jar" className="mage.game.TwoPlayerDuel" typeName="mage.game.TwoPlayerDuelType"/>
|
||||
</gameTypes>
|
||||
<deckTypes>
|
||||
<deckType name="Constructed" jar="Mage.Deck.Constructed.jar" className="mage.deck.Constructed"/>
|
||||
</deckTypes>
|
||||
<server serverAddress="0.0.0.0" serverName="mage-server" port="17171" maxGameThreads="10" maxSecondsIdle="600"/>
|
||||
<playerTypes>
|
||||
<playerType name="Human" jar="Mage.Player.Human.jar" className="mage.player.human.HumanPlayer"/>
|
||||
<playerType name="Computer - default" jar="Mage.Player.AI.jar" className="mage.player.ai.ComputerPlayer"/>
|
||||
</playerTypes>
|
||||
<gameTypes>
|
||||
<gameType name="Two Player Duel" jar="Mage.Game.TwoPlayerDuel.jar" className="mage.game.TwoPlayerDuel" typeName="mage.game.TwoPlayerDuelType"/>
|
||||
</gameTypes>
|
||||
<deckTypes>
|
||||
<deckType name="Constructed" jar="Mage.Deck.Constructed.jar" className="mage.deck.Constructed"/>
|
||||
</deckTypes>
|
||||
</config>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue