-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLiveGamesServlet.java
More file actions
72 lines (62 loc) · 2.6 KB
/
LiveGamesServlet.java
File metadata and controls
72 lines (62 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package adminServlets;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import engine.engine.Engine;
import engine.game.ActiveGameInfo;
import engine.game.Game;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@WebServlet(name = "Live Games Display Servlet", urlPatterns = "/live-games")
public class LiveGamesServlet extends HttpServlet {
private Engine engine;
@Override
public void init() throws ServletException {
engine = (Engine)getServletContext().getAttribute("myEngine");
if(engine == null){
throw new ServletException("Engine not initiated in servlet context!");
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
Gson gson = new Gson();
if(req.getParameterMap().isEmpty()){
//no params, display all active games
List<ActiveGameInfo> activeGamesList = new ArrayList<>();
Game currGame;
for(int i=0;i<engine.getAllGamesList().size();i++){
currGame = engine.getAllGamesList().get(i);
if(currGame.isGameActive()){
activeGamesList.add(new ActiveGameInfo(i,currGame.getGameName(),currGame.getReadyTeamsAmount(),currGame.getTeams().size()));
}
}
String jsonResponse = gson.toJson(activeGamesList);
res.setContentType("application/json");
res.setCharacterEncoding("UTF-8");
res.getWriter().write(jsonResponse);
}
else{
//admin chose game to watch, display live game details
res.setContentType("application/json");
res.setCharacterEncoding("UTF-8");
String liveGameIndexString = req.getParameter("Live game choice");
int liveGameIndex = Integer.parseInt(liveGameIndexString);
if(!engine.getAllGamesList().get(liveGameIndex).isGameActive()){
res.setStatus(HttpServletResponse.SC_CONFLICT);
res.getWriter().write("Game Ended! It returned to Pending!");
}
else{
String jsonResponse = gson.toJson(engine.getAllGamesList().get(liveGameIndex));
res.getWriter().write(jsonResponse);
}
}
}
}