package de.gedoplan.seminar.sbt.sbtrestexercise.rest; import de.gedoplan.seminar.sbt.sbtrestexercise.domain.Person; import de.gedoplan.seminar.sbt.sbtrestexercise.repository.PersonRepository; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.util.UriComponentsBuilder; import java.net.URI; import java.util.List; import java.util.Objects; @RestController @RequestMapping(path = "/personen", produces = MediaType.APPLICATION_JSON_VALUE) public class PersonResource { private final PersonRepository personRepository; public PersonResource(PersonRepository personRepository) { this.personRepository = personRepository; } @GetMapping public List getPersonen() { return personRepository.findAll(); } @GetMapping(path = "{id}",produces = MediaType.APPLICATION_JSON_VALUE) public Person getTalk(@PathVariable Integer id) { return personRepository.findById(id) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); } @ResponseStatus(HttpStatus.NO_CONTENT) @PutMapping(path = "{id}", consumes = MediaType.APPLICATION_JSON_VALUE) public void putPerson(@PathVariable Integer id, @RequestBody Person person) { if(!Objects.equals(id, person.getId())) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST); } personRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); personRepository.save(person); } @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity postPerson(@RequestBody Person person, UriComponentsBuilder uriComponentsBuilder) { if(Objects.nonNull(person.getId())) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "id of new entry must not be set"); } personRepository.save(person); URI uri = uriComponentsBuilder .pathSegment("personen", person.getId().toString()) .build().toUri(); return ResponseEntity.created(uri).build(); } @DeleteMapping("{id}") public void deletePerson(@PathVariable Integer id) { personRepository.deleteById(id); } }