RightServiceJpa.java 2.17 KB
package fr.plil.sio.persistence.jpa;

import fr.plil.sio.persistence.api.Right;
import fr.plil.sio.persistence.api.RightService;
import org.springframework.stereotype.Service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class RightServiceJpa implements RightService {
    
    @Autowired
    private RightRepository rightRepository;
    
    @Override
    public Right create(String name) {
        if(name==null){
            throw new IllegalArgumentException("name cannot be null");
        }
        Right right = new Right();
        right.setName(name);
        
        rightRepository.save(right);
            
        return right;
    }

    @Override
    public Right create(String name, Right parent) {
        if(name==null){
            throw new IllegalArgumentException("name cannot be null");
        }
        if(parent==null){
            throw new IllegalArgumentException("parent cannot be null");
        }
        
        Right right = new Right();
        right.setName(name);
        if(rightRepository.findByName(parent.getName()).size()==0){
           throw new IllegalArgumentException("parent cannot be null");
        }
        
        right.setParent(parent);
        
        rightRepository.save(right);
            
        parent.getSiblings().add(right);
        
        return right;
    }

    @Override
    public boolean delete(Right right) {
        if(right==null){
            throw new IllegalArgumentException("right cannot be null");
        }
        if(rightRepository.findByName(right.getName()).size()==0){
            throw new IllegalArgumentException("right not in database");
        }
        
        rightRepository.delete(right.getId());
        
        return true;
    }

    @Override
    public List<Right> findByName(String name) {
        if(name==null){
            throw new IllegalArgumentException("name cannot be null");
        }
        return rightRepository.findByName(name);
    }

    @Override
    public Right findOne(Long id) {
        if(id==null){
            throw new IllegalArgumentException("name cannot be null");
        }
        return rightRepository.findById(id);
    }
}