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;
86 private final Map<String, Sone> allSones = new HashMap<String, Sone>();
88 /** All posts by their ID. */
89 private final Map<String, Post> allPosts = new HashMap<String, Post>();
91 /** All posts by their Sones. */
92 private final Multimap<String, Post> sonePosts = HashMultimap.create();
94 /** Whether posts are known. */
95 private final Set<String> knownPosts = new HashSet<String>();
97 /** All post replies by their ID. */
98 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
100 /** Replies sorted by Sone. */
101 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
104 public int compare(String leftString, String rightString) {
105 return leftString.compareTo(rightString);
109 /** Whether post replies are known. */
110 private final Set<String> knownPostReplies = new HashSet<String>();
112 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
113 private final Multimap<String, Album> soneAlbums = HashMultimap.create();
115 private final Map<String, Image> allImages = new HashMap<String, Image>();
116 private final Multimap<String, Image> soneImages = HashMultimap.create();
118 private final MemoryBookmarkDatabase memoryBookmarkDatabase =
119 new MemoryBookmarkDatabase(this);
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;
140 * Saves the database.
142 * @throws DatabaseException
143 * if an error occurs while saving
146 public void save() throws DatabaseException {
148 saveKnownPostReplies();
155 /** {@inheritDocs} */
157 protected void doStart() {
159 loadKnownPostReplies();
163 /** {@inheritDocs} */
165 protected void doStop() {
169 } catch (DatabaseException de1) {
175 public SoneBuilder newSoneBuilder() {
176 return new MemorySoneBuilder();
180 public void storeSone(Sone sone) {
181 lock.writeLock().lock();
185 allSones.put(sone.getId(), sone);
186 sonePosts.putAll(sone.getId(), sone.getPosts());
187 for (Post post : sone.getPosts()) {
188 allPosts.put(post.getId(), post);
190 sonePostReplies.putAll(sone.getId(), sone.getReplies());
191 for (PostReply postReply : sone.getReplies()) {
192 allPostReplies.put(postReply.getId(), postReply);
194 soneAlbums.putAll(sone.getId(), toAllAlbums.apply(sone));
195 for (Album album : toAllAlbums.apply(sone)) {
196 allAlbums.put(album.getId(), album);
198 soneImages.putAll(sone.getId(), toAllImages.apply(sone));
199 for (Image image : toAllImages.apply(sone)) {
200 allImages.put(image.getId(), image);
203 lock.writeLock().unlock();
208 public void removeSone(Sone sone) {
209 lock.writeLock().lock();
211 allSones.remove(sone.getId());
212 Collection<Post> removedPosts = sonePosts.removeAll(sone.getId());
213 for (Post removedPost : removedPosts) {
214 allPosts.remove(removedPost.getId());
216 Collection<PostReply> removedPostReplies =
217 sonePostReplies.removeAll(sone.getId());
218 for (PostReply removedPostReply : removedPostReplies) {
219 allPostReplies.remove(removedPostReply.getId());
221 Collection<Album> removedAlbums =
222 soneAlbums.removeAll(sone.getId());
223 for (Album removedAlbum : removedAlbums) {
224 allAlbums.remove(removedAlbum.getId());
226 Collection<Image> removedImages =
227 soneImages.removeAll(sone.getId());
228 for (Image removedImage : removedImages) {
229 allImages.remove(removedImage.getId());
232 lock.writeLock().unlock();
237 public Optional<Sone> getSone(String soneId) {
238 lock.readLock().lock();
240 return fromNullable(allSones.get(soneId));
242 lock.readLock().unlock();
247 public Collection<Sone> getSones() {
248 lock.readLock().lock();
250 return new HashSet<Sone>(allSones.values());
252 lock.readLock().unlock();
257 public Collection<Sone> getLocalSones() {
258 lock.readLock().lock();
260 return from(allSones.values()).filter(LOCAL_SONE_FILTER).toSet();
262 lock.readLock().unlock();
267 public Collection<Sone> getRemoteSones() {
268 lock.readLock().lock();
270 return from(allSones.values())
271 .filter(not(LOCAL_SONE_FILTER)) .toSet();
273 lock.readLock().unlock();
278 // POSTPROVIDER METHODS
281 /** {@inheritDocs} */
283 public Optional<Post> getPost(String postId) {
284 lock.readLock().lock();
286 return fromNullable(allPosts.get(postId));
288 lock.readLock().unlock();
292 /** {@inheritDocs} */
294 public Collection<Post> getPosts(String soneId) {
295 return new HashSet<Post>(getPostsFrom(soneId));
298 /** {@inheritDocs} */
300 public Collection<Post> getDirectedPosts(final String recipientId) {
301 lock.readLock().lock();
303 return from(sonePosts.values()).filter(new Predicate<Post>() {
305 public boolean apply(Post post) {
306 return post.getRecipientId().asSet().contains(recipientId);
310 lock.readLock().unlock();
315 // POSTBUILDERFACTORY METHODS
318 /** {@inheritDocs} */
320 public PostBuilder newPostBuilder() {
321 return new MemoryPostBuilder(this, soneProvider);
328 /** {@inheritDocs} */
330 public void storePost(Post post) {
331 checkNotNull(post, "post must not be null");
332 lock.writeLock().lock();
334 allPosts.put(post.getId(), post);
335 getPostsFrom(post.getSone().getId()).add(post);
337 lock.writeLock().unlock();
341 /** {@inheritDocs} */
343 public void removePost(Post post) {
344 checkNotNull(post, "post must not be null");
345 lock.writeLock().lock();
347 allPosts.remove(post.getId());
348 getPostsFrom(post.getSone().getId()).remove(post);
349 post.getSone().removePost(post);
351 lock.writeLock().unlock();
355 /** {@inheritDocs} */
357 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
358 checkNotNull(sone, "sone must not be null");
359 /* verify that all posts are from the same Sone. */
360 for (Post post : posts) {
361 if (!sone.equals(post.getSone())) {
362 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
366 lock.writeLock().lock();
368 /* remove all posts by the Sone. */
369 Collection<Post> oldPosts = getPostsFrom(sone.getId());
370 for (Post post : oldPosts) {
371 allPosts.remove(post.getId());
375 getPostsFrom(sone.getId()).addAll(posts);
376 for (Post post : posts) {
377 allPosts.put(post.getId(), post);
380 lock.writeLock().unlock();
384 /** {@inheritDocs} */
386 public void removePosts(Sone sone) {
387 checkNotNull(sone, "sone must not be null");
388 lock.writeLock().lock();
390 /* remove all posts by the Sone. */
391 getPostsFrom(sone.getId()).clear();
392 for (Post post : sone.getPosts()) {
393 allPosts.remove(post.getId());
396 lock.writeLock().unlock();
401 // POSTREPLYPROVIDER METHODS
404 /** {@inheritDocs} */
406 public Optional<PostReply> getPostReply(String id) {
407 lock.readLock().lock();
409 return fromNullable(allPostReplies.get(id));
411 lock.readLock().unlock();
415 /** {@inheritDocs} */
417 public List<PostReply> getReplies(final String postId) {
418 lock.readLock().lock();
420 return from(allPostReplies.values())
421 .filter(new Predicate<PostReply>() {
423 public boolean apply(PostReply postReply) {
424 return postReply.getPostId().equals(postId);
426 }).toSortedList(TIME_COMPARATOR);
428 lock.readLock().unlock();
433 // POSTREPLYBUILDERFACTORY METHODS
436 /** {@inheritDocs} */
438 public PostReplyBuilder newPostReplyBuilder() {
439 return new MemoryPostReplyBuilder(this, soneProvider);
443 // POSTREPLYSTORE METHODS
446 /** {@inheritDocs} */
448 public void storePostReply(PostReply postReply) {
449 lock.writeLock().lock();
451 allPostReplies.put(postReply.getId(), postReply);
453 lock.writeLock().unlock();
457 /** {@inheritDocs} */
459 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
460 checkNotNull(sone, "sone must not be null");
461 /* verify that all posts are from the same Sone. */
462 for (PostReply postReply : postReplies) {
463 if (!sone.equals(postReply.getSone())) {
464 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
468 lock.writeLock().lock();
470 /* remove all post replies of the Sone. */
471 for (PostReply postReply : getRepliesFrom(sone.getId())) {
472 removePostReply(postReply);
474 for (PostReply postReply : postReplies) {
475 allPostReplies.put(postReply.getId(), postReply);
476 sonePostReplies.put(postReply.getSone().getId(), postReply);
479 lock.writeLock().unlock();
483 /** {@inheritDocs} */
485 public void removePostReply(PostReply postReply) {
486 lock.writeLock().lock();
488 allPostReplies.remove(postReply.getId());
490 lock.writeLock().unlock();
494 /** {@inheritDocs} */
496 public void removePostReplies(Sone sone) {
497 checkNotNull(sone, "sone must not be null");
499 lock.writeLock().lock();
501 for (PostReply postReply : sone.getReplies()) {
502 removePostReply(postReply);
505 lock.writeLock().unlock();
510 // ALBUMPROVDER METHODS
514 public Optional<Album> getAlbum(String albumId) {
515 lock.readLock().lock();
517 return fromNullable(allAlbums.get(albumId));
519 lock.readLock().unlock();
524 // ALBUMBUILDERFACTORY METHODS
528 public AlbumBuilder newAlbumBuilder() {
529 return new AlbumBuilderImpl();
533 // ALBUMSTORE METHODS
537 public void storeAlbum(Album album) {
538 lock.writeLock().lock();
540 allAlbums.put(album.getId(), album);
541 soneAlbums.put(album.getSone().getId(), album);
543 lock.writeLock().unlock();
548 public void removeAlbum(Album album) {
549 lock.writeLock().lock();
551 allAlbums.remove(album.getId());
552 soneAlbums.remove(album.getSone().getId(), album);
554 lock.writeLock().unlock();
559 // IMAGEPROVIDER METHODS
563 public Optional<Image> getImage(String imageId) {
564 lock.readLock().lock();
566 return fromNullable(allImages.get(imageId));
568 lock.readLock().unlock();
573 // IMAGEBUILDERFACTORY METHODS
577 public ImageBuilder newImageBuilder() {
578 return new ImageBuilderImpl();
582 // IMAGESTORE METHODS
586 public void storeImage(Image image) {
587 lock.writeLock().lock();
589 allImages.put(image.getId(), image);
590 soneImages.put(image.getSone().getId(), image);
592 lock.writeLock().unlock();
597 public void removeImage(Image image) {
598 lock.writeLock().lock();
600 allImages.remove(image.getId());
601 soneImages.remove(image.getSone().getId(), image);
603 lock.writeLock().unlock();
608 public void bookmarkPost(String postId) {
609 memoryBookmarkDatabase.bookmarkPost(postId);
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 lock.writeLock().lock();
738 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
739 if (knownPostId == null) {
742 knownPosts.add(knownPostId);
745 lock.writeLock().unlock();
750 * Saves the known posts to the configuration.
752 * @throws DatabaseException
753 * if a configuration error occurs
755 private void saveKnownPosts() throws DatabaseException {
756 lock.readLock().lock();
759 for (String knownPostId : knownPosts) {
760 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
762 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
763 } catch (ConfigurationException ce1) {
764 throw new DatabaseException("Could not save database.", ce1);
766 lock.readLock().unlock();
771 * Returns all replies by the given Sone.
775 * @return The post replies of the Sone, sorted by time (newest first)
777 private Collection<PostReply> getRepliesFrom(String id) {
778 lock.readLock().lock();
780 return unmodifiableCollection(sonePostReplies.get(id));
782 lock.readLock().unlock();
786 /** Loads the known post replies. */
787 private void loadKnownPostReplies() {
788 lock.writeLock().lock();
790 int replyCounter = 0;
792 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
793 if (knownReplyId == null) {
796 knownPostReplies.add(knownReplyId);
799 lock.writeLock().unlock();
804 * Saves the known post replies to the configuration.
806 * @throws DatabaseException
807 * if a configuration error occurs
809 private void saveKnownPostReplies() throws DatabaseException {
810 lock.readLock().lock();
812 int replyCounter = 0;
813 for (String knownReplyId : knownPostReplies) {
814 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
816 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
817 } catch (ConfigurationException ce1) {
818 throw new DatabaseException("Could not save database.", ce1);
820 lock.readLock().unlock();