Changes to connect messages, added some debug messages to narrow down server user handling bug.

This commit is contained in:
LevelX2 2014-04-14 23:11:34 +02:00
parent cf4913ae96
commit d53a3245d6
8 changed files with 63 additions and 31 deletions

View file

@ -216,7 +216,9 @@ public class SessionImpl implements Session {
UserDataView userDataView = new UserDataView(connection.getAvatarId(), connection.isShowAbilityPickerForced()); UserDataView userDataView = new UserDataView(connection.getAvatarId(), connection.isShowAbilityPickerForced());
// for backward compatibility. don't remove twice call - first one does nothing but for version checking // for backward compatibility. don't remove twice call - first one does nothing but for version checking
registerResult = server.registerClient(connection.getUsername(), sessionId, client.getVersion()); registerResult = server.registerClient(connection.getUsername(), sessionId, client.getVersion());
server.setUserData(connection.getUsername(), sessionId, userDataView); if (registerResult) {
server.setUserData(connection.getUsername(), sessionId, userDataView);
}
} else { } else {
registerResult = server.registerAdmin(connection.getPassword(), sessionId, client.getVersion()); registerResult = server.registerAdmin(connection.getPassword(), sessionId, client.getVersion());
} }
@ -229,7 +231,7 @@ public class SessionImpl implements Session {
return true; return true;
} }
disconnect(false); disconnect(false);
client.showMessage("Unable to connect to server."); // client.showMessage("Unable to connect to server.");
} catch (MalformedURLException ex) { } catch (MalformedURLException ex) {
logger.fatal("", ex); logger.fatal("", ex);
client.showMessage("Unable to connect to server. " + ex.getMessage()); client.showMessage("Unable to connect to server. " + ex.getMessage());

View file

@ -109,9 +109,9 @@ public class MageServerImpl implements MageServer {
LogServiceImpl.instance.log(LogKeys.KEY_WRONG_VERSION, userName, version.toString(), Main.getVersion().toString(), sessionId); LogServiceImpl.instance.log(LogKeys.KEY_WRONG_VERSION, userName, version.toString(), Main.getVersion().toString(), sessionId);
throw new MageVersionException(version, Main.getVersion()); throw new MageVersionException(version, Main.getVersion());
} }
logger.info(new StringBuilder("RegisterClient - userName: ").append(userName).append(" sessionId = ").append(sessionId)); logger.debug(new StringBuilder("RegisterClient - userName: ").append(userName).append(" sessionId = ").append(sessionId));
return SessionManager.getInstance().registerUser(sessionId, userName); return SessionManager.getInstance().registerUser(sessionId, userName);
} catch (Exception ex) { } catch (MageException ex) {
if (ex instanceof MageVersionException) { if (ex instanceof MageVersionException) {
throw (MageVersionException)ex; throw (MageVersionException)ex;
} }
@ -901,7 +901,7 @@ public class MageServerImpl implements MageServer {
return executeWithResult("getUsers", sessionId, new ActionWithNullNegativeResult<List<UserView>>() { return executeWithResult("getUsers", sessionId, new ActionWithNullNegativeResult<List<UserView>>() {
@Override @Override
public List<UserView> execute() throws MageException { public List<UserView> execute() throws MageException {
List<UserView> users = new ArrayList<UserView>(); List<UserView> users = new ArrayList<>();
for (User user : UserManager.getInstance().getUsers()) { for (User user : UserManager.getInstance().getUsers()) {
users.add(new UserView(user.getName(), "", user.getSessionId(), user.getConnectionTime())); users.add(new UserView(user.getName(), "", user.getSessionId(), user.getConnectionTime()));
} }
@ -1037,7 +1037,7 @@ public class MageServerImpl implements MageServer {
@Override @Override
public List<ExpansionInfo> getMissingExpansionData(List<String> codes) { public List<ExpansionInfo> getMissingExpansionData(List<String> codes) {
List<ExpansionInfo> result = new ArrayList<ExpansionInfo>(); List<ExpansionInfo> result = new ArrayList<>();
for (ExpansionInfo expansionInfo : ExpansionRepository.instance.getAll()) { for (ExpansionInfo expansionInfo : ExpansionRepository.instance.getAll()) {
if (!codes.contains(expansionInfo.getCode())) { if (!codes.contains(expansionInfo.getCode())) {
result .add(expansionInfo); result .add(expansionInfo);

View file

@ -28,7 +28,10 @@
package mage.server; package mage.server;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -37,7 +40,6 @@ import mage.interfaces.callback.ClientCallback;
import mage.players.net.UserData; import mage.players.net.UserData;
import mage.players.net.UserGroup; import mage.players.net.UserGroup;
import mage.server.util.ConfigSettings; import mage.server.util.ConfigSettings;
import mage.view.ChatMessage;
import mage.view.UserDataView; import mage.view.UserDataView;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.jboss.remoting.callback.AsynchInvokerCallbackHandler; import org.jboss.remoting.callback.AsynchInvokerCallbackHandler;
@ -68,21 +70,29 @@ public class Session {
this.timeConnected = new Date(); this.timeConnected = new Date();
} }
public void registerUser(String userName) throws MageException { public String registerUser(String userName) throws MageException {
String returnMessage = registerUserHandling(userName);
if (returnMessage != null) {
sendErrorMessageToClient(returnMessage);
}
return returnMessage;
}
public String registerUserHandling(String userName) throws MageException {
this.isAdmin = false; this.isAdmin = false;
if (userName.equals("Admin")) { if (userName.equals("Admin")) {
throw new MageException("User name already in use"); return "User name Admin already in use";
} }
if (userName.length() > ConfigSettings.getInstance().getMaxUserNameLength()) { if (userName.length() > ConfigSettings.getInstance().getMaxUserNameLength()) {
throw new MageException(new StringBuilder("User name may not be longer than ").append(ConfigSettings.getInstance().getMaxUserNameLength()).append(" characters").toString()); return new StringBuilder("User name may not be longer than ").append(ConfigSettings.getInstance().getMaxUserNameLength()).append(" characters").toString();
} }
if (userName.length() < ConfigSettings.getInstance().getMinUserNameLength()) { if (userName.length() < ConfigSettings.getInstance().getMinUserNameLength()) {
throw new MageException(new StringBuilder("User name may not be shorter than ").append(ConfigSettings.getInstance().getMinUserNameLength()).append(" characters").toString()); return new StringBuilder("User name may not be shorter than ").append(ConfigSettings.getInstance().getMinUserNameLength()).append(" characters").toString();
} }
Pattern p = Pattern.compile(ConfigSettings.getInstance().getUserNamePattern(), Pattern.CASE_INSENSITIVE); Pattern p = Pattern.compile(ConfigSettings.getInstance().getUserNamePattern(), Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(userName); Matcher m = p.matcher(userName);
if (m.find()) { if (m.find()) {
throw new MageException("User name '" + userName + "' includes not allowed characters: use a-z, A-Z and 0-9"); return new StringBuilder("User name '").append(userName).append("' includes not allowed characters: use a-z, A-Z and 0-9").toString();
} }
User user = UserManager.getInstance().createUser(userName, host); User user = UserManager.getInstance().createUser(userName, host);
if (user == null) { // user already exists if (user == null) { // user already exists
@ -93,20 +103,20 @@ public class Session {
// ChatManager.getInstance().broadcast([CHAT ID TABLES], "has reconnected", ChatMessage.MessageColor.GREEN); // ChatManager.getInstance().broadcast([CHAT ID TABLES], "has reconnected", ChatMessage.MessageColor.GREEN);
logger.info("Reconnecting session for " + userName); logger.info("Reconnecting session for " + userName);
} else { } else {
//throw new MageException("This machine is already connected"); //throw new MageException("This machine is already connected");
//disconnect previous one //disconnect previous one
logger.info("Disconnecting another user instance: " + userName); logger.info("Disconnecting another user instance: " + userName);
UserManager.getInstance().disconnect(user.getId(), User.DisconnectReason.ConnectingOtherInstance); UserManager.getInstance().disconnect(user.getId(), User.DisconnectReason.ConnectingOtherInstance);
} }
} } else {
else { return new StringBuilder("User name ").append(userName).append(" already in use (or your IP address changed)").toString();
throw new MageException("User name " + userName + " already in use");
} }
} }
if (!UserManager.getInstance().connectToSession(sessionId, user.getId())) { if (!UserManager.getInstance().connectToSession(sessionId, user.getId())) {
throw new MageException("Error connecting " + userName); return new StringBuilder("Error connecting ").append(userName).toString();
} }
this.userId = user.getId(); this.userId = user.getId();
return null;
} }
public void registerAdmin() { public void registerAdmin() {
@ -232,4 +242,11 @@ public class Session {
void setHost(String hostAddress) { void setHost(String hostAddress) {
this.host = hostAddress; this.host = hostAddress;
} }
void sendErrorMessageToClient(String message) {
List<String> messageData = new LinkedList<>();
messageData.add("Error while connecting to server");
messageData.add(message);
fireCallback(new ClientCallback("showUserMessage", null, messageData));
}
} }

View file

@ -66,13 +66,17 @@ public class SessionManager {
public boolean registerUser(String sessionId, String userName) throws MageException { public boolean registerUser(String sessionId, String userName) throws MageException {
Session session = sessions.get(sessionId); Session session = sessions.get(sessionId);
if (session != null) { if (session != null) {
session.registerUser(userName); String returnMessage = session.registerUser(userName);
if (returnMessage == null) {
LogServiceImpl.instance.log(LogKeys.KEY_USER_CONNECTED, userName, session.getHost(), sessionId); LogServiceImpl.instance.log(LogKeys.KEY_USER_CONNECTED, userName, session.getHost(), sessionId);
logger.info(new StringBuilder("User: ").append(userName) logger.info(new StringBuilder("User: ").append(userName)
.append(" userId: ").append(session.getUserId()) .append(" userId: ").append(session.getUserId())
.append(" connected from: ").append(session.getHost()) .append(" connected from: ").append(session.getHost())
.append(" sessionId: ").append(sessionId)); .append(" sessionId: ").append(sessionId));
return true; return true;
} else {
logger.info(new StringBuilder("User not registered - ").append(returnMessage));
}
} }
return false; return false;
} }

View file

@ -209,9 +209,11 @@ public class TableManager {
public void leaveTable(UUID userId, UUID tableId) { public void leaveTable(UUID userId, UUID tableId) {
if (controllers.containsKey(tableId)) { if (controllers.containsKey(tableId)) {
// table not started yet and user is the owner, remove the table // table not started yet and user is the owner, remove the table
if (isTableOwner(tableId, userId) Table table = getTable(tableId);
&& (getTable(tableId).getState().equals(TableState.WAITING) if (table != null
|| getTable(tableId).getState().equals(TableState.STARTING))) { && isTableOwner(tableId, userId)
&& (table.getState().equals(TableState.WAITING)
|| table.getState().equals(TableState.STARTING))) {
removeTable(tableId); removeTable(tableId);
} else { } else {

View file

@ -317,18 +317,23 @@ public class User {
} }
public void kill(DisconnectReason reason) { public void kill(DisconnectReason reason) {
for (GameSession session: gameSessions.values()) { logger.debug("kill: kill game sessions");
session.kill(); for (GameSession gameSession: gameSessions.values()) {
gameSession.kill();
} }
for (DraftSession session: draftSessions.values()) { logger.debug("kill: kill draft sessions");
session.setKilled(); for (DraftSession draftSession: draftSessions.values()) {
draftSession.setKilled();
} }
for (TournamentSession session: tournamentSessions.values()) { logger.debug("kill: kill tournament sessions");
session.setKilled(); for (TournamentSession tournamentSession: tournamentSessions.values()) {
tournamentSession.setKilled();
} }
logger.debug("kill: leave tables");
for (Entry<UUID, Table> entry: tables.entrySet()) { for (Entry<UUID, Table> entry: tables.entrySet()) {
TableManager.getInstance().leaveTable(userId, entry.getValue().getId()); TableManager.getInstance().leaveTable(userId, entry.getValue().getId());
} }
logger.debug("kill: remove user from chat");
ChatManager.getInstance().removeUser(userId, reason); ChatManager.getInstance().removeUser(userId, reason);
} }

View file

@ -233,7 +233,7 @@ public class GameSession extends GameWatcher {
gameView.setHand(new SimpleCardsView(player.getHand().getCards(game))); gameView.setHand(new SimpleCardsView(player.getHand().getCards(game)));
if (player.getPlayersUnderYourControl().size() > 0) { if (player.getPlayersUnderYourControl().size() > 0) {
Map<String, SimpleCardsView> handCards = new HashMap<String, SimpleCardsView>(); Map<String, SimpleCardsView> handCards = new HashMap<>();
for (UUID controlledPlayerId : player.getPlayersUnderYourControl()) { for (UUID controlledPlayerId : player.getPlayersUnderYourControl()) {
Player opponent = game.getPlayer(controlledPlayerId); Player opponent = game.getPlayer(controlledPlayerId);
handCards.put(opponent.getName(), new SimpleCardsView(opponent.getHand().getCards(game))); handCards.put(opponent.getName(), new SimpleCardsView(opponent.getHand().getCards(game)));
@ -243,7 +243,7 @@ public class GameSession extends GameWatcher {
//TODO: should player who controls another player's turn be able to look at all these cards? //TODO: should player who controls another player's turn be able to look at all these cards?
List<LookedAtView> list = new ArrayList<LookedAtView>(); List<LookedAtView> list = new ArrayList<>();
for (Entry<String, Cards> entry : game.getState().getLookedAt(playerId).entrySet()) { for (Entry<String, Cards> entry : game.getState().getLookedAt(playerId).entrySet()) {
list.add(new LookedAtView(entry.getKey(), entry.getValue(), game)); list.add(new LookedAtView(entry.getKey(), entry.getValue(), game));
} }
@ -265,7 +265,9 @@ public class GameSession extends GameWatcher {
} }
public void kill() { public void kill() {
game.quit(playerId); if (game != null) {
game.quit(playerId);
}
} }
public void setUserData(UserData userData) { public void setUserData(UserData userData) {

View file

@ -55,7 +55,7 @@ public enum CardRepository {
private static final String JDBC_URL = "jdbc:sqlite:db/cards.db"; private static final String JDBC_URL = "jdbc:sqlite:db/cards.db";
private static final String VERSION_ENTITY_NAME = "card"; private static final String VERSION_ENTITY_NAME = "card";
private static final long CARD_DB_VERSION = 23; private static final long CARD_DB_VERSION = 24;
private final Random random = new Random(); private final Random random = new Random();
private Dao<CardInfo, Object> cardDao; private Dao<CardInfo, Object> cardDao;