Bläddra i källkod

PollController

Seth 7 år sedan
förälder
incheckning
083cb6f37f

+ 62
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/PollController.java Visa fil

@@ -0,0 +1,62 @@
1
+package io.zipcoder.tc_spring_poll_application.controller;
2
+
3
+import io.zipcoder.tc_spring_poll_application.domain.Poll;
4
+import io.zipcoder.tc_spring_poll_application.repositories.PollRepository;
5
+import org.springframework.beans.factory.annotation.Autowired;
6
+import org.springframework.http.HttpHeaders;
7
+import org.springframework.http.HttpStatus;
8
+import org.springframework.http.ResponseEntity;
9
+import org.springframework.web.bind.annotation.*;
10
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
11
+
12
+import java.net.URI;
13
+
14
+@RestController
15
+public class PollController {
16
+
17
+    private PollRepository pollRepository;
18
+
19
+    @Autowired
20
+    public PollController(PollRepository pollRepository) {
21
+        this.pollRepository = pollRepository;
22
+    }
23
+
24
+    @RequestMapping(value="/polls", method= RequestMethod.GET)
25
+    public ResponseEntity<Iterable<Poll>> getAllPolls() {
26
+        Iterable<Poll> allPolls = pollRepository.findAll();
27
+        return new ResponseEntity<>(allPolls, HttpStatus.OK);
28
+    }
29
+
30
+    @RequestMapping (method=RequestMethod.POST)
31
+    public ResponseEntity<?> createPoll(@RequestBody Poll poll) {
32
+        URI newPollUri = ServletUriComponentsBuilder
33
+                .fromCurrentRequest()
34
+                .path("/{id}")
35
+                .buildAndExpand(poll.getId())
36
+                .toUri();
37
+        HttpHeaders header = new HttpHeaders();
38
+        header.setLocation(newPollUri);
39
+        poll = pollRepository.save(poll);
40
+        return new ResponseEntity<>(header, HttpStatus.CREATED);
41
+    }
42
+
43
+    @RequestMapping(value="/polls/{pollId}", method=RequestMethod.GET)
44
+    public ResponseEntity<?> getPoll(@PathVariable Long pollId) {
45
+        Poll p = pollRepository.findOne(pollId);
46
+        return new ResponseEntity<> (p, HttpStatus.OK);
47
+    }
48
+
49
+    @RequestMapping(value="/polls/{pollId}", method=RequestMethod.PUT)
50
+    public ResponseEntity<?> updatePoll(@RequestBody Poll poll, @PathVariable Long pollId) {
51
+        // Save the entity
52
+        Poll p = pollRepository.save(poll);
53
+        return new ResponseEntity<>(HttpStatus.OK);
54
+    }
55
+
56
+    @RequestMapping(value="/polls/{pollId}", method=RequestMethod.DELETE)
57
+    public ResponseEntity<?> deletePoll(@PathVariable Long pollId) {
58
+        pollRepository.delete(pollId);
59
+        return new ResponseEntity<>(HttpStatus.OK);
60
+    }
61
+
62
+}