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();
360 /** {@inheritDocs} */
362 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
363 checkNotNull(sone, "sone must not be null");
364 /* verify that all posts are from the same Sone. */
365 for (Post post : posts) {
366 if (!sone.equals(post.getSone())) {
367 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
371 lock.writeLock().lock();
373 /* remove all posts by the Sone. */
374 Collection<Post> oldPosts = getPostsFrom(sone.getId());
375 for (Post post : oldPosts) {
376 allPosts.remove(post.getId());
380 getPostsFrom(sone.getId()).addAll(posts);
381 for (Post post : posts) {
382 allPosts.put(post.getId(), post);
385 lock.writeLock().unlock();
389 /** {@inheritDocs} */
391 public void removePosts(Sone sone) {
392 checkNotNull(sone, "sone must not be null");
393 lock.writeLock().lock();
395 /* remove all posts by the Sone. */
396 getPostsFrom(sone.getId()).clear();
397 for (Post post : sone.getPosts()) {
398 allPosts.remove(post.getId());
401 lock.writeLock().unlock();
406 // POSTREPLYPROVIDER METHODS
409 /** {@inheritDocs} */
411 public Optional<PostReply> getPostReply(String id) {
412 lock.readLock().lock();
414 return fromNullable(allPostReplies.get(id));
416 lock.readLock().unlock();
420 /** {@inheritDocs} */
422 public List<PostReply> getReplies(final String postId) {
423 lock.readLock().lock();
425 return from(allPostReplies.values())
426 .filter(new Predicate<PostReply>() {
428 public boolean apply(PostReply postReply) {
429 return postReply.getPostId().equals(postId);
431 }).toSortedList(TIME_COMPARATOR);
433 lock.readLock().unlock();
438 // POSTREPLYBUILDERFACTORY METHODS
441 /** {@inheritDocs} */
443 public PostReplyBuilder newPostReplyBuilder() {
444 return new MemoryPostReplyBuilder(this, soneProvider);
448 // POSTREPLYSTORE METHODS
451 /** {@inheritDocs} */
453 public void storePostReply(PostReply postReply) {
454 lock.writeLock().lock();
456 allPostReplies.put(postReply.getId(), postReply);
458 lock.writeLock().unlock();
462 /** {@inheritDocs} */
464 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
465 checkNotNull(sone, "sone must not be null");
466 /* verify that all posts are from the same Sone. */
467 for (PostReply postReply : postReplies) {
468 if (!sone.equals(postReply.getSone())) {
469 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
473 lock.writeLock().lock();
475 /* remove all post replies of the Sone. */
476 for (PostReply postReply : getRepliesFrom(sone.getId())) {
477 removePostReply(postReply);
479 for (PostReply postReply : postReplies) {
480 allPostReplies.put(postReply.getId(), postReply);
481 sonePostReplies.put(postReply.getSone().getId(), postReply);
484 lock.writeLock().unlock();
488 /** {@inheritDocs} */
490 public void removePostReply(PostReply postReply) {
491 lock.writeLock().lock();
493 allPostReplies.remove(postReply.getId());
495 lock.writeLock().unlock();
499 /** {@inheritDocs} */
501 public void removePostReplies(Sone sone) {
502 checkNotNull(sone, "sone must not be null");
504 lock.writeLock().lock();
506 for (PostReply postReply : sone.getReplies()) {
507 removePostReply(postReply);
510 lock.writeLock().unlock();
515 // ALBUMPROVDER METHODS
519 public Optional<Album> getAlbum(String albumId) {
520 lock.readLock().lock();
522 return fromNullable(allAlbums.get(albumId));
524 lock.readLock().unlock();
529 // ALBUMBUILDERFACTORY METHODS
533 public AlbumBuilder newAlbumBuilder() {
534 return new AlbumBuilderImpl();
538 // ALBUMSTORE METHODS
542 public void storeAlbum(Album album) {
543 lock.writeLock().lock();
545 allAlbums.put(album.getId(), album);
546 soneAlbums.put(album.getSone().getId(), album);
548 lock.writeLock().unlock();
553 public void removeAlbum(Album album) {
554 lock.writeLock().lock();
556 allAlbums.remove(album.getId());
557 soneAlbums.remove(album.getSone().getId(), album);
559 lock.writeLock().unlock();
564 // IMAGEPROVIDER METHODS
568 public Optional<Image> getImage(String imageId) {
569 lock.readLock().lock();
571 return fromNullable(allImages.get(imageId));
573 lock.readLock().unlock();
578 // IMAGEBUILDERFACTORY METHODS
582 public ImageBuilder newImageBuilder() {
583 return new ImageBuilderImpl();
587 // IMAGESTORE METHODS
591 public void storeImage(Image image) {
592 lock.writeLock().lock();
594 allImages.put(image.getId(), image);
595 soneImages.put(image.getSone().getId(), image);
597 lock.writeLock().unlock();
602 public void removeImage(Image image) {
603 lock.writeLock().lock();
605 allImages.remove(image.getId());
606 soneImages.remove(image.getSone().getId(), image);
608 lock.writeLock().unlock();
613 public void bookmarkPost(Post post) {
614 memoryBookmarkDatabase.bookmarkPost(post);
618 public void unbookmarkPost(Post post) {
619 memoryBookmarkDatabase.unbookmarkPost(post);
623 public boolean isPostBookmarked(Post post) {
624 return memoryBookmarkDatabase.isPostBookmarked(post);
628 public Set<Post> getBookmarkedPosts() {
629 return memoryBookmarkDatabase.getBookmarkedPosts();
633 // PACKAGE-PRIVATE METHODS
637 * Returns whether the given post is known.
641 * @return {@code true} if the post is known, {@code false} otherwise
643 boolean isPostKnown(Post post) {
644 lock.readLock().lock();
646 return knownPosts.contains(post.getId());
648 lock.readLock().unlock();
653 * Sets whether the given post is known.
658 * {@code true} if the post is known, {@code false} otherwise
660 void setPostKnown(Post post, boolean known) {
661 lock.writeLock().lock();
664 knownPosts.add(post.getId());
666 knownPosts.remove(post.getId());
669 lock.writeLock().unlock();
674 * Returns whether the given post reply is known.
678 * @return {@code true} if the given post reply is known, {@code false}
681 boolean isPostReplyKnown(PostReply postReply) {
682 lock.readLock().lock();
684 return knownPostReplies.contains(postReply.getId());
686 lock.readLock().unlock();
691 * Sets whether the given post reply is known.
696 * {@code true} if the post reply is known, {@code false} otherwise
698 void setPostReplyKnown(PostReply postReply, boolean known) {
699 lock.writeLock().lock();
702 knownPostReplies.add(postReply.getId());
704 knownPostReplies.remove(postReply.getId());
707 lock.writeLock().unlock();
716 * Gets all posts for the given Sone, creating a new collection if there is
720 * The ID of the Sone to get the posts for
723 private Collection<Post> getPostsFrom(String soneId) {
724 lock.readLock().lock();
726 return sonePosts.get(soneId);
728 lock.readLock().unlock();
732 /** Loads the known posts. */
733 private void loadKnownPosts() {
734 Set<String> knownPosts = configurationLoader.loadKnownPosts();
735 lock.writeLock().lock();
737 this.knownPosts.clear();
738 this.knownPosts.addAll(knownPosts);
740 lock.writeLock().unlock();
745 * Saves the known posts to the configuration.
747 * @throws DatabaseException
748 * if a configuration error occurs
750 private void saveKnownPosts() throws DatabaseException {
751 lock.readLock().lock();
754 for (String knownPostId : knownPosts) {
755 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
757 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
758 } catch (ConfigurationException ce1) {
759 throw new DatabaseException("Could not save database.", ce1);
761 lock.readLock().unlock();
766 * Returns all replies by the given Sone.
770 * @return The post replies of the Sone, sorted by time (newest first)
772 private Collection<PostReply> getRepliesFrom(String id) {
773 lock.readLock().lock();
775 return unmodifiableCollection(sonePostReplies.get(id));
777 lock.readLock().unlock();
781 /** Loads the known post replies. */
782 private void loadKnownPostReplies() {
783 Set<String> knownPostReplies = configurationLoader.loadKnownPostReplies();
784 lock.writeLock().lock();
786 this.knownPostReplies.clear();
787 this.knownPostReplies.addAll(knownPostReplies);
789 lock.writeLock().unlock();
794 * Saves the known post replies to the configuration.
796 * @throws DatabaseException
797 * if a configuration error occurs
799 private void saveKnownPostReplies() throws DatabaseException {
800 lock.readLock().lock();
802 int replyCounter = 0;
803 for (String knownReplyId : knownPostReplies) {
804 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
806 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
807 } catch (ConfigurationException ce1) {
808 throw new DatabaseException("Could not save database.", ce1);
810 lock.readLock().unlock();