View Javadoc
1   package org.oxerr.commons.user.service.impl;
2   
3   import java.util.Optional;
4   import java.util.UUID;
5   
6   import javax.annotation.PostConstruct;
7   
8   import org.oxerr.commons.user.domain.QRole;
9   import org.oxerr.commons.user.domain.Role;
10  import org.oxerr.commons.user.repository.RoleRepository;
11  import org.oxerr.commons.user.service.RoleService;
12  import org.springframework.beans.factory.annotation.Autowired;
13  import org.springframework.data.domain.Page;
14  import org.springframework.data.domain.Pageable;
15  import org.springframework.stereotype.Service;
16  
17  import com.querydsl.core.types.ExpressionUtils;
18  import com.querydsl.core.types.Predicate;
19  
20  @Service
21  public class RoleServiceImpl implements RoleService {
22  
23  	private final QRole qRole = QRole.role;
24  
25  	private final RoleRepository roleRepository;
26  
27  	@Autowired
28  	public RoleServiceImpl(RoleRepository roleRepository) {
29  		this.roleRepository = roleRepository;
30  	}
31  
32  	@Override
33  	public Role saveRole(Role role) {
34  		return this.roleRepository.save(role);
35  	}
36  
37  	@Override
38  	public Optional<Role> getRole(UUID id) {
39  		return this.roleRepository.findById(id);
40  	}
41  
42  	@Override
43  	public Optional<Role> getRoleByName(String name) {
44  		return this.roleRepository.findByName(name);
45  	}
46  
47  	@Override
48  	public Page<Role> getRoles(String name, Pageable pageable) {
49  		final Predicate predicate = ExpressionUtils.allOf(
50  			name != null ? qRole.name.eq(name) : null
51  		);
52  		return this.roleRepository.findAll(predicate, pageable);
53  	}
54  
55  	@PostConstruct
56  	private void init() {
57  		this.getRoleByName(Role.ROLE_ADMIN)
58  			.orElseGet(() -> this.saveRole(new Role(Role.ROLE_ADMIN)));
59  		this.getRoleByName(Role.ROLE_USER)
60  			.orElseGet(() -> this.saveRole(new Role(Role.ROLE_USER)));
61  	}
62  
63  }