Commit e4bb8c7d authored by Thomas's avatar Thomas
Browse files

Added empty constructors in common datamodel objects, completed chat messages...

Added empty constructors in common datamodel objects, completed chat messages reception, fixed UUID comparison issue in Data module
parent 0c256650
package main.java.client.data; package main.java.client.data;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import javafx.stage.Stage;
import main.java.common.dataModel.*;
import main.java.common.interfaces.client.IMainToData;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
...@@ -17,198 +11,210 @@ import java.util.ArrayList; ...@@ -17,198 +11,210 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.UUID; import java.util.UUID;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import javafx.stage.Stage;
import main.java.common.dataModel.GameHeavy;
import main.java.common.dataModel.GameLight;
import main.java.common.dataModel.GameStatus;
import main.java.common.dataModel.UserHeavy;
import main.java.common.dataModel.UserLight;
import main.java.common.interfaces.client.IMainToData;
public class MainToDataImpl implements IMainToData { public class MainToDataImpl implements IMainToData {
DataCoreClient dataCoreClient; DataCoreClient dataCoreClient;
public MainToDataImpl(DataCoreClient dataCoreClient) { public MainToDataImpl(DataCoreClient dataCoreClient) {
this.dataCoreClient = dataCoreClient; this.dataCoreClient = dataCoreClient;
} }
public static void createUser(UserLight userLight, UserHeavy userHeavy) throws Exception { public static void createUser(UserLight userLight, UserHeavy userHeavy) throws Exception {
String userFilePath = Configuration.SAVE_DIR + File.separator + userLight.getPseudo() + ".json"; String userFilePath = Configuration.SAVE_DIR + File.separator + userLight.getPseudo() + ".json";
File userFile = new File(userFilePath); File userFile = new File(userFilePath);
if (userFile.exists()) { if (userFile.exists()) {
throw new Exception("This user already exists on this computer"); throw new Exception("This user already exists on this computer");
} }
JsonObject userJson = new JsonObject(); JsonObject userJson = new JsonObject();
userJson.addProperty("id", userLight.getId().toString()); userJson.addProperty("id", userLight.getId().toString());
userJson.addProperty("pseudo", userLight.getPseudo()); userJson.addProperty("pseudo", userLight.getPseudo());
userJson.addProperty("lastName", userLight.getLastName()); userJson.addProperty("lastName", userLight.getLastName());
userJson.addProperty("firstName", userLight.getFirstName()); userJson.addProperty("firstName", userLight.getFirstName());
if (userLight.getDateOfBirth() == null) { if (userLight.getDateOfBirth() == null) {
userJson.addProperty("dateOfBirth", (String) null); userJson.addProperty("dateOfBirth", (String) null);
} else { } else {
userJson.addProperty("dateOfBirth", new SimpleDateFormat("dd-MM-yyyy").format(userLight.getDateOfBirth())); userJson.addProperty("dateOfBirth", new SimpleDateFormat("dd-MM-yyyy").format(userLight.getDateOfBirth()));
} }
userJson.addProperty("avatarId", userLight.getAvatarId()); userJson.addProperty("avatarId", userLight.getAvatarId());
userJson.addProperty("playedGames", userLight.getPlayedGames()); userJson.addProperty("playedGames", userLight.getPlayedGames());
userJson.addProperty("wonGames", userLight.getWonGames()); userJson.addProperty("wonGames", userLight.getWonGames());
userJson.addProperty("password", userHeavy.getPassword()); userJson.addProperty("password", userHeavy.getPassword());
userJson.addProperty("serverAddress", userHeavy.getServerAddress()); userJson.addProperty("serverAddress", userHeavy.getServerAddress());
userJson.addProperty("serverPort", userHeavy.getServerPort()); userJson.addProperty("serverPort", userHeavy.getServerPort());
userFile.getParentFile().mkdirs(); userFile.getParentFile().mkdirs();
FileWriter fw = new FileWriter(userFilePath); FileWriter fw = new FileWriter(userFilePath);
fw.write(userJson.toString()); fw.write(userJson.toString());
fw.close(); fw.close();
} }
@Override @Override
public void selectGames(GameLight g) { public void selectGames(GameLight g) {
} }
@Override @Override
public void acceptanceAcquired(UUID u_id, Boolean validation) { public void acceptanceAcquired(UUID u_id, Boolean validation) {
} }
@Override @Override
public Stage newGame(UserLight ul, Boolean spectatorsOk, Boolean chatOk, Boolean creatorPlayWhite, int limitMove, public Stage newGame(UserLight ul, Boolean spectatorsOk, Boolean chatOk, Boolean creatorPlayWhite, int limitMove,
Stage stageFx) { Stage stageFx) {
GameLight gameCreated = new GameLight(UUID.randomUUID(), ul, null, GameStatus.PENDING, spectatorsOk, chatOk, GameLight gameCreated = new GameLight(UUID.randomUUID(), ul, null, GameStatus.PENDING, spectatorsOk, chatOk,
creatorPlayWhite, limitMove); creatorPlayWhite, limitMove);
dataCoreClient.getDataToGame().getGameScreen(gameCreated, stageFx); dataCoreClient.getDataToCom().addNewGameAvailable(gameCreated);
return stageFx; dataCoreClient.getDataToGame().getGameScreen(gameCreated, stageFx);
} return stageFx;
}
@Override
public void updatedProfile(UserLight profile) { @Override
public void updatedProfile(UserLight profile) {
}
}
@Override
public void requestToDataToSpecialGame(GameLight game, UserLight user, Stage stageFx) { @Override
public void requestToDataToSpecialGame(GameLight game, UserLight user, Stage stageFx) {
}
}
@Override
public void sendServerParams(String ip, int port) { @Override
public void sendServerParams(String ip, int port) {
}
}
@Override
public ArrayList<GameLight> displaySavedGames(UUID id) { @Override
return null; public ArrayList<GameLight> displaySavedGames(UUID id) {
} return null;
}
@Override
public GameHeavy getSavedGame(UUID id) { @Override
return null; public GameHeavy getSavedGame(UUID id) {
} return null;
}
@Override
public void sendUserInfo(String pseudo, String lastName, String firstName, Date dateOfBirth, int avatarId, @Override
String password) throws Exception { public void sendUserInfo(String pseudo, String lastName, String firstName, Date dateOfBirth, int avatarId,
if (lastName == null || firstName == null || password == null) { String password) throws Exception {
throw new Exception("One or more required field is empty"); if (lastName == null || firstName == null || password == null) {
} throw new Exception("One or more required field is empty");
UUID id = UUID.randomUUID(); }
createUser(new UserLight(id, pseudo, lastName, firstName, dateOfBirth, avatarId, 0, 0), UUID id = UUID.randomUUID();
new UserHeavy(id, pseudo, password, null, null, null)); createUser(new UserLight(id, pseudo, lastName, firstName, dateOfBirth, avatarId, 0, 0),
} new UserHeavy(id, pseudo, password, null, null, null));
}
@Override
public void downloadUserProfile(String filePath) { @Override
public void downloadUserProfile(String filePath) {
}
}
@Override
public void updateProfile(UserLight profileLight, UserHeavy profileHeavy) throws Exception { @Override
String userFilePath = Configuration.SAVE_DIR + File.separator + dataCoreClient.getLocalUserHeavy().getPseudo() public void updateProfile(UserLight profileLight, UserHeavy profileHeavy) throws Exception {
+ ".json"; String userFilePath = Configuration.SAVE_DIR + File.separator + dataCoreClient.getLocalUserHeavy().getPseudo()
File userFile = new File(userFilePath); + ".json";
if (!userFile.exists()) { File userFile = new File(userFilePath);
throw new Exception("File for user " + dataCoreClient.getLocalUserHeavy().getPseudo() + " not found"); if (!userFile.exists()) {
} throw new Exception("File for user " + dataCoreClient.getLocalUserHeavy().getPseudo() + " not found");
String oldFilePath = userFilePath + profileLight.getId().toString(); }
File oldFile = new File(oldFilePath); String oldFilePath = userFilePath + profileLight.getId().toString();
if (oldFile.exists()) { File oldFile = new File(oldFilePath);
throw new Exception("Error while backuping old data"); if (oldFile.exists()) {
} throw new Exception("Error while backuping old data");
userFile.renameTo(oldFile); }
try { userFile.renameTo(oldFile);
createUser(profileLight, profileHeavy); try {
// dataCoreClient.getDataToCom().notifyUpdateProfile(profileLight); TO DISCUSS createUser(profileLight, profileHeavy);
// WITH COM // dataCoreClient.getDataToCom().notifyUpdateProfile(profileLight); TO DISCUSS
} catch (Exception e) { // WITH COM
System.out.println(e.getMessage()); } catch (Exception e) {
oldFile.renameTo(userFile); System.out.println(e.getMessage());
} oldFile.renameTo(userFile);
oldFile.delete(); }
} oldFile.delete();
}
@Override
public void identify(String login, String password, String address) throws Exception { @Override
// blank playername or password public void identify(String login, String password, String address) throws Exception {
if (login.isEmpty() || password.isEmpty()) { // blank playername or password
throw new Exception("Data error: due to empty login or password"); if (login.isEmpty() || password.isEmpty()) {
} throw new Exception("Data error: due to empty login or password");
login(login, password); }
dataCoreClient.getDataToCom().connectUserOnline(getUserLightFromFile(login), address); login(login, password);
} dataCoreClient.getDataToCom().connectUserOnline(getUserLightFromFile(login), address);
}
public UserLight getUserLightFromFile(String pseudo) throws Exception, IOException, ParseException {
String path = Configuration.SAVE_DIR + File.separator + pseudo + ".json"; public UserLight getUserLightFromFile(String pseudo) throws Exception, IOException, ParseException {
File userFile = new File(path); String path = Configuration.SAVE_DIR + File.separator + pseudo + ".json";
if (!userFile.exists()) { File userFile = new File(path);
throw new Exception("Data error: User profile does not exist"); if (!userFile.exists()) {
} throw new Exception("Data error: User profile does not exist");
JsonParser parser = new JsonParser(); }
JsonObject userObject = parser.parse(new String(Files.readAllBytes(Paths.get(path)))).getAsJsonObject(); JsonParser parser = new JsonParser();
JsonObject userObject = parser.parse(new String(Files.readAllBytes(Paths.get(path)))).getAsJsonObject();
UserLight userLight = new UserLight(UUID.fromString(userObject.get("id").getAsString()),
userObject.get("pseudo").getAsString(), userObject.get("lastName").getAsString(), UserLight userLight = new UserLight(UUID.fromString(userObject.get("id").getAsString()),
userObject.get("firstName").getAsString(), userObject.get("pseudo").getAsString(), userObject.get("lastName").getAsString(),
userObject.get("dateOfBirth").isJsonNull() ? null userObject.get("firstName").getAsString(),
: new SimpleDateFormat("dd-MM-yyyy").parse(userObject.get("dateOfBirth").getAsString()), userObject.get("dateOfBirth").isJsonNull() ? null
userObject.get("avatarId").getAsInt(), userObject.get("playedGames").getAsInt(), : new SimpleDateFormat("dd-MM-yyyy").parse(userObject.get("dateOfBirth").getAsString()),
userObject.get("wonGames").getAsInt()); userObject.get("avatarId").getAsInt(), userObject.get("playedGames").getAsInt(),
userObject.get("wonGames").getAsInt());
return userLight;
} return userLight;
}
public UserHeavy getUserHeavyFromFile(String pseudo) throws Exception, IOException, ParseException {
String path = Configuration.SAVE_DIR + File.separator + pseudo + ".json"; public UserHeavy getUserHeavyFromFile(String pseudo) throws Exception, IOException, ParseException {
File userFile = new File(path); String path = Configuration.SAVE_DIR + File.separator + pseudo + ".json";
if (!userFile.exists()) { File userFile = new File(path);
throw new Exception("Data error: User profile does not exist"); if (!userFile.exists()) {
} throw new Exception("Data error: User profile does not exist");
JsonParser parser = new JsonParser(); }
JsonObject userObject = parser.parse(new String(Files.readAllBytes(Paths.get(path)))).getAsJsonObject(); JsonParser parser = new JsonParser();
JsonObject userObject = parser.parse(new String(Files.readAllBytes(Paths.get(path)))).getAsJsonObject();
UserHeavy userHeavy = new UserHeavy(UUID.fromString(userObject.get("id").getAsString()),
userObject.get("pseudo").getAsString(), userObject.get("password").getAsString(), UserHeavy userHeavy = new UserHeavy(UUID.fromString(userObject.get("id").getAsString()),
userObject.get("serverAddress").toString(), userObject.get("serverPort").toString(), null); userObject.get("pseudo").getAsString(), userObject.get("password").getAsString(),
userObject.get("serverAddress").toString(), userObject.get("serverPort").toString(), null);
return userHeavy;
} return userHeavy;
}
public void login(String login, String password) throws Exception {
String path = Configuration.SAVE_DIR + File.separator + login + ".json"; public void login(String login, String password) throws Exception {
File userFile = new File(path); String path = Configuration.SAVE_DIR + File.separator + login + ".json";
File userFile = new File(path);
if (!userFile.exists()) {
throw new Exception("Data error: User profile does not exist"); // throw related error if (!userFile.exists()) {
} else { throw new Exception("Data error: User profile does not exist"); // throw related error
UserLight userLight = getUserLightFromFile(login); } else {
UserHeavy userHeavy = getUserHeavyFromFile(login); UserLight userLight = getUserLightFromFile(login);
UserHeavy userHeavy = getUserHeavyFromFile(login);
if (!userHeavy.getPassword().equals(password)) {
throw new Exception("Data error: User password does not match"); // throw related error if (!userHeavy.getPassword().equals(password)) {
} else { throw new Exception("Data error: User password does not match"); // throw related error
dataCoreClient.setLocalUserHeavy(userHeavy); } else {
dataCoreClient.setLocalUserLight(userLight); dataCoreClient.setLocalUserHeavy(userHeavy);
dataCoreClient.getDataToMain().sendUserInfo(userLight, userHeavy); dataCoreClient.setLocalUserLight(userLight);
} dataCoreClient.getDataToMain().sendUserInfo(userLight, userHeavy);
} }
} }
}
@Override
public void disconnect() { @Override
public void disconnect() {
}
}
} }
package main.java.client.game.controller; package main.java.client.game.controller;
import java.text.SimpleDateFormat;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.scene.control.Button; import javafx.scene.control.Button;
import javafx.scene.control.TabPane; import javafx.scene.control.TabPane;
...@@ -9,8 +14,6 @@ import javafx.scene.input.KeyCode; ...@@ -9,8 +14,6 @@ import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent; import javafx.scene.input.KeyEvent;
import main.java.client.game.GameCore; import main.java.client.game.GameCore;
import main.java.common.dataModel.Message; import main.java.common.dataModel.Message;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/** /**
* IHM-Game main controller class. * IHM-Game main controller class.
...@@ -18,134 +21,137 @@ import org.apache.logging.log4j.Logger; ...@@ -18,134 +21,137 @@ import org.apache.logging.log4j.Logger;
* Links the FXML elements to the correct methods in the specialized controllers * Links the FXML elements to the correct methods in the specialized controllers
*/ */
public class MainGameController { public class MainGameController {
/** /**
* Class logger * Class logger
*/ */
private static final Logger LOGGER = LogManager.getLogger(MainGameController.class); private static final Logger LOGGER = LogManager.getLogger(MainGameController.class);
@FXML @FXML
Button openButton; Button openButton;
@FXML @FXML
TextArea areaSendMessage; TextArea areaSendMessage;
@FXML @FXML
TextArea areaChatHistory; TextArea areaChatHistory;
@FXML @FXML
TabPane sideRightTabPane; TabPane sideRightTabPane;
/** /**
* Side controller * Side controller
*/ */
private MainGameControllerSide sideController; private MainGameControllerSide sideController;
/** /**
* Board controller * Board controller
*/ */
private MainGameControllerBoard boardController; private MainGameControllerBoard boardController;
/** /**
* Application game core * Application game core
*/ */
private GameCore gameCore; private GameCore gameCore;
/** /**
* Controller constructor, instantiates the secondary controllers * Controller constructor, instantiates the secondary controllers
*/ */
public MainGameController() { public MainGameController() {
sideController = new MainGameControllerSide(); sideController = new MainGameControllerSide();
boardController = new MainGameControllerBoard(); boardController = new MainGameControllerBoard();
} }
/** /**
* Sets the module Core reference * Sets the module Core reference
* *
* @param core * @param core
*/ */
public void setCore(GameCore core) { public void setCore(GameCore core) {
gameCore = core; gameCore = core;
sideController.setCore(core); sideController.setCore(core);
} }
/** /**
* Method called after the display of the game Java FX scene * Method called after the display of the game Java FX scene
*/ */
public void initialize() { public void initialize() {
// Remove access to the chat panel if the game configuration says so // Remove access to the chat panel if the game configuration says so
if (!gameCore.getDataToGame().isChatAuthorized()) { if (!gameCore.getDataToGame().isChatAuthorized()) {
sideRightTabPane.getTabs().get(1).setDisable(true); sideRightTabPane.getTabs().get(1).setDisable(true);
sideRightTabPane.getTabs().get(1) sideRightTabPane.getTabs().get(1)
.setTooltip(new Tooltip("La discussion Chat est désactivée pour cette partie.")); .setTooltip(new Tooltip("La discussion Chat est désactivée pour cette partie."));
} }
} }
/** /**
* Called upon a click on the send button * Called upon a click on the send button
*/ */
public void onSendMessage() { public void onSendMessage() {
if (!areaSendMessage.getText().isEmpty()) { if (!areaSendMessage.getText().isEmpty()) {
sendMessage(); sendMessage();
} }
} }
/** /**
* Displays a message to the chat history area after its receiving. * Displays a message to the chat history area after its receiving.
*/ */
public void newMessageToHistory(Message m) { public void newMessageToHistory(Message m) {
LOGGER.debug("Message received -> " + m.getMessage()); LOGGER.debug("Message received -> " + m.getMessage());
areaChatHistory.appendText("-------\n"); String time = new SimpleDateFormat("HH:mm:ss").format(m.getHourMessage());
areaChatHistory.appendText(m.getMessage()); areaChatHistory.appendText("---- " + m.getAuthor().getPseudo() + " à " + time + " ----");
} areaChatHistory.appendText("\n");
areaChatHistory.appendText("> " + m.getMessage());
/** areaChatHistory.appendText("\n");
* Called upon a click on the forfeit button }
*/
public void onForfeit() { /**
LOGGER.debug("Forfeit"); * Called upon a click on the forfeit button
} */
public void onForfeit() {
/** LOGGER.debug("Forfeit");
* ActionKeyPressed event managed by the areaSendMessage TextArea. }