Commit ce9fa9ce authored by tammam.alsoleman's avatar tammam.alsoleman

Update the shared interface & implement the Quiz Service in the Server

parent 7a012f89
package org.example.server;
import org.example.shared.IClientCallback;
import org.example.shared.IQuizService;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.*;
import java.util.stream.Collectors;
public class QuizServiceImpl extends UnicastRemoteObject implements IQuizService {
private List<String> questionList;
private Map<String, String> questionAnswerMap;
private Map<String, Integer> studentScores;
private List<IClientCallback> connectedClients;
public QuizServiceImpl() throws RemoteException {
super();
studentScores = new HashMap<>();
connectedClients = new ArrayList<>();
questionList = new ArrayList<>();
questionAnswerMap = new HashMap<>();
loadScoresFromFile();
loadQuestions();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
broadcastLeaderboard();
}
}, 5000, 30000);
}
private void loadQuestions() {
addQuestion("What is the capital of France?", "Paris");
addQuestion("What is 5 + 5?", "10");
addQuestion("What implies RMI?", "Remote Method Invocation");
addQuestion("Is Java object-oriented? (yes/no)", "yes");
addQuestion("Which protocol is used for web pages?", "HTTP");
addQuestion("What is 1 + 1?", "2");
addQuestion("What is 10 - 5?", "5");
addQuestion("What is 2 * 3?", "6");
addQuestion("Which number comes after 9?", "10");
addQuestion("How many days are in a week?", "7");
addQuestion("What is the name of our planet?", "Earth");
addQuestion("What color is a banana?", "Yellow");
addQuestion("What is the opposite of 'Up'?", "Down");
addQuestion("Which animal says Meow?", "Cat");
addQuestion("Is fire hot? (yes/no)", "yes");
addQuestion("Do fish live in water? (yes/no)", "yes");
addQuestion("Is 5 bigger than 10? (yes/no)", "no");
addQuestion("What do you use to type?", "Keyboard");
addQuestion("What connects your computer to the web?", "Internet");
}
private void addQuestion(String question, String answer) {
questionList.add(question);
questionAnswerMap.put(question, answer);
}
@Override
public synchronized void login(String name, IClientCallback clientCallback) throws RemoteException {
connectedClients.add(clientCallback);
studentScores.putIfAbsent(name, 0);
System.out.println("Client logged in: " + name);
}
@Override
public String getQuestion() throws RemoteException {
if (questionList.isEmpty()) return "No questions available.";
Random rand = new Random();
int index = rand.nextInt(questionList.size());
return questionList.get(index);
}
@Override
public synchronized String submitAnswer(String name, String questionText, String answer) throws RemoteException {
String correctAnswer = questionAnswerMap.get(questionText);
boolean isCorrect = false;
if (correctAnswer != null && correctAnswer.equalsIgnoreCase(answer.trim())) {
isCorrect = true;
int currentScore = studentScores.getOrDefault(name, 0);
studentScores.put(name, currentScore + 10);
}
int score = studentScores.getOrDefault(name, 0);
String feedback = isCorrect ? "Correct Answer! (+10 points)" : "Wrong Answer! The correct answer was: " + correctAnswer;
return feedback + " | Total Score: " + score;
}
private void broadcastLeaderboard() {
if (connectedClients.isEmpty() || studentScores.isEmpty()) return;
String leaderboard = studentScores.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.limit(3)
.map(entry -> entry.getKey() + ": " + entry.getValue())
.collect(Collectors.joining("\n"));
String message = "--- Leaderboard Top 3 ---\n" + leaderboard + "\n-----------------------";
Iterator<IClientCallback> iterator = connectedClients.iterator();
while (iterator.hasNext()) {
IClientCallback client = iterator.next();
try {
client.onLeaderboardUpdate(message);
} catch (RemoteException e) {
iterator.remove();
}
}
}
public void saveScoresToFile() {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("scores.dat"))) {
oos.writeObject(studentScores);
System.out.println("Scores saved to 'scores.dat' successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private void loadScoresFromFile() {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("scores.dat"))) {
studentScores = (Map<String, Integer>) ois.readObject();
System.out.println("Loaded scores from previous session: " + studentScores);
} catch (IOException | ClassNotFoundException e) {
System.out.println("No previous scores found. Starting fresh.");
}
}
}
\ No newline at end of file
......@@ -3,6 +3,7 @@ package org.example.shared;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface IClientCallback extends Remote {
void onLeaderboardUpdate(String leaderboard) throws RemoteException;
void onLeaderboardUpdate(String message) throws RemoteException;
}
\ No newline at end of file
......@@ -3,11 +3,11 @@ package org.example.shared;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface IQuizService extends Remote {
String getRandomQuestion() throws RemoteException;
String submitAnswer(String studentName, String answer) throws RemoteException;
// Combined authentication + callback registration
String authenticateStudent(String studentName, IClientCallback callback) throws RemoteException;
void login(String name, IClientCallback clientCallback) throws RemoteException;
String getQuestion() throws RemoteException;
String submitAnswer(String name, String questionText, String answer) throws RemoteException;
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment