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;
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.FileWriter;
import java.io.IOException;
......@@ -17,198 +11,210 @@ import java.util.ArrayList;
import java.util.Date;
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 {
DataCoreClient dataCoreClient;
public MainToDataImpl(DataCoreClient dataCoreClient) {
this.dataCoreClient = dataCoreClient;
}
public static void createUser(UserLight userLight, UserHeavy userHeavy) throws Exception {
String userFilePath = Configuration.SAVE_DIR + File.separator + userLight.getPseudo() + ".json";
File userFile = new File(userFilePath);
if (userFile.exists()) {
throw new Exception("This user already exists on this computer");
}
JsonObject userJson = new JsonObject();
userJson.addProperty("id", userLight.getId().toString());
userJson.addProperty("pseudo", userLight.getPseudo());
userJson.addProperty("lastName", userLight.getLastName());
userJson.addProperty("firstName", userLight.getFirstName());
if (userLight.getDateOfBirth() == null) {
userJson.addProperty("dateOfBirth", (String) null);
} else {
userJson.addProperty("dateOfBirth", new SimpleDateFormat("dd-MM-yyyy").format(userLight.getDateOfBirth()));
}
userJson.addProperty("avatarId", userLight.getAvatarId());
userJson.addProperty("playedGames", userLight.getPlayedGames());
userJson.addProperty("wonGames", userLight.getWonGames());
userJson.addProperty("password", userHeavy.getPassword());
userJson.addProperty("serverAddress", userHeavy.getServerAddress());
userJson.addProperty("serverPort", userHeavy.getServerPort());
userFile.getParentFile().mkdirs();
FileWriter fw = new FileWriter(userFilePath);
fw.write(userJson.toString());
fw.close();
}
@Override
public void selectGames(GameLight g) {
}
@Override
public void acceptanceAcquired(UUID u_id, Boolean validation) {
}
@Override
public Stage newGame(UserLight ul, Boolean spectatorsOk, Boolean chatOk, Boolean creatorPlayWhite, int limitMove,
Stage stageFx) {
GameLight gameCreated = new GameLight(UUID.randomUUID(), ul, null, GameStatus.PENDING, spectatorsOk, chatOk,
creatorPlayWhite, limitMove);
dataCoreClient.getDataToGame().getGameScreen(gameCreated, stageFx);
return stageFx;
}
@Override
public void updatedProfile(UserLight profile) {
}
@Override
public void requestToDataToSpecialGame(GameLight game, UserLight user, Stage stageFx) {
}
@Override
public void sendServerParams(String ip, int port) {
}
@Override
public ArrayList<GameLight> displaySavedGames(UUID id) {
return null;
}
@Override
public GameHeavy getSavedGame(UUID id) {
return null;
}
@Override
public void sendUserInfo(String pseudo, String lastName, String firstName, Date dateOfBirth, int avatarId,
String password) throws Exception {
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),
new UserHeavy(id, pseudo, password, null, null, null));
}
@Override
public void downloadUserProfile(String filePath) {
}
@Override
public void updateProfile(UserLight profileLight, UserHeavy profileHeavy) throws Exception {
String userFilePath = Configuration.SAVE_DIR + File.separator + dataCoreClient.getLocalUserHeavy().getPseudo()
+ ".json";
File userFile = new File(userFilePath);
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);
if (oldFile.exists()) {
throw new Exception("Error while backuping old data");
}
userFile.renameTo(oldFile);
try {
createUser(profileLight, profileHeavy);
// dataCoreClient.getDataToCom().notifyUpdateProfile(profileLight); TO DISCUSS
// WITH COM
} catch (Exception e) {
System.out.println(e.getMessage());
oldFile.renameTo(userFile);
}
oldFile.delete();
}
@Override
public void identify(String login, String password, String address) throws Exception {
// blank playername 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);
}
public UserLight getUserLightFromFile(String pseudo) throws Exception, IOException, ParseException {
String path = Configuration.SAVE_DIR + File.separator + pseudo + ".json";
File userFile = new File(path);
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();
UserLight userLight = new UserLight(UUID.fromString(userObject.get("id").getAsString()),
userObject.get("pseudo").getAsString(), userObject.get("lastName").getAsString(),
userObject.get("firstName").getAsString(),
userObject.get("dateOfBirth").isJsonNull() ? null
: new SimpleDateFormat("dd-MM-yyyy").parse(userObject.get("dateOfBirth").getAsString()),
userObject.get("avatarId").getAsInt(), userObject.get("playedGames").getAsInt(),
userObject.get("wonGames").getAsInt());
return userLight;
}
public UserHeavy getUserHeavyFromFile(String pseudo) throws Exception, IOException, ParseException {
String path = Configuration.SAVE_DIR + File.separator + pseudo + ".json";
File userFile = new File(path);
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();
UserHeavy userHeavy = new UserHeavy(UUID.fromString(userObject.get("id").getAsString()),
userObject.get("pseudo").getAsString(), userObject.get("password").getAsString(),
userObject.get("serverAddress").toString(), userObject.get("serverPort").toString(), null);
return userHeavy;
}
public void login(String login, String password) throws Exception {
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
} else {
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
} else {
dataCoreClient.setLocalUserHeavy(userHeavy);
dataCoreClient.setLocalUserLight(userLight);
dataCoreClient.getDataToMain().sendUserInfo(userLight, userHeavy);
}
}
}
@Override
public void disconnect() {
}
DataCoreClient dataCoreClient;
public MainToDataImpl(DataCoreClient dataCoreClient) {
this.dataCoreClient = dataCoreClient;
}
public static void createUser(UserLight userLight, UserHeavy userHeavy) throws Exception {
String userFilePath = Configuration.SAVE_DIR + File.separator + userLight.getPseudo() + ".json";
File userFile = new File(userFilePath);
if (userFile.exists()) {
throw new Exception("This user already exists on this computer");
}
JsonObject userJson = new JsonObject();
userJson.addProperty("id", userLight.getId().toString());
userJson.addProperty("pseudo", userLight.getPseudo());
userJson.addProperty("lastName", userLight.getLastName());
userJson.addProperty("firstName", userLight.getFirstName());
if (userLight.getDateOfBirth() == null) {
userJson.addProperty("dateOfBirth", (String) null);
} else {
userJson.addProperty("dateOfBirth", new SimpleDateFormat("dd-MM-yyyy").format(userLight.getDateOfBirth()));
}
userJson.addProperty("avatarId", userLight.getAvatarId());
userJson.addProperty("playedGames", userLight.getPlayedGames());
userJson.addProperty("wonGames", userLight.getWonGames());
userJson.addProperty("password", userHeavy.getPassword());
userJson.addProperty("serverAddress", userHeavy.getServerAddress());
userJson.addProperty("serverPort", userHeavy.getServerPort());
userFile.getParentFile().mkdirs();
FileWriter fw = new FileWriter(userFilePath);
fw.write(userJson.toString());
fw.close();
}
@Override
public void selectGames(GameLight g) {
}
@Override
public void acceptanceAcquired(UUID u_id, Boolean validation) {
}
@Override
public Stage newGame(UserLight ul, Boolean spectatorsOk, Boolean chatOk, Boolean creatorPlayWhite, int limitMove,
Stage stageFx) {
GameLight gameCreated = new GameLight(UUID.randomUUID(), ul, null, GameStatus.PENDING, spectatorsOk, chatOk,
creatorPlayWhite, limitMove);
dataCoreClient.getDataToCom().addNewGameAvailable(gameCreated);
dataCoreClient.getDataToGame().getGameScreen(gameCreated, stageFx);
return stageFx;
}
@Override
public void updatedProfile(UserLight profile) {
}
@Override
public void requestToDataToSpecialGame(GameLight game, UserLight user, Stage stageFx) {
}
@Override
public void sendServerParams(String ip, int port) {
}
@Override
public ArrayList<GameLight> displaySavedGames(UUID id) {
return null;
}
@Override
public GameHeavy getSavedGame(UUID id) {
return null;
}
@Override
public void sendUserInfo(String pseudo, String lastName, String firstName, Date dateOfBirth, int avatarId,
String password) throws Exception {
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),
new UserHeavy(id, pseudo, password, null, null, null));
}
@Override
public void downloadUserProfile(String filePath) {
}
@Override
public void updateProfile(UserLight profileLight, UserHeavy profileHeavy) throws Exception {
String userFilePath = Configuration.SAVE_DIR + File.separator + dataCoreClient.getLocalUserHeavy().getPseudo()
+ ".json";
File userFile = new File(userFilePath);
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);
if (oldFile.exists()) {
throw new Exception("Error while backuping old data");
}
userFile.renameTo(oldFile);
try {
createUser(profileLight, profileHeavy);
// dataCoreClient.getDataToCom().notifyUpdateProfile(profileLight); TO DISCUSS
// WITH COM
} catch (Exception e) {
System.out.println(e.getMessage());
oldFile.renameTo(userFile);
}
oldFile.delete();
}
@Override
public void identify(String login, String password, String address) throws Exception {
// blank playername 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);
}
public UserLight getUserLightFromFile(String pseudo) throws Exception, IOException, ParseException {
String path = Configuration.SAVE_DIR + File.separator + pseudo + ".json";
File userFile = new File(path);
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();
UserLight userLight = new UserLight(UUID.fromString(userObject.get("id").getAsString()),
userObject.get("pseudo").getAsString(), userObject.get("lastName").getAsString(),
userObject.get("firstName").getAsString(),
userObject.get("dateOfBirth").isJsonNull() ? null
: new SimpleDateFormat("dd-MM-yyyy").parse(userObject.get("dateOfBirth").getAsString()),
userObject.get("avatarId").getAsInt(), userObject.get("playedGames").getAsInt(),
userObject.get("wonGames").getAsInt());
return userLight;
}
public UserHeavy getUserHeavyFromFile(String pseudo) throws Exception, IOException, ParseException {
String path = Configuration.SAVE_DIR + File.separator + pseudo + ".json";
File userFile = new File(path);
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();
UserHeavy userHeavy = new UserHeavy(UUID.fromString(userObject.get("id").getAsString()),
userObject.get("pseudo").getAsString(), userObject.get("password").getAsString(),
userObject.get("serverAddress").toString(), userObject.get("serverPort").toString(), null);
return userHeavy;
}
public void login(String login, String password) throws Exception {
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
} else {
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
} else {
dataCoreClient.setLocalUserHeavy(userHeavy);
dataCoreClient.setLocalUserLight(userLight);
dataCoreClient.getDataToMain().sendUserInfo(userLight, userHeavy);
}
}
}
@Override
public void disconnect() {
}
}
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.scene.control.Button;
import javafx.scene.control.TabPane;
......@@ -9,8 +14,6 @@ import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import main.java.client.game.GameCore;
import main.java.common.dataModel.Message;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* IHM-Game main controller class.
......@@ -18,134 +21,137 @@ import org.apache.logging.log4j.Logger;
* Links the FXML elements to the correct methods in the specialized controllers
*/
public class MainGameController {
/**
* Class logger
*/
private static final Logger LOGGER = LogManager.getLogger(MainGameController.class);
@FXML
Button openButton;
@FXML
TextArea areaSendMessage;
@FXML
TextArea areaChatHistory;
@FXML
TabPane sideRightTabPane;
/**
* Side controller
*/
private MainGameControllerSide sideController;
/**
* Board controller
*/
private MainGameControllerBoard boardController;
/**
* Application game core
*/
private GameCore gameCore;
/**
* Controller constructor, instantiates the secondary controllers
*/
public MainGameController() {
sideController = new MainGameControllerSide();
boardController = new MainGameControllerBoard();
}
/**
* Sets the module Core reference
*
* @param core
*/
public void setCore(GameCore core) {
gameCore = core;
sideController.setCore(core);
}
/**
* Method called after the display of the game Java FX scene
*/
public void initialize() {
// Remove access to the chat panel if the game configuration says so
if (!gameCore.getDataToGame().isChatAuthorized()) {
sideRightTabPane.getTabs().get(1).setDisable(true);
sideRightTabPane.getTabs().get(1)
.setTooltip(new Tooltip("La discussion Chat est désactivée pour cette partie."));
}
}
/**
* Called upon a click on the send button
*/
public void onSendMessage() {
if (!areaSendMessage.getText().isEmpty()) {
sendMessage();
}
}
/**
* Displays a message to the chat history area after its receiving.
*/
public void newMessageToHistory(Message m) {
LOGGER.debug("Message received -> " + m.getMessage());
areaChatHistory.appendText("-------\n");
areaChatHistory.appendText(m.getMessage());
}
/**
* Called upon a click on the forfeit button
*/
public void onForfeit() {
LOGGER.debug("Forfeit");
}
/**
* ActionKeyPressed event managed by the areaSendMessage TextArea.
* <p>
* It is used to listen to Enter key, where we want to send a message when Enter
* is pressed
*
* @param event: KeyEvent created upon the key pressed action
*/
@FXML
public void onActionKeyPressed(KeyEvent event) {
/*
* If there is no message and we press enter, we do not want to send an empty
* message. In that case we consume the event, and do nothing afterwards.
*/
if (areaSendMessage.getText().trim().isEmpty() && event.getCode() == KeyCode.ENTER) {
areaSendMessage.clear();
event.consume();
}
/*
* If the message is not empty, we send it if enter is pressed. We check if
* shift is down, if it is the case, the message will not be send, but a new
* line is added to the text area.
*/
else if (event.getCode() == KeyCode.ENTER) {
event.consume();
if (event.isShiftDown()) { // New line
areaSendMessage.appendText(System.getProperty("line.separator"));
} else {
sendMessage(); // New message
}
}
}
/**
* Calls for the main SendMessage in the side controller and clears the message
* in the TextArea.
*/
private void sendMessage() {
sideController.onSendMessage(areaSendMessage.getText().trim());
areaSendMessage.clear();
}
/**
* Class logger
*/
private static final Logger LOGGER = LogManager.getLogger(MainGameController.class);
@FXML
Button openButton;
@FXML
TextArea areaSendMessage;
@FXML
TextArea areaChatHistory;
@FXML
TabPane sideRightTabPane;
/**
* Side controller
*/