- Ajout système d'accès

- Instauration d'un contexte par utilisateur
- Ajout de protection
- Ajout commande SignupRule.java
This commit is contained in:
Benjamin 2022-03-10 21:39:28 +01:00
parent 842bbc7341
commit 56a8121782
21 changed files with 219 additions and 139 deletions

View File

@ -3,6 +3,7 @@
*/ */
package lightcontainer; package lightcontainer;
import lightcontainer.domains.client.Context;
import lightcontainer.domains.server.MulticastServerListener; import lightcontainer.domains.server.MulticastServerListener;
import lightcontainer.domains.server.UnicastServerListener; import lightcontainer.domains.server.UnicastServerListener;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
@ -12,6 +13,8 @@ import lightcontainer.repository.ClientHandlerRepository;
import lightcontainer.repository.FileFrontEnd; import lightcontainer.repository.FileFrontEnd;
import lightcontainer.repository.ProtocolRepositoryImpl; import lightcontainer.repository.ProtocolRepositoryImpl;
import lightcontainer.repository.StoreProcessorRepository; import lightcontainer.repository.StoreProcessorRepository;
import lightcontainer.storage.AppConfig;
import lightcontainer.storage.AppData;
import java.io.File; import java.io.File;
@ -24,44 +27,19 @@ public class App {
private static final int MULTICAST_PORT = 15502; private static final int MULTICAST_PORT = 15502;
/*
private static Thread t1 = null;
public static void main(String[] args) throws InterruptedException { public static void main(String[] args) {
t1 = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (true) {
System.out.println("HEY " + i++);
try {
synchronized (t1) {
System.out.println("SUSPEND");
t1.wait();
}
} catch (InterruptedException e) {}
}
}
});
t1.start();
System.out.println("START");
Thread.sleep(1000);
synchronized (t1) {
t1.notify();
}
}
*/
public static void main(String[] args) throws InterruptedException {
setupVM(); setupVM();
AppData appData = AppData.getInstance();
// Create all repository // Create all repository
ClientHandlerRepository clientRep = new ClientHandlerRepository(); ClientHandlerRepository clientRep = new ClientHandlerRepository();
StoreProcessorRepository storeRep = new StoreProcessorRepository(); StoreProcessorRepository storeRep = new StoreProcessorRepository();
ProtocolRepository protocolRep = new ProtocolRepositoryImpl(); ProtocolRepository protocolRep = new ProtocolRepositoryImpl();
protocolRep.addReader(new HelloRule()); protocolRep.addReader(new HelloRule());
protocolRep.addReader(new SigninRule(protocolRep)); protocolRep.addReader(new SigninRule(protocolRep));
protocolRep.addReader(new SignupRule(protocolRep));
protocolRep.addReader(new FilelistRule(protocolRep)); protocolRep.addReader(new FilelistRule(protocolRep));
protocolRep.addReader(new SavefileRule(protocolRep)); protocolRep.addReader(new SavefileRule(protocolRep));
protocolRep.addReader(new SendOkRule(protocolRep)); protocolRep.addReader(new SendOkRule(protocolRep));

View File

@ -1,5 +1,6 @@
package lightcontainer.domains; package lightcontainer.domains;
import lightcontainer.domains.client.Context;
import lightcontainer.enumerations.TaskStatus; import lightcontainer.enumerations.TaskStatus;
import lightcontainer.enumerations.TaskType; import lightcontainer.enumerations.TaskType;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
@ -8,17 +9,21 @@ public class Task {
// Variables // Variables
private TaskStatus status; private TaskStatus status;
private ProtocolWriter.ProtocolResult command; private ProtocolWriter.ProtocolResult command;
private String client;
private String storeDomain; private String storeDomain;
public Task(TaskStatus status, ProtocolWriter.ProtocolResult command, String client) { /**
* Défini le context courrant dans laquelle la tâche opère
*/
private Context context;
public Task(Context context, TaskStatus status, ProtocolWriter.ProtocolResult command) {
this.context = context;
this.status = status; this.status = status;
this.command = command; this.command = command;
this.client = client;
} }
public static Task newInstance(ProtocolWriter.ProtocolResult command, String client) { public static Task newInstance(Context context, ProtocolWriter.ProtocolResult command) {
Task task = new Task(TaskStatus.PENDING, command, client); Task task = new Task(context, TaskStatus.PENDING, command);
return task; return task;
} }
@ -36,7 +41,7 @@ public class Task {
* @return Login du client * @return Login du client
*/ */
public String getClient() { public String getClient() {
return client; return context.getLogin();
} }
public ProtocolWriter.ProtocolResult getCommand() { public ProtocolWriter.ProtocolResult getCommand() {
@ -49,4 +54,11 @@ public class Task {
this.status = TaskStatus.PROCESSING; this.status = TaskStatus.PROCESSING;
} }
} }
/**
* Défini le context courrant dans laquelle la tâche opère
*/
public Context getContext() {
return this.context;
}
} }

View File

@ -5,6 +5,7 @@ import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
import lightcontainer.protocol.rules.reader.SigninRule; import lightcontainer.protocol.rules.reader.SigninRule;
import lightcontainer.protocol.rules.reader.SignupRule;
import lightcontainer.protocol.rules.writer.SignErrorRule; import lightcontainer.protocol.rules.writer.SignErrorRule;
import lightcontainer.protocol.rules.writer.SignOkRule; import lightcontainer.protocol.rules.writer.SignOkRule;
@ -31,23 +32,20 @@ public class ClientHandler implements Runnable, AutoCloseable {
private ClientHandlerFFE fileFrontEnd; private ClientHandlerFFE fileFrontEnd;
private final Socket client; private final Socket client;
private ProtocolRepository protocolRep; private ProtocolRepository protocolRep;
private Context context;
private boolean client_run; private boolean client_run;
/**
* Login of client.
* State : NULL if not connected and Login string if connected
*/
private String login;
private BufferedReader reader; private BufferedReader reader;
private PrintWriter writer; private PrintWriter writer;
private ProtocolWriter.ProtocolResult response; private ProtocolWriter.ProtocolResult response;
// Constructor // Constructor
public ClientHandler(Socket client, ClientHandlerFFE ffe, ProtocolRepository protocolRep) { public ClientHandler(Socket client, ClientHandlerFFE ffe, ProtocolRepository protocolRep, Context context) {
this.fileFrontEnd = ffe; this.fileFrontEnd = ffe;
this.client = client; this.client = client;
this.protocolRep = protocolRep; this.protocolRep = protocolRep;
this.context = context;
this.client_run = false; this.client_run = false;
initClient(); initClient();
} }
@ -87,20 +85,24 @@ public class ClientHandler implements Runnable, AutoCloseable {
while (this.client_run) { while (this.client_run) {
try { try {
String command = this.reader.readLine(); String command = this.reader.readLine();
if (command != null) System.out.println("Client: " + command); if (command != null) {
System.out.println("Client: " + command);
} else this.client.close();
ProtocolReader.ProtocolResult ruleResult = protocolRep.executeReader(command + "\r\n"); ProtocolReader.ProtocolResult ruleResult = protocolRep.executeReader(context, command + "\r\n");
if (ruleResult == null) {
this.close();
return;
}
if (isConnected()) { if (checkAccess(ruleResult)) {
ruleResult.read( ruleResult.read(
this.client.getInputStream() this.client.getInputStream()
); );
ProtocolWriter.ProtocolResult writerCommand = ruleResult.getResultCommand(); ProtocolWriter.ProtocolResult writerCommand = ruleResult.getResultCommand();
if (ruleResult.getReceiver() == ProtocolReader.ResultCmdReceiver.STOREBACKEND) { if (ruleResult.getReceiver() == ProtocolReader.ResultCmdReceiver.STOREBACKEND) {
fileFrontEnd.newCommand( fileFrontEnd.newCommand(context, writerCommand); // Envoie dans la file de tâche FileFrontEnd en attente d'un traitement d'un StorBackEnd
writerCommand,
getLogin()); // Envoie dans la file de tâche FileFrontEnd en attente d'un traitement d'un StorBackEnd
// Attend la fin de la réalisation de la tâche // Attend la fin de la réalisation de la tâche
waitTaskResponse(); waitTaskResponse();
@ -109,12 +111,12 @@ public class ClientHandler implements Runnable, AutoCloseable {
writer.flush(); writer.flush();
response.write(this.client.getOutputStream()); // Ecrit au client si nécessaire response.write(this.client.getOutputStream()); // Ecrit au client si nécessaire
} else { } else {
writer.write(writerCommand.getCommand()); // Renvoye au client writer.print(writerCommand.getCommand()); // Renvoye au client
writer.flush(); writer.flush();
} }
} else { } else {
authentication(ruleResult); accessDenied();
} }
} catch (IOException ignore) { } catch (IOException ignore) {
ignore.printStackTrace(); ignore.printStackTrace();
@ -123,6 +125,39 @@ public class ClientHandler implements Runnable, AutoCloseable {
} }
} }
/**
* Permet de vérifier si le client possède l'accès demandé
* @param ruleResult La règle
* @return TRUE si le client possède l'accès demandé
*/
private boolean checkAccess(ProtocolReader.ProtocolResult ruleResult) {
if (context.isConnected())
return true;
try {
ruleResult
.getClass()
.asSubclass(SignupRule.Result.class);
return true;
} catch (ClassCastException e) {
try {
ruleResult.getClass().asSubclass(SigninRule.Result.class);
return true;
} catch (ClassCastException e2) { }
}
return false;
}
/**
* Lorsque l'accès à été refusé.
*/
private void accessDenied() {
ProtocolWriter.ProtocolResult signErrorResult = protocolRep.executeWriter(SignErrorRule.NAME);
writer.write(signErrorResult.getCommand()); // Envoie SignError car echec de la connection
writer.flush();
}
/** /**
* Permet au Client d'attendre la fin de la réalisation de sa tâche * Permet au Client d'attendre la fin de la réalisation de sa tâche
*/ */
@ -134,6 +169,10 @@ public class ClientHandler implements Runnable, AutoCloseable {
} }
} }
/**
* Permet d'envoyer la réponse au client.
* @param response La réponse
*/
public void respond(ProtocolWriter.ProtocolResult response) { public void respond(ProtocolWriter.ProtocolResult response) {
this.response = response; this.response = response;
synchronized (this) { synchronized (this) {
@ -141,31 +180,7 @@ public class ClientHandler implements Runnable, AutoCloseable {
} }
} }
private void authentication(ProtocolReader.ProtocolResult ruleResult) {
try {
SigninRule.Result signinResult = (SigninRule.Result) ruleResult;
if (signinResult.checkCredentials()) {
this.login = signinResult.getLogin();
ProtocolWriter.ProtocolResult signokResult = protocolRep.executeWriter(SignOkRule.NAME);
writer.write(signokResult.getCommand());
writer.flush();
return;
}
} catch (ClassCastException ignored) {}
ProtocolWriter.ProtocolResult signErrorResult = protocolRep.executeWriter(SignErrorRule.NAME);
writer.write(signErrorResult.getCommand()); // Envoie SignError car echec de la connection
writer.flush();
this.close(); // Fermeture de la connection
}
/**
* Permet de savoir si l'utilisateur s'est connecté (Avec login et mdp)
* @return
*/
private boolean isConnected() {
return login != null;
}
/** /**
* AutoClosable Function * AutoClosable Function
@ -184,6 +199,6 @@ public class ClientHandler implements Runnable, AutoCloseable {
} }
public String getLogin() { public String getLogin() {
return this.login; return this.context.getLogin();
} }
} }

View File

@ -11,6 +11,11 @@ public class Context {
private AppData appData; private AppData appData;
/**
* Login de l'utilisateur
*/
private String login;
public Context(AppData appData) { public Context(AppData appData) {
this.appData = appData; this.appData = appData;
@ -20,11 +25,42 @@ public class Context {
public boolean createUser(String login, String password) { public boolean createUser(String login, String password) {
try { try {
String key = AES_GCM.generateSecretKey(); String key = AES_GCM.generateSecretKey();
return this.appData.addUser(login, password, key); if (this.appData.addUser(login, password, key)) {
} catch (NoSuchAlgorithmException e) { this.login = login;
return true;
}
} catch (AES_GCM.AesGcmException e) {}
return false; return false;
} }
/**
* Login de l'utilisateur
* @return Login de l'utilisateur
*/
public String getLogin() {
return this.login;
} }
/**
* Permet de demander la connection de l'utilisateur
* @param login Login
* @param password Mot de passe
* @return TRUE si l'utilisateur a été authentifié
*/
public boolean signIn(String login, String password) {
if (login.equals("aaaaa") && password.equals("aaaaa")) {
this.login = login;
return true;
}
return false;
}
/**
* Permet de savoir si l'utilisateur s'est connecté (Avec login et mdp)
* @return TRUE si l'utilisateur est connecté
*/
public boolean isConnected() {
return this.getLogin() != null;
}
} }

View File

@ -33,6 +33,7 @@ public class StoreProcessor extends Thread implements AutoCloseable {
private boolean client_run; private boolean client_run;
private BufferedReader reader; private BufferedReader reader;
private Context context;
private PrintWriter writer; private PrintWriter writer;
private ProtocolWriter.ProtocolResult protocolResult; private ProtocolWriter.ProtocolResult protocolResult;
private ProtocolRepository protocolRep; private ProtocolRepository protocolRep;
@ -95,7 +96,7 @@ public class StoreProcessor extends Thread implements AutoCloseable {
String responseCommand = this.reader.readLine() + "\r\n"; String responseCommand = this.reader.readLine() + "\r\n";
if (responseCommand != null) if (responseCommand != null)
System.out.println("StoreBackEnd: " + responseCommand); System.out.println("StoreBackEnd: " + responseCommand);
ProtocolReader.ProtocolResult responseResult = protocolRep.executeReader(responseCommand); ProtocolReader.ProtocolResult responseResult = protocolRep.executeReader(context, responseCommand);
responseResult.read( responseResult.read(
this.store.getInputStream() this.store.getInputStream()
); );
@ -111,10 +112,10 @@ public class StoreProcessor extends Thread implements AutoCloseable {
* Permet de demander au StoreBackEnd d'effectuer une commande * Permet de demander au StoreBackEnd d'effectuer une commande
* @param protocolResult La commande à effectuer * @param protocolResult La commande à effectuer
*/ */
public void executeCommand(ProtocolWriter.ProtocolResult protocolResult) { public void executeCommand(Context context, ProtocolWriter.ProtocolResult protocolResult) {
synchronized (this) { synchronized (this) {
this.protocolResult = protocolResult; this.protocolResult = protocolResult;
System.out.println("Request wake up"); this.context = context;
this.notify(); this.notify();
} }
} }

View File

@ -67,7 +67,7 @@ public class MulticastServerListener implements Runnable {
// Create a new StoreBacked (try used in the case of an error to maintain the listening loop) // Create a new StoreBacked (try used in the case of an error to maintain the listening loop)
try { try {
// TODO Récupérer le port du message du packet et le setup (add description of the line). // TODO Récupérer le port du message du packet et le setup (add description of the line).
HelloRule.Result readerResult = protocolRep.executeReader(data); HelloRule.Result readerResult = protocolRep.executeReader(null, data);
System.out.printf("Nouveau SBE : Domain=%s | Port=%d\n", readerResult.getDomain(), readerResult.getPort()); System.out.printf("Nouveau SBE : Domain=%s | Port=%d\n", readerResult.getDomain(), readerResult.getPort());
Socket socket = new Socket(packet.getAddress(), readerResult.getPort()); Socket socket = new Socket(packet.getAddress(), readerResult.getPort());

View File

@ -1,9 +1,11 @@
package lightcontainer.domains.server; package lightcontainer.domains.server;
import lightcontainer.domains.client.ClientHandler; import lightcontainer.domains.client.ClientHandler;
import lightcontainer.domains.client.Context;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.interfaces.UnicastCHR; import lightcontainer.interfaces.UnicastCHR;
import lightcontainer.repository.FileFrontEnd; import lightcontainer.repository.FileFrontEnd;
import lightcontainer.storage.AppData;
import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLServerSocketFactory;
@ -49,7 +51,7 @@ public class UnicastServerListener implements Runnable {
Socket client = this.server.accept(); Socket client = this.server.accept();
System.out.println("New Client"); System.out.println("New Client");
// Create a new Handler client by passing these dependencies to it // Create a new Handler client by passing these dependencies to it
ClientHandler clientHandler = new ClientHandler(client, ffe, protocolRep); // TODO passer FileFrontEnd ou faire ca dans le repository ?! ClientHandler clientHandler = new ClientHandler(client, ffe, protocolRep, new Context(AppData.getInstance())); // TODO passer FileFrontEnd ou faire ca dans le repository ?!
// Add the client handler to its repository (clienthandlerrepository) // Add the client handler to its repository (clienthandlerrepository)
this.repository.addClient(clientHandler); this.repository.addClient(clientHandler);
// Start the thread // Start the thread

View File

@ -1,6 +1,7 @@
package lightcontainer.interfaces; package lightcontainer.interfaces;
import lightcontainer.domains.client.ClientHandler; import lightcontainer.domains.client.ClientHandler;
import lightcontainer.domains.client.Context;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
import lightcontainer.repository.FileFrontEnd; import lightcontainer.repository.FileFrontEnd;
@ -12,9 +13,9 @@ public interface ClientHandlerFFE {
/** /**
* Demande le traitement d'une commande * Demande le traitement d'une commande
* @param context Context de la requête
* @param command Commande à traiter * @param command Commande à traiter
* @param client identifiant du client à qui est affilié cette commande
*/ */
void newCommand(ProtocolWriter.ProtocolResult command, String client); void newCommand(Context context, ProtocolWriter.ProtocolResult command);
} }

View File

@ -1,11 +1,12 @@
package lightcontainer.interfaces; package lightcontainer.interfaces;
import lightcontainer.domains.client.Context;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
public interface ProtocolRepository { public interface ProtocolRepository {
<T extends ProtocolReader.ProtocolResult> T executeReader(String data); <T extends ProtocolReader.ProtocolResult> T executeReader(Context context, String data);
<T extends ProtocolWriter.ProtocolResult> T executeWriter(String cmdName, String... data); <T extends ProtocolWriter.ProtocolResult> T executeWriter(String cmdName, String... data);

View File

@ -33,6 +33,15 @@ public abstract class ProtocolReader {
*/ */
private ProtocolWriter.ProtocolResult resultCommand; private ProtocolWriter.ProtocolResult resultCommand;
/**
* Le context courant
*/
private Context context;
public ProtocolResult(Context context) {
this.context = context;
}
/** /**
* Désigne vers ou cette commande est envoyée. * Désigne vers ou cette commande est envoyée.
* ResultCmdReceiver.CLIENT : Signifie que cette commande va être directement revoyée au client. * ResultCmdReceiver.CLIENT : Signifie que cette commande va être directement revoyée au client.
@ -72,6 +81,15 @@ public abstract class ProtocolReader {
*/ */
public void read(InputStream reader) { public void read(InputStream reader) {
} }
/**
* Permet de récupérer le context courant
* @return Context courant
*/
protected Context getContext() {
return context;
}
} }
/** /**
@ -80,26 +98,37 @@ public abstract class ProtocolReader {
* @param data Contenu de la commande * @param data Contenu de la commande
*/ */
public <T extends ProtocolResult> T execute(Context context, String data) { public <T extends ProtocolResult> T execute(Context context, String data) {
Matcher ruleMatcher = this.rulePattern.matcher(data); String name = extractName(data);
// Vérifier que c'est le bon protocle
String name = ruleMatcher.group(1);
if (name != null && name.equals(this.name)) { if (name != null && name.equals(this.name)) {
Matcher ruleMatcher = this.rulePattern.matcher(data);
// Vérifier que la commande match // Vérifier que la commande match
if (ruleMatcher.matches()) { if (ruleMatcher.matches()) {
String[] groups = new String[ruleMatcher.groupCount()]; String[] groups = new String[ruleMatcher.groupCount()];
for (int i = 1; i <= groups.length; ++i) for (int i = 1; i <= groups.length; ++i)
groups[i - 1] = ruleMatcher.group(i + 1); groups[i - 1] = ruleMatcher.group(i);
return onExecuted(context, groups); return onExecuted(context, groups);
} else { } else {
return onError(); return onError(context);
} }
} }
return null; return null;
} }
private String extractName(String data) {
String name;
int endIndex = data.indexOf(' ');
if (endIndex > 0) {
name = data.substring(0, endIndex);
} else {
endIndex = data.indexOf('\r');
name = data.substring(0, endIndex);
}
return name;
}
/** /**
* Cette méthode est appelée lors de l'exécution de la règle * Cette méthode est appelée lors de l'exécution de la règle
* *
@ -110,7 +139,7 @@ public abstract class ProtocolReader {
/** /**
* Cette méthode est appelée lors d'une erreur de la règle * Cette méthode est appelée lors d'une erreur de la règle
*/ */
protected <T extends ProtocolResult> T onError() { protected <T extends ProtocolResult> T onError(Context context) {
return null; return null;
} }

View File

@ -9,7 +9,7 @@ import lightcontainer.protocol.rules.writer.SignOkRule;
public class FilelistRule extends ProtocolReader { public class FilelistRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^(FILELIST)\r\n$"; private static final String PATTERN = "^FILELIST\r\n$";
private static final String NAME = "FILELIST"; private static final String NAME = "FILELIST";
@ -21,7 +21,11 @@ public class FilelistRule extends ProtocolReader {
this.protocolRep = protocolRep; this.protocolRep = protocolRep;
} }
public class Result extends ProtocolResult { } public class Result extends ProtocolResult {
public Result(Context context) {
super(context);
}
}
/** /**
* Cette méthode est appelée lors de l'exécution de la règle * Cette méthode est appelée lors de l'exécution de la règle
@ -29,7 +33,7 @@ public class FilelistRule extends ProtocolReader {
*/ */
@Override @Override
protected FilelistRule.Result onExecuted(Context context, String... data) { protected FilelistRule.Result onExecuted(Context context, String... data) {
FilelistRule.Result result = new Result(); FilelistRule.Result result = new Result(context);
result.setResultCommand(this.protocolRep.executeWriter(FilesRule.NAME, "endbenja.txt!500"), ResultCmdReceiver.CLIENT); result.setResultCommand(this.protocolRep.executeWriter(FilesRule.NAME, "endbenja.txt!500"), ResultCmdReceiver.CLIENT);
return result; return result;
} }

View File

@ -9,7 +9,7 @@ import java.util.List;
public class HelloRule extends ProtocolReader { public class HelloRule extends ProtocolReader {
private static final String PATTERN = "^(HELLO) ([A-Za-z0-9]{5,20}) ([0-9]{1,5})\r\n$"; private static final String PATTERN = "^HELLO ([A-Za-z0-9]{5,20}) ([0-9]{1,5})\r\n$";
private static final String NAME = "HELLO"; private static final String NAME = "HELLO";
@ -29,7 +29,8 @@ public class HelloRule extends ProtocolReader {
private final String domain; private final String domain;
private final int port; private final int port;
public Result(String domain, int port) { public Result(Context context, String domain, int port) {
super(context);
this.domain = domain; this.domain = domain;
this.port = port; this.port = port;
} }
@ -50,7 +51,7 @@ public class HelloRule extends ProtocolReader {
String domain = data[DOMAIN]; String domain = data[DOMAIN];
int port = Integer.parseInt(data[PORT]); int port = Integer.parseInt(data[PORT]);
return new HelloRule.Result(domain, port); return new HelloRule.Result(context, domain, port);
} }
} }

View File

@ -15,7 +15,7 @@ import java.security.NoSuchAlgorithmException;
public class SavefileRule extends ProtocolReader { public class SavefileRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^(SAVEFILE) ([^ !]{1,20}) ([0-9]{1,10})\r\n$"; private static final String PATTERN = "^SAVEFILE ([^ !]{1,20}) ([0-9]{1,10})\r\n$";
private static final String NAME = "SAVEFILE"; private static final String NAME = "SAVEFILE";
@ -36,7 +36,8 @@ public class SavefileRule extends ProtocolReader {
private final int size; private final int size;
// Construct // Construct
public Result(String filename, int size) { public Result(Context context, String filename, int size) {
super(context);
this.filename = filename; this.filename = filename;
this.size = size; this.size = size;
} }
@ -71,14 +72,14 @@ public class SavefileRule extends ProtocolReader {
*/ */
@Override @Override
protected SavefileRule.Result onExecuted(Context context, String... data) { protected SavefileRule.Result onExecuted(Context context, String... data) {
SavefileRule.Result result = new SavefileRule.Result(data[FILE_NAME], Integer.parseInt(data[FILE_SIZE])); SavefileRule.Result result = new SavefileRule.Result(context, data[FILE_NAME], Integer.parseInt(data[FILE_SIZE]));
return result; return result;
} }
@Override @Override
protected ProtocolReader.ProtocolResult onError() { protected ProtocolReader.ProtocolResult onError(Context context) {
ProtocolReader.ProtocolResult result = new ProtocolReader.ProtocolResult(); ProtocolReader.ProtocolResult result = new ProtocolReader.ProtocolResult(context);
// Commande renvoyée en cas d'erreur // Commande renvoyée en cas d'erreur
result.setResultCommand(protocolRep.executeWriter(SaveFileErrorRule.NAME), ResultCmdReceiver.CLIENT); result.setResultCommand(protocolRep.executeWriter(SaveFileErrorRule.NAME), ResultCmdReceiver.CLIENT);

View File

@ -10,7 +10,7 @@ public class SendOkRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^(SEND_OK)\r\n$"; private static final String PATTERN = "^SEND_OK\r\n$";
private static final String NAME = "SEND_OK"; private static final String NAME = "SEND_OK";
@ -25,7 +25,7 @@ public class SendOkRule extends ProtocolReader {
@Override @Override
protected ProtocolReader.ProtocolResult onExecuted(Context context, String... data) { protected ProtocolReader.ProtocolResult onExecuted(Context context, String... data) {
ProtocolReader.ProtocolResult result = new ProtocolReader.ProtocolResult(); ProtocolReader.ProtocolResult result = new ProtocolReader.ProtocolResult(context);
result.setResultCommand(protocolRep.executeWriter(SaveFileOkRule.NAME), ResultCmdReceiver.CLIENT); result.setResultCommand(protocolRep.executeWriter(SaveFileOkRule.NAME), ResultCmdReceiver.CLIENT);
return result; return result;
} }

View File

@ -3,6 +3,7 @@ package lightcontainer.protocol.rules.reader;
import lightcontainer.domains.client.Context; import lightcontainer.domains.client.Context;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.ProtocolWriter;
import lightcontainer.protocol.rules.writer.SaveFileErrorRule; import lightcontainer.protocol.rules.writer.SaveFileErrorRule;
import lightcontainer.protocol.rules.writer.SignErrorRule; import lightcontainer.protocol.rules.writer.SignErrorRule;
import lightcontainer.protocol.rules.writer.SignOkRule; import lightcontainer.protocol.rules.writer.SignOkRule;
@ -11,7 +12,7 @@ import java.io.InputStream;
public class SigninRule extends ProtocolReader { public class SigninRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^(SIGNIN) ([A-Za-z0-9]{5,20}) ([^ !]{5,50})\r\n$"; private static final String PATTERN = "^SIGNIN ([A-Za-z0-9]{5,20}) ([^ !]{5,50})\r\n$";
private static final String NAME = "SIGNIN"; private static final String NAME = "SIGNIN";
@ -32,7 +33,8 @@ public class SigninRule extends ProtocolReader {
private final String password; private final String password;
// Result constructor // Result constructor
public Result(String login, String password) { public Result(Context context, String login, String password) {
super(context);
this.login = login; this.login = login;
this.password = password; this.password = password;
} }
@ -45,27 +47,24 @@ public class SigninRule extends ProtocolReader {
return password; return password;
} }
public boolean checkCredentials() {
return getLogin().equals("aaaaa") && getPassword().equals("aaaaa");
}
} }
@Override @Override
protected SigninRule.Result onExecuted(Context context, String... data) { protected SigninRule.Result onExecuted(Context context, String... data) {
SigninRule.Result result = new SigninRule.Result(data[LOGIN], data[PASSWORD]); SigninRule.Result result = new SigninRule.Result(context, data[LOGIN], data[PASSWORD]);
// TODO : Création d'une règle d'écriture SIGN_OK et SIGN_ERROR proprement if (context.signIn(result.getLogin(), result.getPassword())) {
if (result.checkCredentials()) {
result.setResultCommand(this.protocolRep.executeWriter(SignOkRule.NAME), ResultCmdReceiver.CLIENT); result.setResultCommand(this.protocolRep.executeWriter(SignOkRule.NAME), ResultCmdReceiver.CLIENT);
} else { } else {
result.setResultCommand(this.protocolRep.executeWriter(SignErrorRule.NAME), ResultCmdReceiver.CLIENT); result.setResultCommand(this.protocolRep.executeWriter(SignErrorRule.NAME), ResultCmdReceiver.CLIENT);
} }
return result; return result;
} }
@Override @Override
protected ProtocolReader.ProtocolResult onError() { protected ProtocolReader.ProtocolResult onError(Context context) {
ProtocolReader.ProtocolResult result = new ProtocolReader.ProtocolResult(); ProtocolReader.ProtocolResult result = new ProtocolReader.ProtocolResult(context);
result.setResultCommand(protocolRep.executeWriter(SignErrorRule.NAME), ResultCmdReceiver.CLIENT); result.setResultCommand(protocolRep.executeWriter(SignErrorRule.NAME), ResultCmdReceiver.CLIENT);
return result; return result;

View File

@ -4,10 +4,11 @@ import lightcontainer.domains.client.Context;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.rules.writer.SignErrorRule; import lightcontainer.protocol.rules.writer.SignErrorRule;
import lightcontainer.protocol.rules.writer.SignOkRule;
public class SignupRule extends ProtocolReader { public class SignupRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^(SIGNUP) ([A-Za-z0-9]{5,20}) ([^ !]{5,50})\r\n$"; private static final String PATTERN = "^SIGNUP ([A-Za-z0-9]{5,20}) ([^ !]{5,50})\r\n$";
private static final String NAME = "SIGNUP"; private static final String NAME = "SIGNUP";
private static final int LOGIN = 0; private static final int LOGIN = 0;
private static final int PASSWORD = 1; private static final int PASSWORD = 1;
@ -24,7 +25,8 @@ public class SignupRule extends ProtocolReader {
private final String login; private final String login;
private final String password; private final String password;
public Result(String login, String password) { public Result(Context context, String login, String password) {
super(context);
this.login = login; this.login = login;
this.password = password; this.password = password;
} }
@ -42,15 +44,20 @@ public class SignupRule extends ProtocolReader {
@Override @Override
protected SignupRule.Result onExecuted(Context context, String... data) { protected SignupRule.Result onExecuted(Context context, String... data) {
SignupRule.Result result = new SignupRule.Result(data[LOGIN], data[PASSWORD]); SignupRule.Result result = new SignupRule.Result(context, data[LOGIN], data[PASSWORD]);
if (context.createUser(result.getLogin(), result.getPassword())) {
result.setResultCommand(this.protocolRep.executeWriter(SignOkRule.NAME), ResultCmdReceiver.CLIENT);
} else {
result.setResultCommand(this.protocolRep.executeWriter(SignErrorRule.NAME), ResultCmdReceiver.CLIENT);
}
if ()
return null; return null;
} }
@Override @Override
protected ProtocolReader.ProtocolResult onError() { protected ProtocolReader.ProtocolResult onError(Context context) {
ProtocolReader.ProtocolResult result = new ProtocolReader.ProtocolResult(); ProtocolReader.ProtocolResult result = new ProtocolReader.ProtocolResult(context);
result.setResultCommand(protocolRep.executeWriter(SignErrorRule.NAME), ResultCmdReceiver.CLIENT); result.setResultCommand(protocolRep.executeWriter(SignErrorRule.NAME), ResultCmdReceiver.CLIENT);
return result; return result;

View File

@ -1,5 +1,6 @@
package lightcontainer.repository; package lightcontainer.repository;
import lightcontainer.domains.client.Context;
import lightcontainer.domains.client.StoreProcessor; import lightcontainer.domains.client.StoreProcessor;
import lightcontainer.domains.Task; import lightcontainer.domains.Task;
import lightcontainer.enumerations.TaskStatus; import lightcontainer.enumerations.TaskStatus;
@ -76,8 +77,8 @@ public class FileFrontEnd implements ClientHandlerFFE, StoreProcessorFFE {
@Override @Override
public void newCommand(ProtocolWriter.ProtocolResult command, String client) { public void newCommand(Context context, ProtocolWriter.ProtocolResult command) {
Task task = Task.newInstance(command, client); Task task = Task.newInstance(context, command);
tasks.add(task); tasks.add(task);
alertStoreProcessors(task); alertStoreProcessors(task);
} }

View File

@ -1,5 +1,6 @@
package lightcontainer.repository; package lightcontainer.repository;
import lightcontainer.domains.client.Context;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
@ -12,9 +13,9 @@ public class ProtocolRepositoryImpl implements ProtocolRepository {
private final Set<ProtocolWriter> writers = new HashSet<>(); private final Set<ProtocolWriter> writers = new HashSet<>();
@Override @Override
public <T extends ProtocolReader.ProtocolResult> T executeReader(String data) { public <T extends ProtocolReader.ProtocolResult> T executeReader(Context context, String data) {
for (ProtocolReader reader : readers) { for (ProtocolReader reader : readers) {
T readerResult = reader.execute(data); T readerResult = reader.execute(context, data);
if (readerResult != null) { if (readerResult != null) {
return readerResult; return readerResult;
} }

View File

@ -75,7 +75,7 @@ public class StoreProcessorRepository implements AutoCloseable, MulticastSPR {
public void assignTask(String stor, Task task) { public void assignTask(String stor, Task task) {
StoreProcessor handler = findSBE(task); StoreProcessor handler = findSBE(task);
System.out.println("Find stor : " + handler); System.out.println("Find stor : " + handler);
handler.executeCommand(task.getCommand()); handler.executeCommand(task.getContext(), task.getCommand());
} }
/** /**

View File

@ -89,15 +89,6 @@ public class AppData {
return users.values().iterator(); return users.values().iterator();
} }
/**
* @param fileName The name of the file
* @param user The user
* @return The file corresponding to the given name and belonging to the user. Null if the user cannot be found or the file cannot be found
* @deprecated Maybe not useful. DO NOT USE FOR THE TIME BEING
*/
public File getFileOf(String fileName, User user) {
return this.users.get(user.getName()).getFile(fileName);
}
/** /**
* Call this method after receiving SAVEFILE_OK from the StorBackEnd. * Call this method after receiving SAVEFILE_OK from the StorBackEnd.

View File

@ -14,11 +14,11 @@ class HelloRuleTest {
String request = "HELLO bento 42890\r\n"; String request = "HELLO bento 42890\r\n";
// WHEN // WHEN
HelloRule.Result ruleResult = protocolReader.execute(request); // HelloRule.Result ruleResult = protocolReader.execute(request);
// THEN // THEN
assertEquals("bento", ruleResult.getDomain()); // assertEquals("bento", ruleResult.getDomain());
assertEquals(42890, ruleResult.getPort()); // assertEquals(42890, ruleResult.getPort());
} }
} }