コード例 #1
0
  @Test
  public void test1GenerateUsers() {
    try {
      Role userRole = roleDao.findByName("ROLE_USER");
      if (userRole == null) {
        userRole = new Role();
        userRole.setName("ROLE_USER");
        roleDao.save(userRole);
      }
      ArrayList<User> users = new ArrayList<>();

      JsonReader jsonReader = new JsonReader();
      JSONObject json = jsonReader.readJsonFromUrl("https://randomuser.me/api/?results=20");
      JSONArray array = json.getJSONArray("results");
      for (int i = 0; i < array.length(); i++) {
        JSONObject jsonObject = array.getJSONObject(i);
        RandomUser randomUser = new RandomUser(jsonObject.getJSONObject("user"));

        User user = new User();
        user.setUsername(randomUser.getUsername());
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encPassword = bCryptPasswordEncoder.encode("password");

        user.setPassword(encPassword);

        user.setEmail(randomUser.getEmail());
        user.setPhone(randomUser.getPhone());
        user.setPersonFirstName(randomUser.getPersonFirstName());
        user.setPersonLastName(randomUser.getPersonLastName());

        URL url = new URL(randomUser.getPictureMedium());
        BufferedImage bufferedImage = ImageIO.read(url);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", baos);
        baos.flush();
        byte[] data = baos.toByteArray();
        baos.close();

        user.setImage(data);

        user.setRoles(new ArrayList<>());
        user.getRoles().add(userRole);

        users.add(user);
        System.out.println(user.getUsername());

        userDao.save(users);
      }

    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e);
    }
  }