-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathBookService.java
More file actions
95 lines (77 loc) · 2.76 KB
/
BookService.java
File metadata and controls
95 lines (77 loc) · 2.76 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
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.basaki.example.docker.service;
import com.basaki.example.docker.error.InvalidSearchException;
import com.basaki.example.docker.model.Book;
import com.basaki.example.docker.model.BookRequest;
import com.basaki.example.docker.model.Genre;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
/**
* {@code BookService} service provides data access service for {@code Book}.
* <p/>
*
* @author Indra Basak
* @sice 3/13/17
*/
@Service
@Slf4j
public class BookService {
private Mapper mapper;
private Map<UUID, Book> bookMap;
@Autowired
public BookService(Mapper mapper) {
this.mapper = mapper;
bookMap = new HashMap<>();
}
public Book create(BookRequest request) {
Assert.notNull(request.getTitle(), "Title should not be null.");
Assert.notNull(request.getGenre(), "Genre should not be null.");
Assert.notNull(request.getPublisher(), "Publisher should not be null.");
Assert.notNull(request.getAuthor(), "Author should not be null.");
Assert.state((request.getStar() > 0 && request.getStar() <= 5),
"Star should be between 1 and 5");
Book book = mapper.map(request, Book.class);
book.setId(UUID.randomUUID());
bookMap.put(book.getId(), book);
return book;
}
public Book getById(UUID id) {
Book book = bookMap.get(id);
if (book == null) {
throw new InvalidSearchException(
"Book with ID " + id + " not found!");
}
return book;
}
public List<Book> get(String title, Genre genre, String publisher) {
if (title == null && genre == null && publisher == null) {
return new ArrayList<>(bookMap.values());
}
List<Book> books = bookMap.values().stream()
.filter(b -> title != null && title.equalsIgnoreCase(b.getTitle()))
.filter(b -> genre != null && genre.equals(b.getGenre()))
.filter(b -> publisher != null && publisher.equalsIgnoreCase(b.getPublisher()))
.collect(Collectors.toList());
if (books.isEmpty()) {
throw new InvalidSearchException("No books found!");
}
return books;
}
public void delete(UUID id) {
Book book = bookMap.remove(id);
if (book == null) {
throw new InvalidSearchException("No book found with ID " + id);
}
}
public void deleteAll() {
bookMap.clear();
}
}