@PutMapping("/create") public Book create(Map<String, Object> map) throws Exception { System.out.println("Check if book exists " + map); Book book = new ObjectMapper().convertValue(map, Book.class); Book b = repo.findByTitle(book.getTitle()); if (b != null) { throw new Exception("Book already exists"); } book.setId(UUID.randomUUID().toString()); repo.save(book); log.debug("Book {} by {} is created with id {}", book.getTitle(), book.getAuthor(), book.getId()); return book; } public BookStoreController(BooksRepository repo, Boolean bool, List<String> keys) { this.repo = repo; if (Boolean.TRUE.equals(bool)) { // check first key if(keys != null && !keys.isEmpty()){ String firstKey = keys.get(0); if (firstKey == "public") { for (String key : keys){ // ... some logic log.debug("Using key {}", key); }; } } } }
sobes.tech AI
Answer from AI
The provided code has several important points that should be fixed or improved:
- String comparison using
==
if (firstKey == "public") {
In Java, strings should be compared using .equals(), otherwise, the reference is compared, not the content. Correct:
if ("public".equals(firstKey)) {
- Exception handling
The create method throws a general Exception. It's better to use more specific exceptions, such as IllegalArgumentException or custom ones.
- Converting Map to object
Using ObjectMapper().convertValue(map, Book.class) is a valid approach, but ensure that the structure of map matches the fields of Book.
- Generating ID
UUID.randomUUID().toString() is a good way to create a unique identifier.
- Logging
Using log.debug with parameters is the correct approach for effective logging.
Summary: The main error is comparing strings with ==, which will lead to incorrect behavior. It should be replaced with .equals(). Also, improve exception handling and verify the correctness of data from map.