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.util.config.Configuration;
52 import net.pterodactylus.util.config.ConfigurationException;
54 import com.google.common.base.Function;
55 import com.google.common.base.Optional;
56 import com.google.common.collect.ArrayListMultimap;
57 import com.google.common.collect.ListMultimap;
58 import com.google.common.collect.SortedSetMultimap;
59 import com.google.common.collect.TreeMultimap;
60 import com.google.common.util.concurrent.AbstractService;
61 import com.google.inject.Inject;
64 * Memory-based {@link PostDatabase} implementation.
66 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
68 public class MemoryDatabase extends AbstractService implements Database {
71 private final ReadWriteLock lock = new ReentrantReadWriteLock();
73 /** The configuration. */
74 private final Configuration configuration;
76 private final Map<String, Sone> sones = new HashMap<String, Sone>();
78 /** All posts by their ID. */
79 private final Map<String, Post> allPosts = new HashMap<String, Post>();
81 /** All posts by their Sones. */
82 private final Map<String, Collection<Post>> sonePosts = new HashMap<String, Collection<Post>>();
84 /** All posts by their recipient. */
85 private final Map<String, Collection<Post>> recipientPosts = new HashMap<String, Collection<Post>>();
87 /** Whether posts are known. */
88 private final Set<String> knownPosts = new HashSet<String>();
90 /** All post replies by their ID. */
91 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
93 /** Replies sorted by Sone. */
94 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
97 public int compare(String leftString, String rightString) {
98 return leftString.compareTo(rightString);
100 }, PostReply.TIME_COMPARATOR);
102 /** Replies by post. */
103 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
105 /** Whether post replies are known. */
106 private final Set<String> knownPostReplies = new HashSet<String>();
108 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
109 private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
110 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
112 private final Map<String, Image> allImages = new HashMap<String, Image>();
115 * Creates a new memory database.
117 * @param configuration
118 * The configuration for loading and saving elements
121 public MemoryDatabase(Configuration configuration) {
122 this.configuration = configuration;
130 public void save() throws DatabaseException {
132 saveKnownPostReplies();
140 protected void doStart() {
142 loadKnownPostReplies();
147 protected void doStop() {
151 } catch (DatabaseException de1) {
157 public Optional<Sone> getSone(String soneId) {
158 lock.readLock().lock();
160 return fromNullable(sones.get(soneId));
162 lock.readLock().unlock();
167 public Collection<Sone> getSones() {
168 lock.readLock().lock();
170 return Collections.unmodifiableCollection(sones.values());
172 lock.readLock().unlock();
177 public Collection<Sone> getLocalSones() {
178 lock.readLock().lock();
180 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
182 lock.readLock().unlock();
187 public Collection<Sone> getRemoteSones() {
188 lock.readLock().lock();
190 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
192 lock.readLock().unlock();
197 public SoneBuilder newSoneBuilder() {
202 // POSTPROVIDER METHODS
206 public Optional<Post> getPost(String postId) {
207 lock.readLock().lock();
209 return fromNullable(allPosts.get(postId));
211 lock.readLock().unlock();
216 public Collection<Post> getPosts(String soneId) {
217 return new HashSet<Post>(getPostsFrom(soneId));
221 public Collection<Post> getDirectedPosts(String recipientId) {
222 lock.readLock().lock();
224 Collection<Post> posts = recipientPosts.get(recipientId);
225 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
227 lock.readLock().unlock();
236 public void storePost(Post post) {
237 checkNotNull(post, "post must not be null");
238 lock.writeLock().lock();
240 allPosts.put(post.getId(), post);
241 getPostsFrom(post.getSone().getId()).add(post);
242 if (post.getRecipientId().isPresent()) {
243 getPostsTo(post.getRecipientId().get()).add(post);
246 lock.writeLock().unlock();
251 public void removePost(Post post) {
252 checkNotNull(post, "post must not be null");
253 lock.writeLock().lock();
255 allPosts.remove(post.getId());
256 getPostsFrom(post.getSone().getId()).remove(post);
257 if (post.getRecipientId().isPresent()) {
258 getPostsTo(post.getRecipientId().get()).remove(post);
260 post.getSone().removePost(post);
262 lock.writeLock().unlock();
267 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
268 checkNotNull(sone, "sone must not be null");
269 /* verify that all posts are from the same Sone. */
270 for (Post post : posts) {
271 if (!sone.equals(post.getSone())) {
272 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
276 lock.writeLock().lock();
278 /* remove all posts by the Sone. */
279 getPostsFrom(sone.getId()).clear();
280 for (Post post : posts) {
281 allPosts.remove(post.getId());
282 if (post.getRecipientId().isPresent()) {
283 getPostsTo(post.getRecipientId().get()).remove(post);
288 getPostsFrom(sone.getId()).addAll(posts);
289 for (Post post : posts) {
290 allPosts.put(post.getId(), post);
291 if (post.getRecipientId().isPresent()) {
292 getPostsTo(post.getRecipientId().get()).add(post);
296 lock.writeLock().unlock();
301 public void removePosts(Sone sone) {
302 checkNotNull(sone, "sone must not be null");
303 lock.writeLock().lock();
305 /* remove all posts by the Sone. */
306 getPostsFrom(sone.getId()).clear();
307 for (Post post : sone.getPosts()) {
308 allPosts.remove(post.getId());
309 if (post.getRecipientId().isPresent()) {
310 getPostsTo(post.getRecipientId().get()).remove(post);
314 lock.writeLock().unlock();
319 // POSTREPLYPROVIDER METHODS
323 public Optional<PostReply> getPostReply(String id) {
324 lock.readLock().lock();
326 return fromNullable(allPostReplies.get(id));
328 lock.readLock().unlock();
333 public List<PostReply> getReplies(String postId) {
334 lock.readLock().lock();
336 if (!postReplies.containsKey(postId)) {
339 return new ArrayList<PostReply>(postReplies.get(postId));
341 lock.readLock().unlock();
346 // POSTREPLYSTORE METHODS
350 * Returns whether the given post reply is known.
354 * @return {@code true} if the given post reply is known, {@code false}
357 public boolean isPostReplyKnown(PostReply postReply) {
358 lock.readLock().lock();
360 return knownPostReplies.contains(postReply.getId());
362 lock.readLock().unlock();
367 public void setPostReplyKnown(PostReply postReply) {
368 lock.writeLock().lock();
370 knownPostReplies.add(postReply.getId());
372 lock.writeLock().unlock();
377 public void storePostReply(PostReply postReply) {
378 lock.writeLock().lock();
380 allPostReplies.put(postReply.getId(), postReply);
381 if (postReplies.containsKey(postReply.getPostId())) {
382 postReplies.get(postReply.getPostId()).add(postReply);
384 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
385 replies.add(postReply);
386 postReplies.put(postReply.getPostId(), replies);
389 lock.writeLock().unlock();
394 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
395 checkNotNull(sone, "sone must not be null");
396 /* verify that all posts are from the same Sone. */
397 for (PostReply postReply : postReplies) {
398 if (!sone.equals(postReply.getSone())) {
399 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
403 lock.writeLock().lock();
405 /* remove all post replies of the Sone. */
406 for (PostReply postReply : getRepliesFrom(sone.getId())) {
407 removePostReply(postReply);
409 for (PostReply postReply : postReplies) {
410 allPostReplies.put(postReply.getId(), postReply);
411 sonePostReplies.put(postReply.getSone().getId(), postReply);
412 if (this.postReplies.containsKey(postReply.getPostId())) {
413 this.postReplies.get(postReply.getPostId()).add(postReply);
415 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
416 replies.add(postReply);
417 this.postReplies.put(postReply.getPostId(), replies);
421 lock.writeLock().unlock();
426 public void removePostReply(PostReply postReply) {
427 lock.writeLock().lock();
429 allPostReplies.remove(postReply.getId());
430 if (postReplies.containsKey(postReply.getPostId())) {
431 postReplies.get(postReply.getPostId()).remove(postReply);
432 if (postReplies.get(postReply.getPostId()).isEmpty()) {
433 postReplies.remove(postReply.getPostId());
437 lock.writeLock().unlock();
442 public void removePostReplies(Sone sone) {
443 checkNotNull(sone, "sone must not be null");
445 lock.writeLock().lock();
447 for (PostReply postReply : sone.getReplies()) {
448 removePostReply(postReply);
451 lock.writeLock().unlock();
456 // ALBUMPROVDER METHODS
460 public Optional<Album> getAlbum(String albumId) {
461 lock.readLock().lock();
463 return fromNullable(allAlbums.get(albumId));
465 lock.readLock().unlock();
470 public List<Album> getAlbums(Album parent) {
471 lock.readLock().lock();
473 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
475 lock.readLock().unlock();
480 public void moveUp(Album album) {
481 lock.writeLock().lock();
483 List<String> albums = albumChildren.get(album.getParent().getId());
484 int currentIndex = albums.indexOf(album.getId());
485 if (currentIndex == 0) {
488 albums.remove(album.getId());
489 albums.add(currentIndex - 1, album.getId());
491 lock.writeLock().unlock();
496 public void moveDown(Album album) {
497 lock.writeLock().lock();
499 List<String> albums = albumChildren.get(album.getParent().getId());
500 int currentIndex = albums.indexOf(album.getId());
501 if (currentIndex == (albums.size() - 1)) {
504 albums.remove(album.getId());
505 albums.add(currentIndex + 1, album.getId());
507 lock.writeLock().unlock();
512 // ALBUMSTORE METHODS
516 public void storeAlbum(Album album) {
517 lock.writeLock().lock();
519 allAlbums.put(album.getId(), album);
520 albumChildren.put(album.getParent().getId(), album.getId());
522 lock.writeLock().unlock();
527 public void removeAlbum(Album album) {
528 lock.writeLock().lock();
530 allAlbums.remove(album.getId());
531 albumChildren.remove(album.getParent().getId(), album.getId());
533 lock.writeLock().unlock();
538 // IMAGEPROVIDER METHODS
542 public Optional<Image> getImage(String imageId) {
543 lock.readLock().lock();
545 return fromNullable(allImages.get(imageId));
547 lock.readLock().unlock();
552 public List<Image> getImages(Album parent) {
553 lock.readLock().lock();
555 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
557 lock.readLock().unlock();
562 public void moveUp(Image image) {
563 lock.writeLock().lock();
565 List<String> images = albumImages.get(image.getAlbum().getId());
566 int currentIndex = images.indexOf(image.getId());
567 if (currentIndex == 0) {
570 images.remove(image.getId());
571 images.add(currentIndex - 1, image.getId());
573 lock.writeLock().unlock();
578 public void moveDown(Image image) {
579 lock.writeLock().lock();
581 List<String> images = albumChildren.get(image.getAlbum().getId());
582 int currentIndex = images.indexOf(image.getId());
583 if (currentIndex == (images.size() - 1)) {
586 images.remove(image.getId());
587 images.add(currentIndex + 1, image.getId());
589 lock.writeLock().unlock();
594 // IMAGESTORE METHODS
598 public void storeImage(Image image) {
599 lock.writeLock().lock();
601 allImages.put(image.getId(), image);
602 albumImages.put(image.getAlbum().getId(), image.getId());
604 lock.writeLock().unlock();
609 public void removeImage(Image image) {
610 lock.writeLock().lock();
612 allImages.remove(image.getId());
613 albumImages.remove(image.getAlbum().getId(), image.getId());
615 lock.writeLock().unlock();
620 // PACKAGE-PRIVATE METHODS
624 * Returns whether the given post is known.
628 * @return {@code true} if the post is known, {@code false} otherwise
630 boolean isPostKnown(Post post) {
631 lock.readLock().lock();
633 return knownPosts.contains(post.getId());
635 lock.readLock().unlock();
640 * Sets whether the given post is known.
645 * {@code true} if the post is known, {@code false} otherwise
647 void setPostKnown(Post post, boolean known) {
648 lock.writeLock().lock();
651 knownPosts.add(post.getId());
653 knownPosts.remove(post.getId());
656 lock.writeLock().unlock();
665 * Gets all posts for the given Sone, creating a new collection if there is
669 * The ID of the Sone to get the posts for
672 private Collection<Post> getPostsFrom(String soneId) {
673 Collection<Post> posts = null;
674 lock.readLock().lock();
676 posts = sonePosts.get(soneId);
678 lock.readLock().unlock();
684 posts = new HashSet<Post>();
685 lock.writeLock().lock();
687 sonePosts.put(soneId, posts);
689 lock.writeLock().unlock();
696 * Gets all posts that are directed the given Sone, creating a new collection
697 * if there is none yet.
700 * The ID of the Sone to get the posts for
703 private Collection<Post> getPostsTo(String recipientId) {
704 Collection<Post> posts = null;
705 lock.readLock().lock();
707 posts = recipientPosts.get(recipientId);
709 lock.readLock().unlock();
715 posts = new HashSet<Post>();
716 lock.writeLock().lock();
718 recipientPosts.put(recipientId, posts);
720 lock.writeLock().unlock();
726 /** Loads the known posts. */
727 private void loadKnownPosts() {
728 lock.writeLock().lock();
732 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
733 if (knownPostId == null) {
736 knownPosts.add(knownPostId);
739 lock.writeLock().unlock();
744 * Saves the known posts to the configuration.
746 * @throws DatabaseException
747 * if a configuration error occurs
749 private void saveKnownPosts() throws DatabaseException {
750 lock.readLock().lock();
753 for (String knownPostId : knownPosts) {
754 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
756 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
757 } catch (ConfigurationException ce1) {
758 throw new DatabaseException("Could not save database.", ce1);
760 lock.readLock().unlock();
765 * Returns all replies by the given Sone.
769 * @return The post replies of the Sone, sorted by time (newest first)
771 private Collection<PostReply> getRepliesFrom(String id) {
772 lock.readLock().lock();
774 if (sonePostReplies.containsKey(id)) {
775 return Collections.unmodifiableCollection(sonePostReplies.get(id));
777 return Collections.emptySet();
779 lock.readLock().unlock();
783 /** Loads the known post replies. */
784 private void loadKnownPostReplies() {
785 lock.writeLock().lock();
787 int replyCounter = 0;
789 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
790 if (knownReplyId == null) {
793 knownPostReplies.add(knownReplyId);
796 lock.writeLock().unlock();
801 * Saves the known post replies to the configuration.
803 * @throws DatabaseException
804 * if a configuration error occurs
806 private void saveKnownPostReplies() throws DatabaseException {
807 lock.readLock().lock();
809 int replyCounter = 0;
810 for (String knownReplyId : knownPostReplies) {
811 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
813 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
814 } catch (ConfigurationException ce1) {
815 throw new DatabaseException("Could not save database.", ce1);
817 lock.readLock().unlock();
821 private Function<String, Iterable<Album>> getAlbum() {
822 return new Function<String, Iterable<Album>>() {
824 public Iterable<Album> apply(String input) {
825 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
830 private Function<String, Iterable<Image>> getImage() {
831 return new Function<String, Iterable<Image>>() {
833 public Iterable<Image> apply(String input) {
834 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();