Compare commits

..

1 commit

Author SHA1 Message Date
Lorenzo Iovino
f94b697b59 up 2017-07-07 16:32:54 +02:00
104 changed files with 14614 additions and 3114 deletions

1
.gitignore vendored
View file

@ -1,3 +1,2 @@
log log
out/ out/
*.log

View file

@ -1,10 +0,0 @@
<component name="ArtifactManager">
<artifact type="jar" name="Client:jar">
<output-path>$PROJECT_DIR$/out/artifacts/Client_jar</output-path>
<root id="archive" name="Client.jar">
<element id="module-output" name="Client" />
<element id="module-output" name="Commons" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/com/github/cliftonlabs/json-simple/2.1.2/json-simple-2.1.2.jar" path-in-jar="/" />
</root>
</artifact>
</component>

View file

@ -1,14 +0,0 @@
<component name="ArtifactManager">
<artifact type="jar" name="Server:jar">
<output-path>$PROJECT_DIR$/out/artifacts/Server_jar</output-path>
<root id="archive" name="Server.jar">
<element id="module-output" name="Server" />
<element id="module-output" name="Commons" />
<element id="module-output" name="Client" />
<element id="library" level="application" name="jedis-2.1.0-sources" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/redis/clients/jedis/2.9.0/jedis-2.9.0.jar" path-in-jar="/" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/org/apache/commons/commons-pool2/2.4.2/commons-pool2-2.4.2.jar" path-in-jar="/" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/com/github/cliftonlabs/json-simple/2.1.2/json-simple-2.1.2.jar" path-in-jar="/" />
</root>
</artifact>
</component>

View file

@ -1,13 +0,0 @@
<component name="ArtifactManager">
<artifact type="jar" name="TextTwist:jar">
<output-path>$PROJECT_DIR$/out/artifacts/TextTwist_jar</output-path>
<root id="archive" name="TextTwist.jar">
<element id="module-output" name="Client" />
<element id="module-output" name="Commons" />
<element id="module-output" name="Server" />
<element id="module-output" name="TextTwist" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/com/github/cliftonlabs/json-simple/2.1.2/json-simple-2.1.2.jar" path-in-jar="/" />
<element id="dir-copy" path="$PROJECT_DIR$/Server/resources" />
</root>
</artifact>
</component>

View file

@ -1,11 +0,0 @@
<component name="libraryTable">
<library name="redis.clients:jedis:2.9.0" type="repository">
<properties maven-id="redis.clients:jedis:2.9.0" />
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/redis/clients/jedis/2.9.0/jedis-2.9.0.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/apache/commons/commons-pool2/2.4.2/commons-pool2-2.4.2.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component>

1957
.idea/workspace.xml generated

File diff suppressed because it is too large Load diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

View file

@ -1,3 +0,0 @@
Manifest-Version: 1.0
Main-Class: com.texttwist.client.Main

View file

@ -1,24 +1,19 @@
package com.texttwist.client; package com.texttwist.client;
import com.texttwist.client.services.GameService;
import com.texttwist.client.services.AuthService; import com.texttwist.client.services.AuthService;
import com.texttwist.client.pages.HomePage; import com.texttwist.client.pages.HomePage;
import com.texttwist.client.services.NotificationClientService; import com.texttwist.client.models.Game;
import com.texttwist.client.services.NotificationClient;
import constants.Config; import constants.Config;
import interfaces.INotificationClient; import interfaces.INotificationClient;
import interfaces.INotificationServer; import interfaces.INotificationServer;
import models.Session; import models.Session;
import utilities.Logger; import utilities.Logger;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SocketChannel;
import java.rmi.NotBoundException; import java.rmi.NotBoundException;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry; import java.rmi.registry.LocateRegistry;
@ -26,106 +21,56 @@ import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject; import java.rmi.server.UnicastRemoteObject;
/** /**
* Author: Lorenzo Iovino on 13/06/2017. * Created by loke on 13/06/2017.
* Description: The App entrypoint.
* Here is possible to declare services globally accessible.
*/ */
public class App extends JFrame { public class App extends JFrame {
private static InetSocketAddress clientTCPSocketAddress = new InetSocketAddress(Config.MessageServiceURI, Config.MessageServicePort);
public static InetSocketAddress clientUDPSocketAddress = new InetSocketAddress(Config.WordsReceiverServiceURI, Config.WordsReceiverServicePort);
private static InetAddress clientMulticastSocketAddress;
public static AuthService authService; public static AuthService authService;
public static GameService gameService;
public static Logger logger;
public static Session session; public static Session session;
public static Game game;
public static JFrame app; public static JFrame app;
public static INotificationClient notificationStub;
public static MulticastSocket clientMulticast;
public static SocketChannel clientTCP;
public static DatagramChannel clientUDP;
public App() throws IOException { public App() throws IOException {
setPreferredSize( new Dimension( 640, 480 )); setPreferredSize( new Dimension( 640, 480 ));
setSize(new Dimension(640,480)); setSize(new Dimension(640,480));
setLocation(100,100); setLocation(100,100);
setResizable( false ); setResizable( false );
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*Setup logger*/ //Definitions of registry for auth
String id = ManagementFactory.getRuntimeMXBean().getName(); long id = Thread.currentThread().getId();
logger = new Logger(new File("./client_"+id+".log"), "Client"+id, true); Logger logger = new Logger(new File("./client_"+id+".log"), "Client"+id);
logger.write("Client starting ...");
/*Load fonts*/ Logger.write("Client starting ...");
try { try {
GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment(); Registry registry = LocateRegistry.getRegistry(Config.NotificationServerStubPort);
graphicsEnvironment.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File( INotificationServer server = (INotificationServer) registry.lookup(Config.NotificationServerName);
new File("./Client/resources/fonts/DK Trained Monkey.otf").getCanonicalPath())));
} catch (IOException|FontFormatException e) { /* si registra per la callback */
logger.write("APP: Font not found!"); System.out.println("Registering for callback");
INotificationClient callbackObj = new NotificationClient();
INotificationClient stub = (INotificationClient) UnicastRemoteObject.exportObject(callbackObj, 0);
server.registerForCallback(stub);
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
} }
/*services*/ //Init models
gameService = new GameService(); game = new Game();
//Init services
authService = new AuthService(); authService = new AuthService();
app = this; app = this;
new HomePage(this); HomePage home = new HomePage(this);
}
public static void registerForNotifications() throws RemoteException, NotBoundException {
Registry registry = LocateRegistry.getRegistry(Config.NotificationServiceStubPort);
INotificationClient callbackObj = new NotificationClientService();
notificationStub = (INotificationClient) UnicastRemoteObject.exportObject(callbackObj, 0);
INotificationServer notificationServer = (INotificationServer) registry.lookup(Config.NotificationServiceName);
notificationServer.registerForCallback(notificationStub);
}
public static void openClientTCPSocket(){
try {
clientTCP = SocketChannel.open(clientTCPSocketAddress);
clientTCP.configureBlocking(false);
} catch (IOException e) {
logger.write("APP: Can't open client TCP socket!");
}
}
public static void openClientMulticastSocket(Integer multicastId){
try {
App.gameService.setMulticastId(multicastId);
clientMulticastSocketAddress = InetAddress.getByName(Config.ScoreMulticastServiceURI);
clientMulticast = new MulticastSocket(gameService.multicastId);
clientMulticast.joinGroup(clientMulticastSocketAddress);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void closeClientMulticastSocket(){
//Leave group and close multicast socket
try {
App.clientMulticast.leaveGroup(InetAddress.getByName(Config.ScoreMulticastServiceURI));
App.clientMulticast.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void openClientUDPSocket(){
try {
clientUDP = DatagramChannel.open();
clientUDP.bind(null);
} catch (IOException e) {
e.printStackTrace();
}
} }
public static Point getWindowsPosition(){ public static Point getWindowsPosition(){
return new Point(app.getX(), app.getY()); return new Point(app.getX(), app.getY());
} }
} }

View file

@ -1,14 +1,24 @@
package com.texttwist.client; package com.texttwist.client;
import java.awt.*;
import java.io.File;
import java.io.IOException; import java.io.IOException;
/**
* Author: Lorenzo Iovino on 13/06/2017.
* Description: Main
*/
public class Main { public class Main {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
new App(); System.out.println("Client started");
//Load fonts
try {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File(
new File("./Client/resources/fonts/DK Trained Monkey.otf").getCanonicalPath())));
} catch (IOException|FontFormatException e) {
System.out.println("Font non caricato correttamente");
}
App entrypoint = new App();
} }
} }

View file

@ -1,58 +1,44 @@
package com.texttwist.client.controllers; package com.texttwist.client.controllers;
import com.texttwist.client.App; import com.texttwist.client.App;
import com.texttwist.client.pages.GamePage; import com.texttwist.client.pages.GamePage;
import com.texttwist.client.tasks.SendWords; import com.texttwist.client.tasks.SendWords;
import com.texttwist.client.tasks.StartGame;
import com.texttwist.client.tasks.WaitForPlayers; import com.texttwist.client.tasks.WaitForPlayers;
import com.texttwist.client.tasks.WaitForScore; import com.texttwist.client.tasks.WaitForScore;
import javax.swing.*; import javax.swing.*;
import java.util.concurrent.Callable;
import static com.texttwist.client.App.gameService;
/** /**
* Author: Lorenzo Iovino on 27/06/2017. * GamePage Controller
* Description: Controller of the Game Page
*/ */
public class GameController { public class GameController {
private GamePage gamePage; private GamePage game;
public GameController(GamePage game){
this.game = game;
}
public DefaultListModel<String> getLetters(){
return App.game.letters;
}
public DefaultListModel<String> getWords() {
return App.game.words;
}
public SwingWorker waitForPlayers(SwingWorker callback) {
return new WaitForPlayers(callback);
}
private SwingWorker waitForScore(SwingWorker callback){ private SwingWorker waitForScore(SwingWorker callback){
return new WaitForScore(callback); return new WaitForScore(callback);
} }
private SwingWorker sendWords(SwingWorker callback){ public SwingWorker sendWords(SwingWorker callback){
return new SendWords(gameService.words, waitForScore(callback)); return new SendWords(App.game.words, waitForScore(callback));
} }
public GameController(GamePage gamePage){ public SwingWorker startGame() {
this.gamePage = gamePage; return new StartGame(App.game.letters, game);
}
public SwingWorker waitForPlayers(Callable<Void> callback) {
return new WaitForPlayers(callback);
}
public Callable<Void> startGame = new Callable<Void>() {
@Override
public Void call() throws Exception {
App.gameService.start();
gamePage.showGameIsReadyAlert();
return null;
}
};
public DefaultListModel<String> getLetters() {
return gameService.getLetters();
}
public SwingWorker timeIsOver(SwingWorker callback) {
return sendWords(callback);
}
public DefaultListModel<String> getWords(){
return gameService.getWords();
} }
} }

View file

@ -1,26 +1,28 @@
package com.texttwist.client.controllers; package com.texttwist.client.controllers;
import com.texttwist.client.App;
import com.texttwist.client.pages.HighscoresPage; import com.texttwist.client.pages.HighscoresPage;
import com.texttwist.client.tasks.FetchHighscore; import com.texttwist.client.tasks.FetchHighscore;
import javafx.util.Pair; import javafx.util.Pair;
import javax.swing.*;
import java.io.ObjectOutput;
import java.util.concurrent.Callable;
import static com.texttwist.client.App.gameService; import javax.swing.*;
/** /**
* Author: Lorenzo Iovino on 27/06/2017. * Highscores Controller
* Description: Controller of the Highscore Page
*/ */
public class HighscoresController { public class HighscoresController {
public SwingWorker fetchHighscores(Callable<Void> callback) { private HighscoresPage highscoresPage;
return new FetchHighscore(callback);
public HighscoresController(HighscoresPage highscoresPage){
this.highscoresPage = highscoresPage;
}
public SwingWorker fetchHighscores () {
return new FetchHighscore(highscoresPage);
} }
public DefaultListModel<Pair<String,Integer>> getRanks(Boolean isPartialRank) { public DefaultListModel<Pair<String,Integer>> getRanks(Boolean isPartialRank) {
return isPartialRank ? gameService.ranks : gameService.globalRanks; return isPartialRank ? App.game.ranks : App.game.globalRanks;
} }
} }

View file

@ -1,28 +1,22 @@
package com.texttwist.client.controllers; package com.texttwist.client.controllers;
import com.texttwist.client.App; import com.texttwist.client.App;
import models.Response; import models.Response;
import models.Session; import models.Session;
import models.User; import models.User;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.rmi.NotBoundException; import java.rmi.NotBoundException;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import static com.texttwist.client.App.authService;
/** /**
* Author: Lorenzo Iovino on 20/06/2017. * Created by loke on 15/06/2017.
* Description: Controller of the Home Page
*/ */
public class HomeController { public class HomeController {
public Response login(String userName, String password) throws RemoteException, NotBoundException, MalformedURLException { public Response login(String userName, String password) throws RemoteException, NotBoundException, MalformedURLException {
Response res = authService.login(userName,password); Response res = App.authService.login(userName,password);
System.out.println(res.data);
if (res.code == 200){ if (res.code == 200){
try {
App.registerForNotifications();
} catch (RemoteException e) {
App.logger.write("AUTH SERVICE: Can't register for notification");
}
App.session = (new Session(new User(userName,password,0), res.data.get("token").toString())); App.session = (new Session(new User(userName,password,0), res.data.get("token").toString()));
} }
return res; return res;

View file

@ -1,21 +0,0 @@
package com.texttwist.client.controllers;
import com.texttwist.client.App;
import com.texttwist.client.tasks.JoinMatch;
import javax.swing.*;
/**
* Author: Lorenzo Iovino on 13/072017.
* Description: Controller of the Match Request Page
*/
public class MatchRequestController {
public DefaultListModel<String> getPendingList(){
return App.gameService.pendingList;
}
public void joinMatch(String matchName){
new JoinMatch(matchName).execute();
}
}

View file

@ -1,18 +1,22 @@
package com.texttwist.client.controllers; package com.texttwist.client.controllers;
import com.texttwist.client.tasks.InvitePlayers; import com.texttwist.client.App;
import javax.swing.*; import javax.swing.*;
import static com.texttwist.client.App.gameService; import java.io.IOException;
/** /**
* Author: Lorenzo Iovino on 18/06/2017. * Created by loke on 18/06/2017.
* Description: Controller of the Match Setup Page
*/ */
public class MatchSetupController { public class MatchSetupController {
public void play(DefaultListModel<String> userNames) { public Object play(DefaultListModel<String> userNames) {
new InvitePlayers(userNames).execute(); try {
return App.game.play(userNames);
} catch (IOException e) {
e.printStackTrace();
} }
return null;
}
} }

View file

@ -2,27 +2,21 @@ package com.texttwist.client.controllers;
import com.texttwist.client.App; import com.texttwist.client.App;
import models.Response; import models.Response;
import models.Session;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.rmi.NotBoundException; import java.rmi.NotBoundException;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import static com.texttwist.client.App.authService;
/** /**
* Author: Lorenzo Iovino on 17/06/2017. * Created by loke on 17/06/2017.
* Description: Controller of the Menu Page
*/ */
public class MenuController { public class MenuController {
public void logout() throws RemoteException, NotBoundException, MalformedURLException { public Response logout(String userName) throws RemoteException, NotBoundException, MalformedURLException {
Response res = authService.logout(App.session.account.userName, App.notificationStub); Response res = App.authService.logout(userName);
if (res.code == 200){ if (res.code == 200){
App.session = null; App.session = null;
} }
} return res;
public Session getSession(){
return App.session;
} }
} }

View file

@ -1,18 +1,18 @@
package com.texttwist.client.controllers; package com.texttwist.client.controllers;
import com.texttwist.client.App;
import models.Response; import models.Response;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.rmi.NotBoundException; import java.rmi.NotBoundException;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import static com.texttwist.client.App.authService;
/** /**
* Author: Lorenzo Iovino on 17/06/2017. * Created by loke on 17/06/2017.
* Description: Controller of the Register Page
*/ */
public class RegisterController { public class RegisterController {
public Response register(String userName, String password) throws RemoteException, NotBoundException, MalformedURLException { public Response register(String userName, String password) throws RemoteException, NotBoundException, MalformedURLException {
return authService.register(userName,password); return App.authService.register(userName,password);
} }
} }

View file

@ -0,0 +1,122 @@
package com.texttwist.client.models;
import com.texttwist.client.App;
import com.texttwist.client.pages.GamePage;
import com.texttwist.client.pages.MenuPage;
import com.texttwist.client.pages.Page;
import com.texttwist.client.tasks.InvitePlayers;
import com.texttwist.client.ui.TTDialog;
import constants.Config;
import javafx.util.Pair;
import models.Message;
import javax.swing.*;
import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.*;
/**
* Created by loke on 18/06/2017.
*/
public class Game {
public Integer multicastId = 0 ;
public DefaultListModel<String> pendingList = new DefaultListModel<String>();
private ByteBuffer buffer = ByteBuffer.allocate(1024);
public DefaultListModel<String> words = new DefaultListModel<String>();
public DefaultListModel<String> letters = new DefaultListModel<String>();
public DefaultListModel<Pair<String,Integer>> ranks = new DefaultListModel<>();
public DefaultListModel<Pair<String,Integer>> globalRanks = new DefaultListModel<>();
public MulticastSocket multicastSocket;
public SocketChannel clientSocket = null;
public Game(){
InetSocketAddress socketAddress = new InetSocketAddress(Config.GameServerURI, Config.GameServerPort);
try {
clientSocket = SocketChannel.open(socketAddress);
clientSocket.configureBlocking(false);
System.out.println("Join multicast group");
} catch (IOException e) {
e.printStackTrace();
}
}
public void newMatch(String userName) {
//Aggiungi alla lista di inviti
try {
this.addToPendingList(userName);
} catch (IOException e) {
e.printStackTrace();
}
//Visualizza popup
new TTDialog("success", "New invitation from: " + userName + "!",
new Callable() {
@Override
public Object call() throws Exception {
App.game.joinMatch(userName);
return null;
}
},
new Callable() {
@Override
public Object call() throws Exception {
return new MenuPage(Page.window);
}
});
}
public void setWords(DefaultListModel<String> words){
this.words = words;
}
public void setLetters(DefaultListModel<String> letters){
this.letters = letters;
}
public void joinMatch(String matchName) {
//Svuota la lista dei game pendenti e joina il game selezionato
this.pendingList.clear();
try {
//Invia tcp req a server per dirgli che sto joinando
DefaultListModel<String> matchNames = new DefaultListModel<String>();
matchNames.addElement(matchName);
System.out.println("STO JOINANDO");
Message message = new Message("JOIN_GAME", App.session.account.userName, App.session.token, matchNames);
byte[] byteMessage = new String(message.toString()).getBytes();
buffer = ByteBuffer.wrap(byteMessage);
clientSocket.write(buffer);
new GamePage(Page.window);
} catch (IOException e) {
e.printStackTrace();
}
}
public Object play(DefaultListModel<String> userNames) throws IOException {
SwingWorker worker = new InvitePlayers(userNames,clientSocket);
worker.execute();
return null;
}
public void setMulticastId(Integer multicastId){
this.multicastId = multicastId;
}
public void addToPendingList(String username) throws IOException {
pendingList.addElement(username);
}
}

View file

@ -1,5 +1,4 @@
package com.texttwist.client.pages; package com.texttwist.client.pages;
import com.texttwist.client.controllers.GameController; import com.texttwist.client.controllers.GameController;
import constants.Config; import constants.Config;
import constants.Palette; import constants.Palette;
@ -10,37 +9,34 @@ import java.io.IOException;
import java.util.concurrent.*; import java.util.concurrent.*;
/** /**
* Author: Lorenzo Iovino on 27/06/2017. * GamePage Page
* Description: Game Page
*/ */
public class GamePage extends Page { public class GamePage extends Page {
private TTContainer gameContainer; private TTContainer gameContainer;
private TTGameBox gameBox;
private GameController gameController; private GameController gameController;
public Timer timer; public Timer timer;
//All the spawning points /*Spawnig points fixed and not modifiable*/
private final DefaultListModel<Point> letterSpawningPoints = setLetterSpawningPoint(); private final DefaultListModel<Point> letterSpawningPoints = setLetterSpawningPoint();
//Available spawning points
/*Available spawning points*/
private DefaultListModel<Point> availableLetterSpawningPoint = new DefaultListModel<>(); private DefaultListModel<Point> availableLetterSpawningPoint = new DefaultListModel<>();
public GamePage(JFrame window) throws IOException { public GamePage(JFrame window) throws IOException {
super(window); super(window);
gameController = new GameController(this); gameController = new GameController(this);
//Reset and set spawning point for letters
availableLetterSpawningPoint.clear(); availableLetterSpawningPoint.clear();
availableLetterSpawningPoint = letterSpawningPoints; availableLetterSpawningPoint = letterSpawningPoints;
gameController.waitForPlayers(gameController.startGame()).execute();
//Wait for players, then when all players joined start the game
gameController.waitForPlayers(gameController.startGame).execute();
createUIComponents(); createUIComponents();
window.setVisible(true); window.setVisible(true);
} }
/*Occupy a random position of the available spawning points, if positions ends (can't happen) use position (0,0)*/
private Point occupyRandomPosition(){ private Point occupyRandomPosition(){
if(availableLetterSpawningPoint.size() > 1) { if(availableLetterSpawningPoint.size() > 1) {
int index = ThreadLocalRandom.current().nextInt(0, letterSpawningPoints.size() - 1); int index = ThreadLocalRandom.current().nextInt(0, letterSpawningPoints.size() - 1);
Point placeholder = letterSpawningPoints.get(index); Point placeholder = letterSpawningPoints.get(index);
@ -51,6 +47,18 @@ public class GamePage extends Page {
return new Point(0,0); return new Point(0,0);
} }
private SwingWorker timeIsOver() {
return gameController.sendWords(new SwingWorker() {
@Override
protected Object doInBackground() throws Exception {
new HighscoresPage(window,true);
return null;
}
}
);
}
private DefaultListModel<Point> setLetterSpawningPoint(){ private DefaultListModel<Point> setLetterSpawningPoint(){
DefaultListModel<Point> l = new DefaultListModel<>(); DefaultListModel<Point> l = new DefaultListModel<>();
@ -81,12 +89,11 @@ public class GamePage extends Page {
public void showLetters(){ public void showLetters(){
/* Place letters in an available random spawning point */ /* Place letters in a available random spawning point */
DefaultListModel<String> letters = gameController.getLetters(); for(int i = 0; i < gameController.getLetters().size(); i++){
for(int i = 0; i < letters.size()-1; i++){
new TTLetter( new TTLetter(
occupyRandomPosition(), occupyRandomPosition(),
letters.get(i), gameController.getLetters().get(i),
gameContainer gameContainer
); );
} }
@ -95,19 +102,6 @@ public class GamePage extends Page {
window.revalidate(); window.revalidate();
} }
public void showGameIsReadyAlert(){
//Mostra pannello di conferma che le lettere sono tutte arrivate
new TTDialog("success", "<html>Game is ready. <br/>Press OK to start!</html>",
new Callable() {
@Override
public Object call() throws Exception {
showLetters();
timer.start();
return null;
}
}, null);
}
@Override @Override
public void createUIComponents() throws IOException { public void createUIComponents() throws IOException {
@ -121,7 +115,7 @@ public class GamePage extends Page {
root root
); );
new TTGameBox( gameBox = new TTGameBox(
new Point(150, 90), new Point(150, 90),
new Dimension(250, 40), new Dimension(250, 40),
"Insert word and Press ENTER!", "Insert word and Press ENTER!",
@ -133,15 +127,9 @@ public class GamePage extends Page {
timer = addTimer( timer = addTimer(
footer, footer,
new Font(Palette.numberFont.getFontName(), Font.BOLD, 35), new Font(Palette.inputBox_font.getFontName(), Font.BOLD, 40),
gameController.timeIsOver(new SwingWorker() { timeIsOver(),
@Override Config.timeoutGame
protected Object doInBackground() throws Exception {
new HighscoresPage(window,true);
return null;
}
}),
Config.gameTimeout
); );
} }
} }

View file

@ -9,31 +9,28 @@ import java.io.IOException;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 22/06/2017. * Highscores Page
* Description: Highscores Page
*/ */
public class HighscoresPage extends Page{ public class HighscoresPage extends Page{
private TTContainer highscoreContainer; private TTContainer highscoreContainer;
private Boolean isPartialScore; private Boolean isPartialScore;
private TTScrollList highscoreList;
public JFrame window; public JFrame window;
private HighscoresController highscoreController; private HighscoresController highscoreController;
HighscoresPage(JFrame window, Boolean isPartialScore) throws IOException { public HighscoresPage(JFrame window, Boolean isPartialScore) throws IOException {
super(window); super(window);
this.window = window; this.window = window;
this.isPartialScore = isPartialScore; this.isPartialScore = isPartialScore;
highscoreController = new HighscoresController(this);
highscoreController = new HighscoresController(); highscoreController.fetchHighscores().execute();
highscoreController.fetchHighscores(showHighscoreList).execute();
createUIComponents(); createUIComponents();
window.setVisible(true); window.setVisible(true);
} }
public Callable<Void> showHighscoreList = new Callable<Void>() { public void showHighscoreList(){
@Override highscoreList = new TTScrollList(
public Void call() throws Exception {
new TTScrollList(
new Point(20, 60), new Point(20, 60),
new Dimension(515, 142), new Dimension(515, 142),
highscoreController.getRanks(isPartialScore), highscoreController.getRanks(isPartialScore),
@ -41,9 +38,7 @@ public class HighscoresPage extends Page{
); );
window.revalidate(); window.revalidate();
window.repaint(); window.repaint();
return null;
} }
};
@Override @Override
public void createUIComponents() throws IOException { public void createUIComponents() throws IOException {
@ -57,11 +52,11 @@ public class HighscoresPage extends Page{
root root
); );
new TTLabel( TTLabel title = new TTLabel(
this.isPartialScore ? new Point(120,0) : new Point(200,0), this.isPartialScore ? new Point(150,0) : new Point(200,0),
new Dimension(350,50), new Dimension(350,50),
this.isPartialScore ? "Scores of the match" : "Highscores", this.isPartialScore ? "Scores of the match" : "Highscores",
new Font(Palette.textFont.getFontName(), Font.ITALIC, 34), new Font(Palette.inputBox_font.getFontName(), Font.ITALIC, 38),
null, null,
highscoreContainer highscoreContainer
); );

View file

@ -1,5 +1,4 @@
package com.texttwist.client.pages; package com.texttwist.client.pages;
import com.texttwist.client.controllers.HomeController; import com.texttwist.client.controllers.HomeController;
import constants.Palette; import constants.Palette;
import com.texttwist.client.ui.*; import com.texttwist.client.ui.*;
@ -9,10 +8,6 @@ import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/**
* Author: Lorenzo Iovino on 23/06/2017.
* Description: Home Page
*/
public class HomePage extends Page { public class HomePage extends Page {
private HomeController homeController; private HomeController homeController;
@ -78,7 +73,7 @@ public class HomePage extends Page {
new Point(70,200), new Point(70,200),
new Dimension(350,50), new Dimension(350,50),
"Don't have an account?", "Don't have an account?",
new Font(Palette.textFont.getFontName(), Font.ITALIC, 26), new Font(Palette.inputBox_font.getFontName(), Font.ITALIC, 24),
null, null,
loginDataContainer loginDataContainer
); );
@ -86,8 +81,8 @@ public class HomePage extends Page {
new TTLabelBtn( new TTLabelBtn(
new Point(360, 200), new Point(360, 200),
new Dimension(210, 50), new Dimension(210, 50),
"Register!", "RegisterPage!",
new Font(Palette.textFont.getFontName(), Font.BOLD, 30), new Font(Palette.inputBox_font.getFontName(), Font.BOLD, 34),
null, null,
new Callable<Object>() { new Callable<Object>() {
@Override @Override

View file

@ -1,6 +1,6 @@
package com.texttwist.client.pages; package com.texttwist.client.pages;
import com.texttwist.client.controllers.MatchRequestController; import com.texttwist.client.App;
import constants.Palette; import constants.Palette;
import com.texttwist.client.ui.*; import com.texttwist.client.ui.*;
import javax.swing.*; import javax.swing.*;
@ -11,26 +11,24 @@ import java.io.IOException;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 27/06/2017. * MatchRequest Page
* Description: MatchRequest Page
*/ */
public class MatchRequestsPage extends Page{ public class MatchRequestsPage extends Page{
private MatchRequestController matchRequestController; public TTContainer matchsContainer;
MatchRequestsPage(JFrame window) throws IOException { MatchRequestsPage(JFrame window) throws IOException {
super(window); super(window);
matchRequestController = new MatchRequestController();
createUIComponents(); createUIComponents();
window.setVisible(true); window.setVisible(true);
} }
@Override @Override
public void createUIComponents() throws IOException { public void createUIComponents() throws IOException {
addLogo(root); addLogo(root);
TTContainer matchsContainer = new TTContainer( matchsContainer = new TTContainer(
null, null,
new Dimension(1150, 220), new Dimension(1150,220),
Palette.root_backgroundColor, Palette.root_backgroundColor,
-1, -1,
root root
@ -40,7 +38,7 @@ public class MatchRequestsPage extends Page{
new Point(150,0), new Point(150,0),
new Dimension(350,50), new Dimension(350,50),
"Pending matches", "Pending matches",
new Font(Palette.textFont.getFontName(), Font.ITALIC, 34), new Font(Palette.inputBox_font.getFontName(), Font.ITALIC, 38),
null, null,
matchsContainer matchsContainer
); );
@ -48,7 +46,7 @@ public class MatchRequestsPage extends Page{
TTScrollList pendingMatches = new TTScrollList( TTScrollList pendingMatches = new TTScrollList(
new Point(20, 60), new Point(20, 60),
new Dimension(520, 142), new Dimension(520, 142),
matchRequestController.getPendingList(), App.game.pendingList,
matchsContainer matchsContainer
); );
@ -58,8 +56,9 @@ public class MatchRequestsPage extends Page{
super.mouseClicked(evt); super.mouseClicked(evt);
JList thisList = (JList)evt.getSource(); JList thisList = (JList)evt.getSource();
if (evt.getClickCount() == 2) { if (evt.getClickCount() == 2) {
// Double-click detected
int index = thisList.locationToIndex(evt.getPoint()); int index = thisList.locationToIndex(evt.getPoint());
matchRequestController.joinMatch(matchRequestController.getPendingList().get(index)); App.game.joinMatch(App.game.pendingList.get(index));
} }
} }
}); });

View file

@ -8,8 +8,7 @@ import java.awt.*;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 27/06/2017. * MatchSetup Page
* Description: MatchSetup Page
*/ */
public class MatchSetupPage extends Page{ public class MatchSetupPage extends Page{
@ -35,10 +34,10 @@ public class MatchSetupPage extends Page{
); );
new TTLabel( new TTLabel(
new Point(160,0), new Point(170,0),
new Dimension(350,50), new Dimension(350,50),
"Invite players", "Invite players",
new Font(Palette.textFont.getFontName(), Font.ITALIC, 38), new Font(Palette.inputBox_font.getFontName(), Font.ITALIC, 38),
null, null,
matchSetupContainer matchSetupContainer
); );
@ -57,10 +56,9 @@ public class MatchSetupPage extends Page{
"Play!", "Play!",
new Callable<Object>() { new Callable<Object>() {
@Override @Override
public Void call() throws Exception { public Object call() throws Exception {
//If notificationServer response ok, start newMatch, else error //If server response ok, start play, else error
matchSetupController.play(searchUserBar.list); return matchSetupController.play(searchUserBar.list);
return null;
} }
} }
); );

View file

@ -1,25 +1,26 @@
package com.texttwist.client.pages; package com.texttwist.client.pages;
import com.texttwist.client.App;
import com.texttwist.client.controllers.MenuController; import com.texttwist.client.controllers.MenuController;
import constants.Palette; import constants.Palette;
import com.texttwist.client.ui.*; import com.texttwist.client.ui.*;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 17/06/2017. * Created by loke on 14/06/2017.
* Description: Menu Page
*/ */
public class MenuPage extends Page{ public class MenuPage extends Page{
private TTContainer menuBar;
private MenuController menuController; private MenuController menuController;
public MenuPage(JFrame window) throws IOException { public MenuPage(JFrame window) throws IOException {
super(window); super(window);
menuController = new MenuController();
createUIComponents(); createUIComponents();
menuController = new MenuController();
window.setVisible(true); window.setVisible(true);
} }
@ -27,24 +28,24 @@ public class MenuPage extends Page{
public void createUIComponents() throws IOException { public void createUIComponents() throws IOException {
addLogo(root); addLogo(root);
TTContainer menuBar = new TTContainer( menuBar = new TTContainer(
null, null,
new Dimension(1150, 280), new Dimension(1150,280),
Palette.root_backgroundColor, Palette.root_backgroundColor,
-1, -1,
root root
); );
new TTLabel( TTLabel playerToSendInvite_flavourText = new TTLabel(
new Point(25,15), new Point(25,15),
new Dimension(350,20), new Dimension(350,20),
"Welcome back, " + menuController.getSession().account.userName + "!", "Welcome back, " + App.session.account.userName + "!",
new Font(Palette.textFont.getFontName(), Font.ITALIC, 24), new Font(Palette.inputBox_font.getFontName(), Font.ITALIC, 24),
null, null,
menuBar menuBar
); );
new TTButton( TTButton newMatch = new TTButton(
new Point(25,70), new Point(25,70),
new Dimension(250,75), new Dimension(250,75),
"New Game!", "New Game!",
@ -58,7 +59,7 @@ public class MenuPage extends Page{
menuBar menuBar
); );
new TTButton( TTButton matchRequests = new TTButton(
new Point(290,70), new Point(290,70),
new Dimension(250,75), new Dimension(250,75),
"In pending", "In pending",
@ -72,7 +73,14 @@ public class MenuPage extends Page{
menuBar menuBar
); );
new TTButton( TTCircleCounter circleCounter = new TTCircleCounter(
new Point(290,70),
new Dimension(25,25),
menuBar.getGraphics(),
menuBar
);
TTButton highscores = new TTButton(
new Point(25, 155), new Point(25, 155),
new Dimension(250, 75), new Dimension(250, 75),
"Highscores", "Highscores",
@ -85,14 +93,14 @@ public class MenuPage extends Page{
menuBar menuBar
); );
new TTButton( TTButton logout = new TTButton(
new Point(290, 155), new Point(290, 155),
new Dimension(250, 75), new Dimension(250, 75),
"Logout", "Logout",
new Callable<Object>() { new Callable<Object>() {
@Override @Override
public Object call() throws Exception { public Object call() throws Exception {
menuController.logout(); menuController.logout(App.session.account.userName);
return new HomePage(Page.window); return new HomePage(Page.window);
} }
}, },

View file

@ -1,5 +1,4 @@
package com.texttwist.client.pages; package com.texttwist.client.pages;
import constants.Palette; import constants.Palette;
import com.texttwist.client.ui.*; import com.texttwist.client.ui.*;
import javax.swing.*; import javax.swing.*;
@ -11,8 +10,7 @@ import java.io.IOException;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 14/06/2017. * Base Page
* Description: Controller of the Home Page
*/ */
public class Page { public class Page {
@ -47,7 +45,7 @@ public class Page {
parent); parent);
try { try {
new TTImage( TTImage logoImg = new TTImage(
new Point(0, 10), new Point(0, 10),
new Dimension(1150, 150), new Dimension(1150, 150),
new ImageIcon(new File("./Client/resources/images/logo.png").getCanonicalPath()), new ImageIcon(new File("./Client/resources/images/logo.png").getCanonicalPath()),
@ -59,7 +57,7 @@ public class Page {
public void addBack(TTContainer parent, Callable<Object> clickHandler) { public void addBack(TTContainer parent, Callable<Object> clickHandler) {
try { try {
new TTImageBtn( TTImageBtn back = new TTImageBtn(
new Point(0, 0), new Point(0, 0),
new Dimension(50, 50), new Dimension(50, 50),
new ImageIcon(new File("./Client/resources/images/back.png").getCanonicalPath()), new ImageIcon(new File("./Client/resources/images/back.png").getCanonicalPath()),
@ -80,10 +78,11 @@ public class Page {
} }
public void addNext(TTContainer parent, String caption, Callable<Object> clickHandler) { public void addNext(TTContainer parent, String caption, Callable<Object> clickHandler) {
new TTLabelBtn( TTLabelBtn next = new TTLabelBtn(
new Point(500, 0), new Point(500, 0),
new Dimension(150, 50), new Dimension(150, 50),
caption, new Font(Palette.textFont.getFontName(), Font.ITALIC, 34), caption,
null,
null, null,
clickHandler, clickHandler,
parent); parent);

View file

@ -4,19 +4,19 @@ import com.texttwist.client.controllers.RegisterController;
import constants.Palette; import constants.Palette;
import com.texttwist.client.ui.*; import com.texttwist.client.ui.*;
import models.Response; import models.Response;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 16/06/2017. * Created by loke on 13/06/2017.
* Description: Register Page
*/ */
public class RegisterPage extends Page { public class RegisterPage extends Page {
private TTContainer registerDataContainer;
private RegisterController registerController; private RegisterController registerController;
public RegisterPage(JFrame window) {
RegisterPage(JFrame window) {
super(window); super(window);
createUIComponents(); createUIComponents();
registerController = new RegisterController(); registerController = new RegisterController();
@ -26,18 +26,18 @@ public class RegisterPage extends Page {
@Override @Override
public void createUIComponents() { public void createUIComponents() {
addLogo(root); addLogo(root);
TTContainer registerDataContainer = new TTContainer( registerDataContainer = new TTContainer(
null, null,
new Dimension(1150, 220), new Dimension(1150,220),
Palette.root_backgroundColor, Palette.root_backgroundColor,
-1, -1,
root root
); );
new TTLabel( TTLabel registerText = new TTLabel(
new Point(70,35), new Point(70,35),
new Dimension(400,40), new Dimension(400,40),
"Insert your datas and press Register!", "<html><h2>Insert your datas and press RegisterPage!</h2></html>",
new Font(Palette.textFont.getFontName(), Font.ITALIC, 20), new Font(Palette.inputBox_font.getFontName(), Font.ITALIC, 12),
null, null,
registerDataContainer registerDataContainer
); );
@ -55,13 +55,14 @@ public class RegisterPage extends Page {
registerDataContainer registerDataContainer
); );
new TTButton( TTButton register = new TTButton(
new Point(70,150), new Point(70,150),
new Dimension(430,50), new Dimension(430,50),
"Register!", "RegisterPage!",
new Callable<Object>() { new Callable<Object>() {
@Override @Override
public Object call() throws Exception { public Object call() throws Exception {
//TODO CHIAMA API PER LOGIN E SE TUTTO OKEY MANDA A PAGINA DEL MENU
Response res = registerController.register(usernameField.getText(), String.valueOf(passwordField.getPassword())); Response res = registerController.register(usernameField.getText(), String.valueOf(passwordField.getPassword()));
if (res.code == 200){ if (res.code == 200){
return new TTDialog("success", res.message, return new TTDialog("success", res.message,
@ -95,5 +96,6 @@ public class RegisterPage extends Page {
} }
} }
); );
} }
} }

View file

@ -1,9 +1,7 @@
package com.texttwist.client.services; package com.texttwist.client.services;
import com.texttwist.client.App; import com.texttwist.client.App;
import constants.Config; import constants.Config;
import interfaces.IAuth; import interfaces.IAuth;
import interfaces.INotificationClient;
import models.Response; import models.Response;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.rmi.Naming; import java.rmi.Naming;
@ -11,13 +9,11 @@ import java.rmi.NotBoundException;
import java.rmi.RemoteException; import java.rmi.RemoteException;
/** /**
* Author: Lorenzo Iovino on 17/06/2017. * Authentication Service
* Description: Auth Service.
* Provide the interface for authentication
*/ */
public class AuthService { public class AuthService {
private String baseUrl = Config.getAuthServiceURI().concat("/auth"); private String baseUrl = Config.getAuthServerURI().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);
@ -29,8 +25,8 @@ public class AuthService {
return auth.register(userName, password); return auth.register(userName, password);
} }
public Response logout(String userName, INotificationClient stub) throws RemoteException, NotBoundException, MalformedURLException { public Response logout(String userName) throws RemoteException, NotBoundException, MalformedURLException {
IAuth auth = (IAuth) Naming.lookup(baseUrl); IAuth auth = (IAuth) Naming.lookup(baseUrl);
return auth.logout(userName, App.session.token, stub); return auth.logout(userName, App.session.token);
} }
} }

View file

@ -1,64 +0,0 @@
package com.texttwist.client.services;
import com.texttwist.client.App;
import com.texttwist.client.pages.GamePage;
import com.texttwist.client.pages.MenuPage;
import com.texttwist.client.pages.Page;
import com.texttwist.client.tasks.InvitePlayers;
import com.texttwist.client.tasks.JoinMatch;
import com.texttwist.client.ui.TTDialog;
import javafx.util.Pair;
import models.Message;
import javax.swing.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.concurrent.*;
/**
* Author: Lorenzo Iovino on 18/06/2017.
* Description: GameService.
* Provide the interface for the game.
*/
public class GameService {
public Integer multicastId = 0 ;
public DefaultListModel<String> pendingList = new DefaultListModel<>();
public DefaultListModel<String> words = new DefaultListModel<>();
public DefaultListModel<String> letters = new DefaultListModel<>();
public DefaultListModel<Pair<String,Integer>> globalRanks = new DefaultListModel<>();
public DefaultListModel<Pair<String,Integer>> ranks = new DefaultListModel<>();
public Boolean gameIsStarted = false;
public Boolean isWaiting = false;
public void addToPendingList(String username) throws IOException {
pendingList.addElement(username);
}
public GameService(){
App.openClientTCPSocket();
}
public DefaultListModel<String> getLetters(){
return App.gameService.letters;
}
public DefaultListModel<String> getWords() {
return App.gameService.words;
}
public void setLetters(DefaultListModel<String> letters){
this.letters = letters;
}
public void start(){
gameIsStarted = true;
}
public void stop(){
gameIsStarted = false;
}
public void setMulticastId(Integer multicastId){
this.multicastId = multicastId;
}
}

View file

@ -0,0 +1,39 @@
package com.texttwist.client.services;
import com.texttwist.client.App;
import com.texttwist.client.tasks.FetchHighscore;
import com.texttwist.client.tasks.WaitForScore;
import constants.Config;
import javafx.util.Pair;
import models.Message;
import javax.swing.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable;
/**
* Created by loke on 28/06/2017.
*/
public class HighscoresService {
ByteBuffer buffer = ByteBuffer.allocate(1024);
public DefaultListModel<String> ranks = new DefaultListModel<>();
SocketChannel clientSocket = null;
public HighscoresService(){
InetSocketAddress socketAddress = new InetSocketAddress(Config.GameServerURI, Config.GameServerPort);
try {
clientSocket = SocketChannel.open(socketAddress);
clientSocket.configureBlocking(false);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,29 @@
package com.texttwist.client.services;
import com.texttwist.client.App;
import interfaces.INotificationClient;
import models.Response;
import utilities.Logger;
import javax.swing.*;
import java.rmi.RemoteException;
/**
* Created by loke on 15/06/2017.
*/
public class NotificationClient implements INotificationClient {
public NotificationClient() throws RemoteException {
}
@Override
public Response sendInvite(String userName, DefaultListModel<String> users) throws RemoteException {
Logger.write("Invoked invitation with username=" + userName + "|" + users.toString() );
if(users.contains(App.session.account.userName)){
Logger.write(userName+" ti ha sfidato!");
App.game.newMatch(userName);
}
return null;
}
}

View file

@ -1,28 +0,0 @@
package com.texttwist.client.services;
import com.texttwist.client.App;
import com.texttwist.client.tasks.BeginMatch;
import interfaces.INotificationClient;
import javax.swing.*;
import java.rmi.RemoteException;
/**
* Author: Lorenzo Iovino on 15/06/2017.
* Description: Provide the interface for the notifications.
*/
public class NotificationClientService implements INotificationClient {
@Override
public void sendInvite(String userName, DefaultListModel<String> users) throws RemoteException {
App.logger.write("Invoked invitation with username =" + userName + "|" + users.toString() );
if(App.session != null) {
if (users.contains(App.session.account.userName)) {
App.logger.write(userName + " send a invitation!");
new BeginMatch(userName).execute();
} else {
App.logger.write("User " + userName + " is slogged");
}
}
}
}

View file

@ -1,52 +0,0 @@
package com.texttwist.client.tasks;
import com.texttwist.client.App;
import com.texttwist.client.pages.MenuPage;
import com.texttwist.client.pages.Page;
import com.texttwist.client.ui.TTDialog;
import javax.swing.*;
import java.io.IOException;
import java.util.concurrent.Callable;
/**
* Author: Lorenzo Iovino on 15/07/2017.
* Description: Task: BeginMatch
*
*/
public class BeginMatch extends SwingWorker<Void,Void> {
private String userName;
public BeginMatch(String userName) {
this.userName = userName;
}
@Override
public Void doInBackground() {
//Add to pending invites list
try {
App.gameService.addToPendingList(userName);
} catch (IOException e) {
e.printStackTrace();
}
if(!App.gameService.gameIsStarted && !App.gameService.isWaiting) {
//Show invite popup
new TTDialog("success", "New invite from: " + userName + "!",
new Callable() {
@Override
public Object call() throws Exception {
new JoinMatch(userName).execute();
return null;
}
},
new Callable() {
@Override
public Object call() throws Exception {
return new MenuPage(Page.window);
}
});
}
return null;
}
}

View file

@ -1,64 +1,78 @@
package com.texttwist.client.tasks; package com.texttwist.client.tasks;
import com.texttwist.client.App; import com.texttwist.client.App;
import com.texttwist.client.pages.HighscoresPage;
import javafx.util.Pair;
import models.Message; import models.Message;
import javax.swing.*; import javax.swing.*;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.concurrent.Callable; import java.nio.channels.SocketChannel;
/** /**
* Author: Lorenzo Iovino on 20/06/2017. * Job: FetchHighscore
* Description: Task: FetchHighscore.
* Ask for highscores to server. When received it shows in highscores list
*/ */
public class FetchHighscore extends SwingWorker<Void,Void> { public class FetchHighscore extends SwingWorker<Void,Void> {
private DefaultListModel<Pair<String,Integer>> globalRanks = new DefaultListModel<>();
private SocketChannel socketChannel;
private ByteBuffer buffer = ByteBuffer.allocate(1024); private ByteBuffer buffer = ByteBuffer.allocate(1024);
private Callable<Void> callback; HighscoresPage highscoresPage;
public FetchHighscore(Callable<Void> callback){ public FetchHighscore(HighscoresPage highscoresPage){
this.callback = callback; this.socketChannel = App.game.clientSocket;
this.highscoresPage = highscoresPage;
} }
@Override @Override
public Void doInBackground() { public Void doInBackground() {
Message message = new Message("FETCH_HIGHSCORES", App.session.account.userName, App.session.token, new DefaultListModel<>()); Message message = new Message("FETCH_HIGHSCORES", App.session.account.userName, App.session.token, new DefaultListModel<>());
buffer = ByteBuffer.allocate(1024); buffer = ByteBuffer.allocate(1024);
System.out.println("SENDDDDD MESSAGE");
byte[] byteMessage = message.toString().getBytes(); byte[] byteMessage = message.toString().getBytes();
buffer = ByteBuffer.wrap(byteMessage); buffer = ByteBuffer.wrap(byteMessage);
try { try {
App.clientTCP.write(buffer); socketChannel.write(buffer);
} catch (IOException e) { } catch (IOException e) {
App.logger.write("FETCH HIGHSCORES: Can't write on socket"); e.printStackTrace();
} }
try { try {
buffer = ByteBuffer.allocate(1024); buffer = ByteBuffer.allocate(1024);
while (App.clientTCP.read(buffer) != -1) {
while (socketChannel.read(buffer) != -1) {
buffer.clear();
String line = new String(buffer.array(), buffer.position(), buffer.remaining()); String line = new String(buffer.array(), buffer.position(), buffer.remaining());
if (line.startsWith("MESSAGE")) { if (line.startsWith("MESSAGE")) {
Message msg = Message.toMessage(line); Message msg = Message.toMessage(line);
System.out.println(line);
if (msg.message.equals("HIGHSCORES") && msg.data != null) { if (msg.message.equals("HIGHSCORES") && msg.data != null) {
App.gameService.globalRanks = utilities.Parse.score(msg.data);
break; for(int i = 0; i< msg.data.size()-1; i++){
String[] splitted = msg.data.get(i).split(":");
globalRanks.addElement(new Pair<>(splitted[0],new Integer(splitted[1])));
}
return null;
} }
} }
buffer.clear();
} }
} catch (IOException e) { } catch (IOException e) {
App.logger.write("FETCH HIGHSCORES: Can't read from socket"); e.printStackTrace();
} }
return null; return null;
} }
public void done(){ public void done(){
try { System.out.println("Done Highscores");
callback.call(); App.game.globalRanks = globalRanks;
} catch (Exception e) { this.highscoresPage.showHighscoreList();
e.printStackTrace(); System.out.println("DODODO");
}
} }
} }

View file

@ -5,78 +5,84 @@ import com.texttwist.client.pages.GamePage;
import com.texttwist.client.pages.Page; import com.texttwist.client.pages.Page;
import com.texttwist.client.ui.TTDialog; import com.texttwist.client.ui.TTDialog;
import models.Message; import models.Message;
import javax.swing.*; import javax.swing.*;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 25/06/2017. * Created by loke on 25/06/2017.
* Description: Task: InvitePlayers
* Sends invite to all players of the match
*/ */
public class InvitePlayers extends SwingWorker<Void,Void> { public class InvitePlayers extends SwingWorker<Boolean,Void> {
private ByteBuffer buffer = ByteBuffer.allocate(1024); ByteBuffer buffer = ByteBuffer.allocate(1024);
private DefaultListModel<String> userNames;
public InvitePlayers(DefaultListModel<String> userNames) { public DefaultListModel<String> userNames;
public SocketChannel socketChannel;
public InvitePlayers(DefaultListModel<String> userNames, SocketChannel socketChannel) {
this.socketChannel = socketChannel;
this.userNames = userNames; this.userNames = userNames;
} }
@Override @Override
public Void doInBackground() { public Boolean doInBackground() {
buffer = ByteBuffer.allocate(1024);
Message message = new Message("START_GAME", App.session.account.userName, App.session.token, userNames); Message message = new Message("START_GAME", App.session.account.userName, App.session.token, userNames);
byte[] byteMessage = message.toString().getBytes(); byte[] byteMessage = new String(message.toString()).getBytes();
buffer = ByteBuffer.wrap(byteMessage); buffer = ByteBuffer.wrap(byteMessage);
try { try {
App.clientTCP.write(buffer); socketChannel.write(buffer);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
try { try {
while (App.clientTCP.read(buffer) != -1) { while (socketChannel.read(buffer) != -1) {
buffer.clear();
String line = new String(buffer.array(), buffer.position(), buffer.remaining()); String line = new String(buffer.array(), buffer.position(), buffer.remaining());
if (line.startsWith("MESSAGE")) { if (line.startsWith("MESSAGE")) {
Message msg = Message.toMessage(line); Message msg = Message.toMessage(line);
if (msg.message.equals("USER_NOT_ONLINE")) { if (msg.message.equals("USER_NOT_ONLINE")) {
new TTDialog("alert", "Users not online!", new TTDialog("alert", "Users not online!",
new Callable() { new Callable() {
@Override @Override
public Void call() throws Exception { public Object call() throws Exception {
buffer.clear();
return null; return null;
} }
}, null); }, null);
buffer.clear();
return null; return null;
} }
if (msg.message.equals("INVITES_ALL_SENDED")) { if (msg.message.equals("INVITES_ALL_SENDED")) {
// clientSocket.close();
new TTDialog("success", "Invite all sended!", new TTDialog("success", "Invite all sended!",
new Callable() { new Callable() {
@Override @Override
public Void call() throws Exception { public Object call() throws Exception {
//In attesa dei giocatori //In attesa dei giocatori
new GamePage(Page.window); new GamePage(Page.window);
buffer.clear();
return null; return null;
} }
}, null); }, null);
buffer.clear();
return null; return null;
} }
} }
buffer.clear();
} }
} catch (IOException e) { } catch (IOException e) {
App.logger.write("INVITE PLAYERS: Can't read from socket"); e.printStackTrace();
} }
return null; return null;
} }
@Override
public void done() {
System.out.println("Done invite players");
}
} }

View file

@ -1,47 +0,0 @@
package com.texttwist.client.tasks;
import com.texttwist.client.App;
import com.texttwist.client.pages.GamePage;
import com.texttwist.client.pages.Page;
import models.Message;
import javax.swing.*;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Author: Lorenzo Iovino on 25/06/2017.
* Description: Task: JoinMatch
*
*/
public class JoinMatch extends SwingWorker<Void,Void> {
private String matchName;
public JoinMatch(String matchName) {
this.matchName = matchName;
}
@Override
public Void doInBackground() {
//Clear pending invitation list and join selected match
if(!App.gameService.gameIsStarted) {
App.gameService.pendingList.clear();
try {
DefaultListModel<String> matchNames = new DefaultListModel<>();
matchNames.addElement(matchName);
Message message = new Message("JOIN_GAME", App.session.account.userName, App.session.token, matchNames);
byte[] byteMessage = message.toString().getBytes();
ByteBuffer buffer = ByteBuffer.wrap(byteMessage);
App.clientTCP.write(buffer);
new GamePage(Page.window);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}

View file

@ -1,22 +1,27 @@
package com.texttwist.client.tasks; package com.texttwist.client.tasks;
import com.texttwist.client.App; import com.texttwist.client.App;
import constants.Config;
import javafx.util.Pair;
import models.Message; import models.Message;
import javax.swing.*; import javax.swing.*;
import java.io.IOException; import java.io.IOException;
import java.net.*; import java.net.*;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
/** /**
* Author: Lorenzo Iovino on 29/06/2017. * Created by loke on 29/06/2017.
* Description: Task: SendWords.
* Send words to server and when done it wait for score.
*/ */
public class SendWords extends SwingWorker<Void,Void> { public class SendWords extends SwingWorker<Void,Void> {
private SwingWorker callback; DefaultListModel<Pair<String,Integer>> ranks = new DefaultListModel<Pair<String,Integer>>();
private DefaultListModel<String> words = new DefaultListModel<>();
SwingWorker callback;
DefaultListModel<String> words = new DefaultListModel<>();
//TODO PASSARE LA CALLBACK ALLO SWING WORKER ED ESEGUIRLA AL DONE
public SendWords(DefaultListModel<String> words, SwingWorker callback){ public SendWords(DefaultListModel<String> words, SwingWorker callback){
this.callback = callback; this.callback = callback;
this.words = words; this.words = words;
@ -24,32 +29,53 @@ public class SendWords extends SwingWorker<Void,Void> {
@Override @Override
public Void doInBackground() { public Void doInBackground() {
DatagramSocket clientSocket = null;
try { try {
App.openClientUDPSocket(); InetAddress hostIP = InetAddress.getLocalHost();
InetSocketAddress myAddress =
new InetSocketAddress(hostIP, Config.WordsReceiverServerPort);
DatagramChannel datagramChannel = DatagramChannel.open();
datagramChannel.bind(null);
ByteBuffer buffer = ByteBuffer.allocate(1024); ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.clear(); Message msg = new Message("WORDS", App.session.account.userName, "", words);
Message msg = new Message("WORDS", App.session.account.userName, App.session.token, words);
String sentence = msg.toString(); String sentence = msg.toString();
buffer.put(sentence.getBytes()); buffer.put(sentence.getBytes());
buffer.flip(); buffer.flip();
datagramChannel.send(buffer, myAddress);
buffer.clear();
App.clientUDP.send(buffer, App.clientUDPSocketAddress); /*clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(Config.WordsReceiverServerURI);
byte[] sendData = new byte[1024];
Message msg = new Message("WORDS", App.session.account.userName, "", words);
String sentence = msg.toString();
sendData = sentence.getBytes();
System.out.println("SENDIJIIDIIDIDIDIDDIDIDIDIDI");
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, Config.WordsReceiverServerPort);
clientSocket.send(sendPacket);
clientSocket.close();*/
return null;
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
App.logger.write("SEND WORDS: Host address not correct"); e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
App.logger.write("SEND WORDS: Can't write on socket"); e.printStackTrace();
} }
return null; return null;
} }
@Override @Override
public void done(){ public void done(){
System.out.println("Done send SCOREEEEEE");
try { try {
this.callback.execute(); this.callback.execute();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }

View file

@ -0,0 +1,45 @@
package com.texttwist.client.tasks;
import com.texttwist.client.pages.GamePage;
import com.texttwist.client.ui.TTDialog;
import javax.swing.*;
import java.util.concurrent.Callable;
/**
* Created by loke on 25/06/2017.
*/
public class StartGame extends SwingWorker<Void,Void> {
/*Words inserted from user*/
private DefaultListModel<String> letters = new DefaultListModel<>();
private GamePage gamePage;
public StartGame(DefaultListModel<String> letters, GamePage game){
this.letters = letters;
this.gamePage = game;
}
@Override
public Void doInBackground(){
//Mostra pannello di conferma che le lettere sono tutte arrivate
new TTDialog("success", "GamePage is ready. Press OK to start!",
new Callable() {
@Override
public Object call() throws Exception {
gamePage.showLetters();
System.out.println(letters);
gamePage.timer.start();
return null;
}
}, null);
return null;
}
@Override
public void done(){
System.out.println("Done start gamePage");
}
}

View file

@ -4,37 +4,43 @@ import com.texttwist.client.App;
import com.texttwist.client.pages.MenuPage; import com.texttwist.client.pages.MenuPage;
import com.texttwist.client.pages.Page; import com.texttwist.client.pages.Page;
import com.texttwist.client.ui.TTDialog; import com.texttwist.client.ui.TTDialog;
import constants.Config;
import models.Message; import models.Message;
import javax.swing.*; import javax.swing.*;
import java.io.IOException; import java.io.IOException;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 25/06/2017. * Created by loke on 25/06/2017.
* Description: Task: WaitForPlayers.
* Wait for players joins, when all joined then sends a message of game started to all
*
*/ */
public class WaitForPlayers extends SwingWorker<Void,Void> { public class WaitForPlayers extends SwingWorker<DefaultListModel<String>,DefaultListModel<String>> {
private boolean joinTimeout = false; public SocketChannel socketChannel;
private Callable<Void> callback; public DefaultListModel<String> words;
public DefaultListModel<String> letters;
public WaitForPlayers(Callable<Void> callback) { ByteBuffer buffer = ByteBuffer.allocate(1024);
SwingWorker callback;
public WaitForPlayers(SwingWorker callback) {
this.callback = callback; this.callback = callback;
this.words = words;
this.socketChannel = App.game.clientSocket;
} }
@Override @Override
public Void doInBackground() { public DefaultListModel<String> doInBackground() {
try { try {
App.gameService.isWaiting = true;
ByteBuffer buffer = ByteBuffer.allocate(1024);
TTDialog loading = new TTDialog("alert", "Waiting for users joins",null,null); TTDialog loading = new TTDialog("alert", "Waiting for users joins",null,null);
buffer.flip(); buffer.flip();
while (this.socketChannel.read(this.buffer) != -1) {
while (App.clientTCP.read(buffer) != -1) { String line = new String(this.buffer.array(), this.buffer.position(), this.buffer.remaining());
String line = new String(buffer.array(), buffer.position(), buffer.remaining());
buffer.clear(); buffer.clear();
if (line.startsWith("MESSAGE")) { if (line.startsWith("MESSAGE")) {
@ -42,66 +48,61 @@ public class WaitForPlayers extends SwingWorker<Void,Void> {
Message msg = Message.toMessage(line); Message msg = Message.toMessage(line);
if (msg.message.equals("JOIN_TIMEOUT")) { if (msg.message.equals("JOIN_TIMEOUT")) {
socketChannel.close();
loading.dispose(); loading.dispose();
App.gameService.isWaiting = false;
joinTimeout = true;
new TTDialog("alert", "TIMEOUT!", new TTDialog("alert", "TIMEOUT!",
new Callable() { new Callable() {
@Override @Override
public Void call() throws Exception { public Object call() throws Exception {
new MenuPage(Page.window); return new MenuPage(Page.window);
return null;
} }
}, null); }, null);
return null; return new DefaultListModel<String>();
}
if (msg.message.equals("MATCH_NOT_AVAILABLE")) {
loading.dispose();
joinTimeout = true;
App.gameService.isWaiting = false;
new TTDialog("alert", "THE GAME IS NOT MORE AVAILABLE!",
new Callable() {
@Override
public Void call() throws Exception {
new MenuPage(Page.window);
return null;
}
}, null);
return null;
} }
if (msg.message.equals("GAME_STARTED")) { if (msg.message.equals("GAME_STARTED")) {
loading.dispose(); loading.dispose();
App.gameService.isWaiting = false;
DefaultListModel<String> data;
if(msg.data !=null ) { if(msg.data !=null ) {
DefaultListModel<String> data = msg.data; data= msg.data;
App.openClientMulticastSocket(Integer.valueOf(data.remove(data.size()-2))); System.out.println("HERE");
App.gameService.setLetters(msg.data); Integer multicastId = Integer.valueOf(data.remove(data.size()-2));
break; System.out.println(multicastId);
App.game.setMulticastId(multicastId);
App.game.multicastSocket = new MulticastSocket(App.game.multicastId);
System.out.println(App.game.multicastSocket);
InetAddress ia = InetAddress.getByName(Config.ScoreMulticastServerURI);
App.game.multicastSocket.joinGroup(ia);
letters = msg.data;
//socketChannel.close();
return words;
} }
} }
buffer = ByteBuffer.allocate(1024);
} }
} }
} catch (IOException e) { } catch (IOException e) {
App.logger.write("WAIT FOR SCORE: Can't receive from socket"); e.printStackTrace();
} }
return null; return new DefaultListModel<String>();
} }
@Override @Override
public void done(){ public void done(){
if(!joinTimeout) { System.out.println("Done wait for players");
try { try {
this.callback.call(); System.out.println(letters);
App.game.setLetters(letters);
System.out.println("PAROLE IN INVIO");
this.callback.execute();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
}
} }

View file

@ -1,62 +1,90 @@
package com.texttwist.client.tasks; package com.texttwist.client.tasks;
import com.texttwist.client.App; import com.texttwist.client.App;
import constants.Config;
import javafx.util.Pair;
import models.Message; import models.Message;
import javax.swing.*; import javax.swing.*;
import java.io.IOException; import java.io.IOException;
import java.net.DatagramPacket; import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException; import java.net.UnknownHostException;
/** /**
* Author: Lorenzo Iovino on 27/06/2017. * Created by loke on 27/06/2017.
* Description: Task: WaitForScore.
* This task will waits for the score of the match sent by server, at end it will execute a callback
* function that show the highscore pages.
*/ */
public class WaitForScore extends SwingWorker<Void,Void> { public class WaitForScore extends SwingWorker<Void,Void> {
private SwingWorker callback; DefaultListModel<Pair<String,Integer>> ranks = new DefaultListModel<Pair<String,Integer>>();
SwingWorker callback;
//TODO PASSARE LA CALLBACK ALLO SWING WORKER ED ESEGUIRLA AL DONE
public WaitForScore(SwingWorker callback){ public WaitForScore(SwingWorker callback){
this.callback = callback; this.callback = callback;
} }
@Override @Override
public Void doInBackground() { public Void doInBackground() {
InetAddress group = null;
try { try {
//Wait for the final scores of the match
Message msg;
while(true) { while(true) {
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
DatagramPacket receivedDatagram = new DatagramPacket(buf, buf.length); System.out.println("SONO QUIIIII");
App.clientMulticast.receive(receivedDatagram); DatagramPacket recv = new DatagramPacket(buf, buf.length);
System.out.println("ANCORA QUII");
App.game.multicastSocket.receive(recv);
String s = new String(receivedDatagram.getData()); String s = new String(recv.getData());
Message msg = Message.toMessage(s); System.out.println("HSHSHSHS");
System.out.println(s);
//When arrive a message with message=FINALSCORE => popolate ranks msg = Message.toMessage(s);
if(msg.message.equals("FINALSCORE")){ if(msg.message.equals("FINALSCORE")){
if(msg.data != null) {
App.gameService.ranks = utilities.Parse.score(msg.data);
}
break; break;
} }
} }
if(msg.data != null) {
for (int i = 0; i < msg.data.size() - 1; i++) {
String[] splitted = msg.data.get(i).split(":");
System.out.println(splitted.toString());
ranks.addElement(new Pair<String, Integer>(splitted[0], new Integer(splitted[1])));
}
}
App.game.ranks = ranks;
App.game.multicastSocket.leaveGroup(InetAddress.getByName(Config.ScoreMulticastServerURI));
System.out.println(App.game.ranks);
System.out.println("ENDDDDd");
App.game.multicastSocket.disconnect();
App.game.multicastSocket.close();
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
App.logger.write("WAIT FOR SCORE: Host unknown"); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
App.logger.write("WAIT FOR SCORE: Can't read from multicast Socket"); e.printStackTrace();
} }
return null; return null;
} }
@Override @Override
public void done(){ public void done(){
App.closeClientMulticastSocket(); System.out.println("Done ranks");
App.game.ranks = ranks;
// App.game.multicastSocket.close();
//App.game.clientSocket.close();
//Stop gameService try {
App.gameService.stop();
//Call callback
this.callback.execute(); this.callback.execute();
} catch (Exception e) {
e.printStackTrace();
} }
}
} }

View file

@ -1,16 +1,15 @@
package com.texttwist.client.ui; package com.texttwist.client.ui;
import constants.Palette; import constants.Palette;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.MouseAdapter; import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent; import java.awt.event.MouseEvent;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 13/06/2017. * Created by loke on 13/06/2017.
* Description: TTContainer component
*/ */
public class TTButton extends JButton{ public class TTButton extends JButton{

View file

@ -0,0 +1,35 @@
package com.texttwist.client.ui;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.util.Random;
/**
* Created by loke on 14/06/2017.
*/
public class TTCircleCounter extends JComponent{
private Point position;
private Dimension dimension;
public TTCircleCounter(Point position, Dimension dimension, Graphics g, TTContainer parent){
this.position=position;
this.dimension=dimension;
Graphics2D g2d = (Graphics2D)g;
Ellipse2D.Double circle = new Ellipse2D.Double(position.x, position.y, dimension.width, dimension.height);
g2d.fill(circle);
g2d.setColor(Color.RED);
parent.add(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
Ellipse2D.Double circle = new Ellipse2D.Double(position.x, position.y, dimension.width, dimension.height);
g2d.setColor(Color.RED);
g2d.fill(circle);
}
}

View file

@ -6,10 +6,8 @@ import javax.swing.*;
import javax.swing.border.EmptyBorder; import javax.swing.border.EmptyBorder;
import java.awt.*; import java.awt.*;
/** /**
* Author: Lorenzo Iovino on 13/06/2017. * Created by loke on 13/06/2017.
* Description: TTButton component
*/ */
public class TTContainer extends JPanel{ public class TTContainer extends JPanel{
@ -22,7 +20,7 @@ public class TTContainer extends JPanel{
} }
setBackground(backgroundColor != null ? backgroundColor : new Color(0,0,0,0)); setBackground(backgroundColor != null ? backgroundColor : new Color(0,0,0,0));
setFont(Palette.textFont); setFont(Palette.inputBox_font);
setMaximumSize(dimension); setMaximumSize(dimension);
if(innerPadding != null) { if(innerPadding != null) {
setLocation(innerPadding); setLocation(innerPadding);

View file

@ -2,15 +2,14 @@ package com.texttwist.client.ui;
import com.texttwist.client.App; import com.texttwist.client.App;
import constants.Palette; import constants.Palette;
import javax.swing.*; import javax.swing.*;
import javax.swing.border.EmptyBorder; import javax.swing.border.EmptyBorder;
import java.awt.*; import java.awt.*;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 17/06/2017. * Created by loke on 17/06/2017.
* Description: TTDialog component
*/ */
public class TTDialog extends JFrame { public class TTDialog extends JFrame {
@ -34,6 +33,7 @@ public class TTDialog extends JFrame {
switch (type){ switch (type){
case "alert":{ case "alert":{
root.setBorder(BorderFactory.createLineBorder(Palette.dialog_alert)); root.setBorder(BorderFactory.createLineBorder(Palette.dialog_alert));
} }
case "success": { case "success": {
root.setBorder(BorderFactory.createLineBorder(Palette.dialog_success)); root.setBorder(BorderFactory.createLineBorder(Palette.dialog_success));
@ -41,16 +41,16 @@ public class TTDialog extends JFrame {
} }
add(root); add(root);
new TTLabel( TTLabel msg = new TTLabel(
new Point(60,20), new Point(60,20),
new Dimension(350,50), new Dimension(350,50),
message, message,
new Font(Palette.textFont.getFontName(), Font.ITALIC, 24), new Font(Palette.inputBox_font.getFontName(), Font.ITALIC, 38),
null, null,
root); root);
if(okHandler != null && cancelHandler != null){ if(okHandler != null && cancelHandler != null){
new TTButton( TTButton okBtn = new TTButton(
new Point(60,100), new Point(60,100),
new Dimension(150,50), new Dimension(150,50),
"Ok", "Ok",
@ -63,7 +63,7 @@ public class TTDialog extends JFrame {
} }
}, },
root); root);
new TTButton( TTButton cancelBtn = new TTButton(
new Point(250,100), new Point(250,100),
new Dimension(150,50), new Dimension(150,50),
"Cancel", "Cancel",
@ -78,7 +78,7 @@ public class TTDialog extends JFrame {
root); root);
} else { } else {
if(cancelHandler != null) { if(cancelHandler != null) {
new TTButton( TTButton cancelBtn = new TTButton(
new Point(150, 100), new Point(150, 100),
new Dimension(150, 50), new Dimension(150, 50),
"Cancel", "Cancel",
@ -93,7 +93,7 @@ public class TTDialog extends JFrame {
root); root);
} }
if(okHandler != null) { if(okHandler != null) {
new TTButton( TTButton okBtn = new TTButton(
new Point(150,100), new Point(150,100),
new Dimension(150,50), new Dimension(150,50),
"Ok", "Ok",
@ -135,4 +135,5 @@ public class TTDialog extends JFrame {
g2d.dispose(); g2d.dispose();
} }
} }
} }

View file

@ -1,31 +1,29 @@
package com.texttwist.client.ui; package com.texttwist.client.ui;
import constants.Palette; import constants.Palette;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.KeyAdapter; import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 14/06/2017. * Created by loke on 14/06/2017.
* Description: TTGameBox component
*/ */
public class TTGameBox extends TTInputField{ public class TTGameBox extends TTInputField{
public TTGameBox(Point position, public TTGameBox(Point position,
Dimension dimension, Dimension dimension,
String placeholder, String placeholer,
DefaultListModel<String> list, DefaultListModel<String> list,
TTContainer parent){ TTContainer parent){
super(position, dimension, placeholder, parent); super(position, dimension, placeholer, parent);
setBackground(Palette.scrollPanel_backgroundColor); setBackground(Palette.scrollPanel_backgroundColor);
setFont(Palette.inputboxFont); setFont(Palette.inputBox_font);
setBounds(position.x, position.y, dimension.width, dimension.height); setBounds(position.x, position.y, dimension.width, dimension.height);
setPreferredSize(dimension); setPreferredSize(dimension);
setForeground(Palette.fontColor); setForeground(Palette.fontColor);
list.clear();
addKeyListener(new KeyAdapter() { addKeyListener(new KeyAdapter() {
@Override @Override
@ -39,6 +37,7 @@ public class TTGameBox extends TTInputField{
e1.printStackTrace(); e1.printStackTrace();
} }
} }
//Every time i press a key, execute a search of users
} }
}); });

View file

@ -4,10 +4,8 @@ import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.io.IOException; import java.io.IOException;
/** /**
* Author: Lorenzo Iovino on 13/06/2017. * Created by loke on 13/06/2017.
* Description: TTImage component
*/ */
public class TTImage extends JLabel{ public class TTImage extends JLabel{
@ -18,5 +16,6 @@ public class TTImage extends JLabel{
setIcon(image); setIcon(image);
parent.add(this); parent.add(this);
} }
} }

View file

@ -1,6 +1,7 @@
package com.texttwist.client.ui; package com.texttwist.client.ui;
import constants.Palette; import constants.Palette;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.MouseAdapter; import java.awt.event.MouseAdapter;
@ -9,8 +10,7 @@ import java.io.IOException;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 14/06/2017. * Created by loke on 14/06/2017.
* Description: TTImageBtn component
*/ */
public class TTImageBtn extends TTImage { public class TTImageBtn extends TTImage {
public TTImageBtn(Point position, Dimension dimension, ImageIcon image, Callable<Object> clickHandler, JPanel parent) throws IOException { public TTImageBtn(Point position, Dimension dimension, ImageIcon image, Callable<Object> clickHandler, JPanel parent) throws IOException {

View file

@ -3,14 +3,13 @@ package com.texttwist.client.ui;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
/** /**
* Author: Lorenzo Iovino on 13/06/2017. * Created by loke on 13/06/2017.
* Description: TTInputBox component
*/ */
public class TTInputBox extends JTextField { public class TTInputBox extends JTextField {
public String placeholder; public String placeholder;
public void setPlaceholder(final String s) { public void setPlaceholder(final String s) {
placeholder = s; placeholder = s;
} }
@ -31,4 +30,5 @@ public class TTInputBox extends JTextField {
g.drawString(placeholder, getInsets().left, pG.getFontMetrics() g.drawString(placeholder, getInsets().left, pG.getFontMetrics()
.getMaxAscent() + getInsets().top); .getMaxAscent() + getInsets().top);
} }
} }

View file

@ -1,12 +1,12 @@
package com.texttwist.client.ui; package com.texttwist.client.ui;
import constants.Palette; import constants.Palette;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
/** /**
* Author: Lorenzo Iovino on 13/06/2017. * Created by loke on 13/06/2017.
* Description: TTInputField component
*/ */
public class TTInputField extends TTInputBox{ public class TTInputField extends TTInputBox{
@ -14,11 +14,15 @@ public class TTInputField extends TTInputBox{
super(); super();
setBackground(Palette.inputBox_backgroundColor); setBackground(Palette.inputBox_backgroundColor);
setFont(Palette.textFont); setFont(Palette.inputBox_font);
setBounds(position.x, position.y, dimension.width, dimension.height); setBounds(position.x, position.y, dimension.width, dimension.height);
setPreferredSize(dimension); setPreferredSize(dimension);
setForeground(Palette.fontColor); setForeground(Palette.fontColor);
setPlaceholder(placeholder); setPlaceholder(placeholder);
parent.add(this); parent.add(this);
} }
} }

View file

@ -1,12 +1,12 @@
package com.texttwist.client.ui; package com.texttwist.client.ui;
import constants.Palette; import constants.Palette;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
/** /**
* Author: Lorenzo Iovino on 13/06/2017. * Created by loke on 13/06/2017.
* Description: TTLabel component
*/ */
public class TTLabel extends JLabel{ public class TTLabel extends JLabel{
@ -16,7 +16,7 @@ public class TTLabel extends JLabel{
setBackground(Palette.inputBox_backgroundColor); setBackground(Palette.inputBox_backgroundColor);
if(font == null) { if(font == null) {
setFont(Palette.textFont); setFont(Palette.inputBox_font);
} else { } else {
setFont(font); setFont(font);
} }
@ -30,6 +30,8 @@ public class TTLabel extends JLabel{
} else { } else {
setForeground(fontColor); setForeground(fontColor);
} }
parent.add(this); parent.add(this);
} }
} }

View file

@ -1,6 +1,7 @@
package com.texttwist.client.ui; package com.texttwist.client.ui;
import constants.Palette; import constants.Palette;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.MouseAdapter; import java.awt.event.MouseAdapter;
@ -8,8 +9,7 @@ import java.awt.event.MouseEvent;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 14/06/2017. * Created by loke on 13/06/2017.
* Description: TTLabelBtn component
*/ */
public class TTLabelBtn extends TTLabel{ public class TTLabelBtn extends TTLabel{
@ -23,7 +23,6 @@ public class TTLabelBtn extends TTLabel{
super.mouseClicked(e); super.mouseClicked(e);
setForeground(Palette.registerLblBtn_onmouseclick_color); setForeground(Palette.registerLblBtn_onmouseclick_color);
} }
@Override @Override
public void mouseReleased(MouseEvent e) { public void mouseReleased(MouseEvent e) {
super.mouseClicked(e); super.mouseClicked(e);
@ -39,6 +38,7 @@ public class TTLabelBtn extends TTLabel{
public void mouseEntered(MouseEvent e) { public void mouseEntered(MouseEvent e) {
super.mouseClicked(e); super.mouseClicked(e);
setForeground(Palette.registerLblBtn_onmouseover_color); setForeground(Palette.registerLblBtn_onmouseover_color);
} }
@Override @Override
@ -48,5 +48,6 @@ public class TTLabelBtn extends TTLabel{
} }
}); });
} }
} }

View file

@ -1,22 +1,23 @@
package com.texttwist.client.ui; package com.texttwist.client.ui;
import constants.Palette; import constants.Palette;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
/** /**
* Author: Lorenzo Iovino on 14/06/2017. * Created by loke on 14/06/2017.
* Description: TTLetter component
*/ */
public class TTLetter extends TTLabel{ public class TTLetter extends TTLabel{
public TTLetter(Point position, String caption, JPanel parent) { public TTLetter(Point position, String caption, JPanel parent) {
super(position, super(position,
new Dimension(50,50), new Dimension(50,50),
caption, caption,
new Font(Palette.textFont.getFontName(), Font.ITALIC, 30), new Font(Palette.inputBox_font.getFontName(), Font.ITALIC, 40),
Palette.fontColor, Palette.fontColor,
parent); parent);
parent.add(this); parent.add(this);
} }
} }

View file

@ -1,13 +1,12 @@
package com.texttwist.client.ui; package com.texttwist.client.ui;
import constants.Palette; import constants.Palette;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
/** /**
* Author: Lorenzo Iovino on 13/06/2017. * Created by loke on 13/06/2017.
* Description: TTPasswordField component
*/ */
public class TTPasswordField extends JPasswordField{ public class TTPasswordField extends JPasswordField{
@ -17,11 +16,13 @@ public class TTPasswordField extends JPasswordField{
super(); super();
setBackground(Palette.inputBox_backgroundColor); setBackground(Palette.inputBox_backgroundColor);
setFont(Palette.textFont); setFont(Palette.inputBox_font);
setBounds(position.x, position.y, dimension.width, dimension.height); setBounds(position.x, position.y, dimension.width, dimension.height);
setPreferredSize(dimension); setPreferredSize(dimension);
setForeground(Palette.fontColor); setForeground(Palette.fontColor);
setText(placeholder); setText(placeholder);
parent.add(this); parent.add(this);
} }
} }

View file

@ -1,19 +1,19 @@
package com.texttwist.client.ui; package com.texttwist.client.ui;
import constants.Palette; import constants.Palette;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
/** /**
* Author: Lorenzo Iovino on 14/06/2017. * Created by loke on 14/06/2017.
* Description: TTScrollList component
*/ */
public class TTScrollList extends JList { public class TTScrollList extends JList {
public TTScrollList(Point position, Dimension dimension, ListModel listModel, JPanel parent){ public TTScrollList(Point position, Dimension dimension, ListModel listModel, JPanel parent){
super(listModel); super(listModel);
setBackground(Palette.scrollPanel_backgroundColor); setBackground(Palette.scrollPanel_backgroundColor);
setFont(Palette.numberFont); setFont(Palette.inputBox_font);
setBounds(position.x, position.y, dimension.width, dimension.height); setBounds(position.x, position.y, dimension.width, dimension.height);
setForeground(Palette.fontColor); setForeground(Palette.fontColor);

View file

@ -1,7 +1,7 @@
package com.texttwist.client.ui; package com.texttwist.client.ui;
import com.texttwist.client.App; import com.texttwist.client.App;
import constants.Palette; import constants.Palette;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.KeyAdapter; import java.awt.event.KeyAdapter;
@ -12,11 +12,11 @@ import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 14/06/2017. * Created by loke on 14/06/2017.
* Description: TTSearchBar component
*/ */
public class TTSearchBar extends TTContainer{ public class TTSearchBar extends TTContainer{
private DefaultListModel matchedUsers = new DefaultListModel();
public DefaultListModel<String> list = new DefaultListModel<String>(); public DefaultListModel<String> list = new DefaultListModel<String>();
private Callable<Object> add(TTInputField ctx){ private Callable<Object> add(TTInputField ctx){
@ -33,6 +33,7 @@ public class TTSearchBar extends TTContainer{
}; };
} }
public TTSearchBar(Point position, public TTSearchBar(Point position,
Dimension dimension, Dimension dimension,
String placeholder, String placeholder,
@ -40,16 +41,16 @@ public class TTSearchBar extends TTContainer{
super(position, dimension, Palette.inputBox_backgroundColor, -1, parent); super(position, dimension, Palette.inputBox_backgroundColor, -1, parent);
setBackground(Palette.scrollPanel_backgroundColor); setBackground(Palette.scrollPanel_backgroundColor);
setFont(Palette.textFont); setFont(Palette.inputBox_font);
setBounds(position.x, position.y, dimension.width, dimension.height); setBounds(position.x, position.y, dimension.width, dimension.height);
setPreferredSize(dimension); setPreferredSize(dimension);
setForeground(Palette.fontColor); setForeground(Palette.fontColor);
new TTLabel( TTLabel playerFinder_flavourText = new TTLabel(
new Point(20,40), new Point(20,40),
new Dimension(350,50), new Dimension(350,50),
"Add player", "<html>Add player</html>",
new Font(Palette.textFont.getFontName(), Font.ITALIC, 18), new Font(Palette.inputBox_font.getFontName(), Font.ITALIC, 18),
null, null,
parent); parent);
@ -59,18 +60,26 @@ public class TTSearchBar extends TTContainer{
placeholder, placeholder,
parent); parent);
new TTButton( /*TTScrollList userList = new TTScrollList(
new Point(20,120),
new Dimension(250,95),
matchedUsers,
parent
);*/
TTButton addUser = new TTButton(
new Point(70,140), new Point(70,140),
new Dimension(150,50), new Dimension(150,50),
"Add!", "Add!",
add(usernameField), add(usernameField),
parent); parent);
new TTLabel(
TTLabel playerToSendInvite_flavourText = new TTLabel(
new Point(305,40), new Point(305,40),
new Dimension(350,50), new Dimension(350,50),
"Double-Click on item for remove", "Double-Click on item for remove",
new Font(Palette.textFont.getFontName(), Font.ITALIC, 18), new Font(Palette.inputBox_font.getFontName(), Font.ITALIC, 18),
null, null,
parent); parent);
@ -80,12 +89,15 @@ public class TTSearchBar extends TTContainer{
list, list,
parent); parent);
playerToSendInvite.addMouseListener(new MouseAdapter() { playerToSendInvite.addMouseListener(new MouseAdapter() {
@Override @Override
public void mouseClicked(MouseEvent evt) { public void mouseClicked(MouseEvent evt) {
super.mouseClicked(evt); super.mouseClicked(evt);
JList thisList = (JList)evt.getSource(); JList thisList = (JList)evt.getSource();
if (evt.getClickCount() == 2) { if (evt.getClickCount() == 2) {
// Double-click detected
int index = thisList.locationToIndex(evt.getPoint()); int index = thisList.locationToIndex(evt.getPoint());
list.remove(index); list.remove(index);
} }

View file

@ -1,34 +1,41 @@
package constants; package constants;
/** /**
* Author: Lorenzo Iovino on 15/06/2017. * Created by loke on 15/06/2017.
* Description: Config
*/ */
public class Config { public class Config {
public static String AuthServiceURI = "localhost"; public static String AuthServerURI = "localhost";
public static Integer AuthServicePort = 9999; public static Integer AuthServerPort = 9999;
public static String MessageServiceURI = "localhost"; public static String GameServerURI = "localhost";
public static Integer MessageServicePort = 10000; public static Integer GameServerPort = 10000;
public static String WordsReceiverServiceURI = "localhost";
public static Integer WordsReceiverServicePort = 10001;
public static String ScoreMulticastServiceURI = "226.226.226.226"; public static String WordsReceiverServerURI = "localhost";
public static Integer WordsReceiverServerPort = 10001;
public static Integer NotificationServicePort = 20000; public static String ScoreMulticastServerURI = "226.226.226.226";
public static Integer NotificationServiceStubPort = 30000;
public static String NotificationServiceName ="notification";
public static String RedisServiceURI = "localhost"; public static String NotificationServerURI = "localhost";
public static Integer NotificationServerPort = 20000;
public static Integer NotificationServerStubPort = 5000;
public static String NotificationServerName ="notification";
public static int gameTimeout = 120; //2 minuti in sec
public static int joinMatchTimeout = 7*1000*60; //7 minuti in millisec
public static int sendWordsTimeout = 5*1000*60; //5 minuti in millisec
public static String getAuthServiceURI(){ public static int timeoutGame = 10;
return "rmi://".concat(AuthServiceURI).concat(":").concat(AuthServicePort.toString());
public static String getNotificationServerURI(){
return "rmi://".concat(NotificationServerURI).concat(":").concat(NotificationServerPort.toString());
}
public static String getAuthServerURI(){
return "rmi://".concat(AuthServerURI).concat(":").concat(AuthServerPort.toString());
}
public static String getGameServerURI(){
return "tcp://".concat(GameServerURI).concat(":").concat(GameServerPort.toString());
} }
} }

View file

@ -3,17 +3,14 @@ package constants;
import java.awt.*; import java.awt.*;
/** /**
* Author: Lorenzo Iovino on 13/06/2017. * Created by loke on 13/06/2017.
* Description: Palette and Styles
*/ */
public class Palette { public class Palette {
public static Color root_backgroundColor = new Color(145,181,88); public static Color root_backgroundColor = new Color(145,181,88);
public static Color inputBox_backgroundColor = new Color(250,250,250); //"#FAFAFA; public static Color inputBox_backgroundColor = new Color(250,250,250); //"#FAFAFA;
public static Color button_backgroundColor = new Color(105,130,63); //#69823f public static Color button_backgroundColor = new Color(105,130,63); //#69823f
public static Font textFont = new Font("DK Trained Monkey", Font.BOLD, 20); public static Font inputBox_font = new Font("DK Trained Monkey", Font.BOLD, 26);
public static Font inputboxFont = new Font("DK Trained Monkey", Font.BOLD, 18); public static Font password_font = new Font("Arial Black", Font.BOLD, 26);
public static Font numberFont = new Font("Arial Black", Font.BOLD, 20);
public static Color fontColor = new Color(95,0,0); public static Color fontColor = new Color(95,0,0);
public static Color registerLblBtn_color = new Color(95,0,0); public static Color registerLblBtn_color = new Color(95,0,0);
public static Color registerLblBtn_onmouseover_color = new Color(95,0,0, 127); public static Color registerLblBtn_onmouseover_color = new Color(95,0,0, 127);
@ -21,5 +18,11 @@ public class Palette {
public static Color scrollPanel_backgroundColor = new Color(220,229,207); public static Color scrollPanel_backgroundColor = new Color(220,229,207);
public static Color dialog_alert = Color.red; public static Color dialog_alert = Color.red;
public static Color dialog_success = new Color(53,66,32); public static Color dialog_success = new Color(53,66,32);
public static Font button_font = new Font("DK Trained Monkey", Font.BOLD, 25);
public static Font button_font = new Font("DK Trained Monkey", Font.BOLD, 30);
public Palette() {
//TODO fetchare dal server questi dati
}
} }

View file

@ -1,15 +1,15 @@
package interfaces; package interfaces;
import models.Response; import models.Response;
import java.rmi.Remote; import java.rmi.Remote;
import java.rmi.RemoteException; import java.rmi.RemoteException;
/** /**
* Author: Lorenzo Iovino on 15/06/2017. * Created by loke on 15/06/2017.
* Description: IAuth
*/ */
public interface IAuth extends Remote { public interface IAuth extends Remote {
Response login(String userName, String password) throws RemoteException; Response login(String userName, String password) throws RemoteException;
Response register(String userName, String password) throws RemoteException; Response register(String userName, String password) throws RemoteException;
Response logout(String userName, String token, INotificationClient stub) throws RemoteException; Response logout(String userName, String token) throws RemoteException;
} }

View file

@ -1,13 +1,15 @@
package interfaces; package interfaces;
import models.Response;
import javax.swing.*; import javax.swing.*;
import java.rmi.Remote; import java.rmi.Remote;
import java.rmi.RemoteException; import java.rmi.RemoteException;
/** /**
* Author: Lorenzo Iovino on 19/06/2017. * Created by loke on 19/06/2017.
* Description: INotificationClient
*/ */
public interface INotificationClient extends Remote{ public interface INotificationClient extends Remote{
void sendInvite(String userName, DefaultListModel<String> users) throws RemoteException;
Response sendInvite(String userName, DefaultListModel<String> users) throws RemoteException;
} }

View file

@ -1,15 +1,16 @@
package interfaces; package interfaces;
import javax.swing.*;
import java.rmi.Remote; import java.rmi.Remote;
import java.rmi.RemoteException; import java.rmi.RemoteException;
/** /**
* Author: Lorenzo Iovino on 19/06/2017. * Created by loke on 19/06/2017.
* Description: Main
*/ */
public interface INotificationServer extends Remote { public interface INotificationServer extends Remote {
void registerForCallback (INotificationClient ClientInterface) throws RemoteException; /* registrazione per la callback */
void unregisterForCallback (INotificationClient ClientInterface) throws RemoteException; public void registerForCallback (INotificationClient ClientInterface) throws RemoteException;
void sendInvitations(String username, DefaultListModel<String> users) throws RemoteException;
/* cancella registrazione per la callback */
public void unregisterForCallback (INotificationClient ClientInterface) throws RemoteException;
} }

View file

@ -2,11 +2,11 @@ package models;
import javax.swing.*; import javax.swing.*;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
* Author: Lorenzo Iovino on 18/06/2017. * Created by loke on 18/06/2017.
* Description: Main
*/ */
public class Message implements Serializable { public class Message implements Serializable {
public String sender; public String sender;

View file

@ -1,11 +1,9 @@
package models; package models;
import org.json.simple.JsonObject; import org.json.simple.JsonObject;
import java.io.Serializable; import java.io.Serializable;
/** /**
* Author: Lorenzo Iovino on 15/06/2017. * Created by loke on 15/06/2017.
* Description: Response
*/ */
public class Response implements Serializable{ public class Response implements Serializable{
public String message; public String message;

View file

@ -1,8 +1,7 @@
package models; package models;
/** /**
* Author: Lorenzo Iovino on 17/06/2017. * Created by loke on 17/06/2017.
* Description: Main
*/ */
public class Session { public class Session {
@ -13,4 +12,5 @@ public class Session {
this.token = token; this.token = token;
this.account = account; this.account = account;
} }
} }

View file

@ -1,12 +1,9 @@
package models; package models;
import java.io.Serializable;
/** /**
* Author: Lorenzo Iovino on 18/06/2017. * Created by loke on 18/06/2017.
* Description: Main
*/ */
public class User implements Serializable{ public class User {
public String userName; public String userName;
public String password; public String password;
@ -21,4 +18,6 @@ public class User implements Serializable{
public void addScore(Integer score){ public void addScore(Integer score){
this.score += score; this.score += score;
} }
} }

View file

@ -1,45 +1,48 @@
package utilities; package utilities;
import java.io.*; import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Date; import java.util.Date;
/** /**
* Author: Lorenzo Iovino on 15/06/2017. * Created by loke on 15/06/2017.
* Description: This is a module for logging the System output in files
*/ */
public class Logger { public class Logger {
private final File logFile; private static File logFile;
private final String name; private static String name;
private static PrintWriter out; private static PrintWriter out;
private static BufferedWriter bw; private static BufferedWriter bw;
private static FileWriter fw; private static FileWriter fw;
private Boolean debug;
public Logger(File logFile, String name, Boolean debug) throws IOException { public Logger(File logFile, String name) throws IOException {
this.logFile = logFile; this.logFile = logFile;
this.name = name; this.name = name;
this.debug = debug;
} }
public synchronized void write(String msg){ public synchronized static void write(String msg){
try { try {
fw = new FileWriter(logFile, true); fw = new FileWriter(logFile, true);
bw = new BufferedWriter(fw); bw = new BufferedWriter(fw);
out = new PrintWriter(bw); out = new PrintWriter(bw);
System.out.println(msg);
Date d = new Date(); Date d = new Date();
out.append("LOGGER ("+name+"): " + d.toString() + " - " + msg + "\n"); out.append("LOGGER ("+name+"): " + d.toString() + " - " + msg + "\n");
if(debug) {
System.out.println("LOGGER (" + name + "): " + d.toString() + " - " + msg + "\n");
}
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
finally { finally {
try {
out.close(); out.close();
try {
bw.close(); bw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fw.close(); fw.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();

View file

@ -1,22 +0,0 @@
package utilities;
import javafx.util.Pair;
import javax.swing.*;
/**
* Author: Lorenzo Iovino on 12/07/2017.
* Description: This is a module of parse utilities for different purposes
*/
public class Parse {
//Parse score and split by ":" character
public static DefaultListModel<Pair<String, Integer>> score(DefaultListModel<String> score) {
DefaultListModel<Pair<String, Integer>> list = new DefaultListModel<>();
for (int i = 0; i < score.size() - 1; i++) {
String[] splitted = score.get(i).split(":");
list.addElement(new Pair<>(splitted[0], new Integer(splitted[1])));
}
return list;
}
}

View file

@ -1,3 +0,0 @@
Manifest-Version: 1.0
Main-Class: com.texttwist.server.Main

View file

@ -11,7 +11,5 @@
<orderEntry type="library" name="com.github.cliftonlabs:json-simple:2.1.2" level="project" /> <orderEntry type="library" name="com.github.cliftonlabs:json-simple:2.1.2" level="project" />
<orderEntry type="module" module-name="Commons" /> <orderEntry type="module" module-name="Commons" />
<orderEntry type="module" module-name="Client" /> <orderEntry type="module" module-name="Client" />
<orderEntry type="library" name="jedis-2.1.0-sources" level="application" />
<orderEntry type="library" name="redis.clients:jedis:2.9.0" level="project" />
</component> </component>
</module> </module>

View file

@ -1,3 +0,0 @@
Manifest-Version: 1.0
Main-Class: com.texttwist.server.Main

View file

@ -1,12 +1,13 @@
package com.texttwist.server; package com.texttwist.server;
import utilities.Logger;
import java.io.File;
import java.io.IOException; import java.io.IOException;
/**
* Author: Lorenzo Iovino on 14/06/2017.
* Description: Main
*/
public class Main { public class Main {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
new Server(); Server ttServer = new Server();
} }
} }

View file

@ -1,92 +1,55 @@
package com.texttwist.server; package com.texttwist.server;
import com.texttwist.server.models.Dictionary; import com.texttwist.server.components.Auth;
import com.texttwist.server.services.AuthService; import com.texttwist.server.components.GameServer;
import com.texttwist.server.services.MessageService; import com.texttwist.server.components.NotificationServer;
import com.texttwist.server.services.NotificationService;
import com.texttwist.server.services.ReceiveWordsService;
import constants.Config; import constants.Config;
import interfaces.INotificationServer; import interfaces.INotificationServer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import utilities.Logger; import utilities.Logger;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.rmi.AlreadyBoundException; import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry; import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry; import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject; import java.rmi.server.UnicastRemoteObject;
/** /**
* Author: Lorenzo Iovino on 15/06/2017. * Created by loke on 15/06/2017.
* Description: Server. Initialize all services.
*/ */
public class Server { public class Server {
public static NotificationService notificationServer; public static NotificationServer notificationServer;
public static JedisPool jedisPool;
public static Logger logger;
public static AuthService auth;
private String dictionaryPath = "./Server/resources/dictionary";
public static Dictionary dict;
public static Integer multicastId = Config.NotificationServiceStubPort;
public Server() throws IOException { public Server() throws IOException {
logger = new Logger(new File("./server.log"), "Server", true); //Start services
Server.logger.write("Services starting ..."); Logger logger = new Logger(new File("./server.log"), "Server");
startAuthService();
startJedisService();
startMessageService();
startWordsReceiverService();
startNotificationService();
dict = new Dictionary(dictionaryPath); Logger.write("Server starting ...");
Server.logger.write("Services started correctly ...");
}
private void startAuthService(){
//Starting Auth service based on RMI
try { try {
auth = new AuthService(); //Definitions of registry for auth
Registry authRegistry = LocateRegistry.createRegistry(Config.AuthServicePort); Auth auth = new Auth(Config.AuthServerPort);
Registry authRegistry = LocateRegistry.createRegistry(auth.serverPort);
authRegistry.bind("auth", auth); authRegistry.bind("auth", auth);
} catch (RemoteException e) {
Server.logger.write("SERVER: RMI authentication service error (Remote exception)");
} catch (AlreadyBoundException e) {
Server.logger.write("SERVER: RMI authentication service can't use this port because is busy ");
}
}
private void startJedisService(){ GameServer gameServer = new GameServer(Config.GameServerPort);
//Starting Jedis pool for Redis connection new Thread(gameServer).start();
jedisPool = new JedisPool(new JedisPoolConfig(), Config.RedisServiceURI);
}
private void startMessageService(){
//Starting the Message service based on TCP
new Thread(new MessageService()).start();
}
private void startWordsReceiverService(){
//Starting the Receive Words service based on UDP
new Thread(new ReceiveWordsService()).start();
}
private void startNotificationService(){
//Starting Notification service based on RMI
try { try {
notificationServer = new NotificationService(); /*registrazione presso il registry */
INotificationServer stub = (INotificationServer) UnicastRemoteObject.exportObject(notificationServer, Config.NotificationServicePort); notificationServer = new NotificationServer();
LocateRegistry.createRegistry(Config.NotificationServiceStubPort); INotificationServer stub = (INotificationServer) UnicastRemoteObject.exportObject(notificationServer, Config.NotificationServerPort);
LocateRegistry.createRegistry(Config.NotificationServerStubPort);
Registry notificationRegistry = LocateRegistry.getRegistry(Config.NotificationServerStubPort);
notificationRegistry.bind(Config.NotificationServerName, stub);
Registry notificationRegistry = LocateRegistry.getRegistry(Config.NotificationServiceStubPort);
notificationRegistry.bind(Config.NotificationServiceName, stub); } catch (Exception e) {
} catch (RemoteException e) { System.out.println("Eccezione" + e);
Server.logger.write("SERVER: RMI notification service error (Remote exception)"); }
Logger.write("Server started");
} catch (AlreadyBoundException e) { } catch (AlreadyBoundException e) {
Server.logger.write("SERVER: RMI notification service can't use this port because is busy "); e.printStackTrace();
} }
} }
} }

View file

@ -0,0 +1,83 @@
package com.texttwist.server.components;
import models.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* Created by loke on 18/06/2017.
*/
public class AccountsManager {
public List<User> users = Collections.synchronizedList(new ArrayList<User>());
private static class Holder {
static final AccountsManager INSTANCE = new AccountsManager();
}
public static AccountsManager getInstance() {
return AccountsManager.Holder.INSTANCE;
}
private AccountsManager(){
users.add(new User("a","a",0));
users.add(new User("b","b",0));
users.add(new User("c","c",0));
users.add(new User("d","d",0));
}
public boolean register(String userName, String password) {
if(!exists(userName)){
return users.add(new User(userName, password,0));
} else {
return false;
}
}
public boolean exists(String userName) {
synchronized(users) {
Iterator<User> i = users.iterator();
while (i.hasNext()) {
if (i.next().userName.equals(userName)) {
return true;
}
}
return false;
}
}
public boolean checkPassword(String userName, String password) {
synchronized(users) {
Iterator<User> 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){
synchronized(users) {
Iterator<User> 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();
}
}

View file

@ -0,0 +1,78 @@
package com.texttwist.server.components;
import interfaces.IAuth;
import models.Response;
import org.json.simple.JsonObject;
import utilities.Logger;
import java.math.BigInteger;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.security.SecureRandom;
/**
* 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;
Logger.write("Auth Service running at "+serverPort+" port...");
}
@Override
public Response register(String userName, String password) throws RemoteException {
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)){
Logger.write("Registration successfull");
return new Response("Registration successfull", 200, null);
} else {
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 {
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);
Logger.write("Login successfull");
return new Response("Login successfull", 200, data);
}
}
Logger.write("Login unsuccessfull");
return new Response("Login unsuccessfull", 400, null);
}
@Override
public Response logout(String userName, String token) throws RemoteException {
Logger.write("Invoked logout with username=" + userName + " AND " + " token=" + token);
if ((userName != null && !userName.isEmpty()) && (token != null && !token.isEmpty())) {
boolean res = SessionsManager.getInstance().remove(userName);
if(res) {
Logger.write("Logout successfull");
}
}
SessionsManager.getInstance().remove(userName);
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);
}
}

View file

@ -1,47 +1,80 @@
package com.texttwist.server.services;
import com.texttwist.server.Server; package com.texttwist.server.components;
import com.texttwist.server.tasks.MessageDispatcher; import com.sun.org.apache.xpath.internal.operations.Bool;
import com.texttwist.server.models.Dictionary; import com.texttwist.server.models.Dictionary;
import com.texttwist.server.models.Match;
import com.texttwist.server.tasks.SendInvitations;
import com.texttwist.server.tasks.WaitForPlayers;
import constants.Config; import constants.Config;
import jdk.nashorn.internal.parser.JSONParser;
import models.Message; import models.Message;
import models.Session;
import org.json.simple.JsonObject;
import utilities.Logger;
import javax.swing.*;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.*; import java.net.*;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.*; import java.nio.channels.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static java.nio.channels.SelectionKey.OP_ACCEPT; import static java.nio.channels.SelectionKey.OP_ACCEPT;
import static java.nio.channels.SelectionKey.OP_READ; import static java.nio.channels.SelectionKey.OP_READ;
public class GameServer implements Runnable{
/** protected int serverPort;
* Author: Lorenzo Iovino on 17/06/2017. protected ServerSocketChannel serverSocketChannel = null;
* Description: Message Service protected ThreadProxy proxy;
*/ ByteBuffer buffer = ByteBuffer.allocate(1024);
public class MessageService implements Runnable{ ByteBuffer buffer2 = ByteBuffer.allocate(1024);
private Selector selector = null; DatagramChannel datagramChannel;
private ExecutorService dispatcherPool = Executors.newCachedThreadPool(); protected Selector selector = null;
protected ExecutorService threadPool = Executors.newCachedThreadPool();
private String dictionaryPath = "./Server/resources/dictionary";
public static Dictionary dict;
public MessageService()
{
try {
selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); public static List<Match> activeMatches = Collections.synchronizedList(new ArrayList<>());
serverSocketChannel.configureBlocking(false); public static Integer multicastID = 4000;
serverSocketChannel.socket().bind(new InetSocketAddress(Config.MessageServicePort));
serverSocketChannel.register(selector, OP_ACCEPT);
Server.logger.write("Message Service is running at "+Config.MessageServicePort +" port...");
} catch (IOException e) { public GameServer(int port){
e.printStackTrace(); this.serverPort = port;
}
} }
public void run(){ public void run(){
dict = new Dictionary(dictionaryPath);
try {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(serverPort));
serverSocketChannel.register(selector, OP_ACCEPT);
// datagramSocket = new DatagramSocket(Config.WordsReceiverServerPort);
InetSocketAddress address = new InetSocketAddress(Config.WordsReceiverServerPort);
datagramChannel = DatagramChannel.open();
DatagramSocket datagramSocket = datagramChannel.socket();
datagramSocket.bind(address);
Logger.write("GamePage Service is running at "+this.serverPort+" port...");
} catch (IOException e) {
e.printStackTrace();
}
while (true) { while (true) {
try { try {
selector.select(); selector.select();
@ -51,8 +84,7 @@ public class MessageService implements Runnable{
Iterator<SelectionKey> iter = selector.selectedKeys().iterator(); Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
ByteBuffer bufferMessages = ByteBuffer.allocate(1024); buffer = ByteBuffer.allocate(1024);
bufferMessages.clear();
SocketChannel client = null; SocketChannel client = null;
SelectionKey key = iter.next(); SelectionKey key = iter.next();
iter.remove(); iter.remove();
@ -67,13 +99,17 @@ public class MessageService implements Runnable{
case OP_READ: case OP_READ:
client = (SocketChannel) key.channel(); client = (SocketChannel) key.channel();
if (client.read(bufferMessages) != -1) { //buffer.clear();
bufferMessages.flip(); if (client.read(buffer) != -1) {
String line = new String(bufferMessages.array(), bufferMessages.position(), bufferMessages.remaining()); buffer.flip();
String line = new String(buffer.array(), buffer.position(), buffer.remaining());
if (line.startsWith("MESSAGE")) { if (line.startsWith("MESSAGE")) {
SessionsManager.getInstance().printAll();
Message msg = Message.toMessage(line); Message msg = Message.toMessage(line);
MessageDispatcher proxy = new MessageDispatcher(msg, client, bufferMessages); proxy = new ThreadProxy(msg, client, datagramChannel, buffer2);
dispatcherPool.submit(proxy); Future<Boolean> identifyMessage = threadPool.submit(proxy);
System.out.println(line);
} }
if (line.startsWith("CLOSE")) { if (line.startsWith("CLOSE")) {
@ -90,6 +126,7 @@ public class MessageService implements Runnable{
key.cancel(); key.cancel();
} }
break; break;
default: default:
break; break;
} }
@ -99,6 +136,7 @@ public class MessageService implements Runnable{
} catch (IOException e1) { } catch (IOException e1) {
e1.printStackTrace(); e1.printStackTrace();
} }
e.printStackTrace();
} }
} }
} }

View file

@ -1,54 +1,52 @@
package com.texttwist.server.services; package com.texttwist.server.components;
import com.texttwist.server.Server;
import constants.Config;
import interfaces.INotificationClient; import interfaces.INotificationClient;
import interfaces.INotificationServer; import interfaces.INotificationServer;
import javax.swing.*; import javax.swing.*;
import java.rmi.Remote;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
/** /**
* Author: Lorenzo Iovino on 19/06/2017. * Created by loke on 19/06/2017.
* Description: Notification Service
*/ */
public class NotificationService implements INotificationServer { public class NotificationServer implements INotificationServer {
private List<INotificationClient> clients; private List<INotificationClient> clients;
public NotificationService() throws RemoteException { public NotificationServer() throws RemoteException {
super(); super();
Server.logger.write("Notification Service running at "+ Config.NotificationServicePort +" port..."); clients = new ArrayList<INotificationClient>();
clients = new ArrayList<>();
} }
public synchronized void registerForCallback(INotificationClient clientInterface) throws RemoteException { public synchronized void registerForCallback(INotificationClient clientInterface) throws RemoteException {
if(!clients.contains(clientInterface)){ if(!clients.contains(clientInterface)){
clients.add(clientInterface); clients.add(clientInterface);
System.out.print("New client registered");
} }
} }
public synchronized void unregisterForCallback(INotificationClient client) throws RemoteException { public synchronized void unregisterForCallback(INotificationClient client) throws RemoteException {
clients.remove(client); if(clients.remove(client)) {
System.out.println("Client unregistered");
} else {
System.out.println("Unable to unregister client");
}
} }
public synchronized void sendInvitations(String username, DefaultListModel<String> users){ public synchronized void sendInvitations(String username, DefaultListModel<String> users){
System.out.println("Starting callbacks");
Iterator i = clients.iterator(); Iterator i = clients.iterator();
INotificationClient client = null; while(i.hasNext()){
while (i.hasNext()) { INotificationClient client = (INotificationClient) i.next();
client = (INotificationClient) i.next(); try{
try {
client.sendInvite(username, users); client.sendInvite(username, users);
} catch (RemoteException e) { } catch (RemoteException e) {
try { e.printStackTrace();
unregisterForCallback(client);
} catch (RemoteException e1) {
e1.printStackTrace();
}
} }
} }
} }
} }

View file

@ -0,0 +1,92 @@
package com.texttwist.server.components;
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<Session> sessions = Collections.synchronizedList(new ArrayList<Session>());
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(){
synchronized(sessions) {
Iterator<Session> 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) {
synchronized(sessions) {
Iterator<Session> 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) {
synchronized(sessions) {
Iterator<Session> 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) {
synchronized(sessions) {
Iterator<Session> i = sessions.iterator();
while (i.hasNext()) {
if (i.next().token.equals(token)) {
return true;
}
}
return false;
}
}
}

View file

@ -0,0 +1,229 @@
package com.texttwist.server.components;
import com.texttwist.server.models.Match;
import com.texttwist.server.tasks.*;
import constants.Config;
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<Boolean> {
protected final ExecutorService threadPool = Executors.newCachedThreadPool();
private final Message request;
private final SocketChannel socketChannel;
private final DatagramChannel datagramChannel;
private ByteBuffer buffer;
ThreadProxy(Message request, SocketChannel socketChannel, DatagramChannel datagramChannel, ByteBuffer buffer){
this.request = request;
this.socketChannel = socketChannel;
this.datagramChannel = datagramChannel;
this.buffer = buffer;
}
private Boolean isValidToken(String token){
return SessionsManager.getInstance().isValidToken(token);
}
@Override
public Boolean call() {
ByteBuffer buffer = ByteBuffer.allocate(1024);
byte[] byteMessage = null;
System.out.println("Selecting right task for new thread");
if(isValidToken(request.token)){
switch(request.message){
case "START_GAME":
Future<Boolean> onlineUsers = threadPool.submit(new CheckOnlineUsers(request.data));
try {
Boolean usersOnline = onlineUsers.get();
if(usersOnline){
Future<Boolean> 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<String> matchName = new DefaultListModel<>();
matchName.addElement(request.sender);
Future<Boolean> joinMatch = threadPool.submit(new JoinMatch(request.sender, matchName, socketChannel));
Boolean joinMatchRes = joinMatch.get();
if(!joinMatchRes){
//NON FARE NULLA, ASPETTA GLI ALTRI
Message message = new Message("INVITES_ALL_SENDED", "", "", new DefaultListModel<String>());
byteMessage = message.toString().getBytes();
buffer = ByteBuffer.wrap(byteMessage);
socketChannel.write(buffer);
Future<Boolean> joinTimeout = threadPool.submit(new JoinTimeout(match));
Boolean joinTimeoutRes = joinTimeout.get();
if(!joinTimeoutRes){
Future<Boolean> 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 {
return false;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
Message message = new Message("USER_NOT_ONLINE", "", "", new DefaultListModel<String>());
byteMessage = new String(message.toString()).getBytes();
buffer.clear();
buffer = ByteBuffer.wrap(byteMessage);
this.socketChannel.write(buffer);
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
case "FETCH_HIGHSCORES":
Future<DefaultListModel<String>> computeHighscores = threadPool.submit(new ComputeHighscores());
try {
DefaultListModel<String> computeHighscoresRes = computeHighscores.get();
Message message = new Message("HIGHSCORES", "", "", computeHighscoresRes);
byteMessage = message.toString().getBytes();
buffer = ByteBuffer.wrap(byteMessage);
try {
socketChannel.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
break;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
case "JOIN_GAME":
Future<Boolean> joinMatch = threadPool.submit(new JoinMatch(request.sender, request.data, socketChannel));
try {
Boolean joinMatchRes = joinMatch.get();
if(joinMatchRes){
System.out.print("START THE GAME!!!!");
final Match match = Match.findMatch(activeMatches, request.data.get(0));
Future<DefaultListModel<String>> 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++) {
System.out.println("INVIO");
SocketChannel socketClient = match.playersSocket.get(i).getValue();
if(socketClient != null) {
buffer.clear();
Message message = new Message("GAME_STARTED", "", "", match.letters);
match.startGame();
byteMessage = message.toString().getBytes();
buffer = ByteBuffer.wrap(byteMessage);
try {
socketClient.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
//clientSocket.close();
}
}
//Start receive words: tempo masimo 5 minuti per completare l'invio delle lettere.
Future<Boolean> receiveWords = threadPool.submit(new ReceiveWords(match, datagramChannel, buffer));
Boolean receiveWordsRes = receiveWords.get();
if(receiveWordsRes){
System.out.println("ZERO PUNTI a chi non ha ancora inviato le lettere, TIMER SCADUTO");
} else {
System.out.println("TUTTI I GIOCATORI HANNO CONSEGNATO IN TEMPO");
}
match.setUndefinedScorePlayersToZero();
while(true) {
Message msg = new Message("FINALSCORE", "SERVER", "", match.getMatchPlayersScoreAsStringList());
MulticastSocket multicastSocket = new MulticastSocket(match.multicastId);
System.out.println(multicastSocket);
System.out.println(match.multicastId);
InetAddress ia = InetAddress.getByName(Config.ScoreMulticastServerURI);
DatagramPacket hi = new DatagramPacket(msg.toString().getBytes(), msg.toString().length(), ia, match.multicastId);
System.out.println(msg.toString());
multicastSocket.send(hi);
System.out.println(Match.findMatchIndex(activeMatches, match.matchCreator));
activeMatches.remove(Match.findMatchIndex(activeMatches, match.matchCreator));
//multicastSocket.disconnect();
//multicastSocket.close();
}
//RISPONDI CON LA CLASSIFICA
// break;
//ULTIMO A JOINARE! INIZIA GIOCO
} else {
System.out.print("WAIT FRIENDS");
//NON FARE NULLA, ASPETA GLI ALTRI
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
default:
break;
}
} else {
System.out.print("TOKEN NON VALIDO");
return false;
}
return false;
}
}

View file

@ -1,76 +0,0 @@
package com.texttwist.server.models;
import com.texttwist.server.services.JedisService;
import models.User;
import java.io.Serializable;
import java.util.*;
/**
* Author: Lorenzo Iovino on 18/06/2017.
* Description: Accounts
*/
public class Accounts {
public List<User> users = Collections.synchronizedList(new ArrayList<User>());
private static class Holder {
static final Accounts INSTANCE = new Accounts();
}
public static Accounts getInstance() {
return Accounts.Holder.INSTANCE;
}
private Accounts(){
List<Serializable> l = JedisService.get("users");
for(int i=0; i<l.size(); i++) {
users.add((User) l.get(i));
}
}
public boolean register(String userName, String password) {
if(!exists(userName)){
User newUser = new User(userName, password,0);
Boolean res = users.add(newUser);
JedisService.add("users", newUser);
return res;
} else {
return false;
}
}
public boolean exists(String userName) {
Iterator<User> i = users.iterator();
while (i.hasNext()) {
if (i.next().userName.equals(userName)) {
return true;
}
}
return false;
}
public boolean checkPassword(String userName, String password) {
Iterator<User> 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<User> i = users.iterator();
while (i.hasNext()) {
User u = i.next();
if (u.userName.equals(userName)) {
return u;
}
}
return null;
}
}

View file

@ -1,19 +1,23 @@
package com.texttwist.server.models; package com.texttwist.server.models;
import com.texttwist.server.Server;
import javax.swing.*; import javax.swing.*;
import java.io.*; import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Random; import java.util.Random;
import java.util.stream.Stream;
/** /**
* Author: Lorenzo Iovino on 26/06/2017. * Created by loke on 26/06/2017.
* Description: Dictionary Model. Provides the dictionary and methods for manage it
*/ */
public class Dictionary { public class Dictionary {
private static DefaultListModel<String> wordList = new DefaultListModel<>(); static DefaultListModel<String> wordList = new DefaultListModel<>();
private Random randomGenerator;
public Dictionary(String dictionaryPath) { public Dictionary(String dictionaryPath) {
try (BufferedReader br = new BufferedReader(new FileReader(new File(dictionaryPath)))) { try (BufferedReader br = new BufferedReader(new FileReader(new File(dictionaryPath)))) {
@ -21,16 +25,15 @@ public class Dictionary {
wordList.addElement(line); wordList.addElement(line);
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Server.logger.write("DICTIONARY: Dictionary file not found!"); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
Server.logger.write("DICTIONARY: Can't read dictionary file!"); e.printStackTrace();
} }
} }
//Get a random word in wordsList with minimumWordSize < size < maximumWordSize
public String getRandomWord(int minimumWordSize, int maximumWordSize){ public String getRandomWord(int minimumWordSize, int maximumWordSize){
Random randomGenerator = new Random(); randomGenerator = new Random();
int index = randomGenerator.nextInt(wordList.size()); int index = randomGenerator.nextInt(wordList.size());
String word = wordList.get(index); String word = wordList.get(index);
if(word.length() >= minimumWordSize && word.length() <= maximumWordSize) { if(word.length() >= minimumWordSize && word.length() <= maximumWordSize) {
@ -52,7 +55,6 @@ public class Dictionary {
} }
} }
//Check if a word is contained in dictionary
public static Boolean isContainedInDictionary(String word){ public static Boolean isContainedInDictionary(String word){
if(word.equals("")){ if(word.equals("")){
return true; return true;
@ -64,4 +66,5 @@ public class Dictionary {
} }
return false; return false;
} }
} }

View file

@ -1,58 +1,28 @@
package com.texttwist.server.models; package com.texttwist.server.models;
import com.texttwist.server.Server; import com.texttwist.server.components.GameServer;
import com.texttwist.server.services.MessageService; import constants.Config;
import com.texttwist.server.tasks.TimeoutMatch;
import javafx.util.Pair; import javafx.util.Pair;
import javax.swing.*; import javax.swing.*;
import java.net.DatagramSocket;
import java.net.Socket;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.util.*; import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.texttwist.server.components.GameServer.activeMatches;
/** /**
* Author: Lorenzo Iovino on 23/06/2017. * Created by loke on 23/06/2017.
* Description: Match Model. Methods for manage the matches and model of single match.
* Single point of concurrent access.
*/ */
public class Match { public class Match {
public final List<Pair<String,Integer>> playersStatus = Collections.synchronizedList(new ArrayList<>()); //Usare Liste!!!!!!!
/****GLOBAL AREA OF ALL MATCHES****/
//Players status: A list of pair where elements are <playerName, status>.
// status is 0 if user is not currently in a match, and 1 otherwise
public final List<Pair<String,Integer>> playersStatus = Collections.synchronizedList(new ArrayList<>());
//Players socket: A list of pair where elements are <playerName, socketChannel>.
// socketChannel is the TCP socket associated with client for messages exchange
public final List<Pair<String,SocketChannel>> playersSocket = Collections.synchronizedList(new ArrayList<>()); public final List<Pair<String,SocketChannel>> playersSocket = Collections.synchronizedList(new ArrayList<>());
//Players score: A list of pair where elements are <playerName, score>.
public final List<Pair<String,Integer>> playersScore = Collections.synchronizedList(new ArrayList<>());
//Players score: A list of active matches.
public static List<Match> activeMatches = Collections.synchronizedList(new ArrayList<>());
/****SINGLE INSTANCE OF MATCH****/
//If match is started
private boolean started = false; private boolean started = false;
//Name of the creator of the match
public final String matchCreator; public final String matchCreator;
//MulticastID associated with this match
public Integer multicastId; public Integer multicastId;
//True if happen timeout, false otherwise
public boolean matchTimeout = false;
public boolean joinTimeout = false;
//Letters of the match
public DefaultListModel<String> letters; public DefaultListModel<String> letters;
public final List<Pair<String,Integer>> playersScore = Collections.synchronizedList(new ArrayList<>());
private ExecutorService matchTimeoutThread = Executors.newSingleThreadExecutor();
public Match(String matchCreator, DefaultListModel<String> players){ public Match(String matchCreator, DefaultListModel<String> players){
for (int i =0; i < players.size(); i++){ for (int i =0; i < players.size(); i++){
@ -63,17 +33,26 @@ public class Match {
this.multicastId = this.generateMulticastId(); this.multicastId = this.generateMulticastId();
this.matchCreator = matchCreator; this.matchCreator = matchCreator;
} }
public static Match findMatch(List<Match> matches, String matchName){ public static Match findMatch(List<Match> matches, String matchName){
for (Match match : matches) { for (int i = 0; i < matches.size(); i++) {
if (match.matchCreator.equals(matchName)) { if (matches.get(i).matchCreator.equals(matchName)) {
return match; return matches.get(i);
} }
} }
return null; return null;
} }
public void printAll(){
for (int i = 0; i < playersScore.size(); i++) {
System.out.println(playersScore.get(i).getKey() + " : " +playersScore.get(i).getValue());
}
}
public static int findMatchIndex(List<Match> matches, String matchName){ public static int findMatchIndex(List<Match> matches, String matchName){
for (int i = 0; i < matches.size(); i++) { for (int i = 0; i < matches.size(); i++) {
if (matches.get(i).matchCreator.equals(matchName)) { if (matches.get(i).matchCreator.equals(matchName)) {
@ -87,36 +66,41 @@ public class Match {
return started; return started;
} }
public static Match findMatchByPlayerName(String player){ public Match findMatchByPlayer(String player){
for (Match activeMatch : activeMatches) { for (int i = 0; i < activeMatches.size(); i++) {
for (int j = 0; j < activeMatch.playersStatus.size(); j++) { for (int j = 0; j < playersStatus.size(); j++) {
if (activeMatch.playersStatus.get(j).getKey().equals(player)) { if (activeMatches.get(i).playersStatus.get(j).getKey().equals(player)) {
return activeMatch; return activeMatches.get(i);
} }
} }
/* if (matches.get(i).matchCreator.equals(matchName)) {
return i;
}*/
} }
return null; return null;
} }
public void startGame(){ public void startGame(){
this.started = true; this.started=true;
matchTimeoutThread.submit(new TimeoutMatch(this));
} }
public void setScore(String player, Integer score){ public void setScore(String player, Integer score){
Match m = findMatchByPlayerName(player); final Match m = findMatchByPlayer(player);
if(m!=null) { m.printAll();
System.out.println("ENTRO");
for (int i = 0; i < m.playersScore.size(); i++) { for (int i = 0; i < m.playersScore.size(); i++) {
if (m.playersScore.get(i).getKey().equals(player)) { if (m.playersScore.get(i).getKey().equals(player)) {
m.playersScore.set(i, new Pair<>(player, score)); m.playersScore.set(i, new Pair<String, Integer>(player, score));
} System.out.println("SEtting score of " + m.playersScore.get(i).getKey() + " to " + score);
} }
} }
} }
public Boolean allPlayersSendedHisScore(){ public Boolean allPlayersSendedHisScore(){
for (Pair<String, Integer> player : playersScore) { printAll();
if (player.getValue() == -1) { for (int i = 0; i < playersScore.size(); i++) {
if (playersScore.get(i).getValue() == -1) {
return false; return false;
} }
} }
@ -126,23 +110,24 @@ public class Match {
public void setUndefinedScorePlayersToZero(){ public void setUndefinedScorePlayersToZero(){
for (int i = 0; i < playersScore.size(); i++) { for (int i = 0; i < playersScore.size(); i++) {
if (playersScore.get(i).getValue() == -1) { if (playersScore.get(i).getValue() == -1) {
playersScore.set(i, new Pair<>(playersScore.get(i).getKey(), 0)); playersScore.set(i, new Pair<String, Integer>(playersScore.get(i).getKey(), 0));
} }
} }
} }
public DefaultListModel<String> getMatchPlayersScoreAsStringList(){ public DefaultListModel<String> getMatchPlayersScoreAsStringList(){
DefaultListModel<String> l = new DefaultListModel<>(); DefaultListModel<String> l = new DefaultListModel<>();
for (Pair<String, Integer> player : playersScore) { for (int i = 0; i < playersScore.size(); i++) {
l.addElement(player.getKey() + ":" + player.getValue()); l.addElement(playersScore.get(i).getKey() + ":" + playersScore.get(i).getValue());
} }
return l; return l;
} }
private int generateMulticastId(){ private int generateMulticastId(){
return Server.multicastId++; return GameServer.multicastID++;
} }
public void setLetters(DefaultListModel<String> letters){ public void setLetters(DefaultListModel<String> letters){
this.letters = letters; this.letters = letters;
} }

View file

@ -1,68 +0,0 @@
package com.texttwist.server.models;
import models.Session;
import models.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Author: Lorenzo Iovino on 17/06/2017.
* Description: Sessions. It is a singleton that provides the model and methods for manage sessions
*/
public class Sessions {
private List<Session> sessions = Collections.synchronizedList(new ArrayList<Session>());
private static class Holder {
static final Sessions INSTANCE = new Sessions();
}
public static Sessions getInstance() {
return Holder.INSTANCE;
}
private Session getSession(String userName) {
for (Session elem : sessions) {
if (elem.account.userName.equals(userName)) {
return elem;
}
}
return null;
}
public boolean add(String userName, String token) {
remove(userName);
return sessions.add(new Session(new User(userName,"",0), token));
}
public boolean remove(String userName){
if(exists(userName)) {
Session s = getSession(userName);
if(s != null) {
sessions.remove(s);
return true;
}
}
return false;
}
public boolean exists(String userName) {
for (Session elem : sessions) {
if (elem.account.userName.equals(userName)) {
return true;
}
}
return false;
}
public boolean isValidToken(String token) {
for (Session session : sessions) {
if (session.token.equals(token)) {
return true;
}
}
return false;
}
}

View file

@ -1,84 +0,0 @@
package com.texttwist.server.services;
import com.texttwist.server.Server;
import com.texttwist.server.models.Accounts;
import com.texttwist.server.models.Sessions;
import constants.Config;
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;
/**
* Author: Lorenzo Iovino on 15/06/2017.
* Description: AuthService
*/
public class AuthService extends UnicastRemoteObject implements IAuth {
private SecureRandom random = new SecureRandom();
public AuthService() throws RemoteException{
Server.logger.write("AuthService Service running at "+ Config.AuthServicePort +" 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(Accounts.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("<html><center>Registration unsuccessfull: <br/> Username exist!</center></html>", 400, null);
}
}
return new Response("<html><center>Registration unsuccessfull! <br/> All fields are mandatories</center></html>", 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(Accounts.getInstance().exists(userName) && Accounts.getInstance().checkPassword(userName, password)) {
JsonObject data = new JsonObject();
String token = nextSessionId();
data.put("token", token);
Sessions.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 = Sessions.getInstance().remove(userName);
if(res) {
Server.logger.write("Logout successfull");
}
}
Sessions.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);
}
}

View file

@ -1,95 +0,0 @@
package com.texttwist.server.services;
import com.texttwist.server.Server;
import models.User;
import redis.clients.jedis.Jedis;
import java.io.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import static com.texttwist.server.Server.jedisPool;
/**
* Author: Lorenzo Iovino on 11/07/2017.
* Description: Jedis Service
*/
public class JedisService {
JedisService(){
Server.logger.write("Jedis Service running on localhost...");
}
/** Read the object from Base64 string. */
public static Object fromString(String s) throws IOException, ClassNotFoundException {
byte [] data = Base64.getDecoder().decode(s);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
Object o = ois.readObject();
ois.close();
return o;
}
/** Write the object to a Base64 string. */
public static String toString(Serializable o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
public static Void add(String key, Serializable o){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.append(key, JedisService.toString(o)+"\n");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
public static List<Serializable> get(String key){
Jedis jedis = null;
List<Serializable> l = new ArrayList<>();
try {
jedis = jedisPool.getResource();
String usersString = jedis.get(key);
if(usersString!=null) {
String[] lines = usersString.split("\n");
for (int i = 0; i < lines.length; i++) {
l.add((User) JedisService.fromString(lines[i]));
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
return l;
}
public static Void removeAll(String key){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.del(key);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
}

View file

@ -1,58 +0,0 @@
package com.texttwist.server.services;
import com.texttwist.server.Server;
import com.texttwist.server.models.Sessions;
import com.texttwist.server.models.Match;
import com.texttwist.server.tasks.ComputeScore;
import constants.Config;
import models.Message;
import java.io.IOException;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Author: Lorenzo Iovino on 27/06/2017.
* Description: Receive Words Service
*/
public class ReceiveWordsService implements Runnable {
private ExecutorService threadPool = Executors.newCachedThreadPool();
public ReceiveWordsService() {
Server.logger.write("ReceiveWords Service running at "+Config.WordsReceiverServicePort +" port...");
}
@Override
public void run(){
Message msg;
DatagramSocket s = null;
try {
s = new DatagramSocket(Config.WordsReceiverServicePort);
} catch (SocketException e) {
e.printStackTrace();
}
DatagramPacket packet;
while(true) {
byte[] buf = new byte[1024];
packet = new DatagramPacket(buf, buf.length);
try {
s.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
String rcv = new String(packet.getData());
if (rcv.startsWith("MESSAGE")) {
msg = Message.toMessage(rcv);
if(Sessions.getInstance().isValidToken(msg.token)) {
Match match = Match.findMatchByPlayerName(msg.sender);
threadPool.submit(new ComputeScore(msg.sender, msg.data, match));
}
}
}
}
}

View file

@ -1,13 +1,12 @@
package com.texttwist.server.tasks; package com.texttwist.server.tasks;
import com.texttwist.server.models.Sessions; import com.texttwist.server.components.SessionsManager;
import javax.swing.*; import javax.swing.*;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 19/06/2017. * Created by loke on 19/06/2017.
* Description: Task: Check Online Users
*/ */
public class CheckOnlineUsers implements Callable<Boolean> { public class CheckOnlineUsers implements Callable<Boolean> {
private final DefaultListModel<String> users; private final DefaultListModel<String> users;
@ -18,8 +17,9 @@ public class CheckOnlineUsers implements Callable<Boolean> {
@Override @Override
public Boolean call() throws Exception { public Boolean call() throws Exception {
System.out.print("Check If users are online!");
for(int i = 0; i < users.size(); i++){ for(int i = 0; i < users.size(); i++){
if(!(Sessions.getInstance().exists(users.get(i)))){ if(!(SessionsManager.getInstance().exists(users.get(i)))){
return false; return false;
} }
} }

View file

@ -1,33 +1,23 @@
package com.texttwist.server.tasks; package com.texttwist.server.tasks;
import com.texttwist.server.models.Accounts; import com.texttwist.server.components.AccountsManager;
import com.texttwist.server.services.JedisService;
import models.User;
import javax.swing.*; import javax.swing.*;
import java.util.Comparator;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 28/06/2017. * Created by loke on 28/06/2017.
* Description: Task: Compute Highscores
*/ */
public class ComputeHighscores implements Callable<DefaultListModel<String>> { public class ComputeHighscores implements Callable<DefaultListModel<String>> {
public ComputeHighscores(){}
@Override @Override
public DefaultListModel<String> call() throws Exception { public DefaultListModel<String> call() throws Exception {
System.out.println("COMPUTE HIGHSCORE");
DefaultListModel<String> l = new DefaultListModel<>(); DefaultListModel<String> l = new DefaultListModel<>();
for(int i =0; i< AccountsManager.getInstance().users.size(); i++){
Accounts.getInstance().users.sort(new Comparator<User>() { l.addElement(AccountsManager.getInstance().users.get(i).userName+":"+AccountsManager.getInstance().users.get(i).score);
@Override
public int compare(User o1, User o2) {
return o2.score.compareTo(o1.score);
}
});
JedisService.removeAll("users");
for(int i = 0; i< Accounts.getInstance().users.size(); i++){
l.addElement(Accounts.getInstance().users.get(i).userName+":"+ Accounts.getInstance().users.get(i).score);
JedisService.add("users", Accounts.getInstance().users.get(i));
} }
return l; return l;
} }

View file

@ -1,50 +1,39 @@
package com.texttwist.server.tasks; package com.texttwist.server.tasks;
import com.texttwist.client.App;
import com.texttwist.server.models.Accounts; import com.texttwist.server.components.AccountsManager;
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;
import javax.swing.*; import javax.swing.*;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 27/06/2017. * Created by loke on 27/06/2017.
* Description: Task: Ccmpute Score
*/ */
public class ComputeScore implements Callable<Integer> { public class ComputeScore implements Callable<Integer> {
private DefaultListModel<String> words; public DefaultListModel<String> words;
private final String sender; public final String sender;
public Match match; public final Match match;
private DefaultListModel<String> wordsValid = new DefaultListModel<>();
public ComputeScore(String sender, DefaultListModel<String> words, Match match){ public ComputeScore(String sender, Match match, DefaultListModel<String> words){
this.words = words; this.words = words;
this.match = match;
this.sender = sender; this.sender = sender;
this.match = match;
} }
@Override @Override
public Integer call() throws Exception { public Integer call() throws Exception {
//Compute the score depending on the size of the words
Integer score = 0; Integer score = 0;
for (int i = 0; i < words.size(); i++) { for (int i = 0; i < words.size(); i++) {
if (isValid(words.get(i), match.letters)) { if (isValid(words.get(i), match.letters)) {
score += words.get(i).length(); score += words.get(i).length();
wordsValid.addElement(words.get(i));
} }
} }
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()) {
match.matchTimeout = false;
match.setUndefinedScorePlayersToZero();
new SendFinalScores(match).call();
}
return score; return score;
} }
@ -60,7 +49,8 @@ public class ComputeScore implements Callable<Integer> {
if(word.equals("")){ if(word.equals("")){
return true; return true;
} }
if(!isCharacterPresent || wordsValid.indexOf(word)!=-1){
if(!isCharacterPresent){
return false; return false;
} }
} }

View file

@ -1,21 +1,29 @@
package com.texttwist.server.tasks; package com.texttwist.server.tasks;
import com.texttwist.server.Server; import com.texttwist.server.components.GameServer;
import javax.swing.*; 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; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 25/06/2017. * Created by loke on 25/06/2017.
* Description: Task: Generate Letters
*/ */
public class GenerateLetters implements Callable<DefaultListModel<String>> { public class GenerateLetters implements Callable<DefaultListModel<String>> {
public GenerateLetters(){
}
@Override @Override
public DefaultListModel<String> call() throws Exception { public DefaultListModel<String> call() throws Exception {
DefaultListModel<String> l = new DefaultListModel<>(); DefaultListModel<String> l = new DefaultListModel<String>();
String word = Server.dict.getRandomWord(6, 7); String word = GameServer.dict.getRandomWord(6, 7);
for (int i = 0;i < word.length(); i++){ for (int i = 0;i < word.length(); i++){
l.addElement(String.valueOf(word.charAt(i))); l.addElement(String.valueOf(word.charAt(i)));
} }

View file

@ -2,18 +2,22 @@ package com.texttwist.server.tasks;
import com.texttwist.server.models.Match; import com.texttwist.server.models.Match;
import javafx.util.Pair; import javafx.util.Pair;
import javax.swing.*; import javax.swing.*;
import java.net.Socket;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import static com.texttwist.server.components.GameServer.activeMatches;
import static com.texttwist.server.models.Match.findMatch;
/** /**
* Author: Lorenzo Iovino on 23/06/2017. * Created by loke on 23/06/2017.
* Description: Task: Join Match
*/ */
public class JoinMatch implements Callable<Boolean> { public class JoinMatch implements Callable<Boolean> {
private final String matchName; public final String matchName;
private final String playerName; public final String playerName;
private final SocketChannel socketChannel; public final SocketChannel socketChannel;
public JoinMatch(String playerName, DefaultListModel<String> matchName, SocketChannel socketChannel) { public JoinMatch(String playerName, DefaultListModel<String> matchName, SocketChannel socketChannel) {
this.playerName = playerName; this.playerName = playerName;
@ -21,9 +25,10 @@ public class JoinMatch implements Callable<Boolean> {
this.socketChannel = socketChannel; this.socketChannel = socketChannel;
} }
@Override @Override
public Boolean call() throws Exception { public Boolean call() throws Exception {
final Match thisMatch = Match.findMatch(Match.activeMatches, this.matchName); final Match thisMatch = Match.findMatch(activeMatches, this.matchName);
if (thisMatch != null) { if (thisMatch != null) {
for (int j = 0; j < thisMatch.playersStatus.size(); j++) { for (int j = 0; j < thisMatch.playersStatus.size(); j++) {
String name = thisMatch.playersStatus.get(j).getKey(); String name = thisMatch.playersStatus.get(j).getKey();
@ -32,11 +37,24 @@ public class JoinMatch implements Callable<Boolean> {
thisMatch.playersStatus.add(new Pair<>(name, 1)); thisMatch.playersStatus.add(new Pair<>(name, 1));
thisMatch.playersSocket.remove(j); thisMatch.playersSocket.remove(j);
thisMatch.playersSocket.add(new Pair<>(name, socketChannel)); thisMatch.playersSocket.add(new Pair<>(name, socketChannel));
System.out.println(playerName + ": JOINED");
return allJoined(thisMatch); return allJoined(thisMatch);
} }
} }
} }
return false; return allJoined(thisMatch);
}
private void printAll(Match match){
for (int i = 0; i < match.playersStatus.size(); i++) {
System.out.println(match.playersStatus.get(i).getKey());
System.out.println(match.playersStatus.get(i).getValue());
System.out.println(match.playersSocket.get(i).getKey());
System.out.println(match.playersSocket.get(i).getValue());
}
} }
private Boolean allJoined(Match match) { private Boolean allJoined(Match match) {
@ -45,7 +63,6 @@ public class JoinMatch implements Callable<Boolean> {
return false; return false;
} }
} }
match.joinTimeout = false;
return true; return true;
} }
} }

View file

@ -0,0 +1,36 @@
package com.texttwist.server.tasks;
import com.texttwist.client.App;
import com.texttwist.server.models.Match;
import models.Message;
import javax.swing.*;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.*;
/**
* Created by loke on 23/06/2017.
*/
public class JoinTimeout implements Callable<Boolean> {
public final Match match;
public JoinTimeout(Match match) {
this.match = match;
System.out.println("Math started, countdown for join!");
}
@Override
public Boolean call() throws Exception {
try {
Thread.currentThread().sleep(7*60*1000);
System.out.println("TIMEOUT - MANDA MESSAGGIO ERRORE A TUTTI GLI UTENTI DEL MATCH");
return false;
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
}

View file

@ -0,0 +1,33 @@
package com.texttwist.server.tasks;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.texttwist.server.models.Match;
import java.util.concurrent.Callable;
/**
* Created by loke on 27/06/2017.
*/
public class MatchTimeout implements Callable<Boolean> {
public MatchTimeout() {
System.out.println("GamePage started, countdown for end words!");
}
@Override
public Boolean call() throws Exception {
try {
Thread.currentThread().sleep(3*60*1000); //TODO 5*60*1000
System.out.println("timer scaduto");
System.out.println("TIMEOUT - SETTA A 0 il punteggio degli utenti che non hanno inviato le parole");
return false;
} catch (InterruptedException e) {
System.out.println("TIMER BLOCATO PRIMA");
return true;
}
}
}

View file

@ -1,203 +0,0 @@
package com.texttwist.server.tasks;
import com.texttwist.server.Server;
import com.texttwist.server.models.Sessions;
import com.texttwist.server.models.Match;
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.*;
/**
* Author: Lorenzo Iovino on 18/06/2017.
* Description: Message Dispatcher
* */
public class MessageDispatcher implements Callable<Boolean> {
private final ExecutorService threadPool = Executors.newCachedThreadPool();
private final Message request;
private final SocketChannel socketChannel;
private ByteBuffer bufferMessage;
private boolean matchNotAvailable = false;
public MessageDispatcher(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(Sessions.getInstance().isValidToken(request.token)){
switch(request.message){
case "START_GAME":
Future<Boolean> onlineUsers = threadPool.submit(new CheckOnlineUsers(request.data));
try {
//Check if invited users are online
Boolean usersOnline = onlineUsers.get();
if(usersOnline){
Future<Boolean> sendInvitations = threadPool.submit(new SendInvitations(request.sender, request.data));
Boolean invitationSended = sendInvitations.get();
if (invitationSended) {
//Server create new match
request.data.addElement(request.sender);
final Match match = new Match(request.sender, request.data);
Match.activeMatches.add(match);
DefaultListModel<String> matchName = new DefaultListModel<>();
matchName.addElement(request.sender);
//Match creator join match
Future<Boolean> joinMatch = threadPool.submit(new JoinMatch(request.sender, matchName, socketChannel));
Boolean joinMatchRes = joinMatch.get();
//Notify to the client that invites was sents correctly
if(!joinMatchRes){
bufferMessage = ByteBuffer.allocate(1024);
Message message = new Message("INVITES_ALL_SENDED", "", "", new DefaultListModel<>());
byteMessage = message.toString().getBytes();
bufferMessage = ByteBuffer.wrap(byteMessage);
socketChannel.write(bufferMessage);
}
//Starts to wait until all player joins
Future<Boolean> joinTimeout = threadPool.submit(new TimeoutJoin(match));
Boolean joinTimeoutRes = joinTimeout.get();
//If joinTimeoutRes==true timeout happen, need to notify to all waiting clients
if(joinTimeoutRes){
Future<Boolean> sendMessageToAllPlayers = threadPool.submit(
new SendMessageToAllPlayers(match,
new Message("JOIN_TIMEOUT", "", "", new DefaultListModel<>()), socketChannel));
Boolean sendMessageToAllPlayersRes = sendMessageToAllPlayers.get();
if(!sendMessageToAllPlayersRes){
Match.activeMatches.remove(Match.findMatchIndex(Match.activeMatches, match.matchCreator));
return sendMessageToAllPlayersRes;
}
} else {
//All done, all player joined
return true;
}
}
} else {
//Some user in the list is not online
Message message = new Message("USER_NOT_ONLINE", "", "", new DefaultListModel<>());
byteMessage = message.toString().getBytes();
bufferMessage.clear();
bufferMessage = ByteBuffer.wrap(byteMessage);
this.socketChannel.write(bufferMessage);
return false;
}
} catch (InterruptedException e) {
Server.logger.write("MESSAGE DISPATCHER - START GAME: InterruptedException");
} catch (ExecutionException e) {
Server.logger.write("MESSAGE DISPATCHER - START GAME: ExecutionException");
} catch (IOException e) {
Server.logger.write("MESSAGE DISPATCHER - START GAME: IOException");
}
case "FETCH_HIGHSCORES":
//Fetch hisghscore and send back to client
Future<DefaultListModel<String>> computeHighscores = threadPool.submit(new ComputeHighscores());
try {
DefaultListModel<String> computeHighscoresRes = computeHighscores.get();
bufferMessage.clear();
bufferMessage = ByteBuffer.allocate(1024);
Message message = new Message("HIGHSCORES", "", "", computeHighscoresRes);
byteMessage = message.toString().getBytes();
bufferMessage = ByteBuffer.wrap(byteMessage);
try {
socketChannel.write(bufferMessage);
} catch (IOException e) {
e.printStackTrace();
}
return false;
} catch (InterruptedException e) {
Server.logger.write("MESSAGE DISPATCHER - FETCH HIGHSCORES: InterruptedException");
} catch (ExecutionException e) {
Server.logger.write("MESSAGE DISPATCHER - FETCH HIGHSCORES: ExecutionException");
}
case "JOIN_GAME":
//An user joined the game
Future<Boolean> joinMatch = threadPool.submit(new JoinMatch(request.sender, request.data, socketChannel));
try {
Match match = Match.findMatch(Match.activeMatches, request.data.get(0));;
Boolean joinMatchRes = joinMatch.get();
//If joinMatchRes=true start the game! Because all player joined
if(joinMatchRes){
//If match not fired join timeout, notify all player that game is started
if(!match.joinTimeout) {
//Generate letters to send to clients
Future<DefaultListModel<String>> 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();
byteMessage = message.toString().getBytes();
bufferMessage = ByteBuffer.wrap(byteMessage);
try {
String s = new String(bufferMessage.array(), bufferMessage.position(), bufferMessage.remaining());
socketClient.write(bufferMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (matchNotAvailable) {
matchNotAvailable = false;
return false;
}
}
} else {
//Match doesn't exist more because a timeout happen
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) {
Server.logger.write("MESSAGE DISPATCHER - JOIN GAME: InterruptedException");
} catch (ExecutionException e) {
Server.logger.write("MESSAGE DISPATCHER - JOIN GAME: ExecutionException");
} catch (IOException e) {
Server.logger.write("MESSAGE DISPATCHER - JOIN GAME: IOException");
}
default:
break;
}
} else {
//If token is invalid, return error message to client
threadPool.submit(new TokenInvalid(request.sender, socketChannel, bufferMessage));
return false;
}
return false;
}
}

View file

@ -0,0 +1,86 @@
package com.texttwist.server.tasks;
import com.texttwist.server.Server;
import com.texttwist.server.components.GameServer;
import com.texttwist.server.models.Match;
import constants.Config;
import models.Message;
import javax.swing.*;
import javax.xml.crypto.Data;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Created by loke on 27/06/2017.
*/
public class ReceiveWords implements Callable<Boolean>{
protected ExecutorService threadPool = Executors.newCachedThreadPool();
public DatagramChannel DatagramChannel;
public final Match match;
byte[] receiveData = new byte[1024];
ByteBuffer buffer;
public ReceiveWords(Match match, DatagramChannel DatagramChannel, ByteBuffer buffer) {
this.match = match;
this.buffer = buffer;
this.DatagramChannel = DatagramChannel;
}
@Override
public Boolean call() throws Exception {
System.out.print("READY TO Receive words !!!!");
Future<Boolean> matchTimeout = threadPool.submit(new MatchTimeout());
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
Message msg;
while(true) {
DatagramChannel.receive(buffer);
buffer.flip();
System.out.println(buffer.limit());
int limits = buffer.limit();
byte bytes[] = new byte[limits];
buffer.get(bytes, 0, limits);
String rcv = new String(bytes);
System.out.println("RECEIVED: " + rcv);
buffer.rewind();
msg = Message.toMessage(rcv);
if(msg.message.equals("WORDS")){
break;
}
}
Future<Integer> computeScore = threadPool.submit(new ComputeScore(msg.sender, match, msg.data));
//Se tutti hanno inviato le parole, blocca il timer e restituisci true
computeScore.get();
System.out.println(match.matchCreator);
System.out.println(match.allPlayersSendedHisScore());
if(match.allPlayersSendedHisScore()){
System.out.println("TIMEOUT BLOCCATO, OK");
match.setUndefinedScorePlayersToZero();
matchTimeout.cancel(true);
DatagramChannel.close();
return true;
}
return false;
}
}

View file

@ -1,41 +0,0 @@
package com.texttwist.server.tasks;
import com.texttwist.server.models.Match;
import constants.Config;
import models.Message;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.concurrent.Callable;
/**
* Author: Lorenzo Iovino on 13/07/2017.
* Description: Task: Send Final Scores
*/
public class SendFinalScores implements Callable<Void> {
private Match match;
public SendFinalScores(Match match){
this.match = match;
}
@Override
public Void call() throws Exception {
Message msg = new Message("FINALSCORE", "SERVER", "", match.getMatchPlayersScoreAsStringList());
MulticastSocket multicastSocket = null;
try {
multicastSocket = new MulticastSocket(match.multicastId);
InetAddress ia = InetAddress.getByName(Config.ScoreMulticastServiceURI);
DatagramPacket hi = new DatagramPacket(msg.toString().getBytes(), msg.toString().length(), ia, match.multicastId);
multicastSocket.send(hi);
} catch (IOException e) {
e.printStackTrace();
}
Match.activeMatches.remove(Match.findMatchIndex(Match.activeMatches, match.matchCreator));
return null;
}
}

View file

@ -1,16 +1,23 @@
package com.texttwist.server.tasks; package com.texttwist.server.tasks;
import com.texttwist.server.Server; 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 javax.swing.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 19/06/2017. * Created by loke on 19/06/2017.
* Description: Task: Send Invitations
*/ */
public class SendInvitations implements Callable<Boolean> { public class SendInvitations implements Callable<Boolean> {
private DefaultListModel<String> users; private final DefaultListModel<String> users;
private String sender; private final String sender;
public SendInvitations(String sender, DefaultListModel<String> users) { public SendInvitations(String sender, DefaultListModel<String> users) {
this.users = users; this.users = users;
@ -19,11 +26,14 @@ public class SendInvitations implements Callable<Boolean> {
@Override @Override
public Boolean call() throws Exception { public Boolean call() throws Exception {
System.out.print("SendInvitations!");
try { try {
Server.notificationServer.sendInvitations(sender, users); Server.notificationServer.sendInvitations(sender, users);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); System.out.println("Eccezione" + e);
} }
return true; return true;
} }
} }

View file

@ -2,21 +2,21 @@ package com.texttwist.server.tasks;
import com.texttwist.server.models.Match; import com.texttwist.server.models.Match;
import models.Message; import models.Message;
import javax.swing.*;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
/** /**
* Author: Lorenzo Iovino on 27/06/2017. * Created by loke on 27/06/2017.
* Description: Task: Send Message To All Players
*/ */
public class SendMessageToAllPlayers implements Callable<Boolean> { public class SendMessageToAllPlayers implements Callable<Boolean> {
public final Match match; public final Match match;
private final Message message; public final Message message;
private SocketChannel socketChannel; public SocketChannel socketChannel;
public SendMessageToAllPlayers(Match match, Message message, SocketChannel socketChannel){ public SendMessageToAllPlayers(Match match, Message message, SocketChannel socketChannel){
this.match = match; this.match = match;
this.message = message; this.message = message;
@ -35,11 +35,13 @@ public class SendMessageToAllPlayers implements Callable<Boolean> {
byte[] byteMessage = message.toString().getBytes(); byte[] byteMessage = message.toString().getBytes();
buffer = ByteBuffer.wrap(byteMessage); buffer = ByteBuffer.wrap(byteMessage);
socketChannel.write(buffer); socketChannel.write(buffer);
} //clientSocket.close();
} System.out.println("SEND TO ALL" + message.toString());
return false; return false;
} else { }
}
}
return true; return true;
} }
}
} }

View file

@ -1,38 +0,0 @@
package com.texttwist.server.tasks;
import com.texttwist.server.models.Match;
import constants.Config;
import java.util.concurrent.*;
/**
* Author: Lorenzo Iovino on 23/06/2017.
* Description: Task: Join Timeout
*/
public class TimeoutJoin implements Callable<Boolean> {
public final Match match;
public TimeoutJoin(Match match) {
this.match = match;
}
@Override
public Boolean call() throws Exception {
try {
match.joinTimeout = true;
Thread.currentThread().sleep(Config.joinMatchTimeout);
if(match.joinTimeout) {
match.joinTimeout = false;
return true;
}
else {
match.joinTimeout = false;
return false;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
}

View file

@ -1,37 +0,0 @@
package com.texttwist.server.tasks;
import com.texttwist.server.models.Match;
import constants.Config;
import java.util.concurrent.Callable;
/**
* Author: Lorenzo Iovino on 27/06/2017.
* Description: Task: Match Timeout
*/
public class TimeoutMatch implements Callable<Boolean> {
private Match match;
public TimeoutMatch(Match match) {
this.match = match;
}
@Override
public Boolean call() throws Exception {
try {
Thread.currentThread().sleep(Config.sendWordsTimeout);
if(match.matchTimeout) {
match.setUndefinedScorePlayersToZero();
new SendFinalScores(match).call();
return true;
}
return false;
} catch (InterruptedException e) {
return false;
}
}
}

View file

@ -1,37 +0,0 @@
package com.texttwist.server.tasks;
import com.texttwist.server.Server;
import models.Message;
import javax.swing.*;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable;
/**
* Author: Lorenzo Iovino on 11/07/2017.
* Description: Task: Token Invalid
*/
public class TokenInvalid implements Callable<Void> {
private String sender;
private ByteBuffer buffer;
private SocketChannel channel;
public TokenInvalid (String sender, SocketChannel channel, ByteBuffer buffer){
this.sender=sender;
this.buffer=buffer;
this.channel=channel;
}
@Override
public Void call()throws Exception {
Server.logger.write("TOKEN INVALID: TOKEN USED BY "+ sender+ " IS NOT VALID");
Message msg = new Message("TOKEN_NOT_VALID", "", null, new DefaultListModel<>());
buffer.clear();
byte[] byteMessage = msg.toString().getBytes();
buffer = ByteBuffer.wrap(byteMessage);
channel.write(buffer);
return null;
}
}

View file

@ -0,0 +1,32 @@
package com.texttwist.server.tasks;
import com.texttwist.server.Server;
import com.texttwist.server.components.NotificationServer;
import com.texttwist.server.models.Match;
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;
/**
* Created by loke on 19/06/2017.
*/
public class WaitForPlayers implements Callable<Boolean> {
private final Match match;
private String sender;
public WaitForPlayers(Match match) {
this.match = match;
}
@Override
public Boolean call() throws Exception {
System.out.print("Wait for players!");
return true;
}
}

Some files were not shown because too many files have changed in this diff Show more