diff --git a/src/main/java/com/mycompany/tictactoeserver/datasource/database/dao/ActivityDAO.java b/src/main/java/com/mycompany/tictactoeserver/datasource/database/dao/SessionDAO.java similarity index 67% rename from src/main/java/com/mycompany/tictactoeserver/datasource/database/dao/ActivityDAO.java rename to src/main/java/com/mycompany/tictactoeserver/datasource/database/dao/SessionDAO.java index ba83946..fb0028f 100644 --- a/src/main/java/com/mycompany/tictactoeserver/datasource/database/dao/ActivityDAO.java +++ b/src/main/java/com/mycompany/tictactoeserver/datasource/database/dao/SessionDAO.java @@ -1,9 +1,9 @@ package com.mycompany.tictactoeserver.datasource.database.dao; import com.mycompany.tictactoeserver.datasource.database.Database; -import com.mycompany.tictactoeserver.datasource.model.ActivityPoint; +import com.mycompany.tictactoeserver.datasource.model.Session; import com.mycompany.tictactoeserver.domain.utils.exception.ActiveSessionExistsException; -import com.mycompany.tictactoeserver.domain.utils.exception.ActivityNotFoundException; +import com.mycompany.tictactoeserver.domain.utils.exception.SessionNotFoundException; import com.mycompany.tictactoeserver.domain.utils.exception.DataAccessException; import java.sql.*; @@ -14,43 +14,41 @@ /** * @author Tasneem */ -public class ActivityDAO { +public class SessionDAO { private final Connection connection; - public ActivityDAO() { + public SessionDAO() { this.connection = Database.getInstance().getConnection(); } - public boolean startActivity(ActivityPoint activity) throws ActiveSessionExistsException { - ActivityPoint existingSession = getActiveSessionByPlayerId(activity.getPlayerId()); + public void startSession(Session session) throws ActiveSessionExistsException { + Session existingSession = getActiveSessionByPlayerId(session.getPlayerId()); if (existingSession != null) { throw new ActiveSessionExistsException(); } String sql = "INSERT INTO ACTIVITY (id, player_id, start_date, end_date) VALUES (?, ?, ?, ?)"; try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { - preparedStatement.setString(1, activity.getId()); - preparedStatement.setString(2, activity.getPlayerId()); - preparedStatement.setTimestamp(3, Timestamp.valueOf(activity.getStartTime())); - preparedStatement.setTimestamp(4, activity.getEndTime() != null ? Timestamp.valueOf(activity.getEndTime()) : null); + preparedStatement.setString(1, session.getId()); + preparedStatement.setString(2, session.getPlayerId()); + preparedStatement.setTimestamp(3, Timestamp.valueOf(session.getStartTime())); + preparedStatement.setTimestamp(4, session.getEndTime() != null ? Timestamp.valueOf(session.getEndTime()) : null); - int rowsAffected = preparedStatement.executeUpdate(); - return rowsAffected > 0; + preparedStatement.executeUpdate(); } catch (SQLException e) { - System.err.println("Error starting activity: " + e.getMessage()); - return false; + System.err.println("Error starting session: " + e.getMessage()); } } - public boolean endActivity(ActivityPoint activity) throws ActivityNotFoundException, DataAccessException { + public boolean endSession(Session session) throws SessionNotFoundException, DataAccessException { String sql = "UPDATE ACTIVITY SET end_date = ? WHERE id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { - preparedStatement.setTimestamp(1, Timestamp.valueOf(activity.getEndTime())); - preparedStatement.setString(2, activity.getId()); + preparedStatement.setTimestamp(1, Timestamp.valueOf(session.getEndTime())); + preparedStatement.setString(2, session.getId()); int rowsAffected = preparedStatement.executeUpdate(); if (rowsAffected == 0) { - throw new ActivityNotFoundException(); + throw new SessionNotFoundException(); } return true; } catch (SQLException e) { @@ -58,10 +56,10 @@ public boolean endActivity(ActivityPoint activity) throws ActivityNotFoundExcept } } - public boolean endActivityByPlayerId(String playerId) throws ActivityNotFoundException, DataAccessException { - ActivityPoint activeSession = getActiveSessionByPlayerId(playerId); + public void endSessionByPlayerId(String playerId) throws SessionNotFoundException, DataAccessException { + Session activeSession = getActiveSessionByPlayerId(playerId); if (activeSession == null) { - throw new ActivityNotFoundException(); + throw new SessionNotFoundException(); } String sql = "UPDATE ACTIVITY SET end_date = ? WHERE id = ?"; @@ -70,54 +68,53 @@ public boolean endActivityByPlayerId(String playerId) throws ActivityNotFoundExc preparedStatement.setString(2, activeSession.getId()); int rowsAffected = preparedStatement.executeUpdate(); - return rowsAffected > 0; } catch (SQLException e) { throw new DataAccessException(e.getStackTrace()); } } - public ActivityPoint getActivityById(String activityId) throws ActivityNotFoundException, DataAccessException { + public Session getSessionById(String sessionId) throws SessionNotFoundException, DataAccessException { String sql = "SELECT id, player_id, start_date, end_date FROM ACTIVITY WHERE id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { - preparedStatement.setString(1, activityId); + preparedStatement.setString(1, sessionId); try (ResultSet resultSet = preparedStatement.executeQuery()) { if (resultSet.next()) { - return mapResultSetToActivity(resultSet); + return mapResultSetToSession(resultSet); } - throw new ActivityNotFoundException(); + throw new SessionNotFoundException(); } } catch (SQLException e) { throw new DataAccessException(e.getStackTrace()); } } - public List getActivitiesByPlayerId(String playerId) throws DataAccessException { + public List getSessionByPlayerId(String playerId) throws DataAccessException { String sql = "SELECT id, player_id, start_date, end_date FROM ACTIVITY WHERE player_id = ? ORDER BY start_date DESC"; - List activities = new ArrayList<>(); + List sessions = new ArrayList<>(); try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, playerId); try (ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { - activities.add(mapResultSetToActivity(resultSet)); + sessions.add(mapResultSetToSession(resultSet)); } } } catch (SQLException e) { throw new DataAccessException(e.getStackTrace()); } - return activities; + return sessions; } - public ActivityPoint getActiveSessionByPlayerId(String playerId) { + public Session getActiveSessionByPlayerId(String playerId) { String sql = "SELECT id, player_id, start_date, end_date FROM ACTIVITY WHERE player_id = ? AND end_date IS NULL ORDER BY start_date DESC LIMIT 1"; try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, playerId); try (ResultSet resultSet = preparedStatement.executeQuery()) { if (resultSet.next()) { - return mapResultSetToActivity(resultSet); + return mapResultSetToSession(resultSet); } } } catch (SQLException e) { @@ -126,9 +123,9 @@ public ActivityPoint getActiveSessionByPlayerId(String playerId) { return null; } - public List getActivitiesByDateRange(LocalDateTime startDate, LocalDateTime endDate) throws DataAccessException { + public List getSessionsByDateRange(LocalDateTime startDate, LocalDateTime endDate) throws DataAccessException { String sql = "SELECT id, player_id, start_date, end_date FROM ACTIVITY WHERE start_date BETWEEN ? AND ? ORDER BY start_date DESC"; - List activities = new ArrayList<>(); + List sessions = new ArrayList<>(); try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setTimestamp(1, Timestamp.valueOf(startDate)); @@ -136,16 +133,16 @@ public List getActivitiesByDateRange(LocalDateTime startDate, Loc try (ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { - activities.add(mapResultSetToActivity(resultSet)); + sessions.add(mapResultSetToSession(resultSet)); } } } catch (SQLException e) { throw new DataAccessException(e.getStackTrace()); } - return activities; + return sessions; } - public int getActivityCountByPlayerId(String playerId) throws DataAccessException { + public int getSessionCountByPlayerId(String playerId) throws DataAccessException { String sql = "SELECT COUNT(*) FROM ACTIVITY WHERE player_id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, playerId); @@ -165,14 +162,14 @@ public boolean hasActiveSession(String playerId) { return getActiveSessionByPlayerId(playerId) != null; } - public boolean deleteActivity(String activityId) throws ActivityNotFoundException, DataAccessException { + public boolean deleteSession(String sessionId) throws SessionNotFoundException, DataAccessException { String sql = "DELETE FROM ACTIVITY WHERE id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { - preparedStatement.setString(1, activityId); + preparedStatement.setString(1, sessionId); int rowsAffected = preparedStatement.executeUpdate(); if (rowsAffected == 0) { - throw new ActivityNotFoundException(); + throw new SessionNotFoundException(); } return true; } catch (SQLException e) { @@ -180,7 +177,7 @@ public boolean deleteActivity(String activityId) throws ActivityNotFoundExceptio } } - public int deleteActivitiesByPlayerId(String playerId) throws DataAccessException { + public int deletePlayerSessions(String playerId) throws DataAccessException { String sql = "DELETE FROM ACTIVITY WHERE player_id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, playerId); @@ -190,35 +187,35 @@ public int deleteActivitiesByPlayerId(String playerId) throws DataAccessExceptio } } - public List getAllSessions() throws ActivityNotFoundException { + public List getAllSessions() throws SessionNotFoundException { String sql = "SELECT id, player_id, start_date, end_date FROM ACTIVITY ORDER BY start_date DESC"; - List activities = new ArrayList<>(); + List sessions = new ArrayList<>(); try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { try (ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { - activities.add(mapResultSetToActivity(resultSet)); + sessions.add(mapResultSetToSession(resultSet)); } } } catch (SQLException e) { - throw new ActivityNotFoundException(e.getStackTrace()); + throw new SessionNotFoundException(e.getStackTrace()); } - return activities; + return sessions; } - public List getAllActiveSessions() throws DataAccessException { + public List getAllActiveSessions() throws DataAccessException { String sql = "SELECT id, player_id, start_date, end_date FROM ACTIVITY WHERE end_date IS NULL ORDER BY start_date DESC"; - List activities = new ArrayList<>(); + List sessions = new ArrayList<>(); try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { try (ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { - activities.add(mapResultSetToActivity(resultSet)); + sessions.add(mapResultSetToSession(resultSet)); } } } catch (SQLException e) { throw new DataAccessException(e.getStackTrace()); } - return activities; + return sessions; } public long getTotalPlayTimeMinutes(String playerId) throws DataAccessException { @@ -245,20 +242,20 @@ public long getTotalPlayTimeMinutes(String playerId) throws DataAccessException return totalMinutes; } - private ActivityPoint mapResultSetToActivity(ResultSet resultSet) throws SQLException { - ActivityPoint activity = new ActivityPoint(); - activity.setPlayerId(resultSet.getString("player_id")); + private Session mapResultSetToSession(ResultSet resultSet) throws SQLException { + Session session = new Session(); + session.setPlayerId(resultSet.getString("player_id")); Timestamp startTimestamp = resultSet.getTimestamp("start_date"); if (startTimestamp != null) { - activity.setStartTime(startTimestamp.toLocalDateTime()); + session.setStartTime(startTimestamp.toLocalDateTime()); } Timestamp endTimestamp = resultSet.getTimestamp("end_date"); if (endTimestamp != null) { - activity.setEndTime(endTimestamp.toLocalDateTime()); + session.setEndTime(endTimestamp.toLocalDateTime()); } - return activity; + return session; } } \ No newline at end of file diff --git a/src/main/java/com/mycompany/tictactoeserver/datasource/model/ActivityPoint.java b/src/main/java/com/mycompany/tictactoeserver/datasource/model/Session.java similarity index 90% rename from src/main/java/com/mycompany/tictactoeserver/datasource/model/ActivityPoint.java rename to src/main/java/com/mycompany/tictactoeserver/datasource/model/Session.java index f5ae23c..8fae2ee 100644 --- a/src/main/java/com/mycompany/tictactoeserver/datasource/model/ActivityPoint.java +++ b/src/main/java/com/mycompany/tictactoeserver/datasource/model/Session.java @@ -1,24 +1,21 @@ package com.mycompany.tictactoeserver.datasource.model; import java.util.UUID; - - import java.time.LocalDateTime; -public class ActivityPoint { +public class Session { private final String id; private String playerId; private LocalDateTime startTime; private LocalDateTime endTime; - public ActivityPoint() { + public Session() { this.id = UUID.randomUUID().toString(); this.startTime = LocalDateTime.now(); } - public ActivityPoint(String playerId) { + public Session(String playerId) { this.startTime = LocalDateTime.now(); this.playerId = playerId; - this.id = UUID.randomUUID().toString(); } public String getId() { diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/entity/ActivityPoint.java b/src/main/java/com/mycompany/tictactoeserver/domain/entity/ActivityPoint.java new file mode 100644 index 0000000..358110c --- /dev/null +++ b/src/main/java/com/mycompany/tictactoeserver/domain/entity/ActivityPoint.java @@ -0,0 +1,31 @@ +package com.mycompany.tictactoeserver.domain.entity; + +/** + * + * @author Tasneem + */ +public class ActivityPoint { + private int hour; + private int playerCount; + + public ActivityPoint(int hour, int playerCount) { + this.hour = hour; + this.playerCount = playerCount; + } + + public int getHour() { + return hour; + } + + public void setHour(int hour) { + this.hour = hour; + } + + public int getPlayerCount() { + return playerCount; + } + + public void setPlayerCount(int playerCount) { + this.playerCount = playerCount; + } +} \ No newline at end of file diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/entity/PlayerEntity.java b/src/main/java/com/mycompany/tictactoeserver/domain/entity/PlayerEntity.java new file mode 100644 index 0000000..50038cb --- /dev/null +++ b/src/main/java/com/mycompany/tictactoeserver/domain/entity/PlayerEntity.java @@ -0,0 +1,35 @@ +/* + * 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.entity; + +/** + * + * @author Tasneem + */ +public class PlayerEntity { + private String username; + private int score; + + public PlayerEntity(String username, int score) { + this.username = username; + this.score = score; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public int getScore() { + return score; + } + + public void setScore(int score) { + this.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 617f26c..e730534 100644 --- a/src/main/java/com/mycompany/tictactoeserver/domain/server/GameServerManager.java +++ b/src/main/java/com/mycompany/tictactoeserver/domain/server/GameServerManager.java @@ -95,6 +95,12 @@ public void removePlayer(PlayerConnectionHandler player) { players.remove(player); } } + + public int getOnlinePlayersCount() { + synchronized (lock) { + return players.size(); + } + } } class ServerRunnable implements Runnable { 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 8b80e2c..503cb8d 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 @@ -7,6 +7,7 @@ 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; import com.mycompany.tictactoeserver.domain.services.security.ServerSecurityManager; import com.mycompany.tictactoeserver.domain.utils.exception.ExceptionHandlerMiddleware; import com.mycompany.tictactoeserver.domain.utils.exception.HashingException; @@ -18,9 +19,11 @@ public class AuthenticationService { private static AuthenticationService instance; private final PlayerDAO playerDao; + private final PlayerSessionService playerSessionService; private AuthenticationService() { this.playerDao = new PlayerDAO(); + this.playerSessionService = new PlayerSessionService(); } public static AuthenticationService getInstance() { @@ -86,6 +89,7 @@ public Message login(String username, String plainTextPassword) { return new Message(new Header(MessageType.ERROR, Action.LOGIN), json); } + playerSessionService.startPlayerSession(player.getId()); AuthResponseEntity responseEntity = new AuthResponseEntity(player); return new Message(new Header(MessageType.RESPONSE, Action.LOGIN), responseEntity.toJson()); diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/services/player/PlayerService.java b/src/main/java/com/mycompany/tictactoeserver/domain/services/player/PlayerService.java new file mode 100644 index 0000000..973f460 --- /dev/null +++ b/src/main/java/com/mycompany/tictactoeserver/domain/services/player/PlayerService.java @@ -0,0 +1,22 @@ +package com.mycompany.tictactoeserver.domain.services.player; + +import com.mycompany.tictactoeserver.datasource.database.dao.PlayerDAO; +import com.mycompany.tictactoeserver.datasource.model.Player; + +import java.util.List; + +/** + * + * @author Tasneem + */ +public class PlayerService { + private final PlayerDAO playerDAO; + + public PlayerService(PlayerDAO playerDAO) { + this.playerDAO = playerDAO; + } + + public List getAllPlayers() { + return playerDAO.findAll(); + } +} diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/services/playerSession/PlayerSessionService.java b/src/main/java/com/mycompany/tictactoeserver/domain/services/playerSession/PlayerSessionService.java new file mode 100644 index 0000000..d85bf30 --- /dev/null +++ b/src/main/java/com/mycompany/tictactoeserver/domain/services/playerSession/PlayerSessionService.java @@ -0,0 +1,75 @@ +package com.mycompany.tictactoeserver.domain.services.playerSession; + +import com.mycompany.tictactoeserver.datasource.database.dao.SessionDAO; +import com.mycompany.tictactoeserver.datasource.model.Session; +import com.mycompany.tictactoeserver.domain.utils.exception.*; + +import java.time.LocalDateTime; +import java.util.List; + +public class PlayerSessionService { + private final SessionDAO sessionDao; + private final ExceptionHandlerMiddleware exceptionHandler; + + public PlayerSessionService() { + this.sessionDao = new SessionDAO(); + this.exceptionHandler = ExceptionHandlerMiddleware.getInstance(); + } + + public List getAllPlayerSessions() { + try { + return sessionDao.getAllSessions(); + + } catch (SessionNotFoundException e) { + exceptionHandler.handleException(e); + } + return List.of(); + } + + public void startPlayerSession(String playerId) { + try { + Session session = new Session(playerId); + sessionDao.startSession(session); + + } catch (ActiveSessionExistsException e) { + String[] data = {playerId, e.getMessage()}; + exceptionHandler.handleException(e, data); + } + } + + public void endPlayerSession(String playerId) { + try { + sessionDao.endSessionByPlayerId(playerId); + + } catch (SessionNotFoundException e) { + String[] data = {playerId}; + exceptionHandler.handleException(e, data); + + } catch (DataAccessException e) { + exceptionHandler.handleException(e); + } + } + + public boolean isPlayerActive(String playerId) { + return sessionDao.hasActiveSession(playerId); + } + + public long getPlayerPlayTime(String playerId) { + try { + return sessionDao.getTotalPlayTimeMinutes(playerId); + + } catch (DataAccessException e) { + exceptionHandler.handleException(e); + return 0; + } + } + + public List getSessionsByDateRange(LocalDateTime startDate, LocalDateTime endDate) { + try{ + return sessionDao.getSessionsByDateRange(startDate, endDate); + } catch (DataAccessException e) { + exceptionHandler.handleException(e); + return List.of(); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/services/statistics/ActivityService.java b/src/main/java/com/mycompany/tictactoeserver/domain/services/statistics/ActivityService.java deleted file mode 100644 index 2e40c25..0000000 --- a/src/main/java/com/mycompany/tictactoeserver/domain/services/statistics/ActivityService.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.mycompany.tictactoeserver.domain.services.statistics; - -import com.mycompany.tictactoeserver.datasource.database.dao.*; -import com.mycompany.tictactoeserver.datasource.model.ActivityPoint; -import com.mycompany.tictactoeserver.domain.utils.exception.*; - -public class ActivityService { - private final ActivityDAO activityDao; - private final ExceptionHandlerMiddleware exceptionHandler; - - public ActivityService() { - this.activityDao = new ActivityDAO(); - this.exceptionHandler = ExceptionHandlerMiddleware.getInstance(); - } - - public boolean startPlayerActivity(String playerId) { - try { - ActivityPoint activity = new ActivityPoint(playerId); - return activityDao.startActivity(activity); - - } catch (ActiveSessionExistsException e) { - String[] data = {playerId, e.getMessage()}; - exceptionHandler.handleException(e, data); - return false; - } - } - - public boolean endPlayerActivity(String playerId) { - try { - return activityDao.endActivityByPlayerId(playerId); - - } catch (ActivityNotFoundException e) { - String[] data = {playerId}; - exceptionHandler.handleException(e, data); - return false; - - } catch (DataAccessException e) { - exceptionHandler.handleException(e); - return false; - } - } - - public boolean isPlayerActive(String playerId) { - return activityDao.hasActiveSession(playerId); - } - - public long getPlayerPlayTime(String playerId) { - try { - return activityDao.getTotalPlayTimeMinutes(playerId); - - } catch (DataAccessException e) { - exceptionHandler.handleException(e); - return 0; - } - } -} \ No newline at end of file diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/services/statistics/StatisticsManager.java b/src/main/java/com/mycompany/tictactoeserver/domain/services/statistics/StatisticsManager.java deleted file mode 100644 index aa75c0a..0000000 --- a/src/main/java/com/mycompany/tictactoeserver/domain/services/statistics/StatisticsManager.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.mycompany.tictactoeserver.domain.services.statistics; - -import com.mycompany.tictactoeserver.datasource.model.ActivityPoint; -import com.mycompany.tictactoeserver.datasource.model.Player; - -import java.util.Vector; - -public interface StatisticsManager { - Vector getActivity(); - - Vector getLeaderboard(); -} diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/services/statistics/StatisticsService.java b/src/main/java/com/mycompany/tictactoeserver/domain/services/statistics/StatisticsService.java new file mode 100644 index 0000000..f273cfa --- /dev/null +++ b/src/main/java/com/mycompany/tictactoeserver/domain/services/statistics/StatisticsService.java @@ -0,0 +1,90 @@ +package com.mycompany.tictactoeserver.domain.services.statistics; + +import com.mycompany.tictactoeserver.datasource.database.dao.PlayerDAO; +import com.mycompany.tictactoeserver.datasource.model.Player; +import com.mycompany.tictactoeserver.datasource.model.Session; +import com.mycompany.tictactoeserver.domain.entity.ActivityPoint; +import com.mycompany.tictactoeserver.domain.entity.PlayerEntity; +import com.mycompany.tictactoeserver.domain.server.GameServerManager; +import com.mycompany.tictactoeserver.domain.services.player.PlayerService; +import com.mycompany.tictactoeserver.domain.services.playerSession.PlayerSessionService; + +import java.time.LocalDateTime; +import java.util.*; +import java.util.List; +/** + * + * @author Tasneem + */ +public class StatisticsService { + private final PlayerSessionService playerSessionService; + private final PlayerService playerService; + private final GameServerManager gameServerManager; + + public StatisticsService() { + this.playerService = new PlayerService(new PlayerDAO()); + this.gameServerManager = GameServerManager.getInstance(); + this.playerSessionService = new PlayerSessionService(); + } + + public List getOnlinePlayersCountPerHour() { + LocalDateTime now = LocalDateTime.now(); + LocalDateTime twentyFourHoursAgo = now.minusHours(24); + + List recentSessions = playerSessionService.getSessionsByDateRange(twentyFourHoursAgo, now); + + if (recentSessions.isEmpty()) { + return new ArrayList<>(); + } + + List activityPoints = new ArrayList<>(); + + for (int i = 0; i < 24; i++) { + LocalDateTime hourStart = twentyFourHoursAgo.plusHours(i).withMinute(0).withSecond(0).withNano(0); + LocalDateTime hourEnd = hourStart.plusHours(1); + int playersOnline = 0; + + for (Session session : recentSessions) { + LocalDateTime sessionStart = session.getStartTime(); + LocalDateTime sessionEnd = session.getEndTime() != null ? session.getEndTime() : now; + + if (sessionStart.isBefore(hourEnd) && sessionEnd.isAfter(hourStart)) { + playersOnline++; + } + } + + activityPoints.add(new ActivityPoint(hourStart.getHour(), playersOnline)); + } + + return activityPoints; + } + + public List getLeaderboard() { + List players = playerService.getAllPlayers(); + + List leaderboard = new ArrayList<>(); + for (Player player : players) { + PlayerEntity playerEntity = new PlayerEntity( + player.getUsername(), + player.getScore() + ); + leaderboard.add(playerEntity); + } + + leaderboard.sort((p1, p2) -> Integer.compare(p2.getScore(), p1.getScore())); + + return leaderboard; + } + + public int getTotalPlayersCount() { + return playerService.getAllPlayers().size(); + } + + public int getOnlinePlayersCount() { + return gameServerManager.getOnlinePlayersCount(); + } + + public int getOfflinePlayersCount() { + return getTotalPlayersCount() - getOnlinePlayersCount(); + } +} diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/utils/exception/ActivityNotFoundException.java b/src/main/java/com/mycompany/tictactoeserver/domain/utils/exception/ActivityNotFoundException.java deleted file mode 100644 index 52fd9ed..0000000 --- a/src/main/java/com/mycompany/tictactoeserver/domain/utils/exception/ActivityNotFoundException.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.mycompany.tictactoeserver.domain.utils.exception; - -public class ActivityNotFoundException extends Exception { - public ActivityNotFoundException(StackTraceElement[] stackTraceElements) { - super("activity-not-found-exception"); - setStackTrace(stackTraceElements); - } - - public ActivityNotFoundException() { - super("activity-not-found-exception"); - } -} diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/utils/exception/ExceptionHandlerMiddleware.java b/src/main/java/com/mycompany/tictactoeserver/domain/utils/exception/ExceptionHandlerMiddleware.java index 910927a..ee4b0df 100644 --- a/src/main/java/com/mycompany/tictactoeserver/domain/utils/exception/ExceptionHandlerMiddleware.java +++ b/src/main/java/com/mycompany/tictactoeserver/domain/utils/exception/ExceptionHandlerMiddleware.java @@ -48,8 +48,8 @@ public void handleException(Exception ex, String[] data) { case "active-session-exists-exception": System.out.println("active-session-exists-exception for player " + data[0] + " in session " + data[1] + "."); break; - case "activity-not-found-exception": - System.out.println("activity-not-found-exception for activity " + data[0]); + case "session-not-found-exception": + System.out.println("session-not-found-exception for activity " + data[0]); break; default: System.out.println("unknown-exception"); diff --git a/src/main/java/com/mycompany/tictactoeserver/domain/utils/exception/SessionNotFoundException.java b/src/main/java/com/mycompany/tictactoeserver/domain/utils/exception/SessionNotFoundException.java new file mode 100644 index 0000000..5b6c5b5 --- /dev/null +++ b/src/main/java/com/mycompany/tictactoeserver/domain/utils/exception/SessionNotFoundException.java @@ -0,0 +1,12 @@ +package com.mycompany.tictactoeserver.domain.utils.exception; + +public class SessionNotFoundException extends Exception { + public SessionNotFoundException(StackTraceElement[] stackTraceElements) { + super("session-not-found-exception"); + setStackTrace(stackTraceElements); + } + + public SessionNotFoundException() { + super("session-not-found-exception"); + } +}