diff --git a/pom.xml b/pom.xml index d2433b8..6465682 100644 --- a/pom.xml +++ b/pom.xml @@ -15,6 +15,12 @@ + + + com.google.code.gson + gson + 2.10.1 + org.openjfx javafx-controls diff --git a/src/main/java/com/mycompany/tictactoeserver/App.java b/src/main/java/com/mycompany/tictactoeserver/App.java index 5eadb71..20df6f5 100644 --- a/src/main/java/com/mycompany/tictactoeserver/App.java +++ b/src/main/java/com/mycompany/tictactoeserver/App.java @@ -1,18 +1,16 @@ package com.mycompany.tictactoeserver; import com.mycompany.tictactoeserver.datasource.database.Database; -import com.mycompany.tictactoeserver.domain.services.communication.MessageRouter; import com.mycompany.tictactoeserver.domain.utils.exception.DatabaseConnectionException; import com.mycompany.tictactoeserver.domain.utils.exception.ExceptionHandlerMiddleware; +import java.io.IOException; +import java.net.URL; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; -import java.io.IOException; -import java.net.URL; - public class App extends Application { private static Scene scene; @@ -59,6 +57,6 @@ private void setupDependencies() { ExceptionHandlerMiddleware.getInstance().handleException(e); } - MessageRouter.getInstance(); + } } \ No newline at end of file diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/entity/AuthRequestEntity.java b/src/main/java/com/mycompany/tictactoeserver/domain/entity/AuthRequestEntity.java new file mode 100644 index 0000000..d869e27 --- /dev/null +++ b/src/main/java/com/mycompany/tictactoeserver/domain/entity/AuthRequestEntity.java @@ -0,0 +1,51 @@ +package com.mycompany.tictactoeserver.domain.entity;/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ + + +/** + * + * @author Hazem + */ +public class AuthRequestEntity { + private String userName ; + private String password; + + public AuthRequestEntity(String userName, String password) { + this.userName = userName; + this.password = password; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String toString() { + return "AuthRequestEntity{" + "userName=" + userName + ", password=" + password + '}'; + } + + public AuthRequestEntity() { + } + + public String getUserName() { + return userName; + } + + public String getPassword() { + return password; + } + + public static AuthRequestEntity createAuthEntity(String username , String password) + { + return new AuthRequestEntity(username , password ); + } + + + +} diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/entity/AuthResponseEntity.java b/src/main/java/com/mycompany/tictactoeserver/domain/entity/AuthResponseEntity.java index 18f773c..f7ab0cb 100644 --- a/src/main/java/com/mycompany/tictactoeserver/domain/entity/AuthResponseEntity.java +++ b/src/main/java/com/mycompany/tictactoeserver/domain/entity/AuthResponseEntity.java @@ -1,14 +1,26 @@ package com.mycompany.tictactoeserver.domain.entity; import com.mycompany.tictactoeserver.datasource.model.Player; -import org.json.JSONObject; +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ + +/** + * + * @author Hazem + */ public class AuthResponseEntity { - String id; - String username; - int score; - public AuthResponseEntity() { + private String id; + private String username; + private int score; + + public AuthResponseEntity(String id, String userName, int Score) { + this.id = id; + this.username = userName; + this.score = Score; } public AuthResponseEntity(Player player) { @@ -17,15 +29,40 @@ public AuthResponseEntity(Player player) { score = player.getScore(); } - public JSONObject toJson() { - JSONObject json = new JSONObject(); + public AuthResponseEntity() { + } - json.put("id", id); - json.put("username", username); - json.put("score", score); + public void setId(String id) { + this.id = id; + } + + public void setUserName(String userName) { + this.username = userName; + } - return json; + public void setScore(int Score) { + this.score = Score; + } + + public String getId() { + return id; + } + + public String getUserName() { + return username; + } + + public int getScore() { + return score; + } + + public static AuthResponseEntity createAuthEntity(String id, String username, int score) { + return new AuthResponseEntity(id, username, score); + } + @Override + public String toString() { + return "AuthRequestEntity{" + "id=" + id + ", userName=" + username + ", Score=" + score + '}'; } } diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/server/GameServerManager.java b/src/main/java/com/mycompany/tictactoeserver/domain/server/GameServerManager.java index e730534..93020d4 100644 --- a/src/main/java/com/mycompany/tictactoeserver/domain/server/GameServerManager.java +++ b/src/main/java/com/mycompany/tictactoeserver/domain/server/GameServerManager.java @@ -5,7 +5,6 @@ import com.mycompany.tictactoeserver.domain.utils.exception.ExceptionHandlerMiddleware; import com.mycompany.tictactoeserver.domain.utils.exception.PlayerSendMessageException; import com.mycompany.tictactoeserver.domain.utils.exception.ServerInterruptException; - import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; @@ -75,12 +74,12 @@ public void sendMessage(String message, PlayerConnectionHandler player) throws P } public void onReceiveMessage(String message, PlayerConnectionHandler sender) { - MessageRouter router = MessageRouter.getInstance(); - try { + MessageRouter router = MessageRouter.getInstance(); + System.out.println("testingggggggggg"); router.navigateMessage(message, sender); - } catch (PlayerSendMessageException e) { - ExceptionHandlerMiddleware.getInstance().handleException(e); + } catch (PlayerSendMessageException ex) { + System.getLogger(GameServerManager.class.getName()).log(System.Logger.Level.ERROR, (String) null, ex); } } @@ -151,8 +150,11 @@ public void run() { System.out.println("Server Accepting..."); Socket clientSocket = serverSocket.accept(); if (isRunning) { - onAdd.call(new PlayerConnectionHandler(clientSocket)); + PlayerConnectionHandler player = new PlayerConnectionHandler(clientSocket); + onAdd.call(player); System.out.println("Client Connected: " + clientSocket.getInetAddress().getHostAddress()); + + } else { clientSocket.close(); } diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/server/PlayerConnectionHandler.java b/src/main/java/com/mycompany/tictactoeserver/domain/server/PlayerConnectionHandler.java index 1586b48..1f21d78 100644 --- a/src/main/java/com/mycompany/tictactoeserver/domain/server/PlayerConnectionHandler.java +++ b/src/main/java/com/mycompany/tictactoeserver/domain/server/PlayerConnectionHandler.java @@ -1,12 +1,14 @@ package com.mycompany.tictactoeserver.domain.server; +import com.google.gson.Gson; import com.mycompany.tictactoeserver.datasource.model.Player; +import com.mycompany.tictactoeserver.domain.entity.AuthRequestEntity; +import com.mycompany.tictactoeserver.domain.services.communication.Message; import com.mycompany.tictactoeserver.domain.utils.callbacks.StringCallback; import com.mycompany.tictactoeserver.domain.utils.callbacks.VoidCallback; import com.mycompany.tictactoeserver.domain.utils.exception.ExceptionHandlerMiddleware; import com.mycompany.tictactoeserver.domain.utils.exception.PlayerConnectionException; import com.mycompany.tictactoeserver.domain.utils.exception.PlayerSendMessageException; - import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; @@ -26,8 +28,12 @@ public class PlayerConnectionHandler { thread.start(); } - public void sendMessageToPlayer(String message) throws PlayerSendMessageException { - runnable.sendMessageToSocket(message); + public void sendMessageToPlayer(String message) { + try { + runnable.sendMessageToSocket(message); + } catch (PlayerSendMessageException e) { + System.out.println("Excetion sending message"); + } } public void receiveMessageFromPlayer(String message) { @@ -100,6 +106,7 @@ public void run() { } System.out.println("Player Reading..."); String msg = in.readUTF(); + System.out.println("in: ---> " + msg); onReceive.call(msg); } diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/services/authentication/AuthenticationService.java b/src/main/java/com/mycompany/tictactoeserver/domain/services/authentication/AuthenticationService.java index 503cb8d..2fd9e3a 100644 --- a/src/main/java/com/mycompany/tictactoeserver/domain/services/authentication/AuthenticationService.java +++ b/src/main/java/com/mycompany/tictactoeserver/domain/services/authentication/AuthenticationService.java @@ -2,9 +2,9 @@ import com.mycompany.tictactoeserver.datasource.database.dao.PlayerDAO; import com.mycompany.tictactoeserver.datasource.model.Player; +import com.mycompany.tictactoeserver.domain.entity.AuthRequestEntity; import com.mycompany.tictactoeserver.domain.entity.AuthResponseEntity; import com.mycompany.tictactoeserver.domain.services.communication.Action; -import com.mycompany.tictactoeserver.domain.services.communication.Header; import com.mycompany.tictactoeserver.domain.services.communication.Message; import com.mycompany.tictactoeserver.domain.services.communication.MessageType; import com.mycompany.tictactoeserver.domain.services.playerSession.PlayerSessionService; @@ -12,11 +12,14 @@ import com.mycompany.tictactoeserver.domain.utils.exception.ExceptionHandlerMiddleware; import com.mycompany.tictactoeserver.domain.utils.exception.HashingException; import com.mycompany.tictactoeserver.domain.utils.exception.ServerInterruptException; -import org.json.JSONObject; +/** + * + * @author Hazem + * + */ public class AuthenticationService { - private static AuthenticationService instance; private final PlayerDAO playerDao; private final PlayerSessionService playerSessionService; @@ -27,82 +30,77 @@ private AuthenticationService() { } public static AuthenticationService getInstance() { - if (instance == null) + if (instance == null) { instance = new AuthenticationService(); - + } return instance; } + public Message register(AuthRequestEntity credential) { + Message response; - public Message register(String username, String plainTextPassword) { + System.out.println(credential.getUserName() + " " + credential.getPassword()); + if (credential.getUserName() == null || credential.getPassword() == null) { + response = Message.createMessage(MessageType.ERROR, Action.USERNAME_NOT_FOUND, credential); + } - Player player = playerDao.findByUsername(username); + Player player = playerDao.findByUsername(credential.getUserName()); if (player != null) { - JSONObject json = new JSONObject(); - json.put("error", "Username already exists"); - return new Message(new Header(MessageType.ERROR, Action.REGISTER), json); - } - AuthResponseEntity responseEntity; + response = Message.createMessage(MessageType.ERROR, Action.USERNAME_ALREADY_EXIST, credential); + } try { - - String hashedPassword = ServerSecurityManager.hashText(plainTextPassword); - Player newPlayer = new Player(username, hashedPassword); + String hashedPassword = ServerSecurityManager.hashText(credential.getPassword()); + Player newPlayer = new Player(credential.getUserName(), hashedPassword); playerDao.insert(newPlayer); - responseEntity = new AuthResponseEntity(newPlayer); - } catch (HashingException ex) { + AuthResponseEntity responseEntity = new AuthResponseEntity(newPlayer); + response = Message.createMessage(MessageType.RESPONSE, Action.REGISTERATION_SUCCESS, responseEntity); + } catch (HashingException ex) { ServerInterruptException customException = new ServerInterruptException(ex.getStackTrace()); ExceptionHandlerMiddleware.getInstance().handleException(customException); - JSONObject json = new JSONObject(); - json.put("error", "Internal Server Error"); - return new Message(new Header(MessageType.ERROR, Action.REGISTER), json); - + response = Message.createMessage(MessageType.ERROR, Action.INTERNAL_SERVER_ERROR, credential); } - - - return new Message(new Header(MessageType.RESPONSE, Action.REGISTER), responseEntity.toJson()); - + return response; } - public Message login(String username, String plainTextPassword) { + public Message login(AuthRequestEntity credential) { + Message response; + if (credential == null || credential.getUserName() == null || credential.getPassword() == null) { + response = Message.createMessage(MessageType.ERROR, Action.USERNAME_NOT_FOUND, credential); + } try { - - Player player = playerDao.findByUsername(username); + Player player = playerDao.findByUsername(credential.getUserName()); if (player == null) { - JSONObject json = new JSONObject(); - json.put("error", "Invalid Credentials"); - return new Message(new Header(MessageType.ERROR, Action.LOGIN), json); - } + response = Message.createMessage(MessageType.ERROR, Action.USERNAME_NOT_FOUND, credential); + return response; + } - String hashedPassword = ServerSecurityManager.hashText(plainTextPassword); + String hashedPassword = ServerSecurityManager.hashText(credential.getPassword()); if (!hashedPassword.equals(player.getPassword())) { - JSONObject json = new JSONObject(); - json.put("error", "Invalid Credentials"); - return new Message(new Header(MessageType.ERROR, Action.LOGIN), json); + + response = Message.createMessage(MessageType.ERROR, Action.INVALID_CREDENTIAL, credential); } playerSessionService.startPlayerSession(player.getId()); AuthResponseEntity responseEntity = new AuthResponseEntity(player); - return new Message(new Header(MessageType.RESPONSE, Action.LOGIN), responseEntity.toJson()); + response = Message.createMessage(MessageType.RESPONSE, Action.LOGIN_SUCCESS, responseEntity); } catch (HashingException ex) { ServerInterruptException customException = new ServerInterruptException(ex.getStackTrace()); ExceptionHandlerMiddleware.getInstance().handleException(customException); - JSONObject json = new JSONObject(); - json.put("error", "Internal Server Error"); - return new Message(new Header(MessageType.ERROR, Action.LOGIN), json); + response = Message.createMessage(MessageType.ERROR, Action.INTERNAL_SERVER_ERROR, credential); + } + return response; } - - } diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/Action.java b/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/Action.java index eec918c..b090aa6 100644 --- a/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/Action.java +++ b/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/Action.java @@ -5,9 +5,13 @@ public enum Action { REGISTER(20), REQUEST_GAME(30), GAME_RESPONSE(40), - SEND_GAME_UPDATE(50); - - + SEND_GAME_UPDATE(50), + USERNAME_NOT_FOUND(60), + REGISTERATION_SUCCESS(70), + INTERNAL_SERVER_ERROR(80), + INVALID_CREDENTIAL(90), + LOGIN_SUCCESS(100), + USERNAME_ALREADY_EXIST(110); final int id; Action(int id) { @@ -27,6 +31,14 @@ public static Action valueOf(int id) { return null; } - + public static Action fromString(String msgType) + { + return switch (msgType.toLowerCase()) { + case "login" -> Action.LOGIN; + + + default -> throw new AssertionError(); + }; + } } diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/Header.java b/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/Header.java index c38aa12..5469b3e 100644 --- a/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/Header.java +++ b/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/Header.java @@ -22,6 +22,11 @@ public Header(MessageType msgType, Action action) { this.action = action; } + @Override + public String toString() { + return "Header{" + "msgType=" + msgType + ", action=" + action + '}'; + } + public MessageType getMsgType() { return msgType; } diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/Message.java b/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/Message.java index 81f6fe0..8c8e776 100644 --- a/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/Message.java +++ b/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/Message.java @@ -1,23 +1,23 @@ -/* - * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license - * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template - */ package com.mycompany.tictactoeserver.domain.services.communication; -import org.json.JSONObject; +import com.google.gson.Gson; + + + /** * * @author Hazem - */ + **/ + public class Message { private Header header = null; - private JSONObject data = null; + private String data = null; public Message() { } - public Message(Header header, JSONObject data) { + public Message(Header header, String data) { this.header = header; this.data = data; } @@ -26,20 +26,25 @@ public Header getHeader() { return header; } - public JSONObject getData() { + public String getData() { return data; } - public JSONObject toJson() { - JSONObject jsonMessage = new JSONObject(); - - jsonMessage.put("type", this.header.getMsgType()); - jsonMessage.put("action", this.header.getAction()); - - jsonMessage.put("data", this.data); + @Override + public String toString() { + return "Message{" + "header=" + header + ", data=" + data + '}'; + } + public static Message createMessage(MessageType type , Action action , Object data) + { + return new Message(new Header(type , action), toJson(data)); + } - return jsonMessage; + static private String toJson(Object data) + { + Gson gson = new Gson(); + return gson.toJson(data); } } + diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/MessageRouter.java b/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/MessageRouter.java index a870237..a2f8103 100644 --- a/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/MessageRouter.java +++ b/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/MessageRouter.java @@ -1,14 +1,17 @@ package com.mycompany.tictactoeserver.domain.services.communication; +import com.google.gson.Gson; +import com.mycompany.tictactoeserver.domain.entity.AuthRequestEntity; import com.mycompany.tictactoeserver.domain.server.GameServerManager; import com.mycompany.tictactoeserver.domain.server.PlayerConnectionHandler; import com.mycompany.tictactoeserver.domain.services.authentication.AuthenticationService; import com.mycompany.tictactoeserver.domain.utils.exception.PlayerSendMessageException; -import org.json.JSONObject; public class MessageRouter { + private static MessageRouter instance; private final GameServerManager server; + private Gson gson = new Gson(); private MessageRouter() { server = GameServerManager.getInstance(); @@ -22,15 +25,15 @@ public static MessageRouter getInstance() { } public void navigateMessage(String message, PlayerConnectionHandler sender) throws PlayerSendMessageException { - JSONObject json = new JSONObject(message); - - MessageType messageType = MessageType.valueOf(json.getInt("type")); + Message response = gson.fromJson(message, Message.class); + System.out.println("navigate message"); + MessageType messageType = response.getHeader().getMsgType(); assert messageType != null; switch (messageType) { case REQUEST: - Message msg = handleRequest(json); - server.sendMessage(msg.toJson().toString(), sender); + handleRequest(response , sender); + // server.sendMessage(msg.toJson().toString(), sender); break; case RESPONSE: // Handle response messages @@ -47,21 +50,40 @@ public void navigateMessage(String message, PlayerConnectionHandler sender) thro } } - private Message handleRequest(JSONObject json) { - Action action = Action.valueOf(json.getInt("action")); + private void handleRequest(Message message , PlayerConnectionHandler sender) { + Action action = message.getHeader().getAction(); + Message responseMessage ; + if (action == null) { + System.out.println("Action is null"); + responseMessage= new Message(new Header(MessageType.ERROR, Action.REGISTER), null); + } + + switch (action) { + + case LOGIN -> { + System.out.println(message.toString()); + AuthRequestEntity auth = gson.fromJson(message.getData(), AuthRequestEntity.class); + + Message response= AuthenticationService.getInstance().login(auth); + String msg = gson.toJson(response); + sender.sendMessageToPlayer(msg); + System.out.println(msg); + } + + case REGISTER -> { + System.out.println("come reg"); + + AuthRequestEntity auth = gson.fromJson(message.getData(), AuthRequestEntity.class); + + AuthenticationService.getInstance().register(auth); + + } - assert action != null; - return switch (action) { - case LOGIN -> - AuthenticationService.getInstance().login(json.getString("username"), json.getString("password")); - case REGISTER -> - AuthenticationService.getInstance().register(json.getString("username"), json.getString("password")); default -> { - System.out.println("Unknown Action: " + action); - yield new Message(); +// System.out.println("Unknown Action: " + action); +// yield new Message(new Header(MessageType.ERROR, Action.REGISTER), null); } }; } - } diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/MessageType.java b/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/MessageType.java index b17266e..0c83826 100644 --- a/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/MessageType.java +++ b/src/main/java/com/mycompany/tictactoeserver/domain/services/communication/MessageType.java @@ -33,7 +33,17 @@ public static MessageType valueOf(int id) { return null; } - + public static MessageType fromString(String msgType) + { + return switch (msgType.toLowerCase()) { + case "request" -> MessageType.REQUEST; + case "response"->MessageType.RESPONSE; + case "event"->MessageType.EVENT; + case "error"-> MessageType.ERROR; + + default -> throw new AssertionError(); + }; + } } diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java index 0186d4b..8f3938b 100644 --- a/src/main/java/module-info.java +++ b/src/main/java/module-info.java @@ -4,10 +4,12 @@ requires org.json; requires java.sql; requires derbyclient; - + requires com.google.gson; opens com.mycompany.tictactoeserver to javafx.fxml; opens com.mycompany.tictactoeserver.presentation to javafx.fxml; + opens com.mycompany.tictactoeserver.domain.services.communication to com.google.gson; + opens com.mycompany.tictactoeserver.domain.entity to com.google.gson; exports com.mycompany.tictactoeserver; exports com.mycompany.tictactoeserver.presentation;