This commit is contained in:
Lorenzo Iovino 2017-07-15 16:41:20 +02:00
parent 8eab4d97c1
commit ee230f911c
16 changed files with 438 additions and 483 deletions

785
.idea/workspace.xml generated

File diff suppressed because it is too large Load diff

View file

@ -32,8 +32,8 @@ import java.rmi.server.UnicastRemoteObject;
*/ */
public class App extends JFrame { public class App extends JFrame {
private static InetSocketAddress clientTCPSocketAddress = new InetSocketAddress(Config.GameServerURI, Config.GameServerPort); private static InetSocketAddress clientTCPSocketAddress = new InetSocketAddress(Config.MessageServiceURI, Config.MessageServicePort);
public static InetSocketAddress clientUDPSocketAddress = new InetSocketAddress(Config.WordsReceiverServerURI, Config.WordsReceiverServerPort); public static InetSocketAddress clientUDPSocketAddress = new InetSocketAddress(Config.WordsReceiverServiceURI, Config.WordsReceiverServicePort);
private static InetAddress clientMulticastSocketAddress; private static InetAddress clientMulticastSocketAddress;
public static AuthService authService; public static AuthService authService;
@ -79,10 +79,10 @@ public class App extends JFrame {
public static void registerForNotifications() throws RemoteException, NotBoundException { public static void registerForNotifications() throws RemoteException, NotBoundException {
Registry registry = LocateRegistry.getRegistry(Config.NotificationServerStubPort); Registry registry = LocateRegistry.getRegistry(Config.NotificationServiceStubPort);
INotificationClient callbackObj = new NotificationClientService(); INotificationClient callbackObj = new NotificationClientService();
notificationStub = (INotificationClient) UnicastRemoteObject.exportObject(callbackObj, 0); notificationStub = (INotificationClient) UnicastRemoteObject.exportObject(callbackObj, 0);
INotificationServer notificationServer = (INotificationServer) registry.lookup(Config.NotificationServerName); INotificationServer notificationServer = (INotificationServer) registry.lookup(Config.NotificationServiceName);
notificationServer.registerForCallback(notificationStub); notificationServer.registerForCallback(notificationStub);
} }
@ -98,7 +98,7 @@ public class App extends JFrame {
public static void openClientMulticastSocket(Integer multicastId){ public static void openClientMulticastSocket(Integer multicastId){
try { try {
App.gameService.setMulticastId(multicastId); App.gameService.setMulticastId(multicastId);
clientMulticastSocketAddress = InetAddress.getByName(Config.ScoreMulticastServerURI); clientMulticastSocketAddress = InetAddress.getByName(Config.ScoreMulticastServiceURI);
clientMulticast = new MulticastSocket(gameService.multicastId); clientMulticast = new MulticastSocket(gameService.multicastId);
clientMulticast.joinGroup(clientMulticastSocketAddress); clientMulticast.joinGroup(clientMulticastSocketAddress);
} catch (IOException e) { } catch (IOException e) {
@ -109,7 +109,7 @@ public class App extends JFrame {
public static void closeClientMulticastSocket(){ public static void closeClientMulticastSocket(){
//Leave group and close multicast socket //Leave group and close multicast socket
try { try {
App.clientMulticast.leaveGroup(InetAddress.getByName(Config.ScoreMulticastServerURI)); App.clientMulticast.leaveGroup(InetAddress.getByName(Config.ScoreMulticastServiceURI));
App.clientMulticast.close(); App.clientMulticast.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();

View file

@ -17,7 +17,7 @@ import java.rmi.RemoteException;
*/ */
public class AuthService { public class AuthService {
private String baseUrl = Config.getAuthServerURI().concat("/auth"); private String baseUrl = Config.getAuthServiceURI().concat("/auth");
public Response login(String userName, String password) throws RemoteException, NotBoundException, MalformedURLException { public Response login(String userName, String password) throws RemoteException, NotBoundException, MalformedURLException {
IAuth auth = (IAuth) Naming.lookup(baseUrl); IAuth auth = (IAuth) Naming.lookup(baseUrl);

View file

@ -6,29 +6,29 @@ package constants;
*/ */
public class Config { public class Config {
public static String AuthServerURI = "localhost"; public static String AuthServiceURI = "localhost";
public static Integer AuthServerPort = 9999; public static Integer AuthServicePort = 9999;
public static String GameServerURI = "localhost"; public static String MessageServiceURI = "localhost";
public static Integer GameServerPort = 10000; public static Integer MessageServicePort = 10000;
public static String WordsReceiverServerURI = "localhost"; public static String WordsReceiverServiceURI = "localhost";
public static Integer WordsReceiverServerPort = 10001; public static Integer WordsReceiverServicePort = 10001;
public static String ScoreMulticastServerURI = "226.226.226.226"; public static String ScoreMulticastServiceURI = "226.226.226.226";
public static Integer NotificationServerPort = 20000; public static Integer NotificationServicePort = 20000;
public static Integer NotificationServerStubPort = 30000; public static Integer NotificationServiceStubPort = 30000;
public static String NotificationServerName ="notification"; public static String NotificationServiceName ="notification";
public static String RedisServerURI = "localhost"; public static String RedisServiceURI = "localhost";
public static int gameTimeout = 120; //2 minuti in sec public static int gameTimeout = 120; //2 minuti in sec
public static int joinMatchTimeout = 7*1000*60; //7 minuti in millisec public static int joinMatchTimeout = 7*1000*60; //7 minuti in millisec
public static int sendWordsTimeout = 5*1000*60; //5 minuti in millisec public static int sendWordsTimeout = 5*1000*60; //5 minuti in millisec
public static String getAuthServerURI(){ public static String getAuthServiceURI(){
return "rmi://".concat(AuthServerURI).concat(":").concat(AuthServerPort.toString()); return "rmi://".concat(AuthServiceURI).concat(":").concat(AuthServicePort.toString());
} }
} }

View file

@ -43,7 +43,7 @@ public class Server {
//Starting Auth service based on RMI //Starting Auth service based on RMI
try { try {
auth = new AuthService(); auth = new AuthService();
Registry authRegistry = LocateRegistry.createRegistry(Config.AuthServerPort); Registry authRegistry = LocateRegistry.createRegistry(Config.AuthServicePort);
authRegistry.bind("auth", auth); authRegistry.bind("auth", auth);
} catch (RemoteException e) { } catch (RemoteException e) {
Server.logger.write("SERVER: RMI authentication service error (Remote exception)"); Server.logger.write("SERVER: RMI authentication service error (Remote exception)");
@ -54,7 +54,7 @@ public class Server {
private void startJedisService(){ private void startJedisService(){
//Starting Jedis pool for Redis connection //Starting Jedis pool for Redis connection
jedisPool = new JedisPool(new JedisPoolConfig(), Config.RedisServerURI); jedisPool = new JedisPool(new JedisPoolConfig(), Config.RedisServiceURI);
} }
private void startMessageService(){ private void startMessageService(){
@ -71,11 +71,11 @@ public class Server {
//Starting Notification service based on RMI //Starting Notification service based on RMI
try { try {
notificationServer = new NotificationService(); notificationServer = new NotificationService();
INotificationServer stub = (INotificationServer) UnicastRemoteObject.exportObject(notificationServer, Config.NotificationServerPort); INotificationServer stub = (INotificationServer) UnicastRemoteObject.exportObject(notificationServer, Config.NotificationServicePort);
LocateRegistry.createRegistry(Config.NotificationServerStubPort); LocateRegistry.createRegistry(Config.NotificationServiceStubPort);
Registry notificationRegistry = LocateRegistry.getRegistry(Config.NotificationServerStubPort); Registry notificationRegistry = LocateRegistry.getRegistry(Config.NotificationServiceStubPort);
notificationRegistry.bind(Config.NotificationServerName, stub); notificationRegistry.bind(Config.NotificationServiceName, stub);
} catch (RemoteException e) { } catch (RemoteException e) {
Server.logger.write("SERVER: RMI notification service error (Remote exception)"); Server.logger.write("SERVER: RMI notification service error (Remote exception)");
} catch (AlreadyBoundException e) { } catch (AlreadyBoundException e) {

View file

@ -1,7 +1,7 @@
package com.texttwist.server.proxies; package com.texttwist.server.dispatchers;
import com.texttwist.server.Server; import com.texttwist.server.Server;
import com.texttwist.server.managers.SessionsManager; import com.texttwist.server.models.Sessions;
import com.texttwist.server.models.Match; import com.texttwist.server.models.Match;
import com.texttwist.server.tasks.*; import com.texttwist.server.tasks.*;
import models.Message; import models.Message;
@ -33,7 +33,7 @@ public class MessageDispatcher implements Callable<Boolean> {
public Boolean call() { public Boolean call() {
bufferMessage = ByteBuffer.allocate(1024); bufferMessage = ByteBuffer.allocate(1024);
byte[] byteMessage = null; byte[] byteMessage = null;
if(SessionsManager.getInstance().isValidToken(request.token)){ if(Sessions.getInstance().isValidToken(request.token)){
switch(request.message){ switch(request.message){
case "START_GAME": case "START_GAME":

View file

@ -1,4 +1,4 @@
package com.texttwist.server.managers; package com.texttwist.server.models;
import com.texttwist.server.services.JedisService; import com.texttwist.server.services.JedisService;
import models.User; import models.User;
@ -8,21 +8,21 @@ import java.util.*;
/** /**
* Author: Lorenzo Iovino on 18/06/2017. * Author: Lorenzo Iovino on 18/06/2017.
* Description: AccountsManager * Description: Accounts
*/ */
public class AccountsManager { public class Accounts {
public List<User> users = Collections.synchronizedList(new ArrayList<User>()); public List<User> users = Collections.synchronizedList(new ArrayList<User>());
private static class Holder { private static class Holder {
static final AccountsManager INSTANCE = new AccountsManager(); static final Accounts INSTANCE = new Accounts();
} }
public static AccountsManager getInstance() { public static Accounts getInstance() {
return AccountsManager.Holder.INSTANCE; return Accounts.Holder.INSTANCE;
} }
private AccountsManager(){ private Accounts(){
List<Serializable> l = JedisService.get("users"); List<Serializable> l = JedisService.get("users");
for(int i=0; i<l.size(); i++) { for(int i=0; i<l.size(); i++) {
users.add((User) l.get(i)); users.add((User) l.get(i));

View file

@ -1,4 +1,4 @@
package com.texttwist.server.managers; package com.texttwist.server.models;
import models.Session; import models.Session;
import models.User; import models.User;
@ -9,17 +9,17 @@ import java.util.List;
/** /**
* Author: Lorenzo Iovino on 17/06/2017. * Author: Lorenzo Iovino on 17/06/2017.
* Description: SessionsManager. It is a singleton that provides the model and methods for manage sessions * Description: Sessions. It is a singleton that provides the model and methods for manage sessions
*/ */
public class SessionsManager { public class Sessions {
private List<Session> sessions = Collections.synchronizedList(new ArrayList<Session>()); private List<Session> sessions = Collections.synchronizedList(new ArrayList<Session>());
private static class Holder { private static class Holder {
static final SessionsManager INSTANCE = new SessionsManager(); static final Sessions INSTANCE = new Sessions();
} }
public static SessionsManager getInstance() { public static Sessions getInstance() {
return Holder.INSTANCE; return Holder.INSTANCE;
} }

View file

@ -1,8 +1,8 @@
package com.texttwist.server.services; package com.texttwist.server.services;
import com.texttwist.server.Server; import com.texttwist.server.Server;
import com.texttwist.server.managers.AccountsManager; import com.texttwist.server.models.Accounts;
import com.texttwist.server.managers.SessionsManager; import com.texttwist.server.models.Sessions;
import constants.Config; import constants.Config;
import interfaces.IAuth; import interfaces.IAuth;
import interfaces.INotificationClient; import interfaces.INotificationClient;
@ -24,14 +24,14 @@ public class AuthService extends UnicastRemoteObject implements IAuth {
private SecureRandom random = new SecureRandom(); private SecureRandom random = new SecureRandom();
public AuthService() throws RemoteException{ public AuthService() throws RemoteException{
Server.logger.write("AuthService Service running at "+ Config.AuthServerPort+" port..."); Server.logger.write("AuthService Service running at "+ Config.AuthServicePort +" port...");
} }
@Override @Override
public Response register(String userName, String password) throws RemoteException { public Response register(String userName, String password) throws RemoteException {
Server.logger.write("Invoked register with username=" + userName + " AND " + " password=" + password); Server.logger.write("Invoked register with username=" + userName + " AND " + " password=" + password);
if ((userName != null && !userName.isEmpty()) && (password != null && !password.equals(""))) { if ((userName != null && !userName.isEmpty()) && (password != null && !password.equals(""))) {
if(AccountsManager.getInstance().register(userName, password)){ if(Accounts.getInstance().register(userName, password)){
Server.logger.write("Registration successfull"); Server.logger.write("Registration successfull");
return new Response("Registration successfull", 200, null); return new Response("Registration successfull", 200, null);
} else { } else {
@ -46,11 +46,11 @@ public class AuthService extends UnicastRemoteObject implements IAuth {
public Response login(String userName, String password) throws RemoteException { public Response login(String userName, String password) throws RemoteException {
Server.logger.write("Invoked login with username=" + userName + " AND " + " password=" + password); Server.logger.write("Invoked login with username=" + userName + " AND " + " password=" + password);
if ((userName != null && !userName.isEmpty()) && (password != null && !password.equals(""))) { if ((userName != null && !userName.isEmpty()) && (password != null && !password.equals(""))) {
if(AccountsManager.getInstance().exists(userName) && AccountsManager.getInstance().checkPassword(userName, password)) { if(Accounts.getInstance().exists(userName) && Accounts.getInstance().checkPassword(userName, password)) {
JsonObject data = new JsonObject(); JsonObject data = new JsonObject();
String token = nextSessionId(); String token = nextSessionId();
data.put("token", token); data.put("token", token);
SessionsManager.getInstance().add(userName,token); Sessions.getInstance().add(userName,token);
Server.logger.write("Login successfull"); Server.logger.write("Login successfull");
return new Response("Login successfull", 200, data); return new Response("Login successfull", 200, data);
} }
@ -65,14 +65,14 @@ public class AuthService extends UnicastRemoteObject implements IAuth {
notificationServer.unregisterForCallback(stub); notificationServer.unregisterForCallback(stub);
if ((userName != null && !userName.isEmpty()) && (token != null && !token.isEmpty())) { if ((userName != null && !userName.isEmpty()) && (token != null && !token.isEmpty())) {
boolean res = SessionsManager.getInstance().remove(userName); boolean res = Sessions.getInstance().remove(userName);
if(res) { if(res) {
Server.logger.write("Logout successfull"); Server.logger.write("Logout successfull");
} }
} }
SessionsManager.getInstance().remove(userName); Sessions.getInstance().remove(userName);
Server.logger.write("Logout successfull (but something gone wrong)"); Server.logger.write("Logout successfull (but something gone wrong)");
return new Response("Logout successfull (but something gone wrong)", 200, null); return new Response("Logout successfull (but something gone wrong)", 200, null);
} }

View file

@ -1,7 +1,7 @@
package com.texttwist.server.services; package com.texttwist.server.services;
import com.texttwist.server.Server; import com.texttwist.server.Server;
import com.texttwist.server.proxies.MessageDispatcher; import com.texttwist.server.dispatchers.MessageDispatcher;
import com.texttwist.server.models.Dictionary; import com.texttwist.server.models.Dictionary;
import constants.Config; import constants.Config;
import models.Message; import models.Message;
@ -27,7 +27,7 @@ public class MessageService implements Runnable{
private String dictionaryPath = "./Server/resources/dictionary"; private String dictionaryPath = "./Server/resources/dictionary";
public static Dictionary dict; public static Dictionary dict;
public static Integer multicastId = Config.NotificationServerStubPort; public static Integer multicastId = Config.NotificationServiceStubPort;
public MessageService() public MessageService()
{ {
@ -37,9 +37,9 @@ public class MessageService implements Runnable{
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false); serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(Config.GameServerPort)); serverSocketChannel.socket().bind(new InetSocketAddress(Config.MessageServicePort));
serverSocketChannel.register(selector, OP_ACCEPT); serverSocketChannel.register(selector, OP_ACCEPT);
Server.logger.write("GameService Service is running at "+Config.GameServerPort+" port..."); Server.logger.write("GameService Service is running at "+Config.MessageServicePort +" port...");
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();

View file

@ -21,7 +21,7 @@ public class NotificationService implements INotificationServer {
private List<INotificationClient> clients; private List<INotificationClient> clients;
public NotificationService() throws RemoteException { public NotificationService() throws RemoteException {
super(); super();
Server.logger.write("Notification Service running at "+ Config.NotificationServerPort+" port..."); Server.logger.write("Notification Service running at "+ Config.NotificationServicePort +" port...");
clients = new ArrayList<>(); clients = new ArrayList<>();
} }

View file

@ -1,7 +1,7 @@
package com.texttwist.server.services; package com.texttwist.server.services;
import com.texttwist.server.Server; import com.texttwist.server.Server;
import com.texttwist.server.managers.SessionsManager; import com.texttwist.server.models.Sessions;
import com.texttwist.server.models.Match; import com.texttwist.server.models.Match;
import com.texttwist.server.tasks.ComputeScore; import com.texttwist.server.tasks.ComputeScore;
import constants.Config; import constants.Config;
@ -20,7 +20,7 @@ public class ReceiveWordsService implements Runnable {
private ExecutorService threadPool = Executors.newCachedThreadPool(); private ExecutorService threadPool = Executors.newCachedThreadPool();
public ReceiveWordsService() { public ReceiveWordsService() {
Server.logger.write("ReceiveWords Service running at "+Config.WordsReceiverServerPort+" port..."); Server.logger.write("ReceiveWords Service running at "+Config.WordsReceiverServicePort +" port...");
} }
@Override @Override
@ -29,7 +29,7 @@ public class ReceiveWordsService implements Runnable {
DatagramSocket s = null; DatagramSocket s = null;
try { try {
s = new DatagramSocket(Config.WordsReceiverServerPort); s = new DatagramSocket(Config.WordsReceiverServicePort);
} catch (SocketException e) { } catch (SocketException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -48,7 +48,7 @@ public class ReceiveWordsService implements Runnable {
String rcv = new String(packet.getData()); String rcv = new String(packet.getData());
if (rcv.startsWith("MESSAGE")) { if (rcv.startsWith("MESSAGE")) {
msg = Message.toMessage(rcv); msg = Message.toMessage(rcv);
if(SessionsManager.getInstance().isValidToken(msg.token)) { if(Sessions.getInstance().isValidToken(msg.token)) {
Match match = Match.findMatchByPlayerName(msg.sender); Match match = Match.findMatchByPlayerName(msg.sender);
threadPool.submit(new ComputeScore(msg.sender, msg.data, match)); threadPool.submit(new ComputeScore(msg.sender, msg.data, match));
} }

View file

@ -1,6 +1,6 @@
package com.texttwist.server.tasks; package com.texttwist.server.tasks;
import com.texttwist.server.managers.SessionsManager; import com.texttwist.server.models.Sessions;
import javax.swing.*; import javax.swing.*;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
@ -19,7 +19,7 @@ public class CheckOnlineUsers implements Callable<Boolean> {
@Override @Override
public Boolean call() throws Exception { public Boolean call() throws Exception {
for(int i = 0; i < users.size(); i++){ for(int i = 0; i < users.size(); i++){
if(!(SessionsManager.getInstance().exists(users.get(i)))){ if(!(Sessions.getInstance().exists(users.get(i)))){
return false; return false;
} }
} }

View file

@ -1,6 +1,6 @@
package com.texttwist.server.tasks; package com.texttwist.server.tasks;
import com.texttwist.server.managers.AccountsManager; import com.texttwist.server.models.Accounts;
import com.texttwist.server.services.JedisService; import com.texttwist.server.services.JedisService;
import models.User; import models.User;
@ -18,16 +18,16 @@ public class ComputeHighscores implements Callable<DefaultListModel<String>> {
public DefaultListModel<String> call() throws Exception { public DefaultListModel<String> call() throws Exception {
DefaultListModel<String> l = new DefaultListModel<>(); DefaultListModel<String> l = new DefaultListModel<>();
AccountsManager.getInstance().users.sort(new Comparator<User>() { Accounts.getInstance().users.sort(new Comparator<User>() {
@Override @Override
public int compare(User o1, User o2) { public int compare(User o1, User o2) {
return o2.score.compareTo(o1.score); return o2.score.compareTo(o1.score);
} }
}); });
JedisService.removeAll("users"); JedisService.removeAll("users");
for(int i = 0; i< AccountsManager.getInstance().users.size(); i++){ for(int i = 0; i< Accounts.getInstance().users.size(); i++){
l.addElement(AccountsManager.getInstance().users.get(i).userName+":"+ AccountsManager.getInstance().users.get(i).score); l.addElement(Accounts.getInstance().users.get(i).userName+":"+ Accounts.getInstance().users.get(i).score);
JedisService.add("users", AccountsManager.getInstance().users.get(i)); JedisService.add("users", Accounts.getInstance().users.get(i));
} }
return l; return l;
} }

View file

@ -1,6 +1,6 @@
package com.texttwist.server.tasks; package com.texttwist.server.tasks;
import com.texttwist.server.managers.AccountsManager; import com.texttwist.server.models.Accounts;
import com.texttwist.server.models.Dictionary; import com.texttwist.server.models.Dictionary;
import com.texttwist.server.models.Match; import com.texttwist.server.models.Match;
import models.User; import models.User;
@ -35,7 +35,7 @@ public class ComputeScore implements Callable<Integer> {
} }
match.setScore(sender, score); match.setScore(sender, score);
User u = AccountsManager.getInstance().findUser(sender); User u = Accounts.getInstance().findUser(sender);
u.addScore(score); u.addScore(score);
if(match.allPlayersSendedHisScore()) { if(match.allPlayersSendedHisScore()) {

View file

@ -29,7 +29,7 @@ public class SendScores implements Callable<Void> {
MulticastSocket multicastSocket = null; MulticastSocket multicastSocket = null;
try { try {
multicastSocket = new MulticastSocket(match.multicastId); multicastSocket = new MulticastSocket(match.multicastId);
InetAddress ia = InetAddress.getByName(Config.ScoreMulticastServerURI); InetAddress ia = InetAddress.getByName(Config.ScoreMulticastServiceURI);
DatagramPacket hi = new DatagramPacket(msg.toString().getBytes(), msg.toString().length(), ia, match.multicastId); DatagramPacket hi = new DatagramPacket(msg.toString().getBytes(), msg.toString().length(), ia, match.multicastId);
multicastSocket.send(hi); multicastSocket.send(hi);
} catch (IOException e) { } catch (IOException e) {