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.emptyList;
25 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.Comparator;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.List;
36 import java.util.concurrent.locks.ReadWriteLock;
37 import java.util.concurrent.locks.ReentrantReadWriteLock;
39 import net.pterodactylus.sone.data.Album;
40 import net.pterodactylus.sone.data.Image;
41 import net.pterodactylus.sone.data.Post;
42 import net.pterodactylus.sone.data.PostReply;
43 import net.pterodactylus.sone.data.Sone;
44 import net.pterodactylus.sone.data.impl.DefaultSoneBuilder;
45 import net.pterodactylus.sone.database.Database;
46 import net.pterodactylus.sone.database.DatabaseException;
47 import net.pterodactylus.sone.database.PostDatabase;
48 import net.pterodactylus.sone.database.SoneBuilder;
49 import net.pterodactylus.sone.freenet.wot.Identity;
50 import net.pterodactylus.util.config.Configuration;
51 import net.pterodactylus.util.config.ConfigurationException;
53 import com.google.common.base.Function;
54 import com.google.common.base.Optional;
55 import com.google.common.collect.ArrayListMultimap;
56 import com.google.common.collect.HashMultimap;
57 import com.google.common.collect.ListMultimap;
58 import com.google.common.collect.Maps;
59 import com.google.common.collect.Multimap;
60 import com.google.common.collect.SetMultimap;
61 import com.google.common.collect.SortedSetMultimap;
62 import com.google.common.collect.TreeMultimap;
63 import com.google.common.util.concurrent.AbstractService;
64 import com.google.inject.Inject;
67 * Memory-based {@link PostDatabase} implementation.
69 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
71 public class MemoryDatabase extends AbstractService implements Database {
74 private final ReadWriteLock lock = new ReentrantReadWriteLock();
76 /** The configuration. */
77 private final Configuration configuration;
79 private final Map<String, Identity> identities = Maps.newHashMap();
80 private final Map<String, Sone> sones = new HashMap<String, Sone>();
82 /** All posts by their ID. */
83 private final Map<String, Post> allPosts = new HashMap<String, Post>();
85 /** All posts by their Sones. */
86 private final Multimap<String, Post> sonePosts = HashMultimap.create();
87 private final SetMultimap<String, String> likedPostsBySone = HashMultimap.create();
88 private final SetMultimap<String, String> postLikingSones = HashMultimap.create();
90 /** All posts by their recipient. */
91 private final Multimap<String, Post> recipientPosts = HashMultimap.create();
93 /** Whether posts are known. */
94 private final Set<String> knownPosts = new HashSet<String>();
96 /** All post replies by their ID. */
97 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
98 private final SetMultimap<String, String> likedPostRepliesBySone = HashMultimap.create();
99 private final SetMultimap<String, String> postReplyLikingSones = HashMultimap.create();
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);
108 }, PostReply.TIME_COMPARATOR);
110 /** Replies by post. */
111 private final SortedSetMultimap<String, PostReply> postReplies = TreeMultimap.create(new Comparator<String>() {
114 public int compare(String leftString, String rightString) {
115 return leftString.compareTo(rightString);
117 }, PostReply.TIME_COMPARATOR);
119 /** Whether post replies are known. */
120 private final Set<String> knownPostReplies = new HashSet<String>();
122 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
123 private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
124 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
126 private final Map<String, Image> allImages = new HashMap<String, Image>();
129 * Creates a new memory database.
131 * @param configuration
132 * The configuration for loading and saving elements
135 public MemoryDatabase(Configuration configuration) {
136 this.configuration = configuration;
144 public void save() throws DatabaseException {
146 saveKnownPostReplies();
154 protected void doStart() {
156 loadKnownPostReplies();
161 protected void doStop() {
165 } catch (DatabaseException de1) {
171 public Optional<Identity> getIdentity(String identityId) {
172 lock.readLock().lock();
174 return fromNullable(identities.get(identityId));
176 lock.readLock().unlock();
181 public void storeIdentity(Identity identitiy) {
182 lock.writeLock().lock();
184 identities.put(identitiy.getId(), identitiy);
186 lock.writeLock().unlock();
191 public Function<String, Optional<Sone>> getSone() {
192 return new Function<String, Optional<Sone>>() {
194 public Optional<Sone> apply(String soneId) {
195 return (soneId == null) ? Optional.<Sone>absent() : getSone(soneId);
201 public Optional<Sone> getSone(String soneId) {
202 lock.readLock().lock();
204 return fromNullable(sones.get(soneId));
206 lock.readLock().unlock();
211 public Collection<Sone> getSones() {
212 lock.readLock().lock();
214 return Collections.unmodifiableCollection(sones.values());
216 lock.readLock().unlock();
221 public Collection<Sone> getLocalSones() {
222 lock.readLock().lock();
224 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
226 lock.readLock().unlock();
231 public Collection<Sone> getRemoteSones() {
232 lock.readLock().lock();
234 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
236 lock.readLock().unlock();
241 public SoneBuilder newSoneBuilder() {
242 return new DefaultSoneBuilder(this) {
244 public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
245 Sone sone = super.build(soneCreated);
246 lock.writeLock().lock();
248 sones.put(sone.getId(), sone);
250 lock.writeLock().unlock();
258 // POSTPROVIDER METHODS
262 public Function<String, Optional<Post>> getPost() {
263 return new Function<String, Optional<Post>>() {
265 public Optional<Post> apply(String postId) {
266 return (postId == null) ? Optional.<Post>absent() : getPost(postId);
272 public Optional<Post> getPost(String postId) {
273 lock.readLock().lock();
275 return fromNullable(allPosts.get(postId));
277 lock.readLock().unlock();
282 public Collection<Post> getPosts(String soneId) {
283 lock.readLock().lock();
285 return new HashSet<Post>(sonePosts.get(soneId));
287 lock.readLock().unlock();
292 public Collection<Post> getDirectedPosts(String recipientId) {
293 lock.readLock().lock();
295 Collection<Post> posts = recipientPosts.get(recipientId);
296 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
298 lock.readLock().unlock();
303 public void likePost(Post post, Sone localSone) {
304 lock.writeLock().lock();
306 likedPostsBySone.put(localSone.getId(), post.getId());
307 postLikingSones.put(post.getId(), localSone.getId());
309 lock.writeLock().unlock();
314 public void unlikePost(Post post, Sone localSone) {
315 lock.writeLock().lock();
317 likedPostsBySone.remove(localSone.getId(), post.getId());
318 postLikingSones.remove(post.getId(), localSone.getId());
320 lock.writeLock().unlock();
324 public boolean isLiked(Post post, Sone sone) {
325 lock.readLock().lock();
327 return likedPostsBySone.containsEntry(sone.getId(), post.getId());
329 lock.readLock().unlock();
334 public Set<Sone> getLikes(Post post) {
335 lock.readLock().lock();
337 return from(postLikingSones.get(post.getId())).transform(getSone()).transformAndConcat(this.<Sone>unwrap()).toSet();
339 lock.readLock().unlock();
348 public void storePost(Post post) {
349 checkNotNull(post, "post must not be null");
350 lock.writeLock().lock();
352 allPosts.put(post.getId(), post);
353 sonePosts.put(post.getSone().getId(), post);
354 if (post.getRecipientId().isPresent()) {
355 recipientPosts.put(post.getRecipientId().get(), post);
358 lock.writeLock().unlock();
363 public void removePost(Post post) {
364 checkNotNull(post, "post must not be null");
365 lock.writeLock().lock();
367 allPosts.remove(post.getId());
368 sonePosts.remove(post.getSone().getId(), post);
369 if (post.getRecipientId().isPresent()) {
370 recipientPosts.remove(post.getRecipientId().get(), post);
372 post.getSone().removePost(post);
374 lock.writeLock().unlock();
379 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
380 checkNotNull(sone, "sone must not be null");
381 /* verify that all posts are from the same Sone. */
382 for (Post post : posts) {
383 if (!sone.equals(post.getSone())) {
384 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
388 lock.writeLock().lock();
390 /* remove all posts by the Sone. */
391 sonePosts.removeAll(sone.getId());
392 for (Post post : posts) {
393 allPosts.remove(post.getId());
394 if (post.getRecipientId().isPresent()) {
395 recipientPosts.remove(post.getRecipientId().get(), post);
400 sonePosts.putAll(sone.getId(), posts);
401 for (Post post : posts) {
402 allPosts.put(post.getId(), post);
403 if (post.getRecipientId().isPresent()) {
404 recipientPosts.put(post.getRecipientId().get(), post);
408 lock.writeLock().unlock();
413 public void removePosts(Sone sone) {
414 checkNotNull(sone, "sone must not be null");
415 lock.writeLock().lock();
417 /* remove all posts by the Sone. */
418 sonePosts.removeAll(sone.getId());
419 for (Post post : sone.getPosts()) {
420 allPosts.remove(post.getId());
421 if (post.getRecipientId().isPresent()) {
422 recipientPosts.remove(post.getRecipientId().get(), post);
426 lock.writeLock().unlock();
431 // POSTREPLYPROVIDER METHODS
435 public Optional<PostReply> getPostReply(String id) {
436 lock.readLock().lock();
438 return fromNullable(allPostReplies.get(id));
440 lock.readLock().unlock();
445 public List<PostReply> getReplies(String postId) {
446 lock.readLock().lock();
448 if (!postReplies.containsKey(postId)) {
451 return new ArrayList<PostReply>(postReplies.get(postId));
453 lock.readLock().unlock();
458 public void likePostReply(PostReply postReply, Sone localSone) {
459 lock.writeLock().lock();
461 likedPostRepliesBySone.put(localSone.getId(), postReply.getId());
462 postReplyLikingSones.put(postReply.getId(), localSone.getId());
464 lock.writeLock().unlock();
469 public void unlikePostReply(PostReply postReply, Sone localSone) {
470 lock.writeLock().lock();
472 likedPostRepliesBySone.remove(localSone.getId(), postReply.getId());
473 postReplyLikingSones.remove(postReply.getId(), localSone.getId());
475 lock.writeLock().unlock();
480 public boolean isLiked(PostReply postReply, Sone sone) {
481 lock.readLock().lock();
483 return postReplyLikingSones.containsEntry(postReply.getId(), sone.getId());
485 lock.readLock().unlock();
490 public Set<Sone> getLikes(PostReply postReply) {
491 lock.readLock().lock();
493 return from(postReplyLikingSones.get(postReply.getId())).transform(getSone()).transformAndConcat(this.<Sone>unwrap()).toSet();
495 lock.readLock().unlock();
500 // POSTREPLYSTORE METHODS
504 * Returns whether the given post reply is known.
508 * @return {@code true} if the given post reply is known, {@code false}
511 public boolean isPostReplyKnown(PostReply postReply) {
512 lock.readLock().lock();
514 return knownPostReplies.contains(postReply.getId());
516 lock.readLock().unlock();
521 public void setPostReplyKnown(PostReply postReply) {
522 lock.writeLock().lock();
524 knownPostReplies.add(postReply.getId());
526 lock.writeLock().unlock();
531 public void storePostReply(PostReply postReply) {
532 lock.writeLock().lock();
534 allPostReplies.put(postReply.getId(), postReply);
535 postReplies.put(postReply.getPostId(), postReply);
537 lock.writeLock().unlock();
542 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
543 checkNotNull(sone, "sone must not be null");
544 /* verify that all posts are from the same Sone. */
545 for (PostReply postReply : postReplies) {
546 if (!sone.equals(postReply.getSone())) {
547 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
551 lock.writeLock().lock();
553 /* remove all post replies of the Sone. */
554 for (PostReply postReply : getRepliesFrom(sone.getId())) {
555 removePostReply(postReply);
557 for (PostReply postReply : postReplies) {
558 allPostReplies.put(postReply.getId(), postReply);
559 sonePostReplies.put(postReply.getSone().getId(), postReply);
560 this.postReplies.put(postReply.getPostId(), postReply);
563 lock.writeLock().unlock();
568 public void removePostReply(PostReply postReply) {
569 lock.writeLock().lock();
571 allPostReplies.remove(postReply.getId());
572 postReplies.remove(postReply.getPostId(), postReply);
574 lock.writeLock().unlock();
579 public void removePostReplies(Sone sone) {
580 checkNotNull(sone, "sone must not be null");
582 lock.writeLock().lock();
584 for (PostReply postReply : sone.getReplies()) {
585 removePostReply(postReply);
588 lock.writeLock().unlock();
593 // ALBUMPROVDER METHODS
597 public Optional<Album> getAlbum(String albumId) {
598 lock.readLock().lock();
600 return fromNullable(allAlbums.get(albumId));
602 lock.readLock().unlock();
607 public List<Album> getAlbums(Album parent) {
608 lock.readLock().lock();
610 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
612 lock.readLock().unlock();
617 public void moveUp(Album album) {
618 lock.writeLock().lock();
620 List<String> albums = albumChildren.get(album.getParent().getId());
621 int currentIndex = albums.indexOf(album.getId());
622 if (currentIndex == 0) {
625 albums.remove(album.getId());
626 albums.add(currentIndex - 1, album.getId());
628 lock.writeLock().unlock();
633 public void moveDown(Album album) {
634 lock.writeLock().lock();
636 List<String> albums = albumChildren.get(album.getParent().getId());
637 int currentIndex = albums.indexOf(album.getId());
638 if (currentIndex == (albums.size() - 1)) {
641 albums.remove(album.getId());
642 albums.add(currentIndex + 1, album.getId());
644 lock.writeLock().unlock();
649 // ALBUMSTORE METHODS
653 public void storeAlbum(Album album) {
654 lock.writeLock().lock();
656 allAlbums.put(album.getId(), album);
657 if (!album.isRoot()) {
658 albumChildren.put(album.getParent().getId(), album.getId());
661 lock.writeLock().unlock();
666 public void removeAlbum(Album album) {
667 lock.writeLock().lock();
669 allAlbums.remove(album.getId());
670 albumChildren.remove(album.getParent().getId(), album.getId());
672 lock.writeLock().unlock();
677 // IMAGEPROVIDER METHODS
681 public Optional<Image> getImage(String imageId) {
682 lock.readLock().lock();
684 return fromNullable(allImages.get(imageId));
686 lock.readLock().unlock();
691 public List<Image> getImages(Album parent) {
692 lock.readLock().lock();
694 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
696 lock.readLock().unlock();
701 public void moveUp(Image image) {
702 lock.writeLock().lock();
704 List<String> images = albumImages.get(image.getAlbum().getId());
705 int currentIndex = images.indexOf(image.getId());
706 if (currentIndex == 0) {
709 images.remove(image.getId());
710 images.add(currentIndex - 1, image.getId());
712 lock.writeLock().unlock();
717 public void moveDown(Image image) {
718 lock.writeLock().lock();
720 List<String> images = albumChildren.get(image.getAlbum().getId());
721 int currentIndex = images.indexOf(image.getId());
722 if (currentIndex == (images.size() - 1)) {
725 images.remove(image.getId());
726 images.add(currentIndex + 1, image.getId());
728 lock.writeLock().unlock();
733 // IMAGESTORE METHODS
737 public void storeImage(Image image) {
738 lock.writeLock().lock();
740 allImages.put(image.getId(), image);
741 albumImages.put(image.getAlbum().getId(), image.getId());
743 lock.writeLock().unlock();
748 public void removeImage(Image image) {
749 lock.writeLock().lock();
751 allImages.remove(image.getId());
752 albumImages.remove(image.getAlbum().getId(), image.getId());
754 lock.writeLock().unlock();
759 // PACKAGE-PRIVATE METHODS
763 * Returns whether the given post is known.
767 * @return {@code true} if the post is known, {@code false} otherwise
769 boolean isPostKnown(Post post) {
770 lock.readLock().lock();
772 return knownPosts.contains(post.getId());
774 lock.readLock().unlock();
779 * Sets whether the given post is known.
784 * {@code true} if the post is known, {@code false} otherwise
786 void setPostKnown(Post post, boolean known) {
787 lock.writeLock().lock();
790 knownPosts.add(post.getId());
792 knownPosts.remove(post.getId());
795 lock.writeLock().unlock();
803 /** Loads the known posts. */
804 private void loadKnownPosts() {
805 lock.writeLock().lock();
809 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
810 if (knownPostId == null) {
813 knownPosts.add(knownPostId);
816 lock.writeLock().unlock();
821 * Saves the known posts to the configuration.
823 * @throws DatabaseException
824 * if a configuration error occurs
826 private void saveKnownPosts() throws DatabaseException {
827 lock.readLock().lock();
830 for (String knownPostId : knownPosts) {
831 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
833 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
834 } catch (ConfigurationException ce1) {
835 throw new DatabaseException("Could not save database.", ce1);
837 lock.readLock().unlock();
842 * Returns all replies by the given Sone.
846 * @return The post replies of the Sone, sorted by time (newest first)
848 private Collection<PostReply> getRepliesFrom(String id) {
849 lock.readLock().lock();
851 if (sonePostReplies.containsKey(id)) {
852 return Collections.unmodifiableCollection(sonePostReplies.get(id));
854 return Collections.emptySet();
856 lock.readLock().unlock();
860 /** Loads the known post replies. */
861 private void loadKnownPostReplies() {
862 lock.writeLock().lock();
864 int replyCounter = 0;
866 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
867 if (knownReplyId == null) {
870 knownPostReplies.add(knownReplyId);
873 lock.writeLock().unlock();
878 * Saves the known post replies to the configuration.
880 * @throws DatabaseException
881 * if a configuration error occurs
883 private void saveKnownPostReplies() throws DatabaseException {
884 lock.readLock().lock();
886 int replyCounter = 0;
887 for (String knownReplyId : knownPostReplies) {
888 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
890 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
891 } catch (ConfigurationException ce1) {
892 throw new DatabaseException("Could not save database.", ce1);
894 lock.readLock().unlock();
898 private Function<String, Iterable<Album>> getAlbum() {
899 return new Function<String, Iterable<Album>>() {
901 public Iterable<Album> apply(String input) {
902 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
907 private Function<String, Iterable<Image>> getImage() {
908 return new Function<String, Iterable<Image>>() {
910 public Iterable<Image> apply(String input) {
911 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();
916 private static <T> Function<Optional<T>, Iterable<T>> unwrap() {
917 return new Function<Optional<T>, Iterable<T>>() {
919 public Iterable<T> apply(Optional<T> input) {
920 return (input == null) ? Collections.<T>emptyList() : input.asSet();