/** * Logs in or registers a player. Called by the message receiver thread. * * @param webSocket * @throws IOException * @throws UnknownMesgEx * @return The logged in player, or null on failure. * @author Tiberiu Pasat * @author Paul Nechifor */ public Player loginOrRegister(WebSocket webSocket) throws IOException, UnknownMesgEx { LoginOrRegisterFrom lor = (LoginOrRegisterFrom) MesgFrom.read(webSocket); LoginOrRegisterTo resp = new LoginOrRegisterTo(); resp.accepted = false; Player player = null; String reason = getReasonForInvalid(lor.name, lor.password); if (reason == null) { if (lor.register) { synchronized (players) { try { player = new Player(lor.name, this, webSocket, lor.password); PlayerManager.persist(player); resp.accepted = true; players.put(player.getId(), player); heroes.put(player.getId(), player); } catch (Exception ex) { ex.printStackTrace(); resp.message = ex.getMessage(); } } } else { synchronized (players) { player = new Player(lor.name, this, webSocket, lor.password); // then fill it from database if exists try { PlayerManager.fillByUsernameAndPassword(player); if (players.containsKey(player.getId())) throw new Exception("Account already logged in"); players.put(player.getId(), player); heroes.put(player.getId(), player); resp.accepted = true; } catch (Exception e) { // if not exists will be thrown an error so we don't // accept him e.printStackTrace(); player = null; resp.message = e.getMessage(); } } } } else { resp.message = reason; } if (resp.accepted) { resp.info = new LoginInfo(player); } resp.write(webSocket); if (resp.accepted) { return player; // Return the player (i.e. success). } return null; // Return failure. }
/** * Called to signal that a player should be kicked out due to any reason. * * @param player The player to be kicked. */ public void kickPlayer(Player player) { System.out.println("Kicking player: " + player.getName()); // TODO: The rest. // write infos about player in database try { PlayerManager.merge(player); } catch (Exception ex) { // TODO: Do something if merging was not successful. throw new RuntimeException(ex); } // remove player from logged in players list synchronized (players) { players.remove(player.getId()); player.logout(); } this.getMap().removeObserver(player); }