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.SortedSet;
37 import java.util.TreeSet;
38 import java.util.concurrent.locks.ReadWriteLock;
39 import java.util.concurrent.locks.ReentrantReadWriteLock;
41 import net.pterodactylus.sone.data.Album;
42 import net.pterodactylus.sone.data.Image;
43 import net.pterodactylus.sone.data.Post;
44 import net.pterodactylus.sone.data.PostReply;
45 import net.pterodactylus.sone.data.Reply;
46 import net.pterodactylus.sone.data.Sone;
47 import net.pterodactylus.sone.database.Database;
48 import net.pterodactylus.sone.database.DatabaseException;
49 import net.pterodactylus.sone.database.PostDatabase;
50 import net.pterodactylus.sone.database.SoneBuilder;
51 import net.pterodactylus.sone.freenet.wot.Identity;
52 import net.pterodactylus.util.config.Configuration;
53 import net.pterodactylus.util.config.ConfigurationException;
55 import com.google.common.base.Function;
56 import com.google.common.base.Optional;
57 import com.google.common.collect.ArrayListMultimap;
58 import com.google.common.collect.ListMultimap;
59 import com.google.common.collect.Maps;
60 import com.google.common.collect.SortedSetMultimap;
61 import com.google.common.collect.TreeMultimap;
62 import com.google.common.util.concurrent.AbstractService;
63 import com.google.inject.Inject;
66 * Memory-based {@link PostDatabase} implementation.
68 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
70 public class MemoryDatabase extends AbstractService implements Database {
73 private final ReadWriteLock lock = new ReentrantReadWriteLock();
75 /** The configuration. */
76 private final Configuration configuration;
78 private final Map<String, Identity> identities = Maps.newHashMap();
79 private final Map<String, Sone> sones = new HashMap<String, Sone>();
81 /** All posts by their ID. */
82 private final Map<String, Post> allPosts = new HashMap<String, Post>();
84 /** All posts by their Sones. */
85 private final Map<String, Collection<Post>> sonePosts = new HashMap<String, Collection<Post>>();
87 /** All posts by their recipient. */
88 private final Map<String, Collection<Post>> recipientPosts = new HashMap<String, Collection<Post>>();
90 /** Whether posts are known. */
91 private final Set<String> knownPosts = new HashSet<String>();
93 /** All post replies by their ID. */
94 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
96 /** Replies sorted by Sone. */
97 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
100 public int compare(String leftString, String rightString) {
101 return leftString.compareTo(rightString);
103 }, PostReply.TIME_COMPARATOR);
105 /** Replies by post. */
106 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
108 /** Whether post replies are known. */
109 private final Set<String> knownPostReplies = new HashSet<String>();
111 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
112 private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
113 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
115 private final Map<String, Image> allImages = new HashMap<String, Image>();
118 * Creates a new memory database.
120 * @param configuration
121 * The configuration for loading and saving elements
124 public MemoryDatabase(Configuration configuration) {
125 this.configuration = configuration;
133 public void save() throws DatabaseException {
135 saveKnownPostReplies();
143 protected void doStart() {
145 loadKnownPostReplies();
150 protected void doStop() {
154 } catch (DatabaseException de1) {
160 public Optional<Identity> getIdentity(String identityId) {
161 lock.readLock().lock();
163 return fromNullable(identities.get(identityId));
165 lock.readLock().unlock();
170 public Optional<Sone> getSone(String soneId) {
171 lock.readLock().lock();
173 return fromNullable(sones.get(soneId));
175 lock.readLock().unlock();
180 public Collection<Sone> getSones() {
181 lock.readLock().lock();
183 return Collections.unmodifiableCollection(sones.values());
185 lock.readLock().unlock();
190 public Collection<Sone> getLocalSones() {
191 lock.readLock().lock();
193 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
195 lock.readLock().unlock();
200 public Collection<Sone> getRemoteSones() {
201 lock.readLock().lock();
203 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
205 lock.readLock().unlock();
210 public SoneBuilder newSoneBuilder() {
215 // POSTPROVIDER METHODS
219 public Optional<Post> getPost(String postId) {
220 lock.readLock().lock();
222 return fromNullable(allPosts.get(postId));
224 lock.readLock().unlock();
229 public Collection<Post> getPosts(String soneId) {
230 return new HashSet<Post>(getPostsFrom(soneId));
234 public Collection<Post> getDirectedPosts(String recipientId) {
235 lock.readLock().lock();
237 Collection<Post> posts = recipientPosts.get(recipientId);
238 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
240 lock.readLock().unlock();
249 public void storePost(Post post) {
250 checkNotNull(post, "post must not be null");
251 lock.writeLock().lock();
253 allPosts.put(post.getId(), post);
254 getPostsFrom(post.getSone().getId()).add(post);
255 if (post.getRecipientId().isPresent()) {
256 getPostsTo(post.getRecipientId().get()).add(post);
259 lock.writeLock().unlock();
264 public void removePost(Post post) {
265 checkNotNull(post, "post must not be null");
266 lock.writeLock().lock();
268 allPosts.remove(post.getId());
269 getPostsFrom(post.getSone().getId()).remove(post);
270 if (post.getRecipientId().isPresent()) {
271 getPostsTo(post.getRecipientId().get()).remove(post);
273 post.getSone().removePost(post);
275 lock.writeLock().unlock();
280 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
281 checkNotNull(sone, "sone must not be null");
282 /* verify that all posts are from the same Sone. */
283 for (Post post : posts) {
284 if (!sone.equals(post.getSone())) {
285 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
289 lock.writeLock().lock();
291 /* remove all posts by the Sone. */
292 getPostsFrom(sone.getId()).clear();
293 for (Post post : posts) {
294 allPosts.remove(post.getId());
295 if (post.getRecipientId().isPresent()) {
296 getPostsTo(post.getRecipientId().get()).remove(post);
301 getPostsFrom(sone.getId()).addAll(posts);
302 for (Post post : posts) {
303 allPosts.put(post.getId(), post);
304 if (post.getRecipientId().isPresent()) {
305 getPostsTo(post.getRecipientId().get()).add(post);
309 lock.writeLock().unlock();
314 public void removePosts(Sone sone) {
315 checkNotNull(sone, "sone must not be null");
316 lock.writeLock().lock();
318 /* remove all posts by the Sone. */
319 getPostsFrom(sone.getId()).clear();
320 for (Post post : sone.getPosts()) {
321 allPosts.remove(post.getId());
322 if (post.getRecipientId().isPresent()) {
323 getPostsTo(post.getRecipientId().get()).remove(post);
327 lock.writeLock().unlock();
332 // POSTREPLYPROVIDER METHODS
336 public Optional<PostReply> getPostReply(String id) {
337 lock.readLock().lock();
339 return fromNullable(allPostReplies.get(id));
341 lock.readLock().unlock();
346 public List<PostReply> getReplies(String postId) {
347 lock.readLock().lock();
349 if (!postReplies.containsKey(postId)) {
352 return new ArrayList<PostReply>(postReplies.get(postId));
354 lock.readLock().unlock();
359 // POSTREPLYSTORE METHODS
363 * Returns whether the given post reply is known.
367 * @return {@code true} if the given post reply is known, {@code false}
370 public boolean isPostReplyKnown(PostReply postReply) {
371 lock.readLock().lock();
373 return knownPostReplies.contains(postReply.getId());
375 lock.readLock().unlock();
380 public void setPostReplyKnown(PostReply postReply) {
381 lock.writeLock().lock();
383 knownPostReplies.add(postReply.getId());
385 lock.writeLock().unlock();
390 public void storePostReply(PostReply postReply) {
391 lock.writeLock().lock();
393 allPostReplies.put(postReply.getId(), postReply);
394 if (postReplies.containsKey(postReply.getPostId())) {
395 postReplies.get(postReply.getPostId()).add(postReply);
397 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
398 replies.add(postReply);
399 postReplies.put(postReply.getPostId(), replies);
402 lock.writeLock().unlock();
407 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
408 checkNotNull(sone, "sone must not be null");
409 /* verify that all posts are from the same Sone. */
410 for (PostReply postReply : postReplies) {
411 if (!sone.equals(postReply.getSone())) {
412 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
416 lock.writeLock().lock();
418 /* remove all post replies of the Sone. */
419 for (PostReply postReply : getRepliesFrom(sone.getId())) {
420 removePostReply(postReply);
422 for (PostReply postReply : postReplies) {
423 allPostReplies.put(postReply.getId(), postReply);
424 sonePostReplies.put(postReply.getSone().getId(), postReply);
425 if (this.postReplies.containsKey(postReply.getPostId())) {
426 this.postReplies.get(postReply.getPostId()).add(postReply);
428 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
429 replies.add(postReply);
430 this.postReplies.put(postReply.getPostId(), replies);
434 lock.writeLock().unlock();
439 public void removePostReply(PostReply postReply) {
440 lock.writeLock().lock();
442 allPostReplies.remove(postReply.getId());
443 if (postReplies.containsKey(postReply.getPostId())) {
444 postReplies.get(postReply.getPostId()).remove(postReply);
445 if (postReplies.get(postReply.getPostId()).isEmpty()) {
446 postReplies.remove(postReply.getPostId());
450 lock.writeLock().unlock();
455 public void removePostReplies(Sone sone) {
456 checkNotNull(sone, "sone must not be null");
458 lock.writeLock().lock();
460 for (PostReply postReply : sone.getReplies()) {
461 removePostReply(postReply);
464 lock.writeLock().unlock();
469 // ALBUMPROVDER METHODS
473 public Optional<Album> getAlbum(String albumId) {
474 lock.readLock().lock();
476 return fromNullable(allAlbums.get(albumId));
478 lock.readLock().unlock();
483 public List<Album> getAlbums(Album parent) {
484 lock.readLock().lock();
486 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
488 lock.readLock().unlock();
493 public void moveUp(Album album) {
494 lock.writeLock().lock();
496 List<String> albums = albumChildren.get(album.getParent().getId());
497 int currentIndex = albums.indexOf(album.getId());
498 if (currentIndex == 0) {
501 albums.remove(album.getId());
502 albums.add(currentIndex - 1, album.getId());
504 lock.writeLock().unlock();
509 public void moveDown(Album album) {
510 lock.writeLock().lock();
512 List<String> albums = albumChildren.get(album.getParent().getId());
513 int currentIndex = albums.indexOf(album.getId());
514 if (currentIndex == (albums.size() - 1)) {
517 albums.remove(album.getId());
518 albums.add(currentIndex + 1, album.getId());
520 lock.writeLock().unlock();
525 // ALBUMSTORE METHODS
529 public void storeAlbum(Album album) {
530 lock.writeLock().lock();
532 allAlbums.put(album.getId(), album);
533 albumChildren.put(album.getParent().getId(), album.getId());
535 lock.writeLock().unlock();
540 public void removeAlbum(Album album) {
541 lock.writeLock().lock();
543 allAlbums.remove(album.getId());
544 albumChildren.remove(album.getParent().getId(), album.getId());
546 lock.writeLock().unlock();
551 // IMAGEPROVIDER METHODS
555 public Optional<Image> getImage(String imageId) {
556 lock.readLock().lock();
558 return fromNullable(allImages.get(imageId));
560 lock.readLock().unlock();
565 public List<Image> getImages(Album parent) {
566 lock.readLock().lock();
568 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
570 lock.readLock().unlock();
575 public void moveUp(Image image) {
576 lock.writeLock().lock();
578 List<String> images = albumImages.get(image.getAlbum().getId());
579 int currentIndex = images.indexOf(image.getId());
580 if (currentIndex == 0) {
583 images.remove(image.getId());
584 images.add(currentIndex - 1, image.getId());
586 lock.writeLock().unlock();
591 public void moveDown(Image image) {
592 lock.writeLock().lock();
594 List<String> images = albumChildren.get(image.getAlbum().getId());
595 int currentIndex = images.indexOf(image.getId());
596 if (currentIndex == (images.size() - 1)) {
599 images.remove(image.getId());
600 images.add(currentIndex + 1, image.getId());
602 lock.writeLock().unlock();
607 // IMAGESTORE METHODS
611 public void storeImage(Image image) {
612 lock.writeLock().lock();
614 allImages.put(image.getId(), image);
615 albumImages.put(image.getAlbum().getId(), image.getId());
617 lock.writeLock().unlock();
622 public void removeImage(Image image) {
623 lock.writeLock().lock();
625 allImages.remove(image.getId());
626 albumImages.remove(image.getAlbum().getId(), image.getId());
628 lock.writeLock().unlock();
633 // PACKAGE-PRIVATE METHODS
637 * Returns whether the given post is known.
641 * @return {@code true} if the post is known, {@code false} otherwise
643 boolean isPostKnown(Post post) {
644 lock.readLock().lock();
646 return knownPosts.contains(post.getId());
648 lock.readLock().unlock();
653 * Sets whether the given post is known.
658 * {@code true} if the post is known, {@code false} otherwise
660 void setPostKnown(Post post, boolean known) {
661 lock.writeLock().lock();
664 knownPosts.add(post.getId());
666 knownPosts.remove(post.getId());
669 lock.writeLock().unlock();
678 * Gets all posts for the given Sone, creating a new collection if there is
682 * The ID of the Sone to get the posts for
685 private Collection<Post> getPostsFrom(String soneId) {
686 Collection<Post> posts = null;
687 lock.readLock().lock();
689 posts = sonePosts.get(soneId);
691 lock.readLock().unlock();
697 posts = new HashSet<Post>();
698 lock.writeLock().lock();
700 sonePosts.put(soneId, posts);
702 lock.writeLock().unlock();
709 * Gets all posts that are directed the given Sone, creating a new collection
710 * if there is none yet.
713 * The ID of the Sone to get the posts for
716 private Collection<Post> getPostsTo(String recipientId) {
717 Collection<Post> posts = null;
718 lock.readLock().lock();
720 posts = recipientPosts.get(recipientId);
722 lock.readLock().unlock();
728 posts = new HashSet<Post>();
729 lock.writeLock().lock();
731 recipientPosts.put(recipientId, posts);
733 lock.writeLock().unlock();
739 /** Loads the known posts. */
740 private void loadKnownPosts() {
741 lock.writeLock().lock();
745 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
746 if (knownPostId == null) {
749 knownPosts.add(knownPostId);
752 lock.writeLock().unlock();
757 * Saves the known posts to the configuration.
759 * @throws DatabaseException
760 * if a configuration error occurs
762 private void saveKnownPosts() throws DatabaseException {
763 lock.readLock().lock();
766 for (String knownPostId : knownPosts) {
767 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
769 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
770 } catch (ConfigurationException ce1) {
771 throw new DatabaseException("Could not save database.", ce1);
773 lock.readLock().unlock();
778 * Returns all replies by the given Sone.
782 * @return The post replies of the Sone, sorted by time (newest first)
784 private Collection<PostReply> getRepliesFrom(String id) {
785 lock.readLock().lock();
787 if (sonePostReplies.containsKey(id)) {
788 return Collections.unmodifiableCollection(sonePostReplies.get(id));
790 return Collections.emptySet();
792 lock.readLock().unlock();
796 /** Loads the known post replies. */
797 private void loadKnownPostReplies() {
798 lock.writeLock().lock();
800 int replyCounter = 0;
802 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
803 if (knownReplyId == null) {
806 knownPostReplies.add(knownReplyId);
809 lock.writeLock().unlock();
814 * Saves the known post replies to the configuration.
816 * @throws DatabaseException
817 * if a configuration error occurs
819 private void saveKnownPostReplies() throws DatabaseException {
820 lock.readLock().lock();
822 int replyCounter = 0;
823 for (String knownReplyId : knownPostReplies) {
824 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
826 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
827 } catch (ConfigurationException ce1) {
828 throw new DatabaseException("Could not save database.", ce1);
830 lock.readLock().unlock();
834 private Function<String, Iterable<Album>> getAlbum() {
835 return new Function<String, Iterable<Album>>() {
837 public Iterable<Album> apply(String input) {
838 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
843 private Function<String, Iterable<Image>> getImage() {
844 return new Function<String, Iterable<Image>>() {
846 public Iterable<Image> apply(String input) {
847 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();