import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.UriComponents;
+import java.time.Clock;
import java.time.LocalDateTime;
+import java.time.ZonedDateTime;
+
+import static de.juplo.boot.data.jdbc.UserStatus.CREATED;
+import static de.juplo.boot.data.jdbc.UserStatus.DELETED;
@RestController
@Transactional
private final UserRepository repository;
+ private final Clock clock;
+ private final ApplicationEventPublisher publisher;
- public UserController(UserRepository repository) {
+ public UserController(
+ UserRepository repository,
+ Clock clock,
+ ApplicationEventPublisher publisher)
+ {
this.repository = repository;
+ this.clock = clock;
+ this.publisher = publisher;
}
@RequestBody String username) {
String sanitizedUsername = UserController.sanitize(username);
User user = new User(sanitizedUsername, LocalDateTime.now(), false);
+
+ LOG.info("Request to create user: {}", user);
+
repository.save(user);
+ publisher.publishEvent(
+ new UserEvent(
+ this,
+ sanitizedUsername,
+ CREATED,
+ ZonedDateTime.now(clock)));
+
+ // Triggers an IncorrectResultSizeDataAccessException, if the user already existed!
+ user = repository.findByUsername(sanitizedUsername);
+
UriComponents uri =
builder
.fromCurrentRequest()
return ResponseEntity.notFound().build();
repository.delete(user);
+ publisher.publishEvent(
+ new UserEvent(
+ this,
+ user.getUsername(),
+ DELETED,
+ ZonedDateTime.now(clock)));
return ResponseEntity.ok(user);
}
return string.trim().toLowerCase();
}
+
+ @ExceptionHandler
+ public ResponseEntity<?> incorrectResultSizeDataAccessException(
+ IncorrectResultSizeDataAccessException e
+ )
+ {
+ LOG.info("User already exists!");
+ return ResponseEntity.badRequest().build();
+ }
}