|
@ -0,0 +1,74 @@ |
|
|
|
|
|
package com.jesuspinar.booksearch.dao; |
|
|
|
|
|
|
|
|
|
|
|
import com.jesuspinar.booksearch.config.AppConfig; |
|
|
|
|
|
import com.jesuspinar.booksearch.controller.CsvParser; |
|
|
|
|
|
import com.jesuspinar.booksearch.model.Book; |
|
|
|
|
|
import org.springframework.beans.factory.annotation.Autowired; |
|
|
|
|
|
import org.springframework.stereotype.Repository; |
|
|
|
|
|
|
|
|
|
|
|
import javax.annotation.PostConstruct; |
|
|
|
|
|
import java.util.ArrayList; |
|
|
|
|
|
import java.util.Collection; |
|
|
|
|
|
import java.util.List; |
|
|
|
|
|
import java.util.Optional; |
|
|
|
|
|
|
|
|
|
|
|
@Repository |
|
|
|
|
|
public class BookDao implements IBookDao{ |
|
|
|
|
|
|
|
|
|
|
|
public List<Book> books = new ArrayList<>(); |
|
|
|
|
|
|
|
|
|
|
|
@Autowired |
|
|
|
|
|
private AppConfig appConfig; |
|
|
|
|
|
|
|
|
|
|
|
@PostConstruct |
|
|
|
|
|
public void init() { |
|
|
|
|
|
books = CsvParser.readFile(appConfig.getFile(), appConfig.getSeparator(), appConfig.getListSeparator()); |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
@Override |
|
|
|
|
|
public Book findById(long id) { |
|
|
|
|
|
Optional<Book> result = books |
|
|
|
|
|
.stream() |
|
|
|
|
|
.filter(f -> f.getId() == id) |
|
|
|
|
|
.findFirst(); |
|
|
|
|
|
return result.orElse(null); |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
@Override |
|
|
|
|
|
public Collection<Book> findAll() { |
|
|
|
|
|
return books; |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
@Override |
|
|
|
|
|
public void insert(Book book) { |
|
|
|
|
|
books.add(book); |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
@Override |
|
|
|
|
|
public void edit(Book book) { |
|
|
|
|
|
int index = getIndexOf(book.getId()); |
|
|
|
|
|
if (index != -1) |
|
|
|
|
|
books.set(index, book); |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
@Override |
|
|
|
|
|
public void delete(long id) { |
|
|
|
|
|
int index = getIndexOf(id); |
|
|
|
|
|
if (index != -1) |
|
|
|
|
|
books.remove(index); |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
private int getIndexOf(long id) { |
|
|
|
|
|
boolean find = false; |
|
|
|
|
|
int index = 0; |
|
|
|
|
|
|
|
|
|
|
|
while (!find && index < books.size()) { |
|
|
|
|
|
if (books.get(index).getId() == id) |
|
|
|
|
|
find = true; |
|
|
|
|
|
else |
|
|
|
|
|
index++; |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
return (find) ? index : -1; |
|
|
|
|
|
} |
|
|
|
|
|
} |