package etunicorn; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Created by geoffrey on 29/01/17. */ @RestController public class RoleController implements etunicorn.generated.RoleController { @Autowired private RoleRepository roleRepository; @Autowired private PermissionRepository permissionRepository; @Override public ResponseEntity getRole() { return new ResponseEntity((List) roleRepository.findAll(), HttpStatus.OK); } @Override public ResponseEntity updateRole(@RequestParam String nom) { Role oldRole = roleRepository.findByNom(nom); if (oldRole != null) { return new ResponseEntity(HttpStatus.CONFLICT); } Role role = new Role(); role.setNom(nom); try { roleRepository.save(role); } catch (DataIntegrityViolationException e) { return new ResponseEntity(HttpStatus.CONFLICT); } return new ResponseEntity(role, HttpStatus.CREATED); } @Override public ResponseEntity deleteRoleById(@PathVariable String nomRole) { Role role = roleRepository.findByNom(nomRole); if (role == null) { return new ResponseEntity("Rôle inconnu", HttpStatus.NOT_FOUND); } roleRepository.delete(role); return new ResponseEntity(HttpStatus.NO_CONTENT); } @Override public ResponseEntity updateRoleById(@PathVariable String nomRole, @RequestParam String nom) { Role role = roleRepository.findByNom(nomRole); if (role == null) { return new ResponseEntity("Rôle inconnu", HttpStatus.NOT_FOUND); } Permission permission = permissionRepository.findByNom(nom); if (permission == null) { return new ResponseEntity("Permission inconnue", HttpStatus.NOT_FOUND); } role.addPermission(permission); try { roleRepository.save(role); } catch (DataIntegrityViolationException e) { // Si la permission était déjà là, on fait rien } return new ResponseEntity(role, HttpStatus.ACCEPTED); } @Override public ResponseEntity deleteRoleByNomPermission(@PathVariable String nomPermission, @PathVariable String nomRole) { Role role = roleRepository.findByNom(nomRole); if (role == null) { return new ResponseEntity("Rôle inconnu", HttpStatus.NOT_FOUND); } Permission permission = permissionRepository.findByNom(nomPermission); if (permission == null) { return new ResponseEntity("Permission inconnue", HttpStatus.NOT_FOUND); } role.delPermission(permission); roleRepository.save(role); return new ResponseEntity(role, HttpStatus.ACCEPTED); } @Override public ResponseEntity getPermission() { return new ResponseEntity((List) permissionRepository.findAll(), HttpStatus.OK); } }