2 * Sone - MemoryDatabase.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.database.memory;
20 import static com.google.common.base.Optional.fromNullable;
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static com.google.common.base.Predicates.not;
23 import static com.google.common.collect.FluentIterable.from;
24 import static java.util.Collections.unmodifiableCollection;
25 import static net.pterodactylus.sone.data.Reply.TIME_COMPARATOR;
26 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
27 import static net.pterodactylus.sone.data.Sone.toAllAlbums;
28 import static net.pterodactylus.sone.data.Sone.toAllImages;
30 import java.util.Collection;
31 import java.util.Comparator;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
37 import java.util.concurrent.locks.ReadWriteLock;
38 import java.util.concurrent.locks.ReentrantReadWriteLock;
40 import net.pterodactylus.sone.data.Album;
41 import net.pterodactylus.sone.data.Image;
42 import net.pterodactylus.sone.data.Post;
43 import net.pterodactylus.sone.data.PostReply;
44 import net.pterodactylus.sone.data.Sone;
45 import net.pterodactylus.sone.data.impl.AlbumBuilderImpl;
46 import net.pterodactylus.sone.data.impl.ImageBuilderImpl;
47 import net.pterodactylus.sone.database.AlbumBuilder;
48 import net.pterodactylus.sone.database.Database;
49 import net.pterodactylus.sone.database.DatabaseException;
50 import net.pterodactylus.sone.database.ImageBuilder;
51 import net.pterodactylus.sone.database.PostBuilder;
52 import net.pterodactylus.sone.database.PostDatabase;
53 import net.pterodactylus.sone.database.PostReplyBuilder;
54 import net.pterodactylus.sone.database.SoneBuilder;
55 import net.pterodactylus.sone.database.SoneProvider;
56 import net.pterodactylus.util.config.Configuration;
57 import net.pterodactylus.util.config.ConfigurationException;
59 import com.google.common.base.Optional;
60 import com.google.common.base.Predicate;
61 import com.google.common.collect.HashMultimap;
62 import com.google.common.collect.Multimap;
63 import com.google.common.collect.SortedSetMultimap;
64 import com.google.common.collect.TreeMultimap;
65 import com.google.common.util.concurrent.AbstractService;
66 import com.google.inject.Inject;
67 import com.google.inject.Singleton;
70 * Memory-based {@link PostDatabase} implementation.
72 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
75 public class MemoryDatabase extends AbstractService implements Database {
78 private final ReadWriteLock lock = new ReentrantReadWriteLock();
80 /** The Sone provider. */
81 private final SoneProvider soneProvider;
83 /** The configuration. */
84 private final Configuration configuration;
85 private final ConfigurationLoader configurationLoader;
87 private final Map<String, Sone> allSones = new HashMap<String, Sone>();
89 /** All posts by their ID. */
90 private final Map<String, Post> allPosts = new HashMap<String, Post>();
92 /** All posts by their Sones. */
93 private final Multimap<String, Post> sonePosts = HashMultimap.create();
95 /** Whether posts are known. */
96 private final Set<String> knownPosts = new HashSet<String>();
98 /** All post replies by their ID. */
99 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
101 /** Replies sorted by Sone. */
102 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
105 public int compare(String leftString, String rightString) {
106 return leftString.compareTo(rightString);
110 /** Whether post replies are known. */
111 private final Set<String> knownPostReplies = new HashSet<String>();
113 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
114 private final Multimap<String, Album> soneAlbums = HashMultimap.create();
116 private final Map<String, Image> allImages = new HashMap<String, Image>();
117 private final Multimap<String, Image> soneImages = HashMultimap.create();
119 private final MemoryBookmarkDatabase memoryBookmarkDatabase;
122 * Creates a new memory database.
124 * @param soneProvider
126 * @param configuration
127 * The configuration for loading and saving elements
130 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
131 this.soneProvider = soneProvider;
132 this.configuration = configuration;
133 this.configurationLoader = new ConfigurationLoader(configuration);
134 memoryBookmarkDatabase =
135 new MemoryBookmarkDatabase(this, configurationLoader);
143 * Saves the database.
145 * @throws DatabaseException
146 * if an error occurs while saving
149 public void save() throws DatabaseException {
151 saveKnownPostReplies();
158 /** {@inheritDocs} */
160 protected void doStart() {
161 memoryBookmarkDatabase.start();
163 loadKnownPostReplies();
167 /** {@inheritDocs} */
169 protected void doStop() {
171 memoryBookmarkDatabase.stop();
174 } catch (DatabaseException de1) {
180 public SoneBuilder newSoneBuilder() {
181 return new MemorySoneBuilder();
185 public void storeSone(Sone sone) {
186 lock.writeLock().lock();
190 allSones.put(sone.getId(), sone);
191 sonePosts.putAll(sone.getId(), sone.getPosts());
192 for (Post post : sone.getPosts()) {
193 allPosts.put(post.getId(), post);
195 sonePostReplies.putAll(sone.getId(), sone.getReplies());
196 for (PostReply postReply : sone.getReplies()) {
197 allPostReplies.put(postReply.getId(), postReply);
199 soneAlbums.putAll(sone.getId(), toAllAlbums.apply(sone));
200 for (Album album : toAllAlbums.apply(sone)) {
201 allAlbums.put(album.getId(), album);
203 soneImages.putAll(sone.getId(), toAllImages.apply(sone));
204 for (Image image : toAllImages.apply(sone)) {
205 allImages.put(image.getId(), image);
208 lock.writeLock().unlock();
213 public void removeSone(Sone sone) {
214 lock.writeLock().lock();
216 allSones.remove(sone.getId());
217 Collection<Post> removedPosts = sonePosts.removeAll(sone.getId());
218 for (Post removedPost : removedPosts) {
219 allPosts.remove(removedPost.getId());
221 Collection<PostReply> removedPostReplies =
222 sonePostReplies.removeAll(sone.getId());
223 for (PostReply removedPostReply : removedPostReplies) {
224 allPostReplies.remove(removedPostReply.getId());
226 Collection<Album> removedAlbums =
227 soneAlbums.removeAll(sone.getId());
228 for (Album removedAlbum : removedAlbums) {
229 allAlbums.remove(removedAlbum.getId());
231 Collection<Image> removedImages =
232 soneImages.removeAll(sone.getId());
233 for (Image removedImage : removedImages) {
234 allImages.remove(removedImage.getId());
237 lock.writeLock().unlock();
242 public Optional<Sone> getSone(String soneId) {
243 lock.readLock().lock();
245 return fromNullable(allSones.get(soneId));
247 lock.readLock().unlock();
252 public Collection<Sone> getSones() {
253 lock.readLock().lock();
255 return new HashSet<Sone>(allSones.values());
257 lock.readLock().unlock();
262 public Collection<Sone> getLocalSones() {
263 lock.readLock().lock();
265 return from(allSones.values()).filter(LOCAL_SONE_FILTER).toSet();
267 lock.readLock().unlock();
272 public Collection<Sone> getRemoteSones() {
273 lock.readLock().lock();
275 return from(allSones.values())
276 .filter(not(LOCAL_SONE_FILTER)) .toSet();
278 lock.readLock().unlock();
283 // POSTPROVIDER METHODS
286 /** {@inheritDocs} */
288 public Optional<Post> getPost(String postId) {
289 lock.readLock().lock();
291 return fromNullable(allPosts.get(postId));
293 lock.readLock().unlock();
297 /** {@inheritDocs} */
299 public Collection<Post> getPosts(String soneId) {
300 return new HashSet<Post>(getPostsFrom(soneId));
303 /** {@inheritDocs} */
305 public Collection<Post> getDirectedPosts(final String recipientId) {
306 lock.readLock().lock();
308 return from(sonePosts.values()).filter(new Predicate<Post>() {
310 public boolean apply(Post post) {
311 return post.getRecipientId().asSet().contains(recipientId);
315 lock.readLock().unlock();
320 // POSTBUILDERFACTORY METHODS
323 /** {@inheritDocs} */
325 public PostBuilder newPostBuilder() {
326 return new MemoryPostBuilder(this, soneProvider);
333 /** {@inheritDocs} */
335 public void storePost(Post post) {
336 checkNotNull(post, "post must not be null");
337 lock.writeLock().lock();
339 allPosts.put(post.getId(), post);
340 getPostsFrom(post.getSone().getId()).add(post);
342 lock.writeLock().unlock();
346 /** {@inheritDocs} */
348 public void removePost(Post post) {
349 checkNotNull(post, "post must not be null");
350 lock.writeLock().lock();
352 allPosts.remove(post.getId());
353 getPostsFrom(post.getSone().getId()).remove(post);
354 post.getSone().removePost(post);
356 lock.writeLock().unlock();
361 // POSTREPLYPROVIDER METHODS
364 /** {@inheritDocs} */
366 public Optional<PostReply> getPostReply(String id) {
367 lock.readLock().lock();
369 return fromNullable(allPostReplies.get(id));
371 lock.readLock().unlock();
375 /** {@inheritDocs} */
377 public List<PostReply> getReplies(final String postId) {
378 lock.readLock().lock();
380 return from(allPostReplies.values())
381 .filter(new Predicate<PostReply>() {
383 public boolean apply(PostReply postReply) {
384 return postReply.getPostId().equals(postId);
386 }).toSortedList(TIME_COMPARATOR);
388 lock.readLock().unlock();
393 // POSTREPLYBUILDERFACTORY METHODS
396 /** {@inheritDocs} */
398 public PostReplyBuilder newPostReplyBuilder() {
399 return new MemoryPostReplyBuilder(this, soneProvider);
403 // POSTREPLYSTORE METHODS
406 /** {@inheritDocs} */
408 public void storePostReply(PostReply postReply) {
409 lock.writeLock().lock();
411 allPostReplies.put(postReply.getId(), postReply);
413 lock.writeLock().unlock();
417 /** {@inheritDocs} */
419 public void removePostReply(PostReply postReply) {
420 lock.writeLock().lock();
422 allPostReplies.remove(postReply.getId());
424 lock.writeLock().unlock();
429 // ALBUMPROVDER METHODS
433 public Optional<Album> getAlbum(String albumId) {
434 lock.readLock().lock();
436 return fromNullable(allAlbums.get(albumId));
438 lock.readLock().unlock();
443 // ALBUMBUILDERFACTORY METHODS
447 public AlbumBuilder newAlbumBuilder() {
448 return new AlbumBuilderImpl();
452 // ALBUMSTORE METHODS
456 public void storeAlbum(Album album) {
457 lock.writeLock().lock();
459 allAlbums.put(album.getId(), album);
460 soneAlbums.put(album.getSone().getId(), album);
462 lock.writeLock().unlock();
467 public void removeAlbum(Album album) {
468 lock.writeLock().lock();
470 allAlbums.remove(album.getId());
471 soneAlbums.remove(album.getSone().getId(), album);
473 lock.writeLock().unlock();
478 // IMAGEPROVIDER METHODS
482 public Optional<Image> getImage(String imageId) {
483 lock.readLock().lock();
485 return fromNullable(allImages.get(imageId));
487 lock.readLock().unlock();
492 // IMAGEBUILDERFACTORY METHODS
496 public ImageBuilder newImageBuilder() {
497 return new ImageBuilderImpl();
501 // IMAGESTORE METHODS
505 public void storeImage(Image image) {
506 lock.writeLock().lock();
508 allImages.put(image.getId(), image);
509 soneImages.put(image.getSone().getId(), image);
511 lock.writeLock().unlock();
516 public void removeImage(Image image) {
517 lock.writeLock().lock();
519 allImages.remove(image.getId());
520 soneImages.remove(image.getSone().getId(), image);
522 lock.writeLock().unlock();
527 public void bookmarkPost(Post post) {
528 memoryBookmarkDatabase.bookmarkPost(post);
532 public void unbookmarkPost(Post post) {
533 memoryBookmarkDatabase.unbookmarkPost(post);
537 public boolean isPostBookmarked(Post post) {
538 return memoryBookmarkDatabase.isPostBookmarked(post);
542 public Set<Post> getBookmarkedPosts() {
543 return memoryBookmarkDatabase.getBookmarkedPosts();
547 // PACKAGE-PRIVATE METHODS
551 * Returns whether the given post is known.
555 * @return {@code true} if the post is known, {@code false} otherwise
557 boolean isPostKnown(Post post) {
558 lock.readLock().lock();
560 return knownPosts.contains(post.getId());
562 lock.readLock().unlock();
567 * Sets whether the given post is known.
572 * {@code true} if the post is known, {@code false} otherwise
574 void setPostKnown(Post post, boolean known) {
575 lock.writeLock().lock();
578 knownPosts.add(post.getId());
580 knownPosts.remove(post.getId());
583 lock.writeLock().unlock();
588 * Returns whether the given post reply is known.
592 * @return {@code true} if the given post reply is known, {@code false}
595 boolean isPostReplyKnown(PostReply postReply) {
596 lock.readLock().lock();
598 return knownPostReplies.contains(postReply.getId());
600 lock.readLock().unlock();
605 * Sets whether the given post reply is known.
610 * {@code true} if the post reply is known, {@code false} otherwise
612 void setPostReplyKnown(PostReply postReply, boolean known) {
613 lock.writeLock().lock();
616 knownPostReplies.add(postReply.getId());
618 knownPostReplies.remove(postReply.getId());
621 lock.writeLock().unlock();
630 * Gets all posts for the given Sone, creating a new collection if there is
634 * The ID of the Sone to get the posts for
637 private Collection<Post> getPostsFrom(String soneId) {
638 lock.readLock().lock();
640 return sonePosts.get(soneId);
642 lock.readLock().unlock();
646 /** Loads the known posts. */
647 private void loadKnownPosts() {
648 Set<String> knownPosts = configurationLoader.loadKnownPosts();
649 lock.writeLock().lock();
651 this.knownPosts.clear();
652 this.knownPosts.addAll(knownPosts);
654 lock.writeLock().unlock();
659 * Saves the known posts to the configuration.
661 * @throws DatabaseException
662 * if a configuration error occurs
664 private void saveKnownPosts() throws DatabaseException {
665 lock.readLock().lock();
668 for (String knownPostId : knownPosts) {
669 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
671 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
672 } catch (ConfigurationException ce1) {
673 throw new DatabaseException("Could not save database.", ce1);
675 lock.readLock().unlock();
679 /** Loads the known post replies. */
680 private void loadKnownPostReplies() {
681 Set<String> knownPostReplies = configurationLoader.loadKnownPostReplies();
682 lock.writeLock().lock();
684 this.knownPostReplies.clear();
685 this.knownPostReplies.addAll(knownPostReplies);
687 lock.writeLock().unlock();
692 * Saves the known post replies to the configuration.
694 * @throws DatabaseException
695 * if a configuration error occurs
697 private void saveKnownPostReplies() throws DatabaseException {
698 lock.readLock().lock();
700 int replyCounter = 0;
701 for (String knownReplyId : knownPostReplies) {
702 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
704 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
705 } catch (ConfigurationException ce1) {
706 throw new DatabaseException("Could not save database.", ce1);
708 lock.readLock().unlock();