diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 0a31912..a46aec0 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -5,42 +5,34 @@ - - - + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + @@ -63,33 +55,21 @@ - - - - - - - - - - - - - - + + - + - - + + @@ -101,17 +81,7 @@ - - - - - - - - - - - + @@ -120,53 +90,67 @@ - - + + - - - - - - - - - - - - - - - - - - - - - - + + - + - - + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -178,11 +162,6 @@ - Insert y - Insert you - Insert your - Insert your - Insert your d Registration Registration uns R @@ -195,7 +174,6 @@ registration unsuccess G GameService is - GameService is T TIMEO TIMEOUT @@ -208,6 +186,12 @@ game is read le letters + 120 + 5 + 5000 + 500 + 4 + 4000 C:\Users\loke\TextTwist\out\production @@ -346,10 +330,6 @@ @@ -416,10 +400,9 @@ - @@ -451,386 +434,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -914,6 +517,290 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1444,46 +1331,48 @@ + + - - + - - - - - - - - - - - - + + + + - + - - + + + + + + + + + + @@ -1503,63 +1392,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -1567,9 +1403,6 @@ - - - @@ -1593,11 +1426,6 @@ - - - - - @@ -1605,30 +1433,14 @@ - - - - - - - - - - - - + - - - - - @@ -1636,7 +1448,6 @@ - @@ -1644,19 +1455,6 @@ - - - - - - - - - - - - - @@ -1664,11 +1462,6 @@ - - - - - @@ -1676,9 +1469,6 @@ - - - @@ -1686,7 +1476,6 @@ - @@ -1694,9 +1483,6 @@ - - - @@ -1704,7 +1490,6 @@ - @@ -1712,9 +1497,6 @@ - - - @@ -1722,9 +1504,6 @@ - - - @@ -1732,7 +1511,6 @@ - @@ -1740,9 +1518,6 @@ - - - @@ -1750,9 +1525,6 @@ - - - @@ -1760,9 +1532,6 @@ - - - @@ -1770,9 +1539,6 @@ - - - @@ -1780,9 +1546,6 @@ - - - @@ -1790,7 +1553,6 @@ - @@ -1806,9 +1568,6 @@ - - - @@ -1824,9 +1583,6 @@ - - - @@ -1834,7 +1590,6 @@ - @@ -1842,15 +1597,6 @@ - - - - - - - - - @@ -1858,7 +1604,6 @@ - @@ -1866,22 +1611,13 @@ - - - - - - - - - - - + + @@ -1890,56 +1626,46 @@ - - - - - - + + - - + + - - - - - - - - - - - + + + + + - - + + - - + + @@ -1947,29 +1673,105 @@ - - - - - - - - - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Client/src/com/texttwist/client/pages/GamePage.java b/Client/src/com/texttwist/client/pages/GamePage.java index fc7e10e..ed3571a 100644 --- a/Client/src/com/texttwist/client/pages/GamePage.java +++ b/Client/src/com/texttwist/client/pages/GamePage.java @@ -141,7 +141,7 @@ public class GamePage extends Page { return null; } }), - Config.timeoutGame + Config.gameTimeout ); } } diff --git a/Commons/src/constants/Config.java b/Commons/src/constants/Config.java index 6c34a01..1496241 100644 --- a/Commons/src/constants/Config.java +++ b/Commons/src/constants/Config.java @@ -18,9 +18,14 @@ public class Config { public static String ScoreMulticastServerURI = "226.226.226.226"; public static Integer NotificationServerPort = 20000; - public static Integer NotificationServerStubPort = 5000; + public static Integer NotificationServerStubPort = 30000; public static String NotificationServerName ="notification"; - public static int timeoutGame = 120; + + public static String RedisServerURI = "localhost"; + + public static int gameTimeout = 10; //2 minuti in sec + public static int joinMatchTimeout = 5000; //7 minuti in millisec + public static int sendWordsTimeout = 3000; //5 minuti in millisec public static String getAuthServerURI(){ return "rmi://".concat(AuthServerURI).concat(":").concat(AuthServerPort.toString()); diff --git a/Server/src/com/texttwist/server/Main.java b/Server/src/com/texttwist/server/Main.java index f1484af..7d62414 100644 --- a/Server/src/com/texttwist/server/Main.java +++ b/Server/src/com/texttwist/server/Main.java @@ -1,13 +1,13 @@ package com.texttwist.server; -import utilities.Logger; - -import java.io.File; import java.io.IOException; +/** + * Author: Lorenzo Iovino on 14/06/2017. + * Description: Main + */ public class Main { - public static void main(String[] args) throws IOException { - Server ttServer = new Server(); + new Server(); } } diff --git a/Server/src/com/texttwist/server/Server.java b/Server/src/com/texttwist/server/Server.java index b2bee6d..ea3e5ac 100644 --- a/Server/src/com/texttwist/server/Server.java +++ b/Server/src/com/texttwist/server/Server.java @@ -1,65 +1,78 @@ package com.texttwist.server; -import com.texttwist.server.components.Auth; -import com.texttwist.server.components.GameServer; -import com.texttwist.server.components.NotificationServer; +import com.texttwist.server.services.AuthService; +import com.texttwist.server.services.MessageService; +import com.texttwist.server.services.NotificationService; import constants.Config; import interfaces.INotificationServer; -import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import utilities.Logger; - import java.io.File; import java.io.IOException; import java.rmi.AlreadyBoundException; +import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; + /** - * Created by loke on 15/06/2017. + * Author: Lorenzo Iovino on 15/06/2017. + * Description: Server. Initialize all services. */ public class Server { - public static NotificationServer notificationServer; + public static NotificationService notificationServer; public static JedisPool jedisPool; public static Logger logger; + public static AuthService auth; public Server() throws IOException { logger = new Logger(new File("./notificationServer.log"), "Server", true); - Server.logger.write("Server starting ..."); - - //Start services + Server.logger.write("Services starting ..."); + startAuthService(); + startJedisService(); + startMessageService(); + startNotificationService(); + Server.logger.write("Services started correctly ..."); + } + private void startAuthService(){ + //Starting AuthService service based on RMI try { - //Definitions of registry for auth - Auth auth = new Auth(Config.AuthServerPort); + auth = new AuthService(Config.AuthServerPort); Registry authRegistry = LocateRegistry.createRegistry(auth.serverPort); authRegistry.bind("auth", auth); - - //Connecting to Redis server on localhost - jedisPool = new JedisPool(new JedisPoolConfig(), "localhost"); - - GameServer gameServer = new GameServer(Config.GameServerPort); - new Thread(gameServer).start(); - - try { - /*registrazione presso il registry */ - notificationServer = new NotificationServer(); - INotificationServer stub = (INotificationServer) UnicastRemoteObject.exportObject(notificationServer, Config.NotificationServerPort); - LocateRegistry.createRegistry(Config.NotificationServerStubPort); - Registry notificationRegistry = LocateRegistry.getRegistry(Config.NotificationServerStubPort); - notificationRegistry.bind(Config.NotificationServerName, stub); - - - } catch (Exception e) { - System.out.println("Eccezione" + e); - } - Server.logger.write("Server started"); + } catch (RemoteException e) { + Server.logger.write("SERVER: RMI authentication service error (Remote exception)"); } catch (AlreadyBoundException e) { - e.printStackTrace(); + Server.logger.write("SERVER: RMI authentication service can't use this port because is busy "); } } + private void startJedisService(){ + //Starting Jedis pool for Redis connection + jedisPool = new JedisPool(new JedisPoolConfig(), Config.RedisServerURI); + } -} + private void startMessageService(){ + //Starting the Message service based on TCP + new Thread(new MessageService(Config.GameServerPort)).start(); + } + + private void startNotificationService(){ + //Starting Notification service based on RMI + try { + notificationServer = new NotificationService(); + INotificationServer stub = (INotificationServer) UnicastRemoteObject.exportObject(notificationServer, Config.NotificationServerPort); + LocateRegistry.createRegistry(Config.NotificationServerStubPort); + + Registry notificationRegistry = LocateRegistry.getRegistry(Config.NotificationServerStubPort); + notificationRegistry.bind(Config.NotificationServerName, stub); + } catch (RemoteException e) { + Server.logger.write("SERVER: RMI notification service error (Remote exception)"); + } catch (AlreadyBoundException e) { + Server.logger.write("SERVER: RMI notification service can't use this port because is busy "); + } + } +} \ No newline at end of file diff --git a/Server/src/com/texttwist/server/models/Match.java b/Server/src/com/texttwist/server/models/Match.java index 0f16cd7..b7d35c9 100644 --- a/Server/src/com/texttwist/server/models/Match.java +++ b/Server/src/com/texttwist/server/models/Match.java @@ -1,6 +1,6 @@ package com.texttwist.server.models; -import com.texttwist.server.components.GameServer; +import com.texttwist.server.services.MessageService; import com.texttwist.server.tasks.MatchTimeout; import constants.Config; import javafx.util.Pair; @@ -11,12 +11,11 @@ import java.io.IOException; import java.net.*; import java.nio.channels.SocketChannel; import java.util.*; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import static com.texttwist.server.components.GameServer.activeMatches; +import static com.texttwist.server.services.MessageService.activeMatches; /** * Created by loke on 23/06/2017. @@ -155,7 +154,7 @@ public class Match { private int generateMulticastId(){ - return GameServer.multicastID++; + return MessageService.multicastID++; } public void setLetters(DefaultListModel letters){ this.letters = letters; diff --git a/Server/src/com/texttwist/server/components/ThreadProxy.java b/Server/src/com/texttwist/server/models/servers/ThreadProxy.java similarity index 92% rename from Server/src/com/texttwist/server/components/ThreadProxy.java rename to Server/src/com/texttwist/server/models/servers/ThreadProxy.java index 4d94634..831e929 100644 --- a/Server/src/com/texttwist/server/components/ThreadProxy.java +++ b/Server/src/com/texttwist/server/models/servers/ThreadProxy.java @@ -1,221 +1,213 @@ -package com.texttwist.server.components; - -import com.sun.org.apache.xpath.internal.operations.Bool; -import com.texttwist.client.App; -import com.texttwist.server.models.Match; -import com.texttwist.server.tasks.*; -import constants.Config; -import javafx.util.Pair; -import models.Message; - -import javax.swing.*; -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.MulticastSocket; -import java.nio.ByteBuffer; -import java.nio.channels.DatagramChannel; -import java.nio.channels.SocketChannel; -import java.util.concurrent.*; - -import static com.texttwist.server.components.GameServer.activeMatches; - -/** - * Created by loke on 18/06/2017. - */ -public class ThreadProxy implements Callable { - protected final ExecutorService threadPool = Executors.newCachedThreadPool(); - private final Message request; - private final SocketChannel socketChannel; - private ByteBuffer bufferMessage; - boolean matchNotAvailable =false; - - - ThreadProxy(Message request, SocketChannel socketChannel, ByteBuffer bufferMessage) { - this.request = request; - this.socketChannel = socketChannel; - this.bufferMessage = bufferMessage; - - } - - @Override - public Boolean call() { - bufferMessage = ByteBuffer.allocate(1024); - byte[] byteMessage = null; - if(SessionsManager.getInstance().isValidToken(request.token)){ - switch(request.message){ - case "START_GAME": - Future onlineUsers = threadPool.submit(new CheckOnlineUsers(request.data)); - try { - Boolean usersOnline = onlineUsers.get(); - if(usersOnline){ - Future sendInvitations = threadPool.submit(new SendInvitations(request.sender, request.data)); - try { - Boolean invitationSended = sendInvitations.get(); - if (invitationSended) { - - //Crea nuova partita e attendi i giocatori - request.data.addElement(request.sender); - final Match match = new Match(request.sender, request.data); - match.printAll(); - - activeMatches.add(match); - - DefaultListModel matchName = new DefaultListModel<>(); - matchName.addElement(request.sender); - - Future joinMatch = threadPool.submit(new JoinMatch(request.sender, matchName, socketChannel)); - Boolean joinMatchRes = joinMatch.get(); - - if(!joinMatchRes){ - bufferMessage = ByteBuffer.allocate(1024); - - //NON FARE NULLA, ASPETTA GLI ALTRI - Message message = new Message("INVITES_ALL_SENDED", "", "", new DefaultListModel<>()); - byteMessage = message.toString().getBytes(); - bufferMessage = ByteBuffer.wrap(byteMessage); - socketChannel.write(bufferMessage); - } - - Future joinTimeout = threadPool.submit(new JoinTimeout(match)); - joinTimeout.get(); - if(match.joinTimeout){ - Future sendMessageJoinTimeout = threadPool.submit( - new SendMessageToAllPlayers(match, new Message("JOIN_TIMEOUT", "", "", new DefaultListModel<>()), socketChannel)); - Boolean sendMessageJoinTimeoutRes = sendMessageJoinTimeout.get(); - if(!sendMessageJoinTimeoutRes){ - activeMatches.remove(Match.findMatchIndex(activeMatches, match.matchCreator)); - return sendMessageJoinTimeoutRes; - } - } else { - System.out.println("TIMEOUT FINITO SENZA EFFETTI"); - return true; - } - - } else { - return false; - } - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } - } else { - - Message message = new Message("USER_NOT_ONLINE", "", "", new DefaultListModel<>()); - byteMessage = new String(message.toString()).getBytes(); - bufferMessage.clear(); - bufferMessage = ByteBuffer.wrap(byteMessage); - this.socketChannel.write(bufferMessage); - return false; - } - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - case "FETCH_HIGHSCORES": - Future> computeHighscores = threadPool.submit(new ComputeHighscores()); - try { - DefaultListModel computeHighscoresRes = computeHighscores.get(); - bufferMessage.clear(); - bufferMessage = ByteBuffer.allocate(1024); - - Message message = new Message("HIGHSCORES", "", "", computeHighscoresRes); - byteMessage = message.toString().getBytes(); - - bufferMessage = ByteBuffer.wrap(byteMessage); - try { - String s = new String(bufferMessage.array(), bufferMessage.position(), bufferMessage.remaining()); - System.out.println("INVIO HIGHSCORES "+ s); - socketChannel.write(bufferMessage); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } - - case "JOIN_GAME": - Future joinMatch = threadPool.submit(new JoinMatch(request.sender, request.data, socketChannel)); - try { - Match match = Match.findMatch(activeMatches, request.data.get(0));; - Boolean joinMatchRes = joinMatch.get(); - if(joinMatchRes){ - - if(!match.joinTimeout) { - Future> generateLetters = threadPool.submit(new GenerateLetters()); - match.setLetters(generateLetters.get()); - match.letters.addElement(String.valueOf(match.multicastId)); - - for (int i = 0; i < match.playersSocket.size(); i++) { - SocketChannel socketClient = match.playersSocket.get(i).getValue(); - if (socketClient != null) { - bufferMessage.clear(); - bufferMessage = ByteBuffer.allocate(1024); - - Message message = new Message("GAME_STARTED", "", "", match.letters); - match.startGame(); - - System.out.println("TIMEOUT CANCELLEd"); - byteMessage = message.toString().getBytes(); - - bufferMessage = ByteBuffer.wrap(byteMessage); - try { - String s = new String(bufferMessage.array(), bufferMessage.position(), bufferMessage.remaining()); - System.out.println("INVIO GAME_STARTED "+ s); - socketClient.write(bufferMessage); - } catch (IOException e) { - e.printStackTrace(); - } - } - - } - if (matchNotAvailable) { - return false; - } - } - } else { - if(match == null){ - bufferMessage = ByteBuffer.allocate(1024); - if (socketChannel != null) { - bufferMessage = ByteBuffer.allocate(1024); - - Message msg = new Message("MATCH_NOT_AVAILABLE", "", null, new DefaultListModel<>()); - bufferMessage.clear(); - byteMessage = msg.toString().getBytes(); - bufferMessage = ByteBuffer.wrap(byteMessage); - socketChannel.write(bufferMessage); - matchNotAvailable = true; - } - - } - } - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - default: - - break; - } - - } else { - threadPool.submit(new TokenInvalid(request.sender, socketChannel, bufferMessage)); - return false; - } - - return false; - } -} +package com.texttwist.server.models.servers; + +import com.texttwist.server.models.Match; +import com.texttwist.server.services.SessionsService; +import com.texttwist.server.tasks.*; +import models.Message; + +import javax.swing.*; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.util.concurrent.*; + +import static com.texttwist.server.services.MessageService.activeMatches; + +/** + * Created by loke on 18/06/2017. + */ +public class ThreadProxy implements Callable { + protected final ExecutorService threadPool = Executors.newCachedThreadPool(); + private final Message request; + private final SocketChannel socketChannel; + private ByteBuffer bufferMessage; + boolean matchNotAvailable =false; + + + public ThreadProxy(Message request, SocketChannel socketChannel, ByteBuffer bufferMessage) { + this.request = request; + this.socketChannel = socketChannel; + this.bufferMessage = bufferMessage; + + } + + @Override + public Boolean call() { + bufferMessage = ByteBuffer.allocate(1024); + byte[] byteMessage = null; + if(SessionsService.getInstance().isValidToken(request.token)){ + switch(request.message){ + case "START_GAME": + Future onlineUsers = threadPool.submit(new CheckOnlineUsers(request.data)); + try { + Boolean usersOnline = onlineUsers.get(); + if(usersOnline){ + Future sendInvitations = threadPool.submit(new SendInvitations(request.sender, request.data)); + try { + Boolean invitationSended = sendInvitations.get(); + if (invitationSended) { + + //Crea nuova partita e attendi i giocatori + request.data.addElement(request.sender); + final Match match = new Match(request.sender, request.data); + match.printAll(); + + activeMatches.add(match); + + DefaultListModel matchName = new DefaultListModel<>(); + matchName.addElement(request.sender); + + Future joinMatch = threadPool.submit(new JoinMatch(request.sender, matchName, socketChannel)); + Boolean joinMatchRes = joinMatch.get(); + + if(!joinMatchRes){ + bufferMessage = ByteBuffer.allocate(1024); + + //NON FARE NULLA, ASPETTA GLI ALTRI + Message message = new Message("INVITES_ALL_SENDED", "", "", new DefaultListModel<>()); + byteMessage = message.toString().getBytes(); + bufferMessage = ByteBuffer.wrap(byteMessage); + socketChannel.write(bufferMessage); + } + + Future joinTimeout = threadPool.submit(new JoinTimeout(match)); + joinTimeout.get(); + if(match.joinTimeout){ + Future sendMessageJoinTimeout = threadPool.submit( + new SendMessageToAllPlayers(match, new Message("JOIN_TIMEOUT", "", "", new DefaultListModel<>()), socketChannel)); + Boolean sendMessageJoinTimeoutRes = sendMessageJoinTimeout.get(); + if(!sendMessageJoinTimeoutRes){ + activeMatches.remove(Match.findMatchIndex(activeMatches, match.matchCreator)); + return sendMessageJoinTimeoutRes; + } + } else { + System.out.println("TIMEOUT FINITO SENZA EFFETTI"); + return true; + } + + } else { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } + } else { + + Message message = new Message("USER_NOT_ONLINE", "", "", new DefaultListModel<>()); + byteMessage = new String(message.toString()).getBytes(); + bufferMessage.clear(); + bufferMessage = ByteBuffer.wrap(byteMessage); + this.socketChannel.write(bufferMessage); + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + case "FETCH_HIGHSCORES": + Future> computeHighscores = threadPool.submit(new ComputeHighscores()); + try { + DefaultListModel computeHighscoresRes = computeHighscores.get(); + bufferMessage.clear(); + bufferMessage = ByteBuffer.allocate(1024); + + Message message = new Message("HIGHSCORES", "", "", computeHighscoresRes); + byteMessage = message.toString().getBytes(); + + bufferMessage = ByteBuffer.wrap(byteMessage); + try { + String s = new String(bufferMessage.array(), bufferMessage.position(), bufferMessage.remaining()); + System.out.println("INVIO HIGHSCORES "+ s); + socketChannel.write(bufferMessage); + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } + + case "JOIN_GAME": + Future joinMatch = threadPool.submit(new JoinMatch(request.sender, request.data, socketChannel)); + try { + Match match = Match.findMatch(activeMatches, request.data.get(0));; + Boolean joinMatchRes = joinMatch.get(); + if(joinMatchRes){ + + if(!match.joinTimeout) { + Future> generateLetters = threadPool.submit(new GenerateLetters()); + match.setLetters(generateLetters.get()); + match.letters.addElement(String.valueOf(match.multicastId)); + + for (int i = 0; i < match.playersSocket.size(); i++) { + SocketChannel socketClient = match.playersSocket.get(i).getValue(); + if (socketClient != null) { + bufferMessage.clear(); + bufferMessage = ByteBuffer.allocate(1024); + + Message message = new Message("GAME_STARTED", "", "", match.letters); + match.startGame(); + + System.out.println("TIMEOUT CANCELLEd"); + byteMessage = message.toString().getBytes(); + + bufferMessage = ByteBuffer.wrap(byteMessage); + try { + String s = new String(bufferMessage.array(), bufferMessage.position(), bufferMessage.remaining()); + System.out.println("INVIO GAME_STARTED "+ s); + socketClient.write(bufferMessage); + } catch (IOException e) { + e.printStackTrace(); + } + } + + } + if (matchNotAvailable) { + return false; + } + } + } else { + if(match == null){ + bufferMessage = ByteBuffer.allocate(1024); + if (socketChannel != null) { + bufferMessage = ByteBuffer.allocate(1024); + + Message msg = new Message("MATCH_NOT_AVAILABLE", "", null, new DefaultListModel<>()); + bufferMessage.clear(); + byteMessage = msg.toString().getBytes(); + bufferMessage = ByteBuffer.wrap(byteMessage); + socketChannel.write(bufferMessage); + matchNotAvailable = true; + } + + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + default: + + break; + } + + } else { + threadPool.submit(new TokenInvalid(request.sender, socketChannel, bufferMessage)); + return false; + } + + return false; + } +} diff --git a/Server/src/com/texttwist/server/components/AccountsManager.java b/Server/src/com/texttwist/server/services/AccountsService.java similarity index 82% rename from Server/src/com/texttwist/server/components/AccountsManager.java rename to Server/src/com/texttwist/server/services/AccountsService.java index 5fd93fa..499e19a 100644 --- a/Server/src/com/texttwist/server/components/AccountsManager.java +++ b/Server/src/com/texttwist/server/services/AccountsService.java @@ -1,79 +1,79 @@ -package com.texttwist.server.components; - -import models.User; -import java.io.Serializable; -import java.util.*; - - -/** - * Created by loke on 18/06/2017. - */ -public class AccountsManager { - - public List users = Collections.synchronizedList(new ArrayList()); - - private static class Holder { - static final AccountsManager INSTANCE = new AccountsManager(); - } - - public static AccountsManager getInstance() { - return AccountsManager.Holder.INSTANCE; - } - - private AccountsManager(){ - List l = JedisService.get("users"); - for(int i=0; i i = users.iterator(); - while (i.hasNext()) { - if (i.next().userName.equals(userName)) { - return true; - } - } - return false; - - } - - public boolean checkPassword(String userName, String password) { - Iterator i = users.iterator(); - while (i.hasNext()) { - User account = i.next(); - if (account.userName.equals(userName) && account.password.equals(password)) { - return true; - } - } - return false; - - } - - public User findUser(String userName){ - Iterator i = users.iterator(); - while (i.hasNext()) { - User u = i.next(); - if (u.userName.equals(userName)) { - return u; - } - } - return null; - } - - public int size(){ - return users.size(); - } - -} +package com.texttwist.server.services; + +import models.User; +import java.io.Serializable; +import java.util.*; + + +/** + * Created by loke on 18/06/2017. + */ +public class AccountsService { + + public List users = Collections.synchronizedList(new ArrayList()); + + private static class Holder { + static final AccountsService INSTANCE = new AccountsService(); + } + + public static AccountsService getInstance() { + return AccountsService.Holder.INSTANCE; + } + + private AccountsService(){ + List l = JedisService.get("users"); + for(int i=0; i i = users.iterator(); + while (i.hasNext()) { + if (i.next().userName.equals(userName)) { + return true; + } + } + return false; + + } + + public boolean checkPassword(String userName, String password) { + Iterator i = users.iterator(); + while (i.hasNext()) { + User account = i.next(); + if (account.userName.equals(userName) && account.password.equals(password)) { + return true; + } + } + return false; + + } + + public User findUser(String userName){ + Iterator i = users.iterator(); + while (i.hasNext()) { + User u = i.next(); + if (u.userName.equals(userName)) { + return u; + } + } + return null; + } + + public int size(){ + return users.size(); + } + +} diff --git a/Server/src/com/texttwist/server/components/Auth.java b/Server/src/com/texttwist/server/services/AuthService.java similarity index 80% rename from Server/src/com/texttwist/server/components/Auth.java rename to Server/src/com/texttwist/server/services/AuthService.java index 08dc66b..b12b3cc 100644 --- a/Server/src/com/texttwist/server/components/Auth.java +++ b/Server/src/com/texttwist/server/services/AuthService.java @@ -1,83 +1,83 @@ -package com.texttwist.server.components; - -import com.texttwist.server.Server; -import interfaces.IAuth; -import interfaces.INotificationClient; -import models.Response; -import org.json.simple.JsonObject; -import java.math.BigInteger; -import java.rmi.RemoteException; -import java.rmi.server.UnicastRemoteObject; -import java.security.SecureRandom; - -import static com.texttwist.server.Server.notificationServer; - -/** - * Created by loke on 15/06/2017. - */ -public class Auth extends UnicastRemoteObject implements IAuth { - - private SecureRandom random = new SecureRandom(); - public int serverPort = 9999; - - - public Auth(int serverPort) throws RemoteException{ - this.serverPort=serverPort; - Server.logger.write("Auth Service running at "+serverPort+" port..."); - } - - @Override - public Response register(String userName, String password) throws RemoteException { - Server.logger.write("Invoked register with username=" + userName + " AND " + " password=" + password); - if ((userName != null && !userName.isEmpty()) && (password != null && !password.equals(""))) { - if(AccountsManager.getInstance().register(userName, password)){ - Server.logger.write("Registration successfull"); - return new Response("Registration successfull", 200, null); - } else { - Server.logger.write("Registration unsuccessfull"); - return new Response("
Registration unsuccessfull:
Username exist!
", 400, null); - } - } - return new Response("
Registration unsuccessfull!
All fields are mandatories
", 400, null); - } - - @Override - public Response login(String userName, String password) throws RemoteException { - Server.logger.write("Invoked login with username=" + userName + " AND " + " password=" + password); - if ((userName != null && !userName.isEmpty()) && (password != null && !password.equals(""))) { - if(AccountsManager.getInstance().exists(userName) && AccountsManager.getInstance().checkPassword(userName, password)) { - JsonObject data = new JsonObject(); - String token = nextSessionId(); - data.put("token", token); - SessionsManager.getInstance().add(userName,token); - Server.logger.write("Login successfull"); - return new Response("Login successfull", 200, data); - } - } - Server.logger.write("Login unsuccessfull"); - return new Response("Login unsuccessfull", 400, null); - } - - @Override - public Response logout(String userName, String token, INotificationClient stub) throws RemoteException { - Server.logger.write("Invoked logout with username=" + userName + " AND " + " token=" + token); - notificationServer.unregisterForCallback(stub); - - if ((userName != null && !userName.isEmpty()) && (token != null && !token.isEmpty())) { - boolean res = SessionsManager.getInstance().remove(userName); - if(res) { - Server.logger.write("Logout successfull"); - - } - } - - SessionsManager.getInstance().remove(userName); - Server.logger.write("Logout successfull (but something gone wrong)"); - return new Response("Logout successfull (but something gone wrong)", 200, null); - } - - public String nextSessionId() { - return new BigInteger(130, random).toString(32); - } - -} +package com.texttwist.server.services; + +import com.texttwist.server.Server; +import interfaces.IAuth; +import interfaces.INotificationClient; +import models.Response; +import org.json.simple.JsonObject; +import java.math.BigInteger; +import java.rmi.RemoteException; +import java.rmi.server.UnicastRemoteObject; +import java.security.SecureRandom; + +import static com.texttwist.server.Server.notificationServer; + +/** + * Created by loke on 15/06/2017. + */ +public class AuthService extends UnicastRemoteObject implements IAuth { + + private SecureRandom random = new SecureRandom(); + public int serverPort = 9999; + + + public AuthService(int serverPort) throws RemoteException{ + this.serverPort=serverPort; + Server.logger.write("AuthService Service running at "+serverPort+" port..."); + } + + @Override + public Response register(String userName, String password) throws RemoteException { + Server.logger.write("Invoked register with username=" + userName + " AND " + " password=" + password); + if ((userName != null && !userName.isEmpty()) && (password != null && !password.equals(""))) { + if(AccountsService.getInstance().register(userName, password)){ + Server.logger.write("Registration successfull"); + return new Response("Registration successfull", 200, null); + } else { + Server.logger.write("Registration unsuccessfull"); + return new Response("
Registration unsuccessfull:
Username exist!
", 400, null); + } + } + return new Response("
Registration unsuccessfull!
All fields are mandatories
", 400, null); + } + + @Override + public Response login(String userName, String password) throws RemoteException { + Server.logger.write("Invoked login with username=" + userName + " AND " + " password=" + password); + if ((userName != null && !userName.isEmpty()) && (password != null && !password.equals(""))) { + if(AccountsService.getInstance().exists(userName) && AccountsService.getInstance().checkPassword(userName, password)) { + JsonObject data = new JsonObject(); + String token = nextSessionId(); + data.put("token", token); + SessionsService.getInstance().add(userName,token); + Server.logger.write("Login successfull"); + return new Response("Login successfull", 200, data); + } + } + Server.logger.write("Login unsuccessfull"); + return new Response("Login unsuccessfull", 400, null); + } + + @Override + public Response logout(String userName, String token, INotificationClient stub) throws RemoteException { + Server.logger.write("Invoked logout with username=" + userName + " AND " + " token=" + token); + notificationServer.unregisterForCallback(stub); + + if ((userName != null && !userName.isEmpty()) && (token != null && !token.isEmpty())) { + boolean res = SessionsService.getInstance().remove(userName); + if(res) { + Server.logger.write("Logout successfull"); + + } + } + + SessionsService.getInstance().remove(userName); + Server.logger.write("Logout successfull (but something gone wrong)"); + return new Response("Logout successfull (but something gone wrong)", 200, null); + } + + public String nextSessionId() { + return new BigInteger(130, random).toString(32); + } + +} diff --git a/Server/src/com/texttwist/server/components/JedisService.java b/Server/src/com/texttwist/server/services/JedisService.java similarity index 97% rename from Server/src/com/texttwist/server/components/JedisService.java rename to Server/src/com/texttwist/server/services/JedisService.java index 9b1b627..48aaf29 100644 --- a/Server/src/com/texttwist/server/components/JedisService.java +++ b/Server/src/com/texttwist/server/services/JedisService.java @@ -1,10 +1,9 @@ -package com.texttwist.server.components; +package com.texttwist.server.services; import models.User; import redis.clients.jedis.Jedis; import java.io.*; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Base64; import java.util.List; diff --git a/Server/src/com/texttwist/server/components/GameServer.java b/Server/src/com/texttwist/server/services/MessageService.java similarity index 90% rename from Server/src/com/texttwist/server/components/GameServer.java rename to Server/src/com/texttwist/server/services/MessageService.java index 2680cea..4e046d0 100644 --- a/Server/src/com/texttwist/server/components/GameServer.java +++ b/Server/src/com/texttwist/server/services/MessageService.java @@ -1,138 +1,136 @@ - -package com.texttwist.server.components; -import com.texttwist.client.App; -import com.texttwist.server.Server; -import com.texttwist.server.models.Dictionary; -import com.texttwist.server.models.Match; -import com.texttwist.server.tasks.ReceiveWords; -import constants.Config; -import models.Message; -import utilities.Logger; - -import java.net.*; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.*; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import static java.nio.channels.SelectionKey.OP_ACCEPT; -import static java.nio.channels.SelectionKey.OP_READ; - -public class GameServer implements Runnable{ - - private int serverPort; - private ThreadProxy proxy; - private ReceiveWords wordsReceiver; - - private DatagramChannel datagramChannel; - private Selector selector = null; - private ExecutorService threadPool = Executors.newCachedThreadPool(); - private String dictionaryPath = "./Server/resources/dictionary"; - public static Dictionary dict; - SocketChannel client; - ByteBuffer bufferWords = ByteBuffer.allocate(1024); - ByteBuffer bufferMessages = ByteBuffer.allocate(1024); - - - - public static List activeMatches = Collections.synchronizedList(new ArrayList<>()); - public static Integer multicastID = 4000; - - public GameServer(int port){ - this.serverPort = port; - } - - public void run(){ - - dict = new Dictionary(dictionaryPath); - try { - selector = Selector.open(); - - ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); - serverSocketChannel.configureBlocking(false); - serverSocketChannel.socket().bind(new InetSocketAddress(serverPort)); - serverSocketChannel.register(selector, OP_ACCEPT); - InetSocketAddress address = new InetSocketAddress(Config.WordsReceiverServerURI,Config.WordsReceiverServerPort); - datagramChannel = DatagramChannel.open(); - datagramChannel.configureBlocking(true); - datagramChannel.connect(address); - Server.logger.write("GameService Service is running at "+this.serverPort+" port..."); - - wordsReceiver = new ReceiveWords(datagramChannel, bufferWords, bufferMessages, client); - threadPool.submit(wordsReceiver); - - } catch (IOException e) { - e.printStackTrace(); - } - - while (true) { - System.out.println("WAITING FOR MSG"); - try { - selector.select(); - } catch (IOException e) { - e.printStackTrace(); - } - - Iterator iter = selector.selectedKeys().iterator(); - while (iter.hasNext()) { - bufferMessages = ByteBuffer.allocate(1024); - bufferMessages.clear(); - client = null; - SelectionKey key = iter.next(); - iter.remove(); - - try { - switch (key.readyOps()) { - case OP_ACCEPT: - client = ((ServerSocketChannel) key.channel()).accept(); - client.configureBlocking(false); - client.register(selector, OP_READ); - break; - - case OP_READ: - client = (SocketChannel) key.channel(); - if (client.read(bufferMessages) != -1) { - bufferMessages.flip(); - String line = new String(bufferMessages.array(), bufferMessages.position(), bufferMessages.remaining()); - System.out.println(line); - if (line.startsWith("MESSAGE")) { - SessionsManager.getInstance().printAll(); - Message msg = Message.toMessage(line); - proxy = new ThreadProxy(msg, client, bufferMessages); - threadPool.submit(proxy); - } - - if (line.startsWith("CLOSE")) { - client.close(); - } else if (line.startsWith("QUIT")) { - for (SelectionKey k : selector.keys()) { - k.cancel(); - k.channel().close(); - } - selector.close(); - return; - } - } else { - key.cancel(); - } - break; - - default: - break; - } - } catch (IOException e) { - try { - client.close(); - } catch (IOException e1) { - e1.printStackTrace(); - } - } - } - } - } + +package com.texttwist.server.services; +import com.texttwist.server.Server; +import com.texttwist.server.models.Dictionary; +import com.texttwist.server.models.Match; +import com.texttwist.server.models.servers.ThreadProxy; +import com.texttwist.server.tasks.ReceiveWords; +import constants.Config; +import models.Message; + +import java.net.*; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static java.nio.channels.SelectionKey.OP_ACCEPT; +import static java.nio.channels.SelectionKey.OP_READ; + +public class MessageService implements Runnable{ + + private int serverPort; + private ThreadProxy proxy; + private ReceiveWords wordsReceiver; + + private DatagramChannel datagramChannel; + private Selector selector = null; + private ExecutorService threadPool = Executors.newCachedThreadPool(); + private String dictionaryPath = "./Server/resources/dictionary"; + public static Dictionary dict; + SocketChannel client; + ByteBuffer bufferWords = ByteBuffer.allocate(1024); + ByteBuffer bufferMessages = ByteBuffer.allocate(1024); + + + public static List activeMatches = Collections.synchronizedList(new ArrayList<>()); + public static Integer multicastID = 30000; + + public MessageService(int port){ + this.serverPort = port; + } + + public void run(){ + + dict = new Dictionary(dictionaryPath); + try { + selector = Selector.open(); + + ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); + serverSocketChannel.configureBlocking(false); + serverSocketChannel.socket().bind(new InetSocketAddress(serverPort)); + serverSocketChannel.register(selector, OP_ACCEPT); + InetSocketAddress address = new InetSocketAddress(Config.WordsReceiverServerURI,Config.WordsReceiverServerPort); + datagramChannel = DatagramChannel.open(); + datagramChannel.configureBlocking(true); + datagramChannel.connect(address); + Server.logger.write("MessageService Service is running at "+this.serverPort+" port..."); + + wordsReceiver = new ReceiveWords(datagramChannel, bufferWords, bufferMessages, client); + threadPool.submit(wordsReceiver); + + } catch (IOException e) { + e.printStackTrace(); + } + + while (true) { + System.out.println("WAITING FOR MSG"); + try { + selector.select(); + } catch (IOException e) { + e.printStackTrace(); + } + + Iterator iter = selector.selectedKeys().iterator(); + while (iter.hasNext()) { + bufferMessages = ByteBuffer.allocate(1024); + bufferMessages.clear(); + client = null; + SelectionKey key = iter.next(); + iter.remove(); + + try { + switch (key.readyOps()) { + case OP_ACCEPT: + client = ((ServerSocketChannel) key.channel()).accept(); + client.configureBlocking(false); + client.register(selector, OP_READ); + break; + + case OP_READ: + client = (SocketChannel) key.channel(); + if (client.read(bufferMessages) != -1) { + bufferMessages.flip(); + String line = new String(bufferMessages.array(), bufferMessages.position(), bufferMessages.remaining()); + System.out.println(line); + if (line.startsWith("MESSAGE")) { + SessionsService.getInstance().printAll(); + Message msg = Message.toMessage(line); + proxy = new ThreadProxy(msg, client, bufferMessages); + threadPool.submit(proxy); + } + + if (line.startsWith("CLOSE")) { + client.close(); + } else if (line.startsWith("QUIT")) { + for (SelectionKey k : selector.keys()) { + k.cancel(); + k.channel().close(); + } + selector.close(); + return; + } + } else { + key.cancel(); + } + break; + + default: + break; + } + } catch (IOException e) { + try { + client.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + } + } + } } \ No newline at end of file diff --git a/Server/src/com/texttwist/server/components/NotificationServer.java b/Server/src/com/texttwist/server/services/NotificationService.java similarity index 88% rename from Server/src/com/texttwist/server/components/NotificationServer.java rename to Server/src/com/texttwist/server/services/NotificationService.java index 7ac298b..7c18c28 100644 --- a/Server/src/com/texttwist/server/components/NotificationServer.java +++ b/Server/src/com/texttwist/server/services/NotificationService.java @@ -1,62 +1,62 @@ -package com.texttwist.server.components; - -import interfaces.INotificationClient; -import interfaces.INotificationServer; - -import javax.swing.*; -import java.rmi.RemoteException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - - -/** - * Created by loke on 19/06/2017. - */ -public class NotificationServer implements INotificationServer { - - private List clients; - public NotificationServer() throws RemoteException { - super(); - clients = new ArrayList<>(); - } - - public synchronized void registerForCallback(INotificationClient clientInterface) throws RemoteException { - if(!clients.contains(clientInterface)){ - clients.add(clientInterface); - System.out.println(clientInterface); - System.out.println("New client registered"); - } - } - - public synchronized void unregisterForCallback(INotificationClient client) throws RemoteException { - if (clients.remove(client)) { - System.out.println("Client unregistered"); - } else { - System.out.println("Unable to unregister client"); - } - - } - - public synchronized void sendInvitations(String username, DefaultListModel users){ - Iterator i = clients.iterator(); - INotificationClient client = null; - System.out.println("Starting callbacks"); - while (i.hasNext()) { - client = (INotificationClient) i.next(); - try { - - System.out.println("SENDING INVITE TO "+users); - client.sendInvite(username, users); - } catch (RemoteException e) { - System.out.println("Sembra down"); - try { - unregisterForCallback(client); - } catch (RemoteException e1) { - e1.printStackTrace(); - } - } - } - - } -} +package com.texttwist.server.services; + +import interfaces.INotificationClient; +import interfaces.INotificationServer; + +import javax.swing.*; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + + +/** + * Created by loke on 19/06/2017. + */ +public class NotificationService implements INotificationServer { + + private List clients; + public NotificationService() throws RemoteException { + super(); + clients = new ArrayList<>(); + } + + public synchronized void registerForCallback(INotificationClient clientInterface) throws RemoteException { + if(!clients.contains(clientInterface)){ + clients.add(clientInterface); + System.out.println(clientInterface); + System.out.println("New client registered"); + } + } + + public synchronized void unregisterForCallback(INotificationClient client) throws RemoteException { + if (clients.remove(client)) { + System.out.println("Client unregistered"); + } else { + System.out.println("Unable to unregister client"); + } + + } + + public synchronized void sendInvitations(String username, DefaultListModel users){ + Iterator i = clients.iterator(); + INotificationClient client = null; + System.out.println("Starting callbacks"); + while (i.hasNext()) { + client = (INotificationClient) i.next(); + try { + + System.out.println("SENDING INVITE TO "+users); + client.sendInvite(username, users); + } catch (RemoteException e) { + System.out.println("Sembra down"); + try { + unregisterForCallback(client); + } catch (RemoteException e1) { + e1.printStackTrace(); + } + } + } + + } +} diff --git a/Server/src/com/texttwist/server/components/SessionsManager.java b/Server/src/com/texttwist/server/services/SessionsService.java similarity index 85% rename from Server/src/com/texttwist/server/components/SessionsManager.java rename to Server/src/com/texttwist/server/services/SessionsService.java index a2fa7bd..799dc26 100644 --- a/Server/src/com/texttwist/server/components/SessionsManager.java +++ b/Server/src/com/texttwist/server/services/SessionsService.java @@ -1,88 +1,87 @@ -package com.texttwist.server.components; -import interfaces.INotificationClient; -import models.Session; -import models.User; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -/** - * Created by loke on 17/06/2017. - */ -public class SessionsManager { - - private List sessions = Collections.synchronizedList(new ArrayList()); - private static class Holder { - static final SessionsManager INSTANCE = new SessionsManager(); - } - - public static SessionsManager getInstance() { - return Holder.INSTANCE; - } - - private SessionsManager(){} - - public boolean add(String userName, String token) { - remove(userName); - return sessions.add(new Session(new User(userName,"",0), token)); - } - - public void printAll(){ - Iterator i = sessions.iterator(); - while (i.hasNext()) { - Session elem = i.next(); - System.out.println(elem.account.userName + " | " + elem.token); - } - - } - - public boolean remove(String userName){ - if(exists(userName)) { - Session s = getSession(userName); - if(s != null) { - sessions.remove(s); - return true; - } - } - return false; - } - - public Session getSession(String userName) { - Iterator i = sessions.iterator(); - while (i.hasNext()) { - Session elem = i.next(); - if (elem.account.userName.equals(userName)) { - return elem; - } - } - return null; - - } - - public boolean exists(String userName) { - Iterator i = sessions.iterator(); - while (i.hasNext()) { - Session elem = i.next(); - if (elem.account.userName.equals(userName)) { - return true; - } - } - return false; - - } - - - public boolean isValidToken(String token) { - Iterator i = sessions.iterator(); - while (i.hasNext()) { - if (i.next().token.equals(token)) { - return true; - } - } - return false; - - } - -} +package com.texttwist.server.services; +import models.Session; +import models.User; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +/** + * Created by loke on 17/06/2017. + */ +public class SessionsService { + + private List sessions = Collections.synchronizedList(new ArrayList()); + private static class Holder { + static final SessionsService INSTANCE = new SessionsService(); + } + + public static SessionsService getInstance() { + return Holder.INSTANCE; + } + + private SessionsService(){} + + public boolean add(String userName, String token) { + remove(userName); + return sessions.add(new Session(new User(userName,"",0), token)); + } + + public void printAll(){ + Iterator i = sessions.iterator(); + while (i.hasNext()) { + Session elem = i.next(); + System.out.println(elem.account.userName + " | " + elem.token); + } + + } + + public boolean remove(String userName){ + if(exists(userName)) { + Session s = getSession(userName); + if(s != null) { + sessions.remove(s); + return true; + } + } + return false; + } + + public Session getSession(String userName) { + Iterator i = sessions.iterator(); + while (i.hasNext()) { + Session elem = i.next(); + if (elem.account.userName.equals(userName)) { + return elem; + } + } + return null; + + } + + public boolean exists(String userName) { + Iterator i = sessions.iterator(); + while (i.hasNext()) { + Session elem = i.next(); + if (elem.account.userName.equals(userName)) { + return true; + } + } + return false; + + } + + + public boolean isValidToken(String token) { + Iterator i = sessions.iterator(); + while (i.hasNext()) { + if (i.next().token.equals(token)) { + return true; + } + } + return false; + + } + +} diff --git a/Server/src/com/texttwist/server/tasks/CheckOnlineUsers.java b/Server/src/com/texttwist/server/tasks/CheckOnlineUsers.java index 4379a1e..db0c771 100644 --- a/Server/src/com/texttwist/server/tasks/CheckOnlineUsers.java +++ b/Server/src/com/texttwist/server/tasks/CheckOnlineUsers.java @@ -1,6 +1,6 @@ package com.texttwist.server.tasks; -import com.texttwist.server.components.SessionsManager; +import com.texttwist.server.services.SessionsService; import javax.swing.*; import java.util.concurrent.Callable; @@ -18,7 +18,7 @@ public class CheckOnlineUsers implements Callable { @Override public Boolean call() throws Exception { for(int i = 0; i < users.size(); i++){ - if(!(SessionsManager.getInstance().exists(users.get(i)))){ + if(!(SessionsService.getInstance().exists(users.get(i)))){ return false; } } diff --git a/Server/src/com/texttwist/server/tasks/ComputeHighscores.java b/Server/src/com/texttwist/server/tasks/ComputeHighscores.java index 4f52a8c..79b01c1 100644 --- a/Server/src/com/texttwist/server/tasks/ComputeHighscores.java +++ b/Server/src/com/texttwist/server/tasks/ComputeHighscores.java @@ -1,13 +1,11 @@ package com.texttwist.server.tasks; -import com.texttwist.server.components.AccountsManager; -import com.texttwist.server.components.JedisService; +import com.texttwist.server.services.AccountsService; +import com.texttwist.server.services.JedisService; import models.User; import javax.swing.*; -import java.util.ArrayList; import java.util.Comparator; -import java.util.List; import java.util.concurrent.Callable; /** @@ -21,16 +19,16 @@ public class ComputeHighscores implements Callable> { public DefaultListModel call() throws Exception { DefaultListModel l = new DefaultListModel<>(); - AccountsManager.getInstance().users.sort(new Comparator() { + AccountsService.getInstance().users.sort(new Comparator() { @Override public int compare(User o1, User o2) { return o2.score.compareTo(o1.score); } }); JedisService.removeAll("users"); - for(int i =0; i< AccountsManager.getInstance().users.size(); i++){ - l.addElement(AccountsManager.getInstance().users.get(i).userName+":"+AccountsManager.getInstance().users.get(i).score); - JedisService.add("users",AccountsManager.getInstance().users.get(i)); + for(int i = 0; i< AccountsService.getInstance().users.size(); i++){ + l.addElement(AccountsService.getInstance().users.get(i).userName+":"+ AccountsService.getInstance().users.get(i).score); + JedisService.add("users", AccountsService.getInstance().users.get(i)); } return l; } diff --git a/Server/src/com/texttwist/server/tasks/ComputeScore.java b/Server/src/com/texttwist/server/tasks/ComputeScore.java index 72a0762..351b185 100644 --- a/Server/src/com/texttwist/server/tasks/ComputeScore.java +++ b/Server/src/com/texttwist/server/tasks/ComputeScore.java @@ -1,24 +1,12 @@ package com.texttwist.server.tasks; -import com.texttwist.client.App; -import com.texttwist.server.components.AccountsManager; -import com.texttwist.server.components.JedisService; +import com.texttwist.server.services.AccountsService; import com.texttwist.server.models.Dictionary; import com.texttwist.server.models.Match; -import constants.Config; -import models.Message; import models.User; -import redis.clients.jedis.Jedis; import javax.swing.*; -import java.io.Serializable; -import java.net.DatagramPacket; -import java.net.InetAddress; -import java.net.MulticastSocket; -import java.util.List; import java.util.concurrent.Callable; -import static com.texttwist.server.components.GameServer.activeMatches; - /** * Created by loke on 27/06/2017. */ @@ -52,7 +40,7 @@ public class ComputeScore implements Callable { match.setScore(sender, score); System.out.println(score); - User u = AccountsManager.getInstance().findUser(sender); + User u = AccountsService.getInstance().findUser(sender); u.addScore(score); if(match.allPlayersSendedHisScore()) { diff --git a/Server/src/com/texttwist/server/tasks/GenerateLetters.java b/Server/src/com/texttwist/server/tasks/GenerateLetters.java index a15d09e..5e68c9f 100644 --- a/Server/src/com/texttwist/server/tasks/GenerateLetters.java +++ b/Server/src/com/texttwist/server/tasks/GenerateLetters.java @@ -1,12 +1,8 @@ package com.texttwist.server.tasks; -import com.texttwist.server.components.GameServer; +import com.texttwist.server.services.MessageService; import javax.swing.*; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.charset.Charset; -import java.nio.file.*; import java.util.concurrent.Callable; /** @@ -23,7 +19,7 @@ public class GenerateLetters implements Callable> { public DefaultListModel call() throws Exception { DefaultListModel l = new DefaultListModel(); - String word = GameServer.dict.getRandomWord(6, 7); + String word = MessageService.dict.getRandomWord(6, 7); for (int i = 0;i < word.length(); i++){ l.addElement(String.valueOf(word.charAt(i))); } diff --git a/Server/src/com/texttwist/server/tasks/JoinMatch.java b/Server/src/com/texttwist/server/tasks/JoinMatch.java index e931c13..3120103 100644 --- a/Server/src/com/texttwist/server/tasks/JoinMatch.java +++ b/Server/src/com/texttwist/server/tasks/JoinMatch.java @@ -5,7 +5,7 @@ import javafx.util.Pair; import javax.swing.*; import java.nio.channels.SocketChannel; import java.util.concurrent.Callable; -import static com.texttwist.server.components.GameServer.activeMatches; +import static com.texttwist.server.services.MessageService.activeMatches; /** * Created by loke on 23/06/2017. diff --git a/Server/src/com/texttwist/server/tasks/MatchTimeout.java b/Server/src/com/texttwist/server/tasks/MatchTimeout.java index f878e63..41ad1f7 100644 --- a/Server/src/com/texttwist/server/tasks/MatchTimeout.java +++ b/Server/src/com/texttwist/server/tasks/MatchTimeout.java @@ -1,17 +1,9 @@ package com.texttwist.server.tasks; -import com.sun.org.apache.xpath.internal.operations.Bool; import com.texttwist.server.models.Match; -import constants.Config; -import models.Message; -import java.net.DatagramPacket; -import java.net.InetAddress; -import java.net.MulticastSocket; import java.util.concurrent.Callable; -import static com.texttwist.server.components.GameServer.activeMatches; - /** * Created by loke on 27/06/2017. */ diff --git a/Server/src/com/texttwist/server/tasks/ReceiveWords.java b/Server/src/com/texttwist/server/tasks/ReceiveWords.java index cb5bbc1..f9e6753 100644 --- a/Server/src/com/texttwist/server/tasks/ReceiveWords.java +++ b/Server/src/com/texttwist/server/tasks/ReceiveWords.java @@ -1,6 +1,6 @@ package com.texttwist.server.tasks; -import com.texttwist.server.components.SessionsManager; +import com.texttwist.server.services.SessionsService; import com.texttwist.server.models.Match; import constants.Config; import models.Message; @@ -53,7 +53,7 @@ public class ReceiveWords implements Callable{ System.out.println(rcv); if (rcv.startsWith("MESSAGE")) { msg = Message.toMessage(rcv); - if(SessionsManager.getInstance().isValidToken(msg.token)) { + if(SessionsService.getInstance().isValidToken(msg.token)) { System.out.println(msg.sender); Match match = Match.findMatchByPlayer(msg.sender); threadPool.submit(new ComputeScore(msg.sender, msg.data, match)); diff --git a/Server/src/com/texttwist/server/tasks/SendInvitations.java b/Server/src/com/texttwist/server/tasks/SendInvitations.java index db1693c..8b6676f 100644 --- a/Server/src/com/texttwist/server/tasks/SendInvitations.java +++ b/Server/src/com/texttwist/server/tasks/SendInvitations.java @@ -1,15 +1,8 @@ package com.texttwist.server.tasks; import com.texttwist.server.Server; -import com.texttwist.server.components.NotificationServer; -import com.texttwist.server.components.SessionsManager; -import constants.Config; -import interfaces.INotificationServer; import javax.swing.*; -import java.rmi.registry.LocateRegistry; -import java.rmi.registry.Registry; -import java.rmi.server.UnicastRemoteObject; import java.util.concurrent.Callable; /** diff --git a/notificationServer.log b/notificationServer.log index 3efbe52..90dd9f2 100644 --- a/notificationServer.log +++ b/notificationServer.log @@ -1296,3 +1296,51 @@ LOGGER (Server): Thu Jul 13 03:30:57 CEST 2017 - Invoked login with username=asd LOGGER (Server): Thu Jul 13 03:30:57 CEST 2017 - Login successfull LOGGER (Server): Thu Jul 13 03:31:02 CEST 2017 - Invoked login with username=a AND password=a LOGGER (Server): Thu Jul 13 03:31:02 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:22:29 CEST 2017 - Server starting ... +LOGGER (Server): Thu Jul 13 14:22:30 CEST 2017 - Auth Service running at 9999 port... +LOGGER (Server): Thu Jul 13 14:22:30 CEST 2017 - GameService Service is running at 10000 port... +LOGGER (Server): Thu Jul 13 14:22:30 CEST 2017 - Server started +LOGGER (Server): Thu Jul 13 14:22:35 CEST 2017 - Invoked login with username=a AND password=a +LOGGER (Server): Thu Jul 13 14:22:35 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:22:39 CEST 2017 - Invoked login with username=b AND password=b +LOGGER (Server): Thu Jul 13 14:22:39 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:22:46 CEST 2017 - Invoked login with username=dd AND password=dd +LOGGER (Server): Thu Jul 13 14:22:46 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:22:50 CEST 2017 - Invoked login with username=asd AND password=asd +LOGGER (Server): Thu Jul 13 14:22:50 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:23:30 CEST 2017 - Server starting ... +LOGGER (Server): Thu Jul 13 14:23:31 CEST 2017 - Auth Service running at 9999 port... +LOGGER (Server): Thu Jul 13 14:23:31 CEST 2017 - GameService Service is running at 10000 port... +LOGGER (Server): Thu Jul 13 14:23:31 CEST 2017 - Server started +LOGGER (Server): Thu Jul 13 14:23:40 CEST 2017 - Invoked login with username=asd AND password=asd +LOGGER (Server): Thu Jul 13 14:23:40 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:23:43 CEST 2017 - Invoked login with username=a AND password=a +LOGGER (Server): Thu Jul 13 14:23:43 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:23:49 CEST 2017 - Invoked login with username=b AND password=b +LOGGER (Server): Thu Jul 13 14:23:49 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:23:55 CEST 2017 - Invoked login with username=dd AND password=dd +LOGGER (Server): Thu Jul 13 14:23:55 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:28:32 CEST 2017 - Server starting ... +LOGGER (Server): Thu Jul 13 14:28:33 CEST 2017 - Auth Service running at 9999 port... +LOGGER (Server): Thu Jul 13 14:28:33 CEST 2017 - GameService Service is running at 10000 port... +LOGGER (Server): Thu Jul 13 14:28:33 CEST 2017 - Server started +LOGGER (Server): Thu Jul 13 14:28:43 CEST 2017 - Invoked login with username=a AND password=a +LOGGER (Server): Thu Jul 13 14:28:43 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:28:46 CEST 2017 - Invoked login with username=b AND password=b +LOGGER (Server): Thu Jul 13 14:28:46 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:28:49 CEST 2017 - Invoked login with username=dd AND password=dd +LOGGER (Server): Thu Jul 13 14:28:49 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:28:54 CEST 2017 - Invoked login with username=asd AND password=asd +LOGGER (Server): Thu Jul 13 14:28:54 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:37:57 CEST 2017 - Services starting ... +LOGGER (Server): Thu Jul 13 14:37:57 CEST 2017 - AuthService Service running at 9999 port... +LOGGER (Server): Thu Jul 13 14:37:57 CEST 2017 - Services started correctly ... +LOGGER (Server): Thu Jul 13 14:37:57 CEST 2017 - MessageService Service is running at 10000 port... +LOGGER (Server): Thu Jul 13 14:38:06 CEST 2017 - Invoked login with username=asd AND password=asd +LOGGER (Server): Thu Jul 13 14:38:06 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:38:09 CEST 2017 - Invoked login with username=a AND password=a +LOGGER (Server): Thu Jul 13 14:38:09 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:38:13 CEST 2017 - Invoked login with username=b AND password=b +LOGGER (Server): Thu Jul 13 14:38:13 CEST 2017 - Login successfull +LOGGER (Server): Thu Jul 13 14:38:17 CEST 2017 - Invoked login with username=dd AND password=dd +LOGGER (Server): Thu Jul 13 14:38:17 CEST 2017 - Login successfull