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();
183 Collection<Post> removedPosts = sonePosts.removeAll(sone.getId());
184 for (Post removedPost : removedPosts) {
185 allPosts.remove(removedPost.getId());
187 Collection<PostReply> removedPostReplies =
188 sonePostReplies.removeAll(sone.getId());
189 for (PostReply removedPostReply : removedPostReplies) {
190 allPostReplies.remove(removedPostReply.getId());
192 Collection<Album> removedAlbums =
193 soneAlbums.removeAll(sone.getId());
194 for (Album removedAlbum : removedAlbums) {
195 allAlbums.remove(removedAlbum.getId());
197 Collection<Image> removedImages =
198 soneImages.removeAll(sone.getId());
199 for (Image removedImage : removedImages) {
200 allImages.remove(removedImage.getId());
203 allSones.put(sone.getId(), sone);
204 sonePosts.putAll(sone.getId(), sone.getPosts());
205 for (Post post : sone.getPosts()) {
206 allPosts.put(post.getId(), post);
208 sonePostReplies.putAll(sone.getId(), sone.getReplies());
209 for (PostReply postReply : sone.getReplies()) {
210 allPostReplies.put(postReply.getId(), postReply);
212 soneAlbums.putAll(sone.getId(), toAllAlbums.apply(sone));
213 for (Album album : toAllAlbums.apply(sone)) {
214 allAlbums.put(album.getId(), album);
216 soneImages.putAll(sone.getId(), toAllImages.apply(sone));
217 for (Image image : toAllImages.apply(sone)) {
218 allImages.put(image.getId(), image);
221 lock.writeLock().unlock();
226 public Optional<Sone> getSone(String soneId) {
227 lock.readLock().lock();
229 return fromNullable(allSones.get(soneId));
231 lock.readLock().unlock();
236 public Collection<Sone> getSones() {
237 lock.readLock().lock();
239 return new HashSet<Sone>(allSones.values());
241 lock.readLock().unlock();
246 public Collection<Sone> getLocalSones() {
247 lock.readLock().lock();
249 return from(allSones.values()).filter(LOCAL_SONE_FILTER).toSet();
251 lock.readLock().unlock();
256 public Collection<Sone> getRemoteSones() {
257 lock.readLock().lock();
259 return from(allSones.values())
260 .filter(not(LOCAL_SONE_FILTER)) .toSet();
262 lock.readLock().unlock();
267 // POSTPROVIDER METHODS
270 /** {@inheritDocs} */
272 public Optional<Post> getPost(String postId) {
273 lock.readLock().lock();
275 return fromNullable(allPosts.get(postId));
277 lock.readLock().unlock();
281 /** {@inheritDocs} */
283 public Collection<Post> getPosts(String soneId) {
284 return new HashSet<Post>(getPostsFrom(soneId));
287 /** {@inheritDocs} */
289 public Collection<Post> getDirectedPosts(final String recipientId) {
290 lock.readLock().lock();
292 return from(sonePosts.values()).filter(new Predicate<Post>() {
294 public boolean apply(Post post) {
295 return post.getRecipientId().asSet().contains(recipientId);
299 lock.readLock().unlock();
304 // POSTBUILDERFACTORY METHODS
307 /** {@inheritDocs} */
309 public PostBuilder newPostBuilder() {
310 return new MemoryPostBuilder(this, soneProvider);
317 /** {@inheritDocs} */
319 public void storePost(Post post) {
320 checkNotNull(post, "post must not be null");
321 lock.writeLock().lock();
323 allPosts.put(post.getId(), post);
324 getPostsFrom(post.getSone().getId()).add(post);
326 lock.writeLock().unlock();
330 /** {@inheritDocs} */
332 public void removePost(Post post) {
333 checkNotNull(post, "post must not be null");
334 lock.writeLock().lock();
336 allPosts.remove(post.getId());
337 getPostsFrom(post.getSone().getId()).remove(post);
338 post.getSone().removePost(post);
340 lock.writeLock().unlock();
344 /** {@inheritDocs} */
346 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
347 checkNotNull(sone, "sone must not be null");
348 /* verify that all posts are from the same Sone. */
349 for (Post post : posts) {
350 if (!sone.equals(post.getSone())) {
351 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
355 lock.writeLock().lock();
357 /* remove all posts by the Sone. */
358 Collection<Post> oldPosts = getPostsFrom(sone.getId());
359 for (Post post : oldPosts) {
360 allPosts.remove(post.getId());
364 getPostsFrom(sone.getId()).addAll(posts);
365 for (Post post : posts) {
366 allPosts.put(post.getId(), post);
369 lock.writeLock().unlock();
373 /** {@inheritDocs} */
375 public void removePosts(Sone sone) {
376 checkNotNull(sone, "sone must not be null");
377 lock.writeLock().lock();
379 /* remove all posts by the Sone. */
380 getPostsFrom(sone.getId()).clear();
381 for (Post post : sone.getPosts()) {
382 allPosts.remove(post.getId());
385 lock.writeLock().unlock();
390 // POSTREPLYPROVIDER METHODS
393 /** {@inheritDocs} */
395 public Optional<PostReply> getPostReply(String id) {
396 lock.readLock().lock();
398 return fromNullable(allPostReplies.get(id));
400 lock.readLock().unlock();
404 /** {@inheritDocs} */
406 public List<PostReply> getReplies(final String postId) {
407 lock.readLock().lock();
409 return from(allPostReplies.values())
410 .filter(new Predicate<PostReply>() {
412 public boolean apply(PostReply postReply) {
413 return postReply.getPostId().equals(postId);
415 }).toSortedList(TIME_COMPARATOR);
417 lock.readLock().unlock();
422 // POSTREPLYBUILDERFACTORY METHODS
425 /** {@inheritDocs} */
427 public PostReplyBuilder newPostReplyBuilder() {
428 return new MemoryPostReplyBuilder(this, soneProvider);
432 // POSTREPLYSTORE METHODS
435 /** {@inheritDocs} */
437 public void storePostReply(PostReply postReply) {
438 lock.writeLock().lock();
440 allPostReplies.put(postReply.getId(), postReply);
442 lock.writeLock().unlock();
446 /** {@inheritDocs} */
448 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
449 checkNotNull(sone, "sone must not be null");
450 /* verify that all posts are from the same Sone. */
451 for (PostReply postReply : postReplies) {
452 if (!sone.equals(postReply.getSone())) {
453 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
457 lock.writeLock().lock();
459 /* remove all post replies of the Sone. */
460 for (PostReply postReply : getRepliesFrom(sone.getId())) {
461 removePostReply(postReply);
463 for (PostReply postReply : postReplies) {
464 allPostReplies.put(postReply.getId(), postReply);
465 sonePostReplies.put(postReply.getSone().getId(), postReply);
468 lock.writeLock().unlock();
472 /** {@inheritDocs} */
474 public void removePostReply(PostReply postReply) {
475 lock.writeLock().lock();
477 allPostReplies.remove(postReply.getId());
479 lock.writeLock().unlock();
483 /** {@inheritDocs} */
485 public void removePostReplies(Sone sone) {
486 checkNotNull(sone, "sone must not be null");
488 lock.writeLock().lock();
490 for (PostReply postReply : sone.getReplies()) {
491 removePostReply(postReply);
494 lock.writeLock().unlock();
499 // ALBUMPROVDER METHODS
503 public Optional<Album> getAlbum(String albumId) {
504 lock.readLock().lock();
506 return fromNullable(allAlbums.get(albumId));
508 lock.readLock().unlock();
513 // ALBUMBUILDERFACTORY METHODS
517 public AlbumBuilder newAlbumBuilder() {
518 return new AlbumBuilderImpl();
522 // ALBUMSTORE METHODS
526 public void storeAlbum(Album album) {
527 lock.writeLock().lock();
529 allAlbums.put(album.getId(), album);
530 soneAlbums.put(album.getSone().getId(), album);
532 lock.writeLock().unlock();
537 public void removeAlbum(Album album) {
538 lock.writeLock().lock();
540 allAlbums.remove(album.getId());
541 soneAlbums.remove(album.getSone().getId(), album);
543 lock.writeLock().unlock();
548 // IMAGEPROVIDER METHODS
552 public Optional<Image> getImage(String imageId) {
553 lock.readLock().lock();
555 return fromNullable(allImages.get(imageId));
557 lock.readLock().unlock();
562 // IMAGEBUILDERFACTORY METHODS
566 public ImageBuilder newImageBuilder() {
567 return new ImageBuilderImpl();
571 // IMAGESTORE METHODS
575 public void storeImage(Image image) {
576 lock.writeLock().lock();
578 allImages.put(image.getId(), image);
579 soneImages.put(image.getSone().getId(), image);
581 lock.writeLock().unlock();
586 public void removeImage(Image image) {
587 lock.writeLock().lock();
589 allImages.remove(image.getId());
590 soneImages.remove(image.getSone().getId(), image);
592 lock.writeLock().unlock();
597 public void bookmarkPost(String postId) {
598 memoryBookmarkDatabase.bookmarkPost(postId);
602 public void bookmarkPost(Post post) {
603 memoryBookmarkDatabase.bookmarkPost(post);
607 public void unbookmarkPost(Post post) {
608 memoryBookmarkDatabase.unbookmarkPost(post);
612 public boolean isPostBookmarked(Post post) {
613 return memoryBookmarkDatabase.isPostBookmarked(post);
617 public Set<Post> getBookmarkedPosts() {
618 return memoryBookmarkDatabase.getBookmarkedPosts();
622 // PACKAGE-PRIVATE METHODS
626 * Returns whether the given post is known.
630 * @return {@code true} if the post is known, {@code false} otherwise
632 boolean isPostKnown(Post post) {
633 lock.readLock().lock();
635 return knownPosts.contains(post.getId());
637 lock.readLock().unlock();
642 * Sets whether the given post is known.
647 * {@code true} if the post is known, {@code false} otherwise
649 void setPostKnown(Post post, boolean known) {
650 lock.writeLock().lock();
653 knownPosts.add(post.getId());
655 knownPosts.remove(post.getId());
658 lock.writeLock().unlock();
663 * Returns whether the given post reply is known.
667 * @return {@code true} if the given post reply is known, {@code false}
670 boolean isPostReplyKnown(PostReply postReply) {
671 lock.readLock().lock();
673 return knownPostReplies.contains(postReply.getId());
675 lock.readLock().unlock();
680 * Sets whether the given post reply is known.
685 * {@code true} if the post reply is known, {@code false} otherwise
687 void setPostReplyKnown(PostReply postReply, boolean known) {
688 lock.writeLock().lock();
691 knownPostReplies.add(postReply.getId());
693 knownPostReplies.remove(postReply.getId());
696 lock.writeLock().unlock();
705 * Gets all posts for the given Sone, creating a new collection if there is
709 * The ID of the Sone to get the posts for
712 private Collection<Post> getPostsFrom(String soneId) {
713 lock.readLock().lock();
715 return sonePosts.get(soneId);
717 lock.readLock().unlock();
721 /** Loads the known posts. */
722 private void loadKnownPosts() {
723 lock.writeLock().lock();
727 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
728 if (knownPostId == null) {
731 knownPosts.add(knownPostId);
734 lock.writeLock().unlock();
739 * Saves the known posts to the configuration.
741 * @throws DatabaseException
742 * if a configuration error occurs
744 private void saveKnownPosts() throws DatabaseException {
745 lock.readLock().lock();
748 for (String knownPostId : knownPosts) {
749 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
751 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
752 } catch (ConfigurationException ce1) {
753 throw new DatabaseException("Could not save database.", ce1);
755 lock.readLock().unlock();
760 * Returns all replies by the given Sone.
764 * @return The post replies of the Sone, sorted by time (newest first)
766 private Collection<PostReply> getRepliesFrom(String id) {
767 lock.readLock().lock();
769 return unmodifiableCollection(sonePostReplies.get(id));
771 lock.readLock().unlock();
775 /** Loads the known post replies. */
776 private void loadKnownPostReplies() {
777 lock.writeLock().lock();
779 int replyCounter = 0;
781 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
782 if (knownReplyId == null) {
785 knownPostReplies.add(knownReplyId);
788 lock.writeLock().unlock();
793 * Saves the known post replies to the configuration.
795 * @throws DatabaseException
796 * if a configuration error occurs
798 private void saveKnownPostReplies() throws DatabaseException {
799 lock.readLock().lock();
801 int replyCounter = 0;
802 for (String knownReplyId : knownPostReplies) {
803 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
805 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
806 } catch (ConfigurationException ce1) {
807 throw new DatabaseException("Could not save database.", ce1);
809 lock.readLock().unlock();