Commit ec678b13 authored by rawan's avatar rawan

Clean final upload of RMI project

parents
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
# RMI-HW
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>server</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.36.0.3</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package org.example;
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
\ No newline at end of file
package org.example.Quiz.Client;
import org.example.Quiz.Shared.IQuizClient;
import org.example.Quiz.Shared.IQuizServer;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
public class Client {
private static String currentQuestion = "";
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
IQuizServer serverStub = (IQuizServer) registry.lookup("QuizService");
IQuizClient clientCallbackObject = new QuizClientImpl();
Scanner scanner = new Scanner(System.in, "UTF-8");
System.out.print("Please enter your name:");
String studentName = scanner.nextLine();
serverStub.registerClient(clientCallbackObject, studentName);
System.out.println("...Registered successfully, " + studentName + "!");
String choice = "";
while (true) {
System.out.println("\n---Options menu---");
System.out.println("1. Request a new question");
System.out.println("2. Submit an answer");
System.out.println("Type 'exit' to exit the program");
System.out.print("Choose (1 or 2): ");
choice = scanner.nextLine();
if (choice.equalsIgnoreCase("Exit")) {
break;
}
switch (choice) {
case "1":
currentQuestion = serverStub.getQuestion(studentName);
System.out.println("\n>>> New question: " + currentQuestion);
break;
case "2":
if (currentQuestion.isEmpty()) {
System.out.println("!!! You must ask a question first (option 1)");
continue;
}
System.out.print(">>> Enter your answer to the question: ");
String answer = scanner.nextLine();
String feedback = serverStub.submitAnswer(studentName, answer);
System.out.println("\n--- Answer result---");
System.out.println(feedback);
currentQuestion = "";
break;
default:
System.out.println("!!! Wrong selection, please enter 1 or 2.");
break;
}
}
System.out.println("Thank you ");
System.exit(0);
} catch (Exception e) {
System.err.println("!!! A client error occurred!!!");
if (e instanceof java.rmi.NotBoundException) {
System.err.println("!!! The server (QuizService) cannot be found. Is the server running?");
}
e.printStackTrace();
}
}
}
\ No newline at end of file
package org.example.Quiz.Client;
import org.example.Quiz.Shared.IQuizClient;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;
public class QuizClientImpl extends UnicastRemoteObject implements IQuizClient {
public QuizClientImpl() throws RemoteException {
super();
}
@Override
public void notifyLeaderboardUpdate(List<String> leaderboard) throws RemoteException {
System.out.println("\\n\\n==== Update the leaderboard ===");
if (leaderboard.isEmpty()) {
System.out.println(" (There are no leaderboards currently)");
} else {
for (String entry : leaderboard) {
System.out.println(" " + entry);
}
}
System.out.println("==============================\n");
System.out.print("Select (1: Ask a question, 2: Send an answer): ");
}
}
\ No newline at end of file
package org.example.Quiz.Server;
import org.example.Quiz.Client.QuizClientImpl;
import org.example.Quiz.Shared.IQuizClient;
import org.example.Quiz.Shared.IQuizServer;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class QuizServerImpl extends UnicastRemoteObject implements IQuizServer {
private final Map<String, String> questions;
private final Map<String, Integer> studentScores;
private final Map<String, IQuizClient> connectedClients;
public QuizServerImpl() throws RemoteException {
super();
questions = new ConcurrentHashMap<>();
studentScores = new ConcurrentHashMap<>();
connectedClients = new ConcurrentHashMap<>();
questions.put("What is the capital of Jordan?", "Amman");
questions.put("How many continents are there in the world?", "7");
questions.put("What color is the sky on a clear day?", "blue");
questions.put("2 + 2 = ?", "4");
}
@Override
public void registerClient(IQuizClient clientStub, String studentName) throws RemoteException {
System.out.println("...New customer registration: " + studentName);
studentScores.put(studentName, 0);
connectedClients.put(studentName, clientStub);
System.out.println("... has been registered " + studentName + ". Number of clients now: " + connectedClients.size());
updateAndNotifyLeaderboard();
}
@Override
public void registerClient(QuizClientImpl clientStub, String studentName) throws RemoteException {
}
@Override
public String getQuestion(String studentName) throws RemoteException {
System.out.println("... Student " + studentName + "He asks a question");
List<String> questionList = new ArrayList<>(questions.keySet());
Collections.shuffle(questionList);
return questionList.get(0);
}
@Override
public String submitAnswer(String studentName, String answer) throws RemoteException {
System.out.println("...student" + studentName + "Send answer:" + answer);
String correctAnswer = questions.get("What is the capital of Jordan?");
boolean isCorrect = false;
if (questions.containsValue(answer.trim())) {
isCorrect = true;
}
if (isCorrect) {
int currentScore = studentScores.get(studentName);
studentScores.put(studentName, currentScore + 1);
updateAndNotifyLeaderboard();
return "Correct answer! Your current score is: " + (currentScore + 1);
} else {
return "Wrong answer. Try again.";
}
}
private void updateAndNotifyLeaderboard() {
System.out.println("...The leaderboard is being updated...");
List<Map.Entry<String, Integer>> sortedScores = new ArrayList<>(studentScores.entrySet());
sortedScores.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));
List<String> leaderboard = new ArrayList<>();
int count = 0;
for (Map.Entry<String, Integer> entry : sortedScores) {
if (count >= 3) break;
leaderboard.add((count + 1) + ". " + entry.getKey() + " (" + entry.getValue() + " point)");
count++;
}
System.out.println("... Send notice to " + connectedClients.size() + " client");
for (IQuizClient client : connectedClients.values()) {
try {
client.notifyLeaderboardUpdate(leaderboard);
} catch (RemoteException e) {
System.err.println("...Error sending a notification to a client: " + e.getMessage());
}
}
}
}
\ No newline at end of file
package org.example.Quiz.Server;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
QuizServerImpl quizServer = new QuizServerImpl();
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("QuizService", quizServer);
System.out.println("===================================");
System.out.println(" >>> Quiz Server is Ready <<< ");
System.out.println("... Waiting for client connections on port 1099");
System.out.println("===================================");
} catch (Exception e) {
System.err.println("!!! An error occurred while running the Server !!!");
e.printStackTrace();
}
}
}
\ No newline at end of file
package org.example.Quiz.Shared;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;
public interface IQuizClient extends Remote {
void notifyLeaderboardUpdate(List<String> leaderboard) throws RemoteException;
}
\ No newline at end of file
package org.example.Quiz.Shared;
import org.example.Quiz.Client.QuizClientImpl;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface IQuizServer extends Remote {
void registerClient(IQuizClient clientStub, String studentName) throws RemoteException;
void registerClient(QuizClientImpl clientStub, String studentName) throws RemoteException;
String getQuestion(String studentName) throws RemoteException;
String submitAnswer(String studentName, 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