Fix autoclosable client handler and comment into UnicastThread.java

This commit is contained in:
Jérémi N ‘EndMove’ 2022-03-20 12:47:17 +01:00
parent 60fb6390b4
commit ba60809d2f
Signed by: EndMove
GPG Key ID: 65C4A02E1F5371A4
3 changed files with 97 additions and 73 deletions

View File

@ -10,9 +10,8 @@ import lightcontainer.protocol.rules.reader.SignoutRule;
import lightcontainer.protocol.rules.reader.SignupRule; import lightcontainer.protocol.rules.reader.SignupRule;
import lightcontainer.protocol.rules.writer.SignErrorRule; import lightcontainer.protocol.rules.writer.SignErrorRule;
import java.io.*; import java.io.IOException;
import java.net.Socket; import java.net.Socket;
import java.nio.charset.StandardCharsets;
/** /**
* ClientHandler * ClientHandler
@ -42,7 +41,6 @@ public class ClientHandler extends UnicastThread implements AutoCloseable {
this.protocolRep = protocolRep; this.protocolRep = protocolRep;
} }
/** /**
* Thread Function * Thread Function
* Start the dialogue with the client. * Start the dialogue with the client.
@ -51,23 +49,24 @@ public class ClientHandler extends UnicastThread implements AutoCloseable {
*/ */
@Override @Override
public void run() { public void run() {
// Set process to true
this.setRunning(true); this.setRunning(true);
// Process while
while (this.isRunning()) { while (this.isRunning()) {
// Signifie le démarrage d'une nouvelle rquête // Signifie le démarrage d'une nouvelle rquête
getContext().newBundle(); getContext().newBundle();
try { try {
String command = this.readLine(); String command = this.readLine();
if (command != null) { if (command != null) {
System.out.println("Client: " + command); System.out.println("Client: " + command);
} else { } else {
repository.disconnect(this); this.repository.disconnect(this);
break; break;
} }
ProtocolReader.ProtocolResult ruleResult = protocolRep.executeReader(getContext(), command + "\r\n"); ProtocolReader.ProtocolResult ruleResult = this.protocolRep.executeReader(getContext(), command + "\r\n");
if (ruleResult == null) { if (ruleResult == null) {
repository.disconnect(this); this.repository.disconnect(this);
break; break;
} }
@ -80,33 +79,25 @@ public class ClientHandler extends UnicastThread implements AutoCloseable {
if (ruleResult.getReceiver() == ProtocolReader.ResultCmdReceiver.STOREBACKEND && !fileFrontEnd.canExecuteCommand(ruleResult.getRequestDomain())) { if (ruleResult.getReceiver() == ProtocolReader.ResultCmdReceiver.STOREBACKEND && !fileFrontEnd.canExecuteCommand(ruleResult.getRequestDomain())) {
this.print(ruleResult.onNotExecutable(getContext())); // Renvoie au client this.print(ruleResult.onNotExecutable(getContext())); // Renvoie au client
} else if (ruleResult.getReceiver() == ProtocolReader.ResultCmdReceiver.STOREBACKEND) { } else if (ruleResult.getReceiver() == ProtocolReader.ResultCmdReceiver.STOREBACKEND) {
fileFrontEnd.newCommand(getContext(), writerCommand, ruleResult.getRequestDomain()); // Envoie dans la file de tâche FileFrontEnd en attente d'un traitement d'un StorBackEnd this.fileFrontEnd.newCommand(getContext(), writerCommand, ruleResult.getRequestDomain()); // 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();
if (response != null) { if (this.response != null) {
this.write(response.getCommand()); // Renvoie au client this.write(this.response.getCommand()); // Renvoie au client
response.write(this.getOutputStream()); // Ecrit au client si nécessaire this.response.write(this.getOutputStream()); // Ecrit au client si nécessaire
} else { } else {
this.print(ruleResult.onNotExecutable(getContext())); // Renvoie au client this.print(ruleResult.onNotExecutable(getContext())); // Renvoie au client
} }
} else { } else {
this.print(writerCommand.getCommand()); // Renvoie au client this.print(writerCommand.getCommand()); // Renvoie au client
} }
} else { } else {
accessDenied(); accessDenied();
} }
} catch (IOException e) { } catch (IOException e) {
repository.disconnect(this); this.close();
break;
} }
} }
try {
this.close();
System.out.printf("[CLIENT] %s s'est déconnecté\n", getContext().getLogin());
} catch (Exception ignored) {}
} }
/** /**
@ -119,7 +110,6 @@ public class ClientHandler extends UnicastThread implements AutoCloseable {
checkSignout(ruleResult); checkSignout(ruleResult);
if (getContext().isConnected()) if (getContext().isConnected())
return true; return true;
try { try {
ruleResult ruleResult
.getClass() .getClass()
@ -129,10 +119,8 @@ public class ClientHandler extends UnicastThread implements AutoCloseable {
try { try {
ruleResult.getClass().asSubclass(SigninRule.Result.class); ruleResult.getClass().asSubclass(SigninRule.Result.class);
return true; return true;
} catch (ClassCastException e2) { } catch (ClassCastException ignored) { }
}
} }
return false; return false;
} }
@ -140,8 +128,7 @@ public class ClientHandler extends UnicastThread implements AutoCloseable {
* Lorsque l'accès à été refusé. * Lorsque l'accès à été refusé.
*/ */
private void accessDenied() { private void accessDenied() {
System.out.println("AIEAIEAIE"); ProtocolWriter.ProtocolResult signErrorResult = this.protocolRep.executeWriter(getContext(), SignErrorRule.NAME);
ProtocolWriter.ProtocolResult signErrorResult = protocolRep.executeWriter(getContext(), SignErrorRule.NAME);
this.write(signErrorResult.getCommand()); // Envoie SignError car echec de la connection this.write(signErrorResult.getCommand()); // Envoie SignError car echec de la connection
} }
@ -153,21 +140,10 @@ public class ClientHandler extends UnicastThread implements AutoCloseable {
private void checkSignout(ProtocolReader.ProtocolResult ruleResult) { private void checkSignout(ProtocolReader.ProtocolResult ruleResult) {
try { try {
ruleResult.getClass().asSubclass(SignoutRule.Result.class); ruleResult.getClass().asSubclass(SignoutRule.Result.class);
repository.disconnect(this); this.repository.disconnect(this);
} catch (ClassCastException e2) {} } catch (ClassCastException ignored) {}
} }
/**
* Vérifie s'il s'âgit d'une demande de déconnexion
* @param ruleResult
private void checkSignError(ProtocolWriter.ProtocolResult ruleResult) {
if (ruleResult.getCommand().startsWith(SignErrorRule.NAME)) {
System.out.println("Pas pu connecter");
repository.disconnect(this);
}
}
*/
/** /**
* 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
*/ */
@ -201,11 +177,15 @@ public class ClientHandler extends UnicastThread implements AutoCloseable {
*/ */
@Override @Override
public void close() { public void close() {
try { if (this.isRunning()) {
super.close(); try {
} catch (Exception e) {} super.close();
System.out.println("Call close"); this.repository.disconnect(this);
this.setRunning(false); System.out.printf("[CLIENT] %s s'est déconnecté\n", getContext().getLogin());
} catch (IOException e) {
System.out.println("[CH] Error while closing client.");
}
}
} }
public String getLogin() { public String getLogin() {

View File

@ -1,15 +1,12 @@
package lightcontainer.domains.client; package lightcontainer.domains.client;
import lightcontainer.domains.Task;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.interfaces.StoreProcessorFFE; import lightcontainer.interfaces.StoreProcessorFFE;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
import java.io.*; import java.io.IOException;
import java.net.Socket; import java.net.Socket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Objects; import java.util.Objects;
@ -35,7 +32,6 @@ public class StoreProcessor extends UnicastThread implements AutoCloseable {
private ProtocolWriter.ProtocolResult protocolResult; private ProtocolWriter.ProtocolResult protocolResult;
private final ProtocolRepository protocolRep; private final ProtocolRepository protocolRep;
// Constructor // Constructor
public StoreProcessor(Socket socket, String domain, StoreProcessorFFE ffe, ProtocolRepository protocolRep) { public StoreProcessor(Socket socket, String domain, StoreProcessorFFE ffe, ProtocolRepository protocolRep) {
super(socket); super(socket);
@ -44,7 +40,6 @@ public class StoreProcessor extends UnicastThread implements AutoCloseable {
this.protocolRep = protocolRep; this.protocolRep = protocolRep;
} }
/** /**
* Thread Function * Thread Function
* Start the dialogue with the storebackend. * Start the dialogue with the storebackend.
@ -53,8 +48,9 @@ public class StoreProcessor extends UnicastThread implements AutoCloseable {
*/ */
@Override @Override
public void run() { public void run() {
// Set process to true
this.setRunning(true); this.setRunning(true);
// Process while
while (this.isRunning()) { while (this.isRunning()) {
try { try {
if (protocolResult == null) { // Si on n'a pas encore la commande à envoyer if (protocolResult == null) { // Si on n'a pas encore la commande à envoyer
@ -72,7 +68,6 @@ public class StoreProcessor extends UnicastThread implements AutoCloseable {
alertAvailable(null); alertAvailable(null);
break; break;
} }
// Response // Response
String responseCommand = this.readLine(); String responseCommand = this.readLine();
if (responseCommand != null && !responseCommand.isBlank()) { if (responseCommand != null && !responseCommand.isBlank()) {
@ -100,12 +95,12 @@ public class StoreProcessor extends UnicastThread implements AutoCloseable {
} }
} }
// Fermeture du SBE // Closing SBE
try { try {
super.close(); super.close();
this.fileFrontEnd.onStoreDisconnect(this.domain); this.fileFrontEnd.onStoreDisconnect(this.domain);
} catch (Exception ioException) { } catch (Exception e) {
System.out.println("[ERROR] Error while closing SBE (" + domain + ") : " + ioException.getMessage()); System.out.println("[ERROR] Error while closing SBE (" + domain + ") : " + e.getMessage());
} }
} }

View File

@ -5,21 +5,28 @@ import java.net.Socket;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
public abstract class UnicastThread extends Thread implements AutoCloseable { public abstract class UnicastThread extends Thread implements AutoCloseable {
// Variables
private final Socket socket; private final Socket socket;
private Context context; private Context context;
private BufferedReader reader; private BufferedReader reader;
private PrintWriter writer; private PrintWriter writer;
private boolean isRunning = false; private boolean isRunning = false;
/**
* UnicastThread Constructor
*
* @param socket Unicast Socket
*/
public UnicastThread(Socket socket) { public UnicastThread(Socket socket) {
this(socket, null); this(socket, null);
} }
/**
* UnicastThread Constructor
*
* @param socket Unicast Socket
* @param context Connection context
*/
public UnicastThread(Socket socket, Context context) { public UnicastThread(Socket socket, Context context) {
this.socket = socket; this.socket = socket;
this.context = context; this.context = context;
@ -49,49 +56,91 @@ public abstract class UnicastThread extends Thread implements AutoCloseable {
} }
} }
/**
* Read from the socket.
*
* @return Returns the line that was read
*/
protected String readLine() throws IOException { protected String readLine() throws IOException {
return reader.readLine(); return this.reader.readLine();
} }
/**
* Write to the socket.
*
* @param str Content to write.
*/
protected void write(String str) { protected void write(String str) {
writer.write(str); this.writer.write(str);
writer.flush(); this.writer.flush();
} }
/**
* Print to the socket.
*
* @param str Content to print.
*/
protected void print(String str) { protected void print(String str) {
writer.print(str); this.writer.print(str);
writer.flush(); this.writer.flush();
} }
/**
* Getter, allow to retrieve an inputstream of the socket.
*
* @return Socket inputstream.
*/
protected InputStream getInputStream() throws IOException { protected InputStream getInputStream() throws IOException {
return socket.getInputStream(); return this.socket.getInputStream();
} }
/**
* Getter, allow to retrieve an outputstream of the socket.
*
* @return Socket outputstream.
*/
protected OutputStream getOutputStream() throws IOException { protected OutputStream getOutputStream() throws IOException {
return socket.getOutputStream(); return this.socket.getOutputStream();
} }
/**
* Close all connection stream and resources.
*/
@Override @Override
public void close() throws Exception { public void close() throws IOException {
this.reader.close(); this.reader.close();
this.writer.close(); this.writer.close();
this.socket.close(); this.socket.close();
} }
/**
* Allow to verify if the thread is running.
* @return True; yes, False; no.
*/
protected boolean isRunning() { protected boolean isRunning() {
return isRunning; return this.isRunning;
} }
/**
* Setter, define the running status.
* @param running True; is running, False; is not running.
*/
protected void setRunning(boolean running) { protected void setRunning(boolean running) {
isRunning = running; this.isRunning = running;
} }
/**
* Retrieve connection context.
* @return Context.
*/
protected Context getContext() { protected Context getContext() {
return context; return this.context;
} }
/**
* Set connection context.
* @param context context.
*/
protected void setContext(Context context) { protected void setContext(Context context) {
this.context = context; this.context = context;
} }