MainController.java 17.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
package com.PFE.ServerManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.*;
import java.sql.Timestamp;
import java.text.ParseException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.Authentication;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;

import javax.servlet.annotation.MultipartConfig;
import com.fasterxml.jackson.databind.ObjectMapper;


import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@MultipartConfig(fileSizeThreshold = 100000000) //à changer, taille max des fichiers

public class MainController {

    @Autowired
    NodeRepository nodeRepository;

    @Autowired
    CustomerRepository customerRepository;

    @Autowired
    TeamRepository teamRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    UpdateRepository updateRepository;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @GetMapping(value="/")
    public String uploadRedirection(){
        return "redirect:home";
    }

    @GetMapping(value="/home")
    public ModelAndView home() {
        ModelAndView modelAndView = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        modelAndView.addObject("customerName", customer.getEmail().split("@")[0]);
        modelAndView.addObject("customerRole", customer.getRole());
        modelAndView.setViewName("home");
        return modelAndView;
    }

    @GetMapping(value="/upload")
    public ModelAndView upload() {
        ModelAndView modelAndView = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        modelAndView.addObject("customerName", customer.getEmail().split("@")[0]);
        modelAndView.addObject("customerRole", customer.getRole());
        modelAndView.setViewName("upload");
        return modelAndView;
    }

    @GetMapping(value="/update")
    public ModelAndView update() {
        ModelAndView modelAndView = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        modelAndView.addObject("customerName", customer.getEmail().split("@")[0]);
        modelAndView.addObject("customerRole", customer.getRole());
        modelAndView.addObject("customerMaj", (teamRepository.findByCustomersContaining(customer)).getUpdates());
        List<Node> nodes = nodeRepository.findAll();
        modelAndView.addObject("nodes", nodes);

        File file = new File("files");
        File[] dirs = file.listFiles();
        List<String> filesName = new ArrayList<String>();

        if (dirs != null) {
            for (int i = 0; i < dirs.length; i++) {
                if (dirs[i].isDirectory() == true) {
                    if ((dirs[i].getName().split("_")[0]).equals(customer.getEmail().split("@")[0])) {
                        File dir = new File(dirs[i].getAbsolutePath());
                        File[] f = dir.listFiles();
                        filesName.add(f[0].getName());
                   }
                }
            }
        }

        modelAndView.addObject("customerFiles", filesName);
        modelAndView.setViewName("update");
        return modelAndView;
    }

    @GetMapping(path="/registration")
    public ModelAndView registration(@RequestParam(required=false) String message, @RequestParam(required=false) Integer succeed) {
        ModelAndView modelAndView = new ModelAndView();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        modelAndView.addObject("customerName", customer.getEmail().split("@")[0]);
        modelAndView.addObject("customerRole", customer.getRole());
        modelAndView.addObject("message", message);
        modelAndView.addObject("succeed", succeed);
        System.out.println("all teams : " + teamRepository.findAll());
        modelAndView.addObject("allTeams", teamRepository.findAll());
        modelAndView.addObject("allCustomers", customerRepository.findAll());
        modelAndView.setViewName("registration");
        return modelAndView;
    }

    @GetMapping(path="/denied")
    public String denied() {
        return "denied";
    }

    @PostMapping(path="/addUser")
    public String addNewUser(@RequestParam String email, @RequestParam String password, @RequestParam String role, @RequestParam String team) {

        if(customerRepository.findByEmail(email) != null) {
            return "redirect:/registration?message=L'utilisateur existe+d%C3%A9j%C3%A0&succeed=-1";
        }
        else {
            Customer n = new Customer();
            n.setEmail(email);
            n.setPassword(bCryptPasswordEncoder.encode(password));
            n.setCustomerId((int)(customerRepository.count() + 1));
            n.setActive(1);
            Role userRole = roleRepository.findByRole(role);
            n.addRole(userRole);
            customerRepository.save(n);
            Team temp = teamRepository.findByTeam(team);
            temp.addCustomer(n);
            teamRepository.save(temp);
            return "redirect:/registration?message=L'utilisateur a+%C3%A9t%C3%A9+ajout%C3%A9&succeed=1";
        }
    }

    @PostMapping(path="/addTeam")
    public String addNewTeam(@RequestParam String teamName){

        if(teamRepository.findByTeam(teamName) != null) {
            return "redirect:/registration?message=Le groupe existe+d%C3%A9j%C3%A0&succeed=-1";
        }
        else {
            Team t = new Team();
            t.setTeam(teamName);
            t.setTeamId((int)(teamRepository.count()+1));
            teamRepository.save(t);
            return "redirect:/registration?message=Le groupe a+%C3%A9t%C3%A9+ajout%C3%A9&succeed=1";
        }
    }

    @PostMapping(path="/changeCustomerTeam")
    public String addCustomerTeam(@RequestParam String teamName, @RequestParam String customerName){
        Team newTeam = teamRepository.findByTeam(teamName);
        Customer customer = customerRepository.findByEmail(customerName);
        Team oldTeam = teamRepository.findByCustomersContaining(customer);
        if( newTeam == null || customer == null) {
            return "redirect:/registration?message=le+groupe+ou+l%27utilisateur+n%27existe+plus&succeed=-1";
        }
        else if(oldTeam == newTeam){
            return "redirect:/registration?message=l%27utilisateur+appartient+d%C3%A9j%C3%A0+%C3%A0+ce+groupe&succeed=-1";
        }
        else {
            newTeam.addCustomer(customer);
            oldTeam.removeCustomer(customer);
            teamRepository.save(newTeam);
            teamRepository.save(oldTeam);
            return "redirect:/registration?message=le+groupe+de+l%27utilisateur+a+bien+%C3%A9t%C3%A9+chang%C3%A9&succeed=1";
        }
    }

    @RequestMapping(value = "/file", method = RequestMethod.POST)
    public ResponseEntity submit(@RequestParam MultipartFile file) {
        if(findFile(file.getOriginalFilename()) != null) {
            return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
        }

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        File dirs = new File("files/" + customer.getEmail().split("@")[0] + "_" + timestamp.getTime());
        dirs.mkdirs();
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            File newFile = new File(dirs.getPath() + "/" + file.getOriginalFilename());
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
            outputStream = new FileOutputStream(newFile);
            int read = 0;
            byte[] bytes = new byte[1024];

            while((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                outputStream.close();
            }
            catch(IOException e) {
            }
        }
        return new ResponseEntity<String>(HttpStatus.OK);
    }

    @RequestMapping(value = "/updatenodes", method = RequestMethod.POST)
    @ResponseStatus(value = HttpStatus.OK)
    public void submitConfig(HttpEntity<String> httpEntity) {

        nodeRepository.deleteAll();
        String json = httpEntity.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        NodeJSON[] nodes = null;
        try {
            nodes = objectMapper.readValue(json, NodeJSON[].class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (NodeJSON n : nodes) {
            Node node = new Node();
            node.setName(n.getName());
            node.setArch(n.getArch());
            node.setIp(n.getIp());
            List<SensorJSON> sensors = n.getSensors();
            Set<Sensor> sensorsReal = new HashSet<Sensor>();
            for(SensorJSON s : sensors)
            {
                Sensor ss = new Sensor();
                ss.setName(s.getName());
                sensorsReal.add(ss);
            }
            node.setSensors(sensorsReal);
            nodeRepository.save(node);
        }

    }

    @GetMapping(path="/login")
    public ModelAndView login() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @GetMapping(path="/all")
    public ModelAndView getAllUsers() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("all");
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        modelAndView.addObject("customerName", customer.getEmail().split("@")[0]);
        modelAndView.addObject("customerRole", customer.getRole());

        List<Customer> list = customerRepository.findAll(); // attention : la méthode findAll() de JpaRepository retourne une liste alors que celle de CrudRepository retourne un itérable
        modelAndView.addObject("list", list);
        modelAndView.addObject("team", teamRepository.findAll());
        return modelAndView;
    }

    public static List<ArrayList<String>> getSensorsUsed(List<Node> nodes) {
        Yaml yaml = new Yaml(new Constructor(UpdateYAML.class));
        InputStream inputStream = null;
        List<UpdateYAML> updateYAMLS = new ArrayList<>();
        List<String> state_sensor = new ArrayList<>();
        File dir = new File("toflash");
        if(dir.isDirectory()) {
            String s[] = dir.list();
            for (int i = 0; i < s.length; i++) {
                if(s[i].endsWith("yml.started")) {
                    state_sensor.add(i,"started");
                }
                else{
                    state_sensor.add(i,"programmed");
                }
                try {
                    inputStream = new FileInputStream(new File("toflash/" + s[i]));
                    UpdateYAML update = yaml.load(inputStream);
                    updateYAMLS.add(update);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        List<ArrayList<String>> table = new ArrayList<>();
        int i=0, j=0, k=0;

        for(Node node : nodes){
            table.add(new ArrayList<>());
            for(Sensor sensor : node.getSensors()){
                for(UpdateYAML update : updateYAMLS) {
                    for(String sensorUpdate : update.getNodesSplited()){
                        if(sensor.getName().equals(sensorUpdate)){
                            DateTimeFormatter formatter_date = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
                            DateTimeFormatter formatter_time = DateTimeFormatter.ofPattern("HH:mm");
                            LocalDateTime updateDate = LocalDateTime.parse(update.getDate(),formatter_date);
                            LocalDateTime now = LocalDateTime.now();
                            if(state_sensor.get(k).equals("started")){
                                System.out.println("duration between in minutes " + Duration.between(now,updateDate).toMinutes());
                                LocalTime duration = LocalTime.parse(update.getTime(),formatter_time);
                                updateDate = updateDate.plusMinutes(duration.getMinute());
                                updateDate = updateDate.plusHours(duration.getHour());
                                table.get(i).add(j,"utilisé (disponible dans " + Duration.between(now,updateDate).toHours() + "h " + (Duration.between(now,updateDate).toMinutes())%60 + "min)");
                            }
                            else if(state_sensor.get(k).equals("programmed")){
                                table.get(i).add(j,"programmé (débute dans " + Duration.between(now,updateDate).toHours() + "h " + (Duration.between(now,updateDate).toMinutes())%60 + "min)");
                            }
                        }
                    }
                    k++;
                }
                k=0;
                if(table.get(i).size()==j){
                    table.get(i).add(j,"disponible");
                }
                j++;
            }
            j=0;
            i++;
        }
        System.out.println("table : " + table);
        return table;
    }

    @GetMapping(path="/history")
    public ModelAndView displayHistory() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("history");
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        modelAndView.addObject("customerName", customer.getEmail().split("@")[0]);
        modelAndView.addObject("customerRole", customer.getRole());
        modelAndView.addObject("nodes", nodeRepository.findAll());
        modelAndView.addObject("is_used", getSensorsUsed(nodeRepository.findAll()));
        return modelAndView;
    }

    public static String findFile(String filename) {
        File dir = new File("files");
        if(dir.isDirectory()){
            String s[] = dir.list();
            for(int i = 0; i < s.length; i++) {
                File dirTemp = new File("files/" + s[i]);
                if(dirTemp.isDirectory()) {
                    if(dirTemp.list()[0].equals(filename)) {
                        return s[i];
                    }
                }
            }
        }
        return null;
    }


    @PostMapping(path="/savemaj")
    public String saveMaj(@RequestParam String name, @RequestParam String date, @RequestParam String time, @RequestParam String nodes, @RequestParam String file, @RequestParam String arch){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());

        Update update_c = new Update();
        update_c.setUpdate(name);
        update_c.setDate(date);
        update_c.setNodes(nodes);
        update_c.setFile(file);
        update_c.setTime(time);
        update_c.setArch(arch);
        update_c.setDir(findFile(update_c.getFile()));

        updateRepository.save(update_c); // ajouter la mise a jour dans la table

        Team teamOfCustomer = teamRepository.findByCustomersContaining(customer);
        teamOfCustomer.addUpdate(update_c);
        teamRepository.save(teamOfCustomer); // permet de rendre effective la jointure entre customer et maj

        return "redirect:/update";
    }

    @PostMapping(path="/startsavedmaj")
    @ResponseStatus(value = HttpStatus.OK)
    public void startSavedMaj(@RequestParam String majname){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Customer customer = customerRepository.findByEmail(auth.getName());
        Update update = updateRepository.findByUpdate(majname);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        Date now = new Date();
        Date date = null;
        try {
            date = sdf.parse(update.getDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(date.compareTo(now) < 0) {
            update.setDate(sdf.format(now));
            updateRepository.save(update);
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("name", update.getUpdate());
        data.put("exp_id", update.getUpdateId());
        data.put("date", update.getDate());
        data.put("time", update.getTime());
        data.put("file", update.getFile());
        data.put("dir", update.getDir());
        data.put("arch", update.getArch());
        data.put("nodes", update.getNodes().split(";"));
        Yaml yaml = new Yaml();
        FileWriter writer = null;
        try {
            writer = new FileWriter("toflash/" + customer.getEmail().split("@")[0] + "_" + update.getUpdate() + ".yml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        yaml.dump(data, writer);
    }

}