Hendrik Jungnitsch
2022-09-19 dad2c4321584a4e118e87f71cc8836f3ee56d30a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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<Person> 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<String> 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);
    }
 
}