MainController.java 12.9 KB
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.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;
import java.util.Locale;

@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.setViewName("registration");
        return modelAndView;
    }

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

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

        if(teamRepository.findByTeam(teamName) != null) {
            return "redirect:/registration?message=Le groupe&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&succeed=1";
        }
    }

    @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&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);
            System.out.println("team found : " + team);
            Team temp = teamRepository.findByTeam(team);
            temp.addCustomer(n);
            teamRepository.save(temp);
            return "redirect:/registration?message=L'utilisateur&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 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);
    }

}