1 package net.pterodactylus.sone.database.memory;
3 import static com.google.common.base.Optional.fromNullable;
4 import static com.google.common.collect.FluentIterable.from;
6 import java.util.HashSet;
8 import java.util.concurrent.locks.ReadWriteLock;
9 import java.util.concurrent.locks.ReentrantReadWriteLock;
11 import net.pterodactylus.sone.data.Post;
12 import net.pterodactylus.sone.data.Post.EmptyPost;
13 import net.pterodactylus.sone.database.BookmarkDatabase;
15 import com.google.common.base.Function;
18 * Memory-based {@link BookmarkDatabase} implementation.
20 public class MemoryBookmarkDatabase implements BookmarkDatabase {
22 private final ReadWriteLock lock = new ReentrantReadWriteLock();
23 private final MemoryDatabase memoryDatabase;
24 private final ConfigurationLoader configurationLoader;
25 private final Set<String> bookmarkedPosts = new HashSet<>();
27 public MemoryBookmarkDatabase(MemoryDatabase memoryDatabase,
28 ConfigurationLoader configurationLoader) {
29 this.memoryDatabase = memoryDatabase;
30 this.configurationLoader = configurationLoader;
34 loadBookmarkedPosts();
37 private void loadBookmarkedPosts() {
38 Set<String> bookmarkedPosts = configurationLoader.loadBookmarkedPosts();
39 lock.writeLock().lock();
41 this.bookmarkedPosts.clear();
42 this.bookmarkedPosts.addAll(bookmarkedPosts);
44 lock.writeLock().unlock();
49 saveBookmarkedPosts();
52 private void saveBookmarkedPosts() {
53 lock.readLock().lock();
55 configurationLoader.saveBookmarkedPosts(this.bookmarkedPosts);
57 lock.readLock().unlock();
62 public void bookmarkPost(Post post) {
63 lock.writeLock().lock();
65 bookmarkedPosts.add(post.getId());
66 saveBookmarkedPosts();
68 lock.writeLock().unlock();
73 public void unbookmarkPost(Post post) {
74 lock.writeLock().lock();
76 bookmarkedPosts.remove(post.getId());
77 saveBookmarkedPosts();
79 lock.writeLock().unlock();
84 public boolean isPostBookmarked(Post post) {
85 lock.readLock().lock();
87 return bookmarkedPosts.contains(post.getId());
89 lock.readLock().unlock();
94 public Set<Post> getBookmarkedPosts() {
95 lock.readLock().lock();
97 return from(bookmarkedPosts).transform(
98 new Function<String, Post>() {
100 public Post apply(String postId) {
101 return fromNullable(memoryDatabase.getPost(postId))
102 .or(new EmptyPost(postId));
106 lock.readLock().unlock();