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>();
99 /** Replies sorted by Sone. */
100 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
103 public int compare(String leftString, String rightString) {
104 return leftString.compareTo(rightString);
106 }, PostReply.TIME_COMPARATOR);
108 /** Replies by post. */
109 private final SortedSetMultimap<String, PostReply> postReplies = TreeMultimap.create(new Comparator<String>() {
112 public int compare(String leftString, String rightString) {
113 return leftString.compareTo(rightString);
115 }, PostReply.TIME_COMPARATOR);
117 /** Whether post replies are known. */
118 private final Set<String> knownPostReplies = new HashSet<String>();
120 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
121 private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
122 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
124 private final Map<String, Image> allImages = new HashMap<String, Image>();
127 * Creates a new memory database.
129 * @param configuration
130 * The configuration for loading and saving elements
133 public MemoryDatabase(Configuration configuration) {
134 this.configuration = configuration;
142 public void save() throws DatabaseException {
144 saveKnownPostReplies();
152 protected void doStart() {
154 loadKnownPostReplies();
159 protected void doStop() {
163 } catch (DatabaseException de1) {
169 public Optional<Identity> getIdentity(String identityId) {
170 lock.readLock().lock();
172 return fromNullable(identities.get(identityId));
174 lock.readLock().unlock();
179 public Function<String, Optional<Sone>> getSone() {
180 return new Function<String, Optional<Sone>>() {
182 public Optional<Sone> apply(String soneId) {
183 return (soneId == null) ? Optional.<Sone>absent() : getSone(soneId);
189 public Optional<Sone> getSone(String soneId) {
190 lock.readLock().lock();
192 return fromNullable(sones.get(soneId));
194 lock.readLock().unlock();
199 public Collection<Sone> getSones() {
200 lock.readLock().lock();
202 return Collections.unmodifiableCollection(sones.values());
204 lock.readLock().unlock();
209 public Collection<Sone> getLocalSones() {
210 lock.readLock().lock();
212 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
214 lock.readLock().unlock();
219 public Collection<Sone> getRemoteSones() {
220 lock.readLock().lock();
222 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
224 lock.readLock().unlock();
229 public SoneBuilder newSoneBuilder() {
230 return new DefaultSoneBuilder(this) {
232 public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
233 Sone sone = super.build(soneCreated);
234 lock.writeLock().lock();
236 sones.put(sone.getId(), sone);
238 lock.writeLock().unlock();
246 // POSTPROVIDER METHODS
250 public Function<String, Optional<Post>> getPost() {
251 return new Function<String, Optional<Post>>() {
253 public Optional<Post> apply(String postId) {
254 return (postId == null) ? Optional.<Post>absent() : getPost(postId);
260 public Optional<Post> getPost(String postId) {
261 lock.readLock().lock();
263 return fromNullable(allPosts.get(postId));
265 lock.readLock().unlock();
270 public Collection<Post> getPosts(String soneId) {
271 lock.readLock().lock();
273 return new HashSet<Post>(sonePosts.get(soneId));
275 lock.readLock().unlock();
280 public Collection<Post> getDirectedPosts(String recipientId) {
281 lock.readLock().lock();
283 Collection<Post> posts = recipientPosts.get(recipientId);
284 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
286 lock.readLock().unlock();
291 public void likePost(Post post, Sone localSone) {
292 lock.writeLock().lock();
294 likedPostsBySone.put(localSone.getId(), post.getId());
295 postLikingSones.put(post.getId(), localSone.getId());
297 lock.writeLock().unlock();
302 public void unlikePost(Post post, Sone localSone) {
303 lock.writeLock().lock();
305 likedPostsBySone.remove(localSone.getId(), post.getId());
306 postLikingSones.remove(post.getId(), localSone.getId());
308 lock.writeLock().unlock();
312 public boolean isLiked(Post post, Sone sone) {
313 lock.readLock().lock();
315 return likedPostsBySone.containsEntry(sone.getId(), post.getId());
317 lock.readLock().unlock();
322 public Set<Sone> getLikes(Post post) {
323 lock.readLock().lock();
325 return from(postLikingSones.get(post.getId())).transform(getSone()).transformAndConcat(this.<Sone>unwrap()).toSet();
327 lock.readLock().unlock();
336 public void storePost(Post post) {
337 checkNotNull(post, "post must not be null");
338 lock.writeLock().lock();
340 allPosts.put(post.getId(), post);
341 sonePosts.put(post.getSone().getId(), post);
342 if (post.getRecipientId().isPresent()) {
343 recipientPosts.put(post.getRecipientId().get(), post);
346 lock.writeLock().unlock();
351 public void removePost(Post post) {
352 checkNotNull(post, "post must not be null");
353 lock.writeLock().lock();
355 allPosts.remove(post.getId());
356 sonePosts.remove(post.getSone().getId(), post);
357 if (post.getRecipientId().isPresent()) {
358 recipientPosts.remove(post.getRecipientId().get(), post);
360 post.getSone().removePost(post);
362 lock.writeLock().unlock();
367 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
368 checkNotNull(sone, "sone must not be null");
369 /* verify that all posts are from the same Sone. */
370 for (Post post : posts) {
371 if (!sone.equals(post.getSone())) {
372 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
376 lock.writeLock().lock();
378 /* remove all posts by the Sone. */
379 sonePosts.removeAll(sone.getId());
380 for (Post post : posts) {
381 allPosts.remove(post.getId());
382 if (post.getRecipientId().isPresent()) {
383 recipientPosts.remove(post.getRecipientId().get(), post);
388 sonePosts.putAll(sone.getId(), posts);
389 for (Post post : posts) {
390 allPosts.put(post.getId(), post);
391 if (post.getRecipientId().isPresent()) {
392 recipientPosts.put(post.getRecipientId().get(), post);
396 lock.writeLock().unlock();
401 public void removePosts(Sone sone) {
402 checkNotNull(sone, "sone must not be null");
403 lock.writeLock().lock();
405 /* remove all posts by the Sone. */
406 sonePosts.removeAll(sone.getId());
407 for (Post post : sone.getPosts()) {
408 allPosts.remove(post.getId());
409 if (post.getRecipientId().isPresent()) {
410 recipientPosts.remove(post.getRecipientId().get(), post);
414 lock.writeLock().unlock();
419 // POSTREPLYPROVIDER METHODS
423 public Optional<PostReply> getPostReply(String id) {
424 lock.readLock().lock();
426 return fromNullable(allPostReplies.get(id));
428 lock.readLock().unlock();
433 public List<PostReply> getReplies(String postId) {
434 lock.readLock().lock();
436 if (!postReplies.containsKey(postId)) {
439 return new ArrayList<PostReply>(postReplies.get(postId));
441 lock.readLock().unlock();
446 // POSTREPLYSTORE METHODS
450 * Returns whether the given post reply is known.
454 * @return {@code true} if the given post reply is known, {@code false}
457 public boolean isPostReplyKnown(PostReply postReply) {
458 lock.readLock().lock();
460 return knownPostReplies.contains(postReply.getId());
462 lock.readLock().unlock();
467 public void setPostReplyKnown(PostReply postReply) {
468 lock.writeLock().lock();
470 knownPostReplies.add(postReply.getId());
472 lock.writeLock().unlock();
477 public void storePostReply(PostReply postReply) {
478 lock.writeLock().lock();
480 allPostReplies.put(postReply.getId(), postReply);
481 postReplies.put(postReply.getPostId(), postReply);
483 lock.writeLock().unlock();
488 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
489 checkNotNull(sone, "sone must not be null");
490 /* verify that all posts are from the same Sone. */
491 for (PostReply postReply : postReplies) {
492 if (!sone.equals(postReply.getSone())) {
493 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
497 lock.writeLock().lock();
499 /* remove all post replies of the Sone. */
500 for (PostReply postReply : getRepliesFrom(sone.getId())) {
501 removePostReply(postReply);
503 for (PostReply postReply : postReplies) {
504 allPostReplies.put(postReply.getId(), postReply);
505 sonePostReplies.put(postReply.getSone().getId(), postReply);
506 this.postReplies.put(postReply.getPostId(), postReply);
509 lock.writeLock().unlock();
514 public void removePostReply(PostReply postReply) {
515 lock.writeLock().lock();
517 allPostReplies.remove(postReply.getId());
518 postReplies.remove(postReply.getPostId(), postReply);
520 lock.writeLock().unlock();
525 public void removePostReplies(Sone sone) {
526 checkNotNull(sone, "sone must not be null");
528 lock.writeLock().lock();
530 for (PostReply postReply : sone.getReplies()) {
531 removePostReply(postReply);
534 lock.writeLock().unlock();
539 // ALBUMPROVDER METHODS
543 public Optional<Album> getAlbum(String albumId) {
544 lock.readLock().lock();
546 return fromNullable(allAlbums.get(albumId));
548 lock.readLock().unlock();
553 public List<Album> getAlbums(Album parent) {
554 lock.readLock().lock();
556 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
558 lock.readLock().unlock();
563 public void moveUp(Album album) {
564 lock.writeLock().lock();
566 List<String> albums = albumChildren.get(album.getParent().getId());
567 int currentIndex = albums.indexOf(album.getId());
568 if (currentIndex == 0) {
571 albums.remove(album.getId());
572 albums.add(currentIndex - 1, album.getId());
574 lock.writeLock().unlock();
579 public void moveDown(Album album) {
580 lock.writeLock().lock();
582 List<String> albums = albumChildren.get(album.getParent().getId());
583 int currentIndex = albums.indexOf(album.getId());
584 if (currentIndex == (albums.size() - 1)) {
587 albums.remove(album.getId());
588 albums.add(currentIndex + 1, album.getId());
590 lock.writeLock().unlock();
595 // ALBUMSTORE METHODS
599 public void storeAlbum(Album album) {
600 lock.writeLock().lock();
602 allAlbums.put(album.getId(), album);
603 if (!album.isRoot()) {
604 albumChildren.put(album.getParent().getId(), album.getId());
607 lock.writeLock().unlock();
612 public void removeAlbum(Album album) {
613 lock.writeLock().lock();
615 allAlbums.remove(album.getId());
616 albumChildren.remove(album.getParent().getId(), album.getId());
618 lock.writeLock().unlock();
623 // IMAGEPROVIDER METHODS
627 public Optional<Image> getImage(String imageId) {
628 lock.readLock().lock();
630 return fromNullable(allImages.get(imageId));
632 lock.readLock().unlock();
637 public List<Image> getImages(Album parent) {
638 lock.readLock().lock();
640 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
642 lock.readLock().unlock();
647 public void moveUp(Image image) {
648 lock.writeLock().lock();
650 List<String> images = albumImages.get(image.getAlbum().getId());
651 int currentIndex = images.indexOf(image.getId());
652 if (currentIndex == 0) {
655 images.remove(image.getId());
656 images.add(currentIndex - 1, image.getId());
658 lock.writeLock().unlock();
663 public void moveDown(Image image) {
664 lock.writeLock().lock();
666 List<String> images = albumChildren.get(image.getAlbum().getId());
667 int currentIndex = images.indexOf(image.getId());
668 if (currentIndex == (images.size() - 1)) {
671 images.remove(image.getId());
672 images.add(currentIndex + 1, image.getId());
674 lock.writeLock().unlock();
679 // IMAGESTORE METHODS
683 public void storeImage(Image image) {
684 lock.writeLock().lock();
686 allImages.put(image.getId(), image);
687 albumImages.put(image.getAlbum().getId(), image.getId());
689 lock.writeLock().unlock();
694 public void removeImage(Image image) {
695 lock.writeLock().lock();
697 allImages.remove(image.getId());
698 albumImages.remove(image.getAlbum().getId(), image.getId());
700 lock.writeLock().unlock();
705 // PACKAGE-PRIVATE METHODS
709 * Returns whether the given post is known.
713 * @return {@code true} if the post is known, {@code false} otherwise
715 boolean isPostKnown(Post post) {
716 lock.readLock().lock();
718 return knownPosts.contains(post.getId());
720 lock.readLock().unlock();
725 * Sets whether the given post is known.
730 * {@code true} if the post is known, {@code false} otherwise
732 void setPostKnown(Post post, boolean known) {
733 lock.writeLock().lock();
736 knownPosts.add(post.getId());
738 knownPosts.remove(post.getId());
741 lock.writeLock().unlock();
749 /** Loads the known posts. */
750 private void loadKnownPosts() {
751 lock.writeLock().lock();
755 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
756 if (knownPostId == null) {
759 knownPosts.add(knownPostId);
762 lock.writeLock().unlock();
767 * Saves the known posts to the configuration.
769 * @throws DatabaseException
770 * if a configuration error occurs
772 private void saveKnownPosts() throws DatabaseException {
773 lock.readLock().lock();
776 for (String knownPostId : knownPosts) {
777 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
779 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
780 } catch (ConfigurationException ce1) {
781 throw new DatabaseException("Could not save database.", ce1);
783 lock.readLock().unlock();
788 * Returns all replies by the given Sone.
792 * @return The post replies of the Sone, sorted by time (newest first)
794 private Collection<PostReply> getRepliesFrom(String id) {
795 lock.readLock().lock();
797 if (sonePostReplies.containsKey(id)) {
798 return Collections.unmodifiableCollection(sonePostReplies.get(id));
800 return Collections.emptySet();
802 lock.readLock().unlock();
806 /** Loads the known post replies. */
807 private void loadKnownPostReplies() {
808 lock.writeLock().lock();
810 int replyCounter = 0;
812 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
813 if (knownReplyId == null) {
816 knownPostReplies.add(knownReplyId);
819 lock.writeLock().unlock();
824 * Saves the known post replies to the configuration.
826 * @throws DatabaseException
827 * if a configuration error occurs
829 private void saveKnownPostReplies() throws DatabaseException {
830 lock.readLock().lock();
832 int replyCounter = 0;
833 for (String knownReplyId : knownPostReplies) {
834 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
836 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
837 } catch (ConfigurationException ce1) {
838 throw new DatabaseException("Could not save database.", ce1);
840 lock.readLock().unlock();
844 private Function<String, Iterable<Album>> getAlbum() {
845 return new Function<String, Iterable<Album>>() {
847 public Iterable<Album> apply(String input) {
848 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
853 private Function<String, Iterable<Image>> getImage() {
854 return new Function<String, Iterable<Image>>() {
856 public Iterable<Image> apply(String input) {
857 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();
862 private static <T> Function<Optional<T>, Iterable<T>> unwrap() {
863 return new Function<Optional<T>, Iterable<T>>() {
865 public Iterable<T> apply(Optional<T> input) {
866 return (input == null) ? Collections.<T>emptyList() : input.asSet();