-
Notifications
You must be signed in to change notification settings - Fork 53.6k
Expand file tree
/
Copy pathArticleController.java
More file actions
82 lines (70 loc) · 2.67 KB
/
ArticleController.java
File metadata and controls
82 lines (70 loc) · 2.67 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.baeldung.restclient;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/articles")
class ArticleController {
Map<Integer, Article> database = new HashMap<>();
@GetMapping
ResponseEntity<Collection<Article>> getArticles() {
Collection<Article> values = database.values();
if (values.isEmpty()) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.ok(values);
}
@GetMapping("/{id}")
ResponseEntity<Article> getArticle(@PathVariable("id") Integer id) {
Article article = database.get(id);
if (article == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(article);
}
@GetMapping(value = "/{id}", headers = "API-Version=2")
ResponseEntity<Article> getArticleV2(@PathVariable("id") Integer id) {
return ResponseEntity.ok(new Article(100, "SECRET ARTICLE"));
}
@GetMapping("/search")
ResponseEntity<Article> searchArticleByTitle(@RequestParam(name = "title") String title) {
Optional<Article> article = database.values().stream()
.filter(a -> a.getTitle().contains(title))
.findFirst();
if (article.isEmpty()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(article.get());
}
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
void createArticle(@RequestBody Article article) {
database.put(article.getId(), article);
}
@PutMapping("/{id}")
void updateArticle(@PathVariable("id") Integer id, @RequestBody Article article) {
assert Objects.equals(id, article.getId());
database.remove(id);
database.put(id, article);
}
@DeleteMapping("/{id}")
void deleteArticle(@PathVariable("id") Integer id) {
database.remove(id);
}
@DeleteMapping
void deleteAllArticles() {
database.clear();
}
}