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 * Returns whether the given post is known.
317 * @return {@code true} if the post is known, {@code false} otherwise
320 public boolean isPostKnown(Post post) {
321 lock.readLock().lock();
323 return knownPosts.contains(post.getId());
325 lock.readLock().unlock();
330 * Sets whether the given post is known.
336 public void setPostKnown(Post post) {
337 lock.writeLock().lock();
339 knownPosts.add(post.getId());
341 lock.writeLock().unlock();
346 public void likePost(Post post, Sone localSone) {
347 lock.writeLock().lock();
349 likedPostsBySone.put(localSone.getId(), post.getId());
350 postLikingSones.put(post.getId(), localSone.getId());
352 lock.writeLock().unlock();
357 public void unlikePost(Post post, Sone localSone) {
358 lock.writeLock().lock();
360 likedPostsBySone.remove(localSone.getId(), post.getId());
361 postLikingSones.remove(post.getId(), localSone.getId());
363 lock.writeLock().unlock();
367 public boolean isLiked(Post post, Sone sone) {
368 lock.readLock().lock();
370 return likedPostsBySone.containsEntry(sone.getId(), post.getId());
372 lock.readLock().unlock();
377 public Set<Sone> getLikes(Post post) {
378 lock.readLock().lock();
380 return from(postLikingSones.get(post.getId())).transform(getSone()).transformAndConcat(this.<Sone>unwrap()).toSet();
382 lock.readLock().unlock();
391 public void storePost(Post post) {
392 checkNotNull(post, "post must not be null");
393 lock.writeLock().lock();
395 allPosts.put(post.getId(), post);
396 sonePosts.put(post.getSone().getId(), post);
397 if (post.getRecipientId().isPresent()) {
398 recipientPosts.put(post.getRecipientId().get(), post);
401 lock.writeLock().unlock();
406 public void removePost(Post post) {
407 checkNotNull(post, "post must not be null");
408 lock.writeLock().lock();
410 allPosts.remove(post.getId());
411 sonePosts.remove(post.getSone().getId(), post);
412 if (post.getRecipientId().isPresent()) {
413 recipientPosts.remove(post.getRecipientId().get(), post);
415 post.getSone().removePost(post);
417 lock.writeLock().unlock();
422 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
423 checkNotNull(sone, "sone must not be null");
424 /* verify that all posts are from the same Sone. */
425 for (Post post : posts) {
426 if (!sone.equals(post.getSone())) {
427 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
431 lock.writeLock().lock();
433 /* remove all posts by the Sone. */
434 sonePosts.removeAll(sone.getId());
435 for (Post post : posts) {
436 allPosts.remove(post.getId());
437 if (post.getRecipientId().isPresent()) {
438 recipientPosts.remove(post.getRecipientId().get(), post);
443 sonePosts.putAll(sone.getId(), posts);
444 for (Post post : posts) {
445 allPosts.put(post.getId(), post);
446 if (post.getRecipientId().isPresent()) {
447 recipientPosts.put(post.getRecipientId().get(), post);
451 lock.writeLock().unlock();
456 public void removePosts(Sone sone) {
457 checkNotNull(sone, "sone must not be null");
458 lock.writeLock().lock();
460 /* remove all posts by the Sone. */
461 sonePosts.removeAll(sone.getId());
462 for (Post post : sone.getPosts()) {
463 allPosts.remove(post.getId());
464 if (post.getRecipientId().isPresent()) {
465 recipientPosts.remove(post.getRecipientId().get(), post);
469 lock.writeLock().unlock();
474 // POSTREPLYPROVIDER METHODS
478 public Optional<PostReply> getPostReply(String id) {
479 lock.readLock().lock();
481 return fromNullable(allPostReplies.get(id));
483 lock.readLock().unlock();
488 public List<PostReply> getReplies(String postId) {
489 lock.readLock().lock();
491 if (!postReplies.containsKey(postId)) {
494 return new ArrayList<PostReply>(postReplies.get(postId));
496 lock.readLock().unlock();
501 public void likePostReply(PostReply postReply, Sone localSone) {
502 lock.writeLock().lock();
504 likedPostRepliesBySone.put(localSone.getId(), postReply.getId());
505 postReplyLikingSones.put(postReply.getId(), localSone.getId());
507 lock.writeLock().unlock();
512 public void unlikePostReply(PostReply postReply, Sone localSone) {
513 lock.writeLock().lock();
515 likedPostRepliesBySone.remove(localSone.getId(), postReply.getId());
516 postReplyLikingSones.remove(postReply.getId(), localSone.getId());
518 lock.writeLock().unlock();
523 public boolean isLiked(PostReply postReply, Sone sone) {
524 lock.readLock().lock();
526 return postReplyLikingSones.containsEntry(postReply.getId(), sone.getId());
528 lock.readLock().unlock();
533 public Set<Sone> getLikes(PostReply postReply) {
534 lock.readLock().lock();
536 return from(postReplyLikingSones.get(postReply.getId())).transform(getSone()).transformAndConcat(this.<Sone>unwrap()).toSet();
538 lock.readLock().unlock();
543 // POSTREPLYSTORE METHODS
547 * Returns whether the given post reply is known.
551 * @return {@code true} if the given post reply is known, {@code false}
554 public boolean isPostReplyKnown(PostReply postReply) {
555 lock.readLock().lock();
557 return knownPostReplies.contains(postReply.getId());
559 lock.readLock().unlock();
564 public void setPostReplyKnown(PostReply postReply) {
565 lock.writeLock().lock();
567 knownPostReplies.add(postReply.getId());
569 lock.writeLock().unlock();
574 public void storePostReply(PostReply postReply) {
575 lock.writeLock().lock();
577 allPostReplies.put(postReply.getId(), postReply);
578 postReplies.put(postReply.getPostId(), postReply);
580 lock.writeLock().unlock();
585 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
586 checkNotNull(sone, "sone must not be null");
587 /* verify that all posts are from the same Sone. */
588 for (PostReply postReply : postReplies) {
589 if (!sone.equals(postReply.getSone())) {
590 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
594 lock.writeLock().lock();
596 /* remove all post replies of the Sone. */
597 for (PostReply postReply : getRepliesFrom(sone.getId())) {
598 removePostReply(postReply);
600 for (PostReply postReply : postReplies) {
601 allPostReplies.put(postReply.getId(), postReply);
602 sonePostReplies.put(postReply.getSone().getId(), postReply);
603 this.postReplies.put(postReply.getPostId(), postReply);
606 lock.writeLock().unlock();
611 public void removePostReply(PostReply postReply) {
612 lock.writeLock().lock();
614 allPostReplies.remove(postReply.getId());
615 postReplies.remove(postReply.getPostId(), postReply);
617 lock.writeLock().unlock();
622 public void removePostReplies(Sone sone) {
623 checkNotNull(sone, "sone must not be null");
625 lock.writeLock().lock();
627 for (PostReply postReply : sone.getReplies()) {
628 removePostReply(postReply);
631 lock.writeLock().unlock();
636 // ALBUMPROVDER METHODS
640 public Optional<Album> getAlbum(String albumId) {
641 lock.readLock().lock();
643 return fromNullable(allAlbums.get(albumId));
645 lock.readLock().unlock();
650 public List<Album> getAlbums(Album parent) {
651 lock.readLock().lock();
653 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
655 lock.readLock().unlock();
660 public void moveUp(Album album) {
661 lock.writeLock().lock();
663 List<String> albums = albumChildren.get(album.getParent().getId());
664 int currentIndex = albums.indexOf(album.getId());
665 if (currentIndex == 0) {
668 albums.remove(album.getId());
669 albums.add(currentIndex - 1, album.getId());
671 lock.writeLock().unlock();
676 public void moveDown(Album album) {
677 lock.writeLock().lock();
679 List<String> albums = albumChildren.get(album.getParent().getId());
680 int currentIndex = albums.indexOf(album.getId());
681 if (currentIndex == (albums.size() - 1)) {
684 albums.remove(album.getId());
685 albums.add(currentIndex + 1, album.getId());
687 lock.writeLock().unlock();
692 // ALBUMSTORE METHODS
696 public void storeAlbum(Album album) {
697 lock.writeLock().lock();
699 allAlbums.put(album.getId(), album);
700 if (!album.isRoot()) {
701 albumChildren.put(album.getParent().getId(), album.getId());
704 lock.writeLock().unlock();
709 public void removeAlbum(Album album) {
710 lock.writeLock().lock();
712 allAlbums.remove(album.getId());
713 albumChildren.remove(album.getParent().getId(), album.getId());
715 lock.writeLock().unlock();
720 // IMAGEPROVIDER METHODS
724 public Optional<Image> getImage(String imageId) {
725 lock.readLock().lock();
727 return fromNullable(allImages.get(imageId));
729 lock.readLock().unlock();
734 public List<Image> getImages(Album parent) {
735 lock.readLock().lock();
737 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
739 lock.readLock().unlock();
744 public void moveUp(Image image) {
745 lock.writeLock().lock();
747 List<String> images = albumImages.get(image.getAlbum().getId());
748 int currentIndex = images.indexOf(image.getId());
749 if (currentIndex == 0) {
752 images.remove(image.getId());
753 images.add(currentIndex - 1, image.getId());
755 lock.writeLock().unlock();
760 public void moveDown(Image image) {
761 lock.writeLock().lock();
763 List<String> images = albumChildren.get(image.getAlbum().getId());
764 int currentIndex = images.indexOf(image.getId());
765 if (currentIndex == (images.size() - 1)) {
768 images.remove(image.getId());
769 images.add(currentIndex + 1, image.getId());
771 lock.writeLock().unlock();
776 // IMAGESTORE METHODS
780 public void storeImage(Image image) {
781 lock.writeLock().lock();
783 allImages.put(image.getId(), image);
784 albumImages.put(image.getAlbum().getId(), image.getId());
786 lock.writeLock().unlock();
791 public void removeImage(Image image) {
792 lock.writeLock().lock();
794 allImages.remove(image.getId());
795 albumImages.remove(image.getAlbum().getId(), image.getId());
797 lock.writeLock().unlock();
805 /** Loads the known posts. */
806 private void loadKnownPosts() {
807 lock.writeLock().lock();
811 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
812 if (knownPostId == null) {
815 knownPosts.add(knownPostId);
818 lock.writeLock().unlock();
823 * Saves the known posts to the configuration.
825 * @throws DatabaseException
826 * if a configuration error occurs
828 private void saveKnownPosts() throws DatabaseException {
829 lock.readLock().lock();
832 for (String knownPostId : knownPosts) {
833 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
835 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
836 } catch (ConfigurationException ce1) {
837 throw new DatabaseException("Could not save database.", ce1);
839 lock.readLock().unlock();
844 * Returns all replies by the given Sone.
848 * @return The post replies of the Sone, sorted by time (newest first)
850 private Collection<PostReply> getRepliesFrom(String id) {
851 lock.readLock().lock();
853 if (sonePostReplies.containsKey(id)) {
854 return Collections.unmodifiableCollection(sonePostReplies.get(id));
856 return Collections.emptySet();
858 lock.readLock().unlock();
862 /** Loads the known post replies. */
863 private void loadKnownPostReplies() {
864 lock.writeLock().lock();
866 int replyCounter = 0;
868 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
869 if (knownReplyId == null) {
872 knownPostReplies.add(knownReplyId);
875 lock.writeLock().unlock();
880 * Saves the known post replies to the configuration.
882 * @throws DatabaseException
883 * if a configuration error occurs
885 private void saveKnownPostReplies() throws DatabaseException {
886 lock.readLock().lock();
888 int replyCounter = 0;
889 for (String knownReplyId : knownPostReplies) {
890 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
892 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
893 } catch (ConfigurationException ce1) {
894 throw new DatabaseException("Could not save database.", ce1);
896 lock.readLock().unlock();
900 private Function<String, Iterable<Album>> getAlbum() {
901 return new Function<String, Iterable<Album>>() {
903 public Iterable<Album> apply(String input) {
904 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
909 private Function<String, Iterable<Image>> getImage() {
910 return new Function<String, Iterable<Image>>() {
912 public Iterable<Image> apply(String input) {
913 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();
918 private static <T> Function<Optional<T>, Iterable<T>> unwrap() {
919 return new Function<Optional<T>, Iterable<T>>() {
921 public Iterable<T> apply(Optional<T> input) {
922 return (input == null) ? Collections.<T>emptyList() : input.asSet();