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 Function<String, Optional<Sone>> getSone() {
182 return new Function<String, Optional<Sone>>() {
184 public Optional<Sone> apply(String soneId) {
185 return (soneId == null) ? Optional.<Sone>absent() : getSone(soneId);
191 public Optional<Sone> getSone(String soneId) {
192 lock.readLock().lock();
194 return fromNullable(sones.get(soneId));
196 lock.readLock().unlock();
201 public Collection<Sone> getSones() {
202 lock.readLock().lock();
204 return Collections.unmodifiableCollection(sones.values());
206 lock.readLock().unlock();
211 public Collection<Sone> getLocalSones() {
212 lock.readLock().lock();
214 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
216 lock.readLock().unlock();
221 public Collection<Sone> getRemoteSones() {
222 lock.readLock().lock();
224 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
226 lock.readLock().unlock();
231 public SoneBuilder newSoneBuilder() {
232 return new DefaultSoneBuilder(this) {
234 public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
235 Sone sone = super.build(soneCreated);
236 lock.writeLock().lock();
238 sones.put(sone.getId(), sone);
240 lock.writeLock().unlock();
248 // POSTPROVIDER METHODS
252 public Function<String, Optional<Post>> getPost() {
253 return new Function<String, Optional<Post>>() {
255 public Optional<Post> apply(String postId) {
256 return (postId == null) ? Optional.<Post>absent() : getPost(postId);
262 public Optional<Post> getPost(String postId) {
263 lock.readLock().lock();
265 return fromNullable(allPosts.get(postId));
267 lock.readLock().unlock();
272 public Collection<Post> getPosts(String soneId) {
273 lock.readLock().lock();
275 return new HashSet<Post>(sonePosts.get(soneId));
277 lock.readLock().unlock();
282 public Collection<Post> getDirectedPosts(String recipientId) {
283 lock.readLock().lock();
285 Collection<Post> posts = recipientPosts.get(recipientId);
286 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
288 lock.readLock().unlock();
293 public void likePost(Post post, Sone localSone) {
294 lock.writeLock().lock();
296 likedPostsBySone.put(localSone.getId(), post.getId());
297 postLikingSones.put(post.getId(), localSone.getId());
299 lock.writeLock().unlock();
304 public void unlikePost(Post post, Sone localSone) {
305 lock.writeLock().lock();
307 likedPostsBySone.remove(localSone.getId(), post.getId());
308 postLikingSones.remove(post.getId(), localSone.getId());
310 lock.writeLock().unlock();
314 public boolean isLiked(Post post, Sone sone) {
315 lock.readLock().lock();
317 return likedPostsBySone.containsEntry(sone.getId(), post.getId());
319 lock.readLock().unlock();
324 public Set<Sone> getLikes(Post post) {
325 lock.readLock().lock();
327 return from(postLikingSones.get(post.getId())).transform(getSone()).transformAndConcat(this.<Sone>unwrap()).toSet();
329 lock.readLock().unlock();
338 public void storePost(Post post) {
339 checkNotNull(post, "post must not be null");
340 lock.writeLock().lock();
342 allPosts.put(post.getId(), post);
343 sonePosts.put(post.getSone().getId(), post);
344 if (post.getRecipientId().isPresent()) {
345 recipientPosts.put(post.getRecipientId().get(), post);
348 lock.writeLock().unlock();
353 public void removePost(Post post) {
354 checkNotNull(post, "post must not be null");
355 lock.writeLock().lock();
357 allPosts.remove(post.getId());
358 sonePosts.remove(post.getSone().getId(), post);
359 if (post.getRecipientId().isPresent()) {
360 recipientPosts.remove(post.getRecipientId().get(), post);
362 post.getSone().removePost(post);
364 lock.writeLock().unlock();
369 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
370 checkNotNull(sone, "sone must not be null");
371 /* verify that all posts are from the same Sone. */
372 for (Post post : posts) {
373 if (!sone.equals(post.getSone())) {
374 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
378 lock.writeLock().lock();
380 /* remove all posts by the Sone. */
381 sonePosts.removeAll(sone.getId());
382 for (Post post : posts) {
383 allPosts.remove(post.getId());
384 if (post.getRecipientId().isPresent()) {
385 recipientPosts.remove(post.getRecipientId().get(), post);
390 sonePosts.putAll(sone.getId(), posts);
391 for (Post post : posts) {
392 allPosts.put(post.getId(), post);
393 if (post.getRecipientId().isPresent()) {
394 recipientPosts.put(post.getRecipientId().get(), post);
398 lock.writeLock().unlock();
403 public void removePosts(Sone sone) {
404 checkNotNull(sone, "sone must not be null");
405 lock.writeLock().lock();
407 /* remove all posts by the Sone. */
408 sonePosts.removeAll(sone.getId());
409 for (Post post : sone.getPosts()) {
410 allPosts.remove(post.getId());
411 if (post.getRecipientId().isPresent()) {
412 recipientPosts.remove(post.getRecipientId().get(), post);
416 lock.writeLock().unlock();
421 // POSTREPLYPROVIDER METHODS
425 public Optional<PostReply> getPostReply(String id) {
426 lock.readLock().lock();
428 return fromNullable(allPostReplies.get(id));
430 lock.readLock().unlock();
435 public List<PostReply> getReplies(String postId) {
436 lock.readLock().lock();
438 if (!postReplies.containsKey(postId)) {
441 return new ArrayList<PostReply>(postReplies.get(postId));
443 lock.readLock().unlock();
448 public void likePostReply(PostReply postReply, Sone localSone) {
449 lock.writeLock().lock();
451 likedPostRepliesBySone.put(localSone.getId(), postReply.getId());
452 postReplyLikingSones.put(postReply.getId(), localSone.getId());
454 lock.writeLock().unlock();
459 public void unlikePostReply(PostReply postReply, Sone localSone) {
460 lock.writeLock().lock();
462 likedPostRepliesBySone.remove(localSone.getId(), postReply.getId());
463 postReplyLikingSones.remove(postReply.getId(), localSone.getId());
465 lock.writeLock().unlock();
470 public boolean isLiked(PostReply postReply, Sone sone) {
471 lock.readLock().lock();
473 return postReplyLikingSones.containsEntry(postReply.getId(), sone.getId());
475 lock.readLock().unlock();
480 public Set<Sone> getLikes(PostReply postReply) {
481 lock.readLock().lock();
483 return from(postReplyLikingSones.get(postReply.getId())).transform(getSone()).transformAndConcat(this.<Sone>unwrap()).toSet();
485 lock.readLock().unlock();
490 // POSTREPLYSTORE METHODS
494 * Returns whether the given post reply is known.
498 * @return {@code true} if the given post reply is known, {@code false}
501 public boolean isPostReplyKnown(PostReply postReply) {
502 lock.readLock().lock();
504 return knownPostReplies.contains(postReply.getId());
506 lock.readLock().unlock();
511 public void setPostReplyKnown(PostReply postReply) {
512 lock.writeLock().lock();
514 knownPostReplies.add(postReply.getId());
516 lock.writeLock().unlock();
521 public void storePostReply(PostReply postReply) {
522 lock.writeLock().lock();
524 allPostReplies.put(postReply.getId(), postReply);
525 postReplies.put(postReply.getPostId(), postReply);
527 lock.writeLock().unlock();
532 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
533 checkNotNull(sone, "sone must not be null");
534 /* verify that all posts are from the same Sone. */
535 for (PostReply postReply : postReplies) {
536 if (!sone.equals(postReply.getSone())) {
537 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
541 lock.writeLock().lock();
543 /* remove all post replies of the Sone. */
544 for (PostReply postReply : getRepliesFrom(sone.getId())) {
545 removePostReply(postReply);
547 for (PostReply postReply : postReplies) {
548 allPostReplies.put(postReply.getId(), postReply);
549 sonePostReplies.put(postReply.getSone().getId(), postReply);
550 this.postReplies.put(postReply.getPostId(), postReply);
553 lock.writeLock().unlock();
558 public void removePostReply(PostReply postReply) {
559 lock.writeLock().lock();
561 allPostReplies.remove(postReply.getId());
562 postReplies.remove(postReply.getPostId(), postReply);
564 lock.writeLock().unlock();
569 public void removePostReplies(Sone sone) {
570 checkNotNull(sone, "sone must not be null");
572 lock.writeLock().lock();
574 for (PostReply postReply : sone.getReplies()) {
575 removePostReply(postReply);
578 lock.writeLock().unlock();
583 // ALBUMPROVDER METHODS
587 public Optional<Album> getAlbum(String albumId) {
588 lock.readLock().lock();
590 return fromNullable(allAlbums.get(albumId));
592 lock.readLock().unlock();
597 public List<Album> getAlbums(Album parent) {
598 lock.readLock().lock();
600 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
602 lock.readLock().unlock();
607 public void moveUp(Album album) {
608 lock.writeLock().lock();
610 List<String> albums = albumChildren.get(album.getParent().getId());
611 int currentIndex = albums.indexOf(album.getId());
612 if (currentIndex == 0) {
615 albums.remove(album.getId());
616 albums.add(currentIndex - 1, album.getId());
618 lock.writeLock().unlock();
623 public void moveDown(Album album) {
624 lock.writeLock().lock();
626 List<String> albums = albumChildren.get(album.getParent().getId());
627 int currentIndex = albums.indexOf(album.getId());
628 if (currentIndex == (albums.size() - 1)) {
631 albums.remove(album.getId());
632 albums.add(currentIndex + 1, album.getId());
634 lock.writeLock().unlock();
639 // ALBUMSTORE METHODS
643 public void storeAlbum(Album album) {
644 lock.writeLock().lock();
646 allAlbums.put(album.getId(), album);
647 if (!album.isRoot()) {
648 albumChildren.put(album.getParent().getId(), album.getId());
651 lock.writeLock().unlock();
656 public void removeAlbum(Album album) {
657 lock.writeLock().lock();
659 allAlbums.remove(album.getId());
660 albumChildren.remove(album.getParent().getId(), album.getId());
662 lock.writeLock().unlock();
667 // IMAGEPROVIDER METHODS
671 public Optional<Image> getImage(String imageId) {
672 lock.readLock().lock();
674 return fromNullable(allImages.get(imageId));
676 lock.readLock().unlock();
681 public List<Image> getImages(Album parent) {
682 lock.readLock().lock();
684 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
686 lock.readLock().unlock();
691 public void moveUp(Image image) {
692 lock.writeLock().lock();
694 List<String> images = albumImages.get(image.getAlbum().getId());
695 int currentIndex = images.indexOf(image.getId());
696 if (currentIndex == 0) {
699 images.remove(image.getId());
700 images.add(currentIndex - 1, image.getId());
702 lock.writeLock().unlock();
707 public void moveDown(Image image) {
708 lock.writeLock().lock();
710 List<String> images = albumChildren.get(image.getAlbum().getId());
711 int currentIndex = images.indexOf(image.getId());
712 if (currentIndex == (images.size() - 1)) {
715 images.remove(image.getId());
716 images.add(currentIndex + 1, image.getId());
718 lock.writeLock().unlock();
723 // IMAGESTORE METHODS
727 public void storeImage(Image image) {
728 lock.writeLock().lock();
730 allImages.put(image.getId(), image);
731 albumImages.put(image.getAlbum().getId(), image.getId());
733 lock.writeLock().unlock();
738 public void removeImage(Image image) {
739 lock.writeLock().lock();
741 allImages.remove(image.getId());
742 albumImages.remove(image.getAlbum().getId(), image.getId());
744 lock.writeLock().unlock();
749 // PACKAGE-PRIVATE METHODS
753 * Returns whether the given post is known.
757 * @return {@code true} if the post is known, {@code false} otherwise
759 boolean isPostKnown(Post post) {
760 lock.readLock().lock();
762 return knownPosts.contains(post.getId());
764 lock.readLock().unlock();
769 * Sets whether the given post is known.
774 * {@code true} if the post is known, {@code false} otherwise
776 void setPostKnown(Post post, boolean known) {
777 lock.writeLock().lock();
780 knownPosts.add(post.getId());
782 knownPosts.remove(post.getId());
785 lock.writeLock().unlock();
793 /** Loads the known posts. */
794 private void loadKnownPosts() {
795 lock.writeLock().lock();
799 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
800 if (knownPostId == null) {
803 knownPosts.add(knownPostId);
806 lock.writeLock().unlock();
811 * Saves the known posts to the configuration.
813 * @throws DatabaseException
814 * if a configuration error occurs
816 private void saveKnownPosts() throws DatabaseException {
817 lock.readLock().lock();
820 for (String knownPostId : knownPosts) {
821 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
823 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
824 } catch (ConfigurationException ce1) {
825 throw new DatabaseException("Could not save database.", ce1);
827 lock.readLock().unlock();
832 * Returns all replies by the given Sone.
836 * @return The post replies of the Sone, sorted by time (newest first)
838 private Collection<PostReply> getRepliesFrom(String id) {
839 lock.readLock().lock();
841 if (sonePostReplies.containsKey(id)) {
842 return Collections.unmodifiableCollection(sonePostReplies.get(id));
844 return Collections.emptySet();
846 lock.readLock().unlock();
850 /** Loads the known post replies. */
851 private void loadKnownPostReplies() {
852 lock.writeLock().lock();
854 int replyCounter = 0;
856 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
857 if (knownReplyId == null) {
860 knownPostReplies.add(knownReplyId);
863 lock.writeLock().unlock();
868 * Saves the known post replies to the configuration.
870 * @throws DatabaseException
871 * if a configuration error occurs
873 private void saveKnownPostReplies() throws DatabaseException {
874 lock.readLock().lock();
876 int replyCounter = 0;
877 for (String knownReplyId : knownPostReplies) {
878 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
880 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
881 } catch (ConfigurationException ce1) {
882 throw new DatabaseException("Could not save database.", ce1);
884 lock.readLock().unlock();
888 private Function<String, Iterable<Album>> getAlbum() {
889 return new Function<String, Iterable<Album>>() {
891 public Iterable<Album> apply(String input) {
892 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
897 private Function<String, Iterable<Image>> getImage() {
898 return new Function<String, Iterable<Image>>() {
900 public Iterable<Image> apply(String input) {
901 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();
906 private static <T> Function<Optional<T>, Iterable<T>> unwrap() {
907 return new Function<Optional<T>, Iterable<T>>() {
909 public Iterable<T> apply(Optional<T> input) {
910 return (input == null) ? Collections.<T>emptyList() : input.asSet();