3 * * ============LICENSE_START=======================================================
5 * * ================================================================================
6 * * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved.
7 * * ================================================================================
8 * * Licensed under the Apache License, Version 2.0 (the "License");
9 * * you may not use this file except in compliance with the License.
10 * * You may obtain a copy of the License at
12 * * http://www.apache.org/licenses/LICENSE-2.0
14 * * Unless required by applicable law or agreed to in writing, software
15 * * distributed under the License is distributed on an "AS IS" BASIS,
16 * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * * See the License for the specific language governing permissions and
18 * * limitations under the License.
19 * * ============LICENSE_END=========================================================
23 package org.onap.dcaegen2.platform.mod;
25 import org.onap.dcaegen2.platform.mod.models.ModUser;
26 import org.onap.dcaegen2.platform.mod.models.Role;
27 import org.onap.dcaegen2.platform.mod.repositories.RoleRepository;
28 import org.onap.dcaegen2.platform.mod.repositories.UserRepository;
29 import org.springframework.beans.factory.annotation.Autowired;
30 import org.springframework.boot.ApplicationArguments;
31 import org.springframework.boot.ApplicationRunner;
32 import org.springframework.security.crypto.password.PasswordEncoder;
33 import org.springframework.stereotype.Component;
35 import java.util.Arrays;
36 import java.util.HashSet;
37 import java.util.List;
42 * To Initialize Roles and create Default Admin User
45 public class DataLoader implements ApplicationRunner {
48 private RoleRepository roleRepository;
51 private UserRepository userRepository;
54 PasswordEncoder passwordEncoder;
57 public void run(ApplicationArguments args) throws Exception {
62 private void populateRoles() {
63 List<Role> roles = createRoles();
64 roles.forEach((role) -> {
65 boolean roleNotPresent = !roleRepository.findByName(role.getName()).isPresent();
67 roleRepository.save(role);
72 private List<Role> createRoles() {
73 Role admin = new Role("ROLE_ADMIN");
74 Role user = new Role("ROLE_USER");
75 Role developer = new Role("ROLE_DEVELOPER");
76 return Arrays.asList(admin, user, developer);
79 private void populateAdminUser() {
80 boolean adminNotPresent = !userRepository.findByUsername("admin").isPresent();
82 ModUser admin = createAdmin();
83 userRepository.save(admin);
87 private ModUser createAdmin() {
88 ModUser admin = new ModUser();
89 admin.setUsername("admin");
90 admin.setFullName("Admin");
91 admin.setPassword(passwordEncoder.encode("admin@mod"));
92 HashSet<Role> roleAdmin = new HashSet<>();
93 roleAdmin.add(roleRepository.findByName("ROLE_ADMIN").get());
94 admin.setRoles(roleAdmin);