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.PostBuilder;
50 import net.pterodactylus.sone.database.PostDatabase;
51 import net.pterodactylus.sone.database.PostReplyBuilder;
52 import net.pterodactylus.sone.database.SoneBuilder;
53 import net.pterodactylus.util.config.Configuration;
54 import net.pterodactylus.util.config.ConfigurationException;
56 import com.google.common.base.Function;
57 import com.google.common.base.Optional;
58 import com.google.common.collect.ArrayListMultimap;
59 import com.google.common.collect.ListMultimap;
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, Sone> sones = new HashMap<String, Sone>();
80 /** All posts by their ID. */
81 private final Map<String, Post> allPosts = new HashMap<String, Post>();
83 /** All posts by their Sones. */
84 private final Map<String, Collection<Post>> sonePosts = new HashMap<String, Collection<Post>>();
86 /** All posts by their recipient. */
87 private final Map<String, Collection<Post>> recipientPosts = new HashMap<String, Collection<Post>>();
89 /** Whether posts are known. */
90 private final Set<String> knownPosts = new HashSet<String>();
92 /** All post replies by their ID. */
93 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
95 /** Replies sorted by Sone. */
96 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
99 public int compare(String leftString, String rightString) {
100 return leftString.compareTo(rightString);
102 }, PostReply.TIME_COMPARATOR);
104 /** Replies by post. */
105 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
107 /** Whether post replies are known. */
108 private final Set<String> knownPostReplies = new HashSet<String>();
110 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
111 private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
112 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
114 private final Map<String, Image> allImages = new HashMap<String, Image>();
117 * Creates a new memory database.
119 * @param configuration
120 * The configuration for loading and saving elements
123 public MemoryDatabase(Configuration configuration) {
124 this.configuration = configuration;
132 * Saves the database.
134 * @throws DatabaseException
135 * if an error occurs while saving
138 public void save() throws DatabaseException {
140 saveKnownPostReplies();
147 /** {@inheritDocs} */
149 protected void doStart() {
151 loadKnownPostReplies();
155 /** {@inheritDocs} */
157 protected void doStop() {
161 } catch (DatabaseException de1) {
167 public Optional<Sone> getSone(String soneId) {
168 lock.readLock().lock();
170 return fromNullable(sones.get(soneId));
172 lock.readLock().unlock();
177 public Collection<Sone> getSones() {
178 lock.readLock().lock();
180 return Collections.unmodifiableCollection(sones.values());
182 lock.readLock().unlock();
187 public Collection<Sone> getLocalSones() {
188 lock.readLock().lock();
190 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
192 lock.readLock().unlock();
197 public Collection<Sone> getRemoteSones() {
198 lock.readLock().lock();
200 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
202 lock.readLock().unlock();
207 public SoneBuilder newSoneBuilder() {
212 // POSTPROVIDER METHODS
215 /** {@inheritDocs} */
217 public Optional<Post> getPost(String postId) {
218 lock.readLock().lock();
220 return fromNullable(allPosts.get(postId));
222 lock.readLock().unlock();
226 /** {@inheritDocs} */
228 public Collection<Post> getPosts(String soneId) {
229 return new HashSet<Post>(getPostsFrom(soneId));
232 /** {@inheritDocs} */
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();
245 // POSTBUILDERFACTORY METHODS
248 /** {@inheritDocs} */
250 public PostBuilder newPostBuilder() {
251 return new MemoryPostBuilder(this);
258 /** {@inheritDocs} */
260 public void storePost(Post post) {
261 checkNotNull(post, "post must not be null");
262 lock.writeLock().lock();
264 allPosts.put(post.getId(), post);
265 getPostsFrom(post.getSone().getId()).add(post);
266 if (post.getRecipientId().isPresent()) {
267 getPostsTo(post.getRecipientId().get()).add(post);
270 lock.writeLock().unlock();
274 /** {@inheritDocs} */
276 public void removePost(Post post) {
277 checkNotNull(post, "post must not be null");
278 lock.writeLock().lock();
280 allPosts.remove(post.getId());
281 getPostsFrom(post.getSone().getId()).remove(post);
282 if (post.getRecipientId().isPresent()) {
283 getPostsTo(post.getRecipientId().get()).remove(post);
285 post.getSone().removePost(post);
287 lock.writeLock().unlock();
291 /** {@inheritDocs} */
293 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
294 checkNotNull(sone, "sone must not be null");
295 /* verify that all posts are from the same Sone. */
296 for (Post post : posts) {
297 if (!sone.equals(post.getSone())) {
298 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
302 lock.writeLock().lock();
304 /* remove all posts by the Sone. */
305 getPostsFrom(sone.getId()).clear();
306 for (Post post : posts) {
307 allPosts.remove(post.getId());
308 if (post.getRecipientId().isPresent()) {
309 getPostsTo(post.getRecipientId().get()).remove(post);
314 getPostsFrom(sone.getId()).addAll(posts);
315 for (Post post : posts) {
316 allPosts.put(post.getId(), post);
317 if (post.getRecipientId().isPresent()) {
318 getPostsTo(post.getRecipientId().get()).add(post);
322 lock.writeLock().unlock();
326 /** {@inheritDocs} */
328 public void removePosts(Sone sone) {
329 checkNotNull(sone, "sone must not be null");
330 lock.writeLock().lock();
332 /* remove all posts by the Sone. */
333 getPostsFrom(sone.getId()).clear();
334 for (Post post : sone.getPosts()) {
335 allPosts.remove(post.getId());
336 if (post.getRecipientId().isPresent()) {
337 getPostsTo(post.getRecipientId().get()).remove(post);
341 lock.writeLock().unlock();
346 // POSTREPLYPROVIDER METHODS
349 /** {@inheritDocs} */
351 public Optional<PostReply> getPostReply(String id) {
352 lock.readLock().lock();
354 return fromNullable(allPostReplies.get(id));
356 lock.readLock().unlock();
360 /** {@inheritDocs} */
362 public List<PostReply> getReplies(String postId) {
363 lock.readLock().lock();
365 if (!postReplies.containsKey(postId)) {
366 return Collections.emptyList();
368 return new ArrayList<PostReply>(postReplies.get(postId));
370 lock.readLock().unlock();
375 // POSTREPLYBUILDERFACTORY METHODS
378 /** {@inheritDocs} */
380 public PostReplyBuilder newPostReplyBuilder() {
381 return new MemoryPostReplyBuilder(this, this);
385 // POSTREPLYSTORE METHODS
388 /** {@inheritDocs} */
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();
406 /** {@inheritDocs} */
408 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
409 checkNotNull(sone, "sone must not be null");
410 /* verify that all posts are from the same Sone. */
411 for (PostReply postReply : postReplies) {
412 if (!sone.equals(postReply.getSone())) {
413 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
417 lock.writeLock().lock();
419 /* remove all post replies of the Sone. */
420 for (PostReply postReply : getRepliesFrom(sone.getId())) {
421 removePostReply(postReply);
423 for (PostReply postReply : postReplies) {
424 allPostReplies.put(postReply.getId(), postReply);
425 sonePostReplies.put(postReply.getSone().getId(), postReply);
426 if (this.postReplies.containsKey(postReply.getPostId())) {
427 this.postReplies.get(postReply.getPostId()).add(postReply);
429 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
430 replies.add(postReply);
431 this.postReplies.put(postReply.getPostId(), replies);
435 lock.writeLock().unlock();
439 /** {@inheritDocs} */
441 public void removePostReply(PostReply postReply) {
442 lock.writeLock().lock();
444 allPostReplies.remove(postReply.getId());
445 if (postReplies.containsKey(postReply.getPostId())) {
446 postReplies.get(postReply.getPostId()).remove(postReply);
447 if (postReplies.get(postReply.getPostId()).isEmpty()) {
448 postReplies.remove(postReply.getPostId());
452 lock.writeLock().unlock();
456 /** {@inheritDocs} */
458 public void removePostReplies(Sone sone) {
459 checkNotNull(sone, "sone must not be null");
461 lock.writeLock().lock();
463 for (PostReply postReply : sone.getReplies()) {
464 removePostReply(postReply);
467 lock.writeLock().unlock();
472 // ALBUMPROVDER METHODS
476 public Optional<Album> getAlbum(String albumId) {
477 lock.readLock().lock();
479 return fromNullable(allAlbums.get(albumId));
481 lock.readLock().unlock();
486 public List<Album> getAlbums(Album parent) {
487 lock.readLock().lock();
489 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
491 lock.readLock().unlock();
496 // ALBUMSTORE METHODS
500 public void storeAlbum(Album album) {
501 lock.writeLock().lock();
503 allAlbums.put(album.getId(), album);
504 albumChildren.put(album.getParent().getId(), album.getId());
506 lock.writeLock().unlock();
511 public void removeAlbum(Album album) {
512 lock.writeLock().lock();
514 allAlbums.remove(album.getId());
515 albumChildren.remove(album.getParent().getId(), album.getId());
517 lock.writeLock().unlock();
522 // IMAGEPROVIDER METHODS
526 public Optional<Image> getImage(String imageId) {
527 lock.readLock().lock();
529 return fromNullable(allImages.get(imageId));
531 lock.readLock().unlock();
536 // IMAGESTORE METHODS
540 public void storeImage(Image image) {
541 lock.writeLock().lock();
543 allImages.put(image.getId(), image);
544 albumImages.put(image.getAlbum().getId(), image.getId());
546 lock.writeLock().unlock();
551 public void removeImage(Image image) {
552 lock.writeLock().lock();
554 allImages.remove(image.getId());
555 albumImages.remove(image.getAlbum().getId(), image.getId());
557 lock.writeLock().unlock();
562 // PACKAGE-PRIVATE METHODS
566 * Returns whether the given post is known.
570 * @return {@code true} if the post is known, {@code false} otherwise
572 boolean isPostKnown(Post post) {
573 lock.readLock().lock();
575 return knownPosts.contains(post.getId());
577 lock.readLock().unlock();
582 * Sets whether the given post is known.
587 * {@code true} if the post is known, {@code false} otherwise
589 void setPostKnown(Post post, boolean known) {
590 lock.writeLock().lock();
593 knownPosts.add(post.getId());
595 knownPosts.remove(post.getId());
598 lock.writeLock().unlock();
603 * Returns whether the given post reply is known.
607 * @return {@code true} if the given post reply is known, {@code false}
610 boolean isPostReplyKnown(PostReply postReply) {
611 lock.readLock().lock();
613 return knownPostReplies.contains(postReply.getId());
615 lock.readLock().unlock();
620 * Sets whether the given post reply is known.
625 * {@code true} if the post reply is known, {@code false} otherwise
627 void setPostReplyKnown(PostReply postReply, boolean known) {
628 lock.writeLock().lock();
631 knownPostReplies.add(postReply.getId());
633 knownPostReplies.remove(postReply.getId());
636 lock.writeLock().unlock();
640 void moveUp(Album album) {
641 lock.writeLock().lock();
643 List<String> albums = albumChildren.get(album.getParent().getId());
644 int currentIndex = albums.indexOf(album.getId());
645 if (currentIndex == 0) {
648 albums.remove(album.getId());
649 albums.add(currentIndex - 1, album.getId());
651 lock.writeLock().unlock();
655 void moveDown(Album album) {
656 lock.writeLock().lock();
658 List<String> albums = albumChildren.get(album.getParent().getId());
659 int currentIndex = albums.indexOf(album.getId());
660 if (currentIndex == (albums.size() - 1)) {
663 albums.remove(album.getId());
664 albums.add(currentIndex + 1, album.getId());
666 lock.writeLock().unlock();
670 void moveUp(Image image) {
671 lock.writeLock().lock();
673 List<String> images = albumImages.get(image.getAlbum().getId());
674 int currentIndex = images.indexOf(image.getId());
675 if (currentIndex == 0) {
678 images.remove(image.getId());
679 images.add(currentIndex - 1, image.getId());
681 lock.writeLock().unlock();
685 void moveDown(Image image) {
686 lock.writeLock().lock();
688 List<String> images = albumChildren.get(image.getAlbum().getId());
689 int currentIndex = images.indexOf(image.getId());
690 if (currentIndex == (images.size() - 1)) {
693 images.remove(image.getId());
694 images.add(currentIndex + 1, image.getId());
696 lock.writeLock().unlock();
705 * Gets all posts for the given Sone, creating a new collection if there is
709 * The ID of the Sone to get the posts for
712 private Collection<Post> getPostsFrom(String soneId) {
713 Collection<Post> posts = null;
714 lock.readLock().lock();
716 posts = sonePosts.get(soneId);
718 lock.readLock().unlock();
724 posts = new HashSet<Post>();
725 lock.writeLock().lock();
727 sonePosts.put(soneId, posts);
729 lock.writeLock().unlock();
736 * Gets all posts that are directed the given Sone, creating a new collection
737 * if there is none yet.
740 * The ID of the Sone to get the posts for
743 private Collection<Post> getPostsTo(String recipientId) {
744 Collection<Post> posts = null;
745 lock.readLock().lock();
747 posts = recipientPosts.get(recipientId);
749 lock.readLock().unlock();
755 posts = new HashSet<Post>();
756 lock.writeLock().lock();
758 recipientPosts.put(recipientId, posts);
760 lock.writeLock().unlock();
766 /** Loads the known posts. */
767 private void loadKnownPosts() {
768 lock.writeLock().lock();
772 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
773 if (knownPostId == null) {
776 knownPosts.add(knownPostId);
779 lock.writeLock().unlock();
784 * Saves the known posts to the configuration.
786 * @throws DatabaseException
787 * if a configuration error occurs
789 private void saveKnownPosts() throws DatabaseException {
790 lock.readLock().lock();
793 for (String knownPostId : knownPosts) {
794 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
796 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
797 } catch (ConfigurationException ce1) {
798 throw new DatabaseException("Could not save database.", ce1);
800 lock.readLock().unlock();
805 * Returns all replies by the given Sone.
809 * @return The post replies of the Sone, sorted by time (newest first)
811 private Collection<PostReply> getRepliesFrom(String id) {
812 lock.readLock().lock();
814 if (sonePostReplies.containsKey(id)) {
815 return Collections.unmodifiableCollection(sonePostReplies.get(id));
817 return Collections.emptySet();
819 lock.readLock().unlock();
823 /** Loads the known post replies. */
824 private void loadKnownPostReplies() {
825 lock.writeLock().lock();
827 int replyCounter = 0;
829 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
830 if (knownReplyId == null) {
833 knownPostReplies.add(knownReplyId);
836 lock.writeLock().unlock();
841 * Saves the known post replies to the configuration.
843 * @throws DatabaseException
844 * if a configuration error occurs
846 private void saveKnownPostReplies() throws DatabaseException {
847 lock.readLock().lock();
849 int replyCounter = 0;
850 for (String knownReplyId : knownPostReplies) {
851 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
853 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
854 } catch (ConfigurationException ce1) {
855 throw new DatabaseException("Could not save database.", ce1);
857 lock.readLock().unlock();
861 private Function<String, Iterable<Album>> getAlbum() {
862 return new Function<String, Iterable<Album>>() {
864 public Iterable<Album> apply(String input) {
865 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();