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 void storeSone(Sone sone) {
242 lock.writeLock().lock();
244 sones.put(sone.getId(), sone);
246 lock.writeLock().unlock();
251 public SoneBuilder newSoneBuilder() {
252 return new DefaultSoneBuilder(this) {
254 public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
255 Sone sone = super.build(soneCreated);
256 lock.writeLock().lock();
258 sones.put(sone.getId(), sone);
260 lock.writeLock().unlock();
268 // POSTPROVIDER METHODS
272 public Function<String, Optional<Post>> getPost() {
273 return new Function<String, Optional<Post>>() {
275 public Optional<Post> apply(String postId) {
276 return (postId == null) ? Optional.<Post>absent() : getPost(postId);
282 public Optional<Post> getPost(String postId) {
283 lock.readLock().lock();
285 return fromNullable(allPosts.get(postId));
287 lock.readLock().unlock();
292 public Collection<Post> getPosts(String soneId) {
293 lock.readLock().lock();
295 return new HashSet<Post>(sonePosts.get(soneId));
297 lock.readLock().unlock();
302 public Collection<Post> getDirectedPosts(String recipientId) {
303 lock.readLock().lock();
305 Collection<Post> posts = recipientPosts.get(recipientId);
306 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
308 lock.readLock().unlock();
313 public void likePost(Post post, Sone localSone) {
314 lock.writeLock().lock();
316 likedPostsBySone.put(localSone.getId(), post.getId());
317 postLikingSones.put(post.getId(), localSone.getId());
319 lock.writeLock().unlock();
324 public void unlikePost(Post post, Sone localSone) {
325 lock.writeLock().lock();
327 likedPostsBySone.remove(localSone.getId(), post.getId());
328 postLikingSones.remove(post.getId(), localSone.getId());
330 lock.writeLock().unlock();
334 public boolean isLiked(Post post, Sone sone) {
335 lock.readLock().lock();
337 return likedPostsBySone.containsEntry(sone.getId(), post.getId());
339 lock.readLock().unlock();
344 public Set<Sone> getLikes(Post post) {
345 lock.readLock().lock();
347 return from(postLikingSones.get(post.getId())).transform(getSone()).transformAndConcat(this.<Sone>unwrap()).toSet();
349 lock.readLock().unlock();
358 public void storePost(Post post) {
359 checkNotNull(post, "post must not be null");
360 lock.writeLock().lock();
362 allPosts.put(post.getId(), post);
363 sonePosts.put(post.getSone().getId(), post);
364 if (post.getRecipientId().isPresent()) {
365 recipientPosts.put(post.getRecipientId().get(), post);
368 lock.writeLock().unlock();
373 public void removePost(Post post) {
374 checkNotNull(post, "post must not be null");
375 lock.writeLock().lock();
377 allPosts.remove(post.getId());
378 sonePosts.remove(post.getSone().getId(), post);
379 if (post.getRecipientId().isPresent()) {
380 recipientPosts.remove(post.getRecipientId().get(), post);
382 post.getSone().removePost(post);
384 lock.writeLock().unlock();
389 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
390 checkNotNull(sone, "sone must not be null");
391 /* verify that all posts are from the same Sone. */
392 for (Post post : posts) {
393 if (!sone.equals(post.getSone())) {
394 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
398 lock.writeLock().lock();
400 /* remove all posts by the Sone. */
401 sonePosts.removeAll(sone.getId());
402 for (Post post : posts) {
403 allPosts.remove(post.getId());
404 if (post.getRecipientId().isPresent()) {
405 recipientPosts.remove(post.getRecipientId().get(), post);
410 sonePosts.putAll(sone.getId(), posts);
411 for (Post post : posts) {
412 allPosts.put(post.getId(), post);
413 if (post.getRecipientId().isPresent()) {
414 recipientPosts.put(post.getRecipientId().get(), post);
418 lock.writeLock().unlock();
423 public void removePosts(Sone sone) {
424 checkNotNull(sone, "sone must not be null");
425 lock.writeLock().lock();
427 /* remove all posts by the Sone. */
428 sonePosts.removeAll(sone.getId());
429 for (Post post : sone.getPosts()) {
430 allPosts.remove(post.getId());
431 if (post.getRecipientId().isPresent()) {
432 recipientPosts.remove(post.getRecipientId().get(), post);
436 lock.writeLock().unlock();
441 // POSTREPLYPROVIDER METHODS
445 public Optional<PostReply> getPostReply(String id) {
446 lock.readLock().lock();
448 return fromNullable(allPostReplies.get(id));
450 lock.readLock().unlock();
455 public List<PostReply> getReplies(String postId) {
456 lock.readLock().lock();
458 if (!postReplies.containsKey(postId)) {
461 return new ArrayList<PostReply>(postReplies.get(postId));
463 lock.readLock().unlock();
468 public void likePostReply(PostReply postReply, Sone localSone) {
469 lock.writeLock().lock();
471 likedPostRepliesBySone.put(localSone.getId(), postReply.getId());
472 postReplyLikingSones.put(postReply.getId(), localSone.getId());
474 lock.writeLock().unlock();
479 public void unlikePostReply(PostReply postReply, Sone localSone) {
480 lock.writeLock().lock();
482 likedPostRepliesBySone.remove(localSone.getId(), postReply.getId());
483 postReplyLikingSones.remove(postReply.getId(), localSone.getId());
485 lock.writeLock().unlock();
490 public boolean isLiked(PostReply postReply, Sone sone) {
491 lock.readLock().lock();
493 return postReplyLikingSones.containsEntry(postReply.getId(), sone.getId());
495 lock.readLock().unlock();
500 public Set<Sone> getLikes(PostReply postReply) {
501 lock.readLock().lock();
503 return from(postReplyLikingSones.get(postReply.getId())).transform(getSone()).transformAndConcat(this.<Sone>unwrap()).toSet();
505 lock.readLock().unlock();
510 // POSTREPLYSTORE METHODS
514 * Returns whether the given post reply is known.
518 * @return {@code true} if the given post reply is known, {@code false}
521 public boolean isPostReplyKnown(PostReply postReply) {
522 lock.readLock().lock();
524 return knownPostReplies.contains(postReply.getId());
526 lock.readLock().unlock();
531 public void setPostReplyKnown(PostReply postReply) {
532 lock.writeLock().lock();
534 knownPostReplies.add(postReply.getId());
536 lock.writeLock().unlock();
541 public void storePostReply(PostReply postReply) {
542 lock.writeLock().lock();
544 allPostReplies.put(postReply.getId(), postReply);
545 postReplies.put(postReply.getPostId(), postReply);
547 lock.writeLock().unlock();
552 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
553 checkNotNull(sone, "sone must not be null");
554 /* verify that all posts are from the same Sone. */
555 for (PostReply postReply : postReplies) {
556 if (!sone.equals(postReply.getSone())) {
557 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
561 lock.writeLock().lock();
563 /* remove all post replies of the Sone. */
564 for (PostReply postReply : getRepliesFrom(sone.getId())) {
565 removePostReply(postReply);
567 for (PostReply postReply : postReplies) {
568 allPostReplies.put(postReply.getId(), postReply);
569 sonePostReplies.put(postReply.getSone().getId(), postReply);
570 this.postReplies.put(postReply.getPostId(), postReply);
573 lock.writeLock().unlock();
578 public void removePostReply(PostReply postReply) {
579 lock.writeLock().lock();
581 allPostReplies.remove(postReply.getId());
582 postReplies.remove(postReply.getPostId(), postReply);
584 lock.writeLock().unlock();
589 public void removePostReplies(Sone sone) {
590 checkNotNull(sone, "sone must not be null");
592 lock.writeLock().lock();
594 for (PostReply postReply : sone.getReplies()) {
595 removePostReply(postReply);
598 lock.writeLock().unlock();
603 // ALBUMPROVDER METHODS
607 public Optional<Album> getAlbum(String albumId) {
608 lock.readLock().lock();
610 return fromNullable(allAlbums.get(albumId));
612 lock.readLock().unlock();
617 public List<Album> getAlbums(Album parent) {
618 lock.readLock().lock();
620 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
622 lock.readLock().unlock();
627 public void moveUp(Album album) {
628 lock.writeLock().lock();
630 List<String> albums = albumChildren.get(album.getParent().getId());
631 int currentIndex = albums.indexOf(album.getId());
632 if (currentIndex == 0) {
635 albums.remove(album.getId());
636 albums.add(currentIndex - 1, album.getId());
638 lock.writeLock().unlock();
643 public void moveDown(Album album) {
644 lock.writeLock().lock();
646 List<String> albums = albumChildren.get(album.getParent().getId());
647 int currentIndex = albums.indexOf(album.getId());
648 if (currentIndex == (albums.size() - 1)) {
651 albums.remove(album.getId());
652 albums.add(currentIndex + 1, album.getId());
654 lock.writeLock().unlock();
659 // ALBUMSTORE METHODS
663 public void storeAlbum(Album album) {
664 lock.writeLock().lock();
666 allAlbums.put(album.getId(), album);
667 if (!album.isRoot()) {
668 albumChildren.put(album.getParent().getId(), album.getId());
671 lock.writeLock().unlock();
676 public void removeAlbum(Album album) {
677 lock.writeLock().lock();
679 allAlbums.remove(album.getId());
680 albumChildren.remove(album.getParent().getId(), album.getId());
682 lock.writeLock().unlock();
687 // IMAGEPROVIDER METHODS
691 public Optional<Image> getImage(String imageId) {
692 lock.readLock().lock();
694 return fromNullable(allImages.get(imageId));
696 lock.readLock().unlock();
701 public List<Image> getImages(Album parent) {
702 lock.readLock().lock();
704 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
706 lock.readLock().unlock();
711 public void moveUp(Image image) {
712 lock.writeLock().lock();
714 List<String> images = albumImages.get(image.getAlbum().getId());
715 int currentIndex = images.indexOf(image.getId());
716 if (currentIndex == 0) {
719 images.remove(image.getId());
720 images.add(currentIndex - 1, image.getId());
722 lock.writeLock().unlock();
727 public void moveDown(Image image) {
728 lock.writeLock().lock();
730 List<String> images = albumChildren.get(image.getAlbum().getId());
731 int currentIndex = images.indexOf(image.getId());
732 if (currentIndex == (images.size() - 1)) {
735 images.remove(image.getId());
736 images.add(currentIndex + 1, image.getId());
738 lock.writeLock().unlock();
743 // IMAGESTORE METHODS
747 public void storeImage(Image image) {
748 lock.writeLock().lock();
750 allImages.put(image.getId(), image);
751 albumImages.put(image.getAlbum().getId(), image.getId());
753 lock.writeLock().unlock();
758 public void removeImage(Image image) {
759 lock.writeLock().lock();
761 allImages.remove(image.getId());
762 albumImages.remove(image.getAlbum().getId(), image.getId());
764 lock.writeLock().unlock();
769 // PACKAGE-PRIVATE METHODS
773 * Returns whether the given post is known.
777 * @return {@code true} if the post is known, {@code false} otherwise
779 boolean isPostKnown(Post post) {
780 lock.readLock().lock();
782 return knownPosts.contains(post.getId());
784 lock.readLock().unlock();
789 * Sets whether the given post is known.
794 * {@code true} if the post is known, {@code false} otherwise
796 void setPostKnown(Post post, boolean known) {
797 lock.writeLock().lock();
800 knownPosts.add(post.getId());
802 knownPosts.remove(post.getId());
805 lock.writeLock().unlock();
813 /** Loads the known posts. */
814 private void loadKnownPosts() {
815 lock.writeLock().lock();
819 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
820 if (knownPostId == null) {
823 knownPosts.add(knownPostId);
826 lock.writeLock().unlock();
831 * Saves the known posts to the configuration.
833 * @throws DatabaseException
834 * if a configuration error occurs
836 private void saveKnownPosts() throws DatabaseException {
837 lock.readLock().lock();
840 for (String knownPostId : knownPosts) {
841 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
843 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
844 } catch (ConfigurationException ce1) {
845 throw new DatabaseException("Could not save database.", ce1);
847 lock.readLock().unlock();
852 * Returns all replies by the given Sone.
856 * @return The post replies of the Sone, sorted by time (newest first)
858 private Collection<PostReply> getRepliesFrom(String id) {
859 lock.readLock().lock();
861 if (sonePostReplies.containsKey(id)) {
862 return Collections.unmodifiableCollection(sonePostReplies.get(id));
864 return Collections.emptySet();
866 lock.readLock().unlock();
870 /** Loads the known post replies. */
871 private void loadKnownPostReplies() {
872 lock.writeLock().lock();
874 int replyCounter = 0;
876 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
877 if (knownReplyId == null) {
880 knownPostReplies.add(knownReplyId);
883 lock.writeLock().unlock();
888 * Saves the known post replies to the configuration.
890 * @throws DatabaseException
891 * if a configuration error occurs
893 private void saveKnownPostReplies() throws DatabaseException {
894 lock.readLock().lock();
896 int replyCounter = 0;
897 for (String knownReplyId : knownPostReplies) {
898 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
900 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
901 } catch (ConfigurationException ce1) {
902 throw new DatabaseException("Could not save database.", ce1);
904 lock.readLock().unlock();
908 private Function<String, Iterable<Album>> getAlbum() {
909 return new Function<String, Iterable<Album>>() {
911 public Iterable<Album> apply(String input) {
912 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
917 private Function<String, Iterable<Image>> getImage() {
918 return new Function<String, Iterable<Image>>() {
920 public Iterable<Image> apply(String input) {
921 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();
926 private static <T> Function<Optional<T>, Iterable<T>> unwrap() {
927 return new Function<Optional<T>, Iterable<T>>() {
929 public Iterable<T> apply(Optional<T> input) {
930 return (input == null) ? Collections.<T>emptyList() : input.asSet();