AppConfig.java 2.09 KB
package com.PFE.ServerManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.*;


@Component
public class AppConfig {

    @Autowired
    CustomerRepository customerRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    MajRepository majRepository;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    NodeRepository nodeRepository;

    @PostConstruct
    public void init() {
        System.out.println("============= Configuration de l'application =============");

        Yaml yaml = new Yaml(new Constructor(ConfYAML.class));
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File("app.conf"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ConfYAML conf = yaml.load(inputStream);

        Customer n = new Customer();
        n.setEmail(conf.getAdminEmail());
        n.setPassword(bCryptPasswordEncoder.encode(conf.getAdminPassword()));
        n.setId((int)(customerRepository.count() + 1));
        n.setActive(1);

        Customer temp = customerRepository.findByEmail(conf.getAdminEmail());
        Role userRole = roleRepository.findByRole("ADMIN");
        n.setRoles(new HashSet<Role>(Arrays.asList(userRole)));

        if(temp == null) {
            customerRepository.save(n);
        }

        Iterator<NodeYAML> iter = conf.getNodes().iterator();
        while (iter.hasNext()) {
            NodeYAML element = iter.next();
            Node node = new Node();
            node.setName(element.getName());
            node.setArch(element.getArch());
            node.setIp(element.getIp());
            node.setNode_id((int)(nodeRepository.count() + 1));
            nodeRepository.save(node);
        }

    }
}