1 package de.juplo.boot.data.jdbc;
3 import org.slf4j.Logger;
4 import org.slf4j.LoggerFactory;
5 import org.springframework.context.ApplicationEventPublisher;
6 import org.springframework.http.ResponseEntity;
7 import org.springframework.transaction.annotation.Transactional;
8 import org.springframework.web.bind.annotation.*;
9 import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
10 import org.springframework.web.util.UriComponents;
12 import java.time.Clock;
13 import java.time.LocalDateTime;
14 import java.time.ZonedDateTime;
16 import static de.juplo.boot.data.jdbc.UserStatus.CREATED;
17 import static de.juplo.boot.data.jdbc.UserStatus.DELETED;
21 @RequestMapping("/users")
22 public class UserController {
24 private static final Logger LOG = LoggerFactory.getLogger(UserController.class);
27 private final UserRepository repository;
28 private final Clock clock;
29 private final ApplicationEventPublisher publisher;
32 public UserController(
33 UserRepository repository,
35 ApplicationEventPublisher publisher)
37 this.repository = repository;
39 this.publisher = publisher;
44 public ResponseEntity<Void> createUser(
45 ServletUriComponentsBuilder builder,
46 @RequestBody String username) {
47 String sanitizedUsername = UserController.sanitize(username);
48 User user = new User(sanitizedUsername, LocalDateTime.now(), false);
49 repository.save(user);
50 publisher.publishEvent(
55 ZonedDateTime.now(clock)));
59 .pathSegment("{username}")
60 .buildAndExpand(sanitizedUsername);
61 return ResponseEntity.created(uri.toUri()).build();
64 @GetMapping("{username}")
65 public ResponseEntity<User> getUser(@PathVariable String username) {
66 User user = repository.findByUsername(UserController.sanitize(username));
69 return ResponseEntity.notFound().build();
71 return ResponseEntity.ok(user);
74 @DeleteMapping("{username}")
75 public ResponseEntity<User> removeUser(@PathVariable String username) {
76 User user = repository.findByUsername(UserController.sanitize(username));
79 return ResponseEntity.notFound().build();
81 repository.delete(user);
82 publisher.publishEvent(
87 ZonedDateTime.now(clock)));
89 return ResponseEntity.ok(user);
93 public ResponseEntity<Iterable<User>> getUsers() {
94 return ResponseEntity.ok(repository.findAll());
98 private static String sanitize(String string) {
102 return string.trim().toLowerCase();