1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- 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 entete = this.socket.receive();
- //Si rien on continue
- if (entete == null) {
- continue;
- }
- //On recup les parametres
- String param = this.socket.receive();
- //Si rien on continue
- if (param == null) {
- continue;
- }
- //Regarde la requete
- String[] requete = entete.split(" ");
- if (requete.length < 2) {
- continue;
- }
- if (!requete[0].equals("POST")) {
- continue;
- }
- //Regarde si il existe un handler
- String ressource = requete[1];
- if (!this.handlers.containsKey(ressource)) {
- continue;
- }
- //Recup json
- JSONObject json = null;
- try {
- json = new JSONObject(param);
- } 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 " + ressource);
- }
- }
- //Fermeture socket
- this.socket.close();
- }
- }
|