| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package rsx;
- import java.io.IOException;
- import java.net.InetAddress;
- import java.util.HashMap;
- import java.util.concurrent.atomic.AtomicBoolean;
- import org.json.JSONException;
- import org.json.JSONObject;
- import rsx.tcp.TcpClient;
- /**
- * Analyse les requetes emises par le serveur
- *
- * @author Arthur Brandao
- */
- public class BomberStudentRequest extends Thread {
- /**
- * Indique si on coupe la boucle
- */
- private final AtomicBoolean running = new AtomicBoolean(true);
- /**
- * Connexion au serveur
- */
- protected TcpClient socket;
- /**
- * Liste des handler à appeler
- */
- protected HashMap<String, BomberStudentHandler> handlers;
- /* --- Constructeur --- */
- public BomberStudentRequest(InetAddress adr, int port, HashMap<String, BomberStudentHandler> handlers) throws IOException {
- this.handlers = handlers;
- this.socket = new TcpClient(adr, port);
- this.socket.timeout(2);
- if (!this.socket.connect()) {
- System.err.println("Impossible de créer la socket");
- throw new IOException("Connexion impossible");
- }
- }
- /* --- Surcharge --- */
- @Override
- public void interrupt() {
- this.running.set(false);
- super.interrupt();
- }
- @Override
- public void run() {
- //Tant qu'actif
- while (this.running.get()) {
- //Attente contact serveur
- String msg = this.socket.receive();
- //Si rien on continue
- if (msg == null) {
- continue;
- }
- //Traitement du message
- String[] requete = msg.split("\n");
- if (requete.length < 2) {
- continue;
- }
- //Regarde la requete
- String[] entete = requete[0].split(" ");
- if (entete.length < 2) {
- continue;
- }
- if (!entete[0].equals("POST")) {
- continue;
- }
- //Regarde si il existe un handler
- String ressource = entete[1];
- if (!this.handlers.containsKey(ressource)) {
- continue;
- }
- //Recup json
- JSONObject json = null;
- try {
- json = new JSONObject(requete[1]);
- } catch (JSONException ex) {
- System.err.println("La requete n'est pas en JSON : " + ex.getMessage());
- continue;
- }
- //Appel handler
- BomberStudentHandler handler = this.handlers.get(ressource);
- if(!handler.handle(json)){
- System.err.println("Erreur pendant l'execution du handler");
- }
- }
- //Fermeture socket
- this.socket.close();
- }
- }
|