dr1v3r3k

createUserFromCsv

Nov 26th, 2020 (edited)
466
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  public boolean createUsersFromFile(MultipartFile file) throws IOException {
  2.         BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
  3.         InputStreamReader reader = new InputStreamReader(file.getInputStream());
  4.         CSVParser csvParser = new CSVParser(reader, CSVFormat.newFormat(';')
  5.                 .withRecordSeparator(",").withIgnoreEmptyLines());
  6.         CSVPrinter printer = new CSVPrinter(new FileWriter("users.csv"), CSVFormat.EXCEL);
  7.         List<User> users = new ArrayList<>();
  8.         String name = "";
  9.         String pass = "";
  10.         for (CSVRecord record : csvParser) {
  11.             name = record.get(0).trim();
  12.             pass = myPasswordGenerator.generateStrongPassword();
  13.             User user = new User();
  14.             user.setUsername(record.get(0).trim());
  15.             user.setPassword(encoder.encode(pass));
  16.             user.setRoles(Arrays.asList(Role.USER));
  17.             user.setActive(true);
  18.             users.add(user);
  19.             printer.printRecord(name, pass);
  20.         }
  21.         userRepository.insert(users);
  22.         reader.close();
  23.         printer.close();
  24.         return false;
  25.     }
  26.  
  27.  @PostMapping("/registerFromFile")
  28.     public String registerUsersFromFile(MultipartFile file, Model model) throws IOException {
  29.        userService.createUsersFromFile(file);
  30.             model.addAttribute("exist", true);
  31.         return "manager/users/usersOptions";
  32.     }
RAW Paste Data