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 =
120 new MemoryBookmarkDatabase(this);
123 * Creates a new memory database.
125 * @param soneProvider
127 * @param configuration
128 * The configuration for loading and saving elements
131 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
132 this.soneProvider = soneProvider;
133 this.configuration = configuration;
134 this.configurationLoader = new ConfigurationLoader(configuration);
142 * Saves the database.
144 * @throws DatabaseException
145 * if an error occurs while saving
148 public void save() throws DatabaseException {
150 saveKnownPostReplies();
157 /** {@inheritDocs} */
159 protected void doStart() {
161 loadKnownPostReplies();
165 /** {@inheritDocs} */
167 protected void doStop() {
171 } catch (DatabaseException de1) {
177 public SoneBuilder newSoneBuilder() {
178 return new MemorySoneBuilder();
182 public void storeSone(Sone sone) {
183 lock.writeLock().lock();
187 allSones.put(sone.getId(), sone);
188 sonePosts.putAll(sone.getId(), sone.getPosts());
189 for (Post post : sone.getPosts()) {
190 allPosts.put(post.getId(), post);
192 sonePostReplies.putAll(sone.getId(), sone.getReplies());
193 for (PostReply postReply : sone.getReplies()) {
194 allPostReplies.put(postReply.getId(), postReply);
196 soneAlbums.putAll(sone.getId(), toAllAlbums.apply(sone));
197 for (Album album : toAllAlbums.apply(sone)) {
198 allAlbums.put(album.getId(), album);
200 soneImages.putAll(sone.getId(), toAllImages.apply(sone));
201 for (Image image : toAllImages.apply(sone)) {
202 allImages.put(image.getId(), image);
205 lock.writeLock().unlock();
210 public void removeSone(Sone sone) {
211 lock.writeLock().lock();
213 allSones.remove(sone.getId());
214 Collection<Post> removedPosts = sonePosts.removeAll(sone.getId());
215 for (Post removedPost : removedPosts) {
216 allPosts.remove(removedPost.getId());
218 Collection<PostReply> removedPostReplies =
219 sonePostReplies.removeAll(sone.getId());
220 for (PostReply removedPostReply : removedPostReplies) {
221 allPostReplies.remove(removedPostReply.getId());
223 Collection<Album> removedAlbums =
224 soneAlbums.removeAll(sone.getId());
225 for (Album removedAlbum : removedAlbums) {
226 allAlbums.remove(removedAlbum.getId());
228 Collection<Image> removedImages =
229 soneImages.removeAll(sone.getId());
230 for (Image removedImage : removedImages) {
231 allImages.remove(removedImage.getId());
234 lock.writeLock().unlock();
239 public Optional<Sone> getSone(String soneId) {
240 lock.readLock().lock();
242 return fromNullable(allSones.get(soneId));
244 lock.readLock().unlock();
249 public Collection<Sone> getSones() {
250 lock.readLock().lock();
252 return new HashSet<Sone>(allSones.values());
254 lock.readLock().unlock();
259 public Collection<Sone> getLocalSones() {
260 lock.readLock().lock();
262 return from(allSones.values()).filter(LOCAL_SONE_FILTER).toSet();
264 lock.readLock().unlock();
269 public Collection<Sone> getRemoteSones() {
270 lock.readLock().lock();
272 return from(allSones.values())
273 .filter(not(LOCAL_SONE_FILTER)) .toSet();
275 lock.readLock().unlock();
280 // POSTPROVIDER METHODS
283 /** {@inheritDocs} */
285 public Optional<Post> getPost(String postId) {
286 lock.readLock().lock();
288 return fromNullable(allPosts.get(postId));
290 lock.readLock().unlock();
294 /** {@inheritDocs} */
296 public Collection<Post> getPosts(String soneId) {
297 return new HashSet<Post>(getPostsFrom(soneId));
300 /** {@inheritDocs} */
302 public Collection<Post> getDirectedPosts(final String recipientId) {
303 lock.readLock().lock();
305 return from(sonePosts.values()).filter(new Predicate<Post>() {
307 public boolean apply(Post post) {
308 return post.getRecipientId().asSet().contains(recipientId);
312 lock.readLock().unlock();
317 // POSTBUILDERFACTORY METHODS
320 /** {@inheritDocs} */
322 public PostBuilder newPostBuilder() {
323 return new MemoryPostBuilder(this, soneProvider);
330 /** {@inheritDocs} */
332 public void storePost(Post post) {
333 checkNotNull(post, "post must not be null");
334 lock.writeLock().lock();
336 allPosts.put(post.getId(), post);
337 getPostsFrom(post.getSone().getId()).add(post);
339 lock.writeLock().unlock();
343 /** {@inheritDocs} */
345 public void removePost(Post post) {
346 checkNotNull(post, "post must not be null");
347 lock.writeLock().lock();
349 allPosts.remove(post.getId());
350 getPostsFrom(post.getSone().getId()).remove(post);
351 post.getSone().removePost(post);
353 lock.writeLock().unlock();
357 /** {@inheritDocs} */
359 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
360 checkNotNull(sone, "sone must not be null");
361 /* verify that all posts are from the same Sone. */
362 for (Post post : posts) {
363 if (!sone.equals(post.getSone())) {
364 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
368 lock.writeLock().lock();
370 /* remove all posts by the Sone. */
371 Collection<Post> oldPosts = getPostsFrom(sone.getId());
372 for (Post post : oldPosts) {
373 allPosts.remove(post.getId());
377 getPostsFrom(sone.getId()).addAll(posts);
378 for (Post post : posts) {
379 allPosts.put(post.getId(), post);
382 lock.writeLock().unlock();
386 /** {@inheritDocs} */
388 public void removePosts(Sone sone) {
389 checkNotNull(sone, "sone must not be null");
390 lock.writeLock().lock();
392 /* remove all posts by the Sone. */
393 getPostsFrom(sone.getId()).clear();
394 for (Post post : sone.getPosts()) {
395 allPosts.remove(post.getId());
398 lock.writeLock().unlock();
403 // POSTREPLYPROVIDER METHODS
406 /** {@inheritDocs} */
408 public Optional<PostReply> getPostReply(String id) {
409 lock.readLock().lock();
411 return fromNullable(allPostReplies.get(id));
413 lock.readLock().unlock();
417 /** {@inheritDocs} */
419 public List<PostReply> getReplies(final String postId) {
420 lock.readLock().lock();
422 return from(allPostReplies.values())
423 .filter(new Predicate<PostReply>() {
425 public boolean apply(PostReply postReply) {
426 return postReply.getPostId().equals(postId);
428 }).toSortedList(TIME_COMPARATOR);
430 lock.readLock().unlock();
435 // POSTREPLYBUILDERFACTORY METHODS
438 /** {@inheritDocs} */
440 public PostReplyBuilder newPostReplyBuilder() {
441 return new MemoryPostReplyBuilder(this, soneProvider);
445 // POSTREPLYSTORE METHODS
448 /** {@inheritDocs} */
450 public void storePostReply(PostReply postReply) {
451 lock.writeLock().lock();
453 allPostReplies.put(postReply.getId(), postReply);
455 lock.writeLock().unlock();
459 /** {@inheritDocs} */
461 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
462 checkNotNull(sone, "sone must not be null");
463 /* verify that all posts are from the same Sone. */
464 for (PostReply postReply : postReplies) {
465 if (!sone.equals(postReply.getSone())) {
466 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
470 lock.writeLock().lock();
472 /* remove all post replies of the Sone. */
473 for (PostReply postReply : getRepliesFrom(sone.getId())) {
474 removePostReply(postReply);
476 for (PostReply postReply : postReplies) {
477 allPostReplies.put(postReply.getId(), postReply);
478 sonePostReplies.put(postReply.getSone().getId(), postReply);
481 lock.writeLock().unlock();
485 /** {@inheritDocs} */
487 public void removePostReply(PostReply postReply) {
488 lock.writeLock().lock();
490 allPostReplies.remove(postReply.getId());
492 lock.writeLock().unlock();
496 /** {@inheritDocs} */
498 public void removePostReplies(Sone sone) {
499 checkNotNull(sone, "sone must not be null");
501 lock.writeLock().lock();
503 for (PostReply postReply : sone.getReplies()) {
504 removePostReply(postReply);
507 lock.writeLock().unlock();
512 // ALBUMPROVDER METHODS
516 public Optional<Album> getAlbum(String albumId) {
517 lock.readLock().lock();
519 return fromNullable(allAlbums.get(albumId));
521 lock.readLock().unlock();
526 // ALBUMBUILDERFACTORY METHODS
530 public AlbumBuilder newAlbumBuilder() {
531 return new AlbumBuilderImpl();
535 // ALBUMSTORE METHODS
539 public void storeAlbum(Album album) {
540 lock.writeLock().lock();
542 allAlbums.put(album.getId(), album);
543 soneAlbums.put(album.getSone().getId(), album);
545 lock.writeLock().unlock();
550 public void removeAlbum(Album album) {
551 lock.writeLock().lock();
553 allAlbums.remove(album.getId());
554 soneAlbums.remove(album.getSone().getId(), album);
556 lock.writeLock().unlock();
561 // IMAGEPROVIDER METHODS
565 public Optional<Image> getImage(String imageId) {
566 lock.readLock().lock();
568 return fromNullable(allImages.get(imageId));
570 lock.readLock().unlock();
575 // IMAGEBUILDERFACTORY METHODS
579 public ImageBuilder newImageBuilder() {
580 return new ImageBuilderImpl();
584 // IMAGESTORE METHODS
588 public void storeImage(Image image) {
589 lock.writeLock().lock();
591 allImages.put(image.getId(), image);
592 soneImages.put(image.getSone().getId(), image);
594 lock.writeLock().unlock();
599 public void removeImage(Image image) {
600 lock.writeLock().lock();
602 allImages.remove(image.getId());
603 soneImages.remove(image.getSone().getId(), image);
605 lock.writeLock().unlock();
610 public void bookmarkPost(String postId) {
611 memoryBookmarkDatabase.bookmarkPost(postId);
615 public void bookmarkPost(Post post) {
616 memoryBookmarkDatabase.bookmarkPost(post);
620 public void unbookmarkPost(Post post) {
621 memoryBookmarkDatabase.unbookmarkPost(post);
625 public boolean isPostBookmarked(Post post) {
626 return memoryBookmarkDatabase.isPostBookmarked(post);
630 public Set<Post> getBookmarkedPosts() {
631 return memoryBookmarkDatabase.getBookmarkedPosts();
635 // PACKAGE-PRIVATE METHODS
639 * Returns whether the given post is known.
643 * @return {@code true} if the post is known, {@code false} otherwise
645 boolean isPostKnown(Post post) {
646 lock.readLock().lock();
648 return knownPosts.contains(post.getId());
650 lock.readLock().unlock();
655 * Sets whether the given post is known.
660 * {@code true} if the post is known, {@code false} otherwise
662 void setPostKnown(Post post, boolean known) {
663 lock.writeLock().lock();
666 knownPosts.add(post.getId());
668 knownPosts.remove(post.getId());
671 lock.writeLock().unlock();
676 * Returns whether the given post reply is known.
680 * @return {@code true} if the given post reply is known, {@code false}
683 boolean isPostReplyKnown(PostReply postReply) {
684 lock.readLock().lock();
686 return knownPostReplies.contains(postReply.getId());
688 lock.readLock().unlock();
693 * Sets whether the given post reply is known.
698 * {@code true} if the post reply is known, {@code false} otherwise
700 void setPostReplyKnown(PostReply postReply, boolean known) {
701 lock.writeLock().lock();
704 knownPostReplies.add(postReply.getId());
706 knownPostReplies.remove(postReply.getId());
709 lock.writeLock().unlock();
718 * Gets all posts for the given Sone, creating a new collection if there is
722 * The ID of the Sone to get the posts for
725 private Collection<Post> getPostsFrom(String soneId) {
726 lock.readLock().lock();
728 return sonePosts.get(soneId);
730 lock.readLock().unlock();
734 /** Loads the known posts. */
735 private void loadKnownPosts() {
736 Set<String> knownPosts = configurationLoader.loadKnownPosts();
737 lock.writeLock().lock();
739 this.knownPosts.clear();
740 this.knownPosts.addAll(knownPosts);
742 lock.writeLock().unlock();
747 * Saves the known posts to the configuration.
749 * @throws DatabaseException
750 * if a configuration error occurs
752 private void saveKnownPosts() throws DatabaseException {
753 lock.readLock().lock();
756 for (String knownPostId : knownPosts) {
757 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
759 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
760 } catch (ConfigurationException ce1) {
761 throw new DatabaseException("Could not save database.", ce1);
763 lock.readLock().unlock();
768 * Returns all replies by the given Sone.
772 * @return The post replies of the Sone, sorted by time (newest first)
774 private Collection<PostReply> getRepliesFrom(String id) {
775 lock.readLock().lock();
777 return unmodifiableCollection(sonePostReplies.get(id));
779 lock.readLock().unlock();
783 /** Loads the known post replies. */
784 private void loadKnownPostReplies() {
785 lock.writeLock().lock();
787 int replyCounter = 0;
789 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
790 if (knownReplyId == null) {
793 knownPostReplies.add(knownReplyId);
796 lock.writeLock().unlock();
801 * Saves the known post replies to the configuration.
803 * @throws DatabaseException
804 * if a configuration error occurs
806 private void saveKnownPostReplies() throws DatabaseException {
807 lock.readLock().lock();
809 int replyCounter = 0;
810 for (String knownReplyId : knownPostReplies) {
811 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
813 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
814 } catch (ConfigurationException ce1) {
815 throw new DatabaseException("Could not save database.", ce1);
817 lock.readLock().unlock();