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();
248 /** {@inheritDocs} */
250 public void storePost(Post post) {
251 checkNotNull(post, "post must not be null");
252 lock.writeLock().lock();
254 allPosts.put(post.getId(), post);
255 getPostsFrom(post.getSone().getId()).add(post);
256 if (post.getRecipientId().isPresent()) {
257 getPostsTo(post.getRecipientId().get()).add(post);
260 lock.writeLock().unlock();
264 /** {@inheritDocs} */
266 public void removePost(Post post) {
267 checkNotNull(post, "post must not be null");
268 lock.writeLock().lock();
270 allPosts.remove(post.getId());
271 getPostsFrom(post.getSone().getId()).remove(post);
272 if (post.getRecipientId().isPresent()) {
273 getPostsTo(post.getRecipientId().get()).remove(post);
275 post.getSone().removePost(post);
277 lock.writeLock().unlock();
281 /** {@inheritDocs} */
283 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
284 checkNotNull(sone, "sone must not be null");
285 /* verify that all posts are from the same Sone. */
286 for (Post post : posts) {
287 if (!sone.equals(post.getSone())) {
288 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
292 lock.writeLock().lock();
294 /* remove all posts by the Sone. */
295 getPostsFrom(sone.getId()).clear();
296 for (Post post : posts) {
297 allPosts.remove(post.getId());
298 if (post.getRecipientId().isPresent()) {
299 getPostsTo(post.getRecipientId().get()).remove(post);
304 getPostsFrom(sone.getId()).addAll(posts);
305 for (Post post : posts) {
306 allPosts.put(post.getId(), post);
307 if (post.getRecipientId().isPresent()) {
308 getPostsTo(post.getRecipientId().get()).add(post);
312 lock.writeLock().unlock();
316 /** {@inheritDocs} */
318 public void removePosts(Sone sone) {
319 checkNotNull(sone, "sone must not be null");
320 lock.writeLock().lock();
322 /* remove all posts by the Sone. */
323 getPostsFrom(sone.getId()).clear();
324 for (Post post : sone.getPosts()) {
325 allPosts.remove(post.getId());
326 if (post.getRecipientId().isPresent()) {
327 getPostsTo(post.getRecipientId().get()).remove(post);
331 lock.writeLock().unlock();
336 // POSTREPLYPROVIDER METHODS
339 /** {@inheritDocs} */
341 public Optional<PostReply> getPostReply(String id) {
342 lock.readLock().lock();
344 return fromNullable(allPostReplies.get(id));
346 lock.readLock().unlock();
350 /** {@inheritDocs} */
352 public List<PostReply> getReplies(String postId) {
353 lock.readLock().lock();
355 if (!postReplies.containsKey(postId)) {
358 return new ArrayList<PostReply>(postReplies.get(postId));
360 lock.readLock().unlock();
365 // POSTREPLYSTORE METHODS
368 /** {@inheritDocs} */
370 public void storePostReply(PostReply postReply) {
371 lock.writeLock().lock();
373 allPostReplies.put(postReply.getId(), postReply);
374 if (postReplies.containsKey(postReply.getPostId())) {
375 postReplies.get(postReply.getPostId()).add(postReply);
377 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
378 replies.add(postReply);
379 postReplies.put(postReply.getPostId(), replies);
382 lock.writeLock().unlock();
386 /** {@inheritDocs} */
388 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
389 checkNotNull(sone, "sone must not be null");
390 /* verify that all posts are from the same Sone. */
391 for (PostReply postReply : postReplies) {
392 if (!sone.equals(postReply.getSone())) {
393 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
397 lock.writeLock().lock();
399 /* remove all post replies of the Sone. */
400 for (PostReply postReply : getRepliesFrom(sone.getId())) {
401 removePostReply(postReply);
403 for (PostReply postReply : postReplies) {
404 allPostReplies.put(postReply.getId(), postReply);
405 sonePostReplies.put(postReply.getSone().getId(), postReply);
406 if (this.postReplies.containsKey(postReply.getPostId())) {
407 this.postReplies.get(postReply.getPostId()).add(postReply);
409 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
410 replies.add(postReply);
411 this.postReplies.put(postReply.getPostId(), replies);
415 lock.writeLock().unlock();
419 /** {@inheritDocs} */
421 public void removePostReply(PostReply postReply) {
422 lock.writeLock().lock();
424 allPostReplies.remove(postReply.getId());
425 if (postReplies.containsKey(postReply.getPostId())) {
426 postReplies.get(postReply.getPostId()).remove(postReply);
427 if (postReplies.get(postReply.getPostId()).isEmpty()) {
428 postReplies.remove(postReply.getPostId());
432 lock.writeLock().unlock();
436 /** {@inheritDocs} */
438 public void removePostReplies(Sone sone) {
439 checkNotNull(sone, "sone must not be null");
441 lock.writeLock().lock();
443 for (PostReply postReply : sone.getReplies()) {
444 removePostReply(postReply);
447 lock.writeLock().unlock();
452 // ALBUMPROVDER METHODS
456 public Optional<Album> getAlbum(String albumId) {
457 lock.readLock().lock();
459 return fromNullable(allAlbums.get(albumId));
461 lock.readLock().unlock();
466 public List<Album> getAlbums(Album parent) {
467 lock.readLock().lock();
469 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
471 lock.readLock().unlock();
476 public void moveUp(Album album) {
477 lock.writeLock().lock();
479 List<String> albums = albumChildren.get(album.getParent().getId());
480 int currentIndex = albums.indexOf(album.getId());
481 if (currentIndex == 0) {
484 albums.remove(album.getId());
485 albums.add(currentIndex - 1, album.getId());
487 lock.writeLock().unlock();
492 public void moveDown(Album album) {
493 lock.writeLock().lock();
495 List<String> albums = albumChildren.get(album.getParent().getId());
496 int currentIndex = albums.indexOf(album.getId());
497 if (currentIndex == (albums.size() - 1)) {
500 albums.remove(album.getId());
501 albums.add(currentIndex + 1, album.getId());
503 lock.writeLock().unlock();
508 // ALBUMSTORE METHODS
512 public void storeAlbum(Album album) {
513 lock.writeLock().lock();
515 allAlbums.put(album.getId(), album);
516 albumChildren.put(album.getParent().getId(), album.getId());
518 lock.writeLock().unlock();
523 public void removeAlbum(Album album) {
524 lock.writeLock().lock();
526 allAlbums.remove(album.getId());
527 albumChildren.remove(album.getParent().getId(), album.getId());
529 lock.writeLock().unlock();
534 // IMAGEPROVIDER METHODS
538 public Optional<Image> getImage(String imageId) {
539 lock.readLock().lock();
541 return fromNullable(allImages.get(imageId));
543 lock.readLock().unlock();
548 public List<Image> getImages(Album parent) {
549 lock.readLock().lock();
551 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
553 lock.readLock().unlock();
558 public void moveUp(Image image) {
559 lock.writeLock().lock();
561 List<String> images = albumImages.get(image.getAlbum().getId());
562 int currentIndex = images.indexOf(image.getId());
563 if (currentIndex == 0) {
566 images.remove(image.getId());
567 images.add(currentIndex - 1, image.getId());
569 lock.writeLock().unlock();
574 public void moveDown(Image image) {
575 lock.writeLock().lock();
577 List<String> images = albumChildren.get(image.getAlbum().getId());
578 int currentIndex = images.indexOf(image.getId());
579 if (currentIndex == (images.size() - 1)) {
582 images.remove(image.getId());
583 images.add(currentIndex + 1, image.getId());
585 lock.writeLock().unlock();
590 // IMAGESTORE METHODS
594 public void storeImage(Image image) {
595 lock.writeLock().lock();
597 allImages.put(image.getId(), image);
598 albumImages.put(image.getAlbum().getId(), image.getId());
600 lock.writeLock().unlock();
605 public void removeImage(Image image) {
606 lock.writeLock().lock();
608 allImages.remove(image.getId());
609 albumImages.remove(image.getAlbum().getId(), image.getId());
611 lock.writeLock().unlock();
616 // PACKAGE-PRIVATE METHODS
620 * Returns whether the given post is known.
624 * @return {@code true} if the post is known, {@code false} otherwise
626 boolean isPostKnown(Post post) {
627 lock.readLock().lock();
629 return knownPosts.contains(post.getId());
631 lock.readLock().unlock();
636 * Sets whether the given post is known.
641 * {@code true} if the post is known, {@code false} otherwise
643 void setPostKnown(Post post, boolean known) {
644 lock.writeLock().lock();
647 knownPosts.add(post.getId());
649 knownPosts.remove(post.getId());
652 lock.writeLock().unlock();
657 * Returns whether the given post reply is known.
661 * @return {@code true} if the given post reply is known, {@code false}
664 boolean isPostReplyKnown(PostReply postReply) {
665 lock.readLock().lock();
667 return knownPostReplies.contains(postReply.getId());
669 lock.readLock().unlock();
674 * Sets whether the given post reply is known.
679 * {@code true} if the post reply is known, {@code false} otherwise
681 void setPostReplyKnown(PostReply postReply, boolean known) {
682 lock.writeLock().lock();
685 knownPostReplies.add(postReply.getId());
687 knownPostReplies.remove(postReply.getId());
690 lock.writeLock().unlock();
699 * Gets all posts for the given Sone, creating a new collection if there is
703 * The ID of the Sone to get the posts for
706 private Collection<Post> getPostsFrom(String soneId) {
707 Collection<Post> posts = null;
708 lock.readLock().lock();
710 posts = sonePosts.get(soneId);
712 lock.readLock().unlock();
718 posts = new HashSet<Post>();
719 lock.writeLock().lock();
721 sonePosts.put(soneId, posts);
723 lock.writeLock().unlock();
730 * Gets all posts that are directed the given Sone, creating a new collection
731 * if there is none yet.
734 * The ID of the Sone to get the posts for
737 private Collection<Post> getPostsTo(String recipientId) {
738 Collection<Post> posts = null;
739 lock.readLock().lock();
741 posts = recipientPosts.get(recipientId);
743 lock.readLock().unlock();
749 posts = new HashSet<Post>();
750 lock.writeLock().lock();
752 recipientPosts.put(recipientId, posts);
754 lock.writeLock().unlock();
760 /** Loads the known posts. */
761 private void loadKnownPosts() {
762 lock.writeLock().lock();
766 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
767 if (knownPostId == null) {
770 knownPosts.add(knownPostId);
773 lock.writeLock().unlock();
778 * Saves the known posts to the configuration.
780 * @throws DatabaseException
781 * if a configuration error occurs
783 private void saveKnownPosts() throws DatabaseException {
784 lock.readLock().lock();
787 for (String knownPostId : knownPosts) {
788 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
790 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
791 } catch (ConfigurationException ce1) {
792 throw new DatabaseException("Could not save database.", ce1);
794 lock.readLock().unlock();
799 * Returns all replies by the given Sone.
803 * @return The post replies of the Sone, sorted by time (newest first)
805 private Collection<PostReply> getRepliesFrom(String id) {
806 lock.readLock().lock();
808 if (sonePostReplies.containsKey(id)) {
809 return Collections.unmodifiableCollection(sonePostReplies.get(id));
811 return Collections.emptySet();
813 lock.readLock().unlock();
817 /** Loads the known post replies. */
818 private void loadKnownPostReplies() {
819 lock.writeLock().lock();
821 int replyCounter = 0;
823 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
824 if (knownReplyId == null) {
827 knownPostReplies.add(knownReplyId);
830 lock.writeLock().unlock();
835 * Saves the known post replies to the configuration.
837 * @throws DatabaseException
838 * if a configuration error occurs
840 private void saveKnownPostReplies() throws DatabaseException {
841 lock.readLock().lock();
843 int replyCounter = 0;
844 for (String knownReplyId : knownPostReplies) {
845 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
847 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
848 } catch (ConfigurationException ce1) {
849 throw new DatabaseException("Could not save database.", ce1);
851 lock.readLock().unlock();
855 private Function<String, Iterable<Album>> getAlbum() {
856 return new Function<String, Iterable<Album>>() {
858 public Iterable<Album> apply(String input) {
859 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
864 private Function<String, Iterable<Image>> getImage() {
865 return new Function<String, Iterable<Image>>() {
867 public Iterable<Image> apply(String input) {
868 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();