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;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
32 import java.util.SortedSet;
33 import java.util.TreeSet;
34 import java.util.concurrent.locks.ReadWriteLock;
35 import java.util.concurrent.locks.ReentrantReadWriteLock;
37 import net.pterodactylus.sone.data.Album;
38 import net.pterodactylus.sone.data.Image;
39 import net.pterodactylus.sone.data.Post;
40 import net.pterodactylus.sone.data.PostReply;
41 import net.pterodactylus.sone.data.Reply;
42 import net.pterodactylus.sone.data.Sone;
43 import net.pterodactylus.sone.database.Database;
44 import net.pterodactylus.sone.database.DatabaseException;
45 import net.pterodactylus.sone.database.PostBuilder;
46 import net.pterodactylus.sone.database.PostDatabase;
47 import net.pterodactylus.sone.database.PostReplyBuilder;
48 import net.pterodactylus.sone.database.SoneProvider;
49 import net.pterodactylus.util.config.Configuration;
50 import net.pterodactylus.util.config.ConfigurationException;
52 import com.google.common.base.Optional;
53 import com.google.common.collect.ArrayListMultimap;
54 import com.google.common.collect.ListMultimap;
55 import com.google.common.collect.SortedSetMultimap;
56 import com.google.common.collect.TreeMultimap;
57 import com.google.common.util.concurrent.AbstractService;
58 import com.google.inject.Inject;
61 * Memory-based {@link PostDatabase} implementation.
63 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
65 public class MemoryDatabase extends AbstractService implements Database {
68 private final ReadWriteLock lock = new ReentrantReadWriteLock();
70 /** The Sone provider. */
71 private final SoneProvider soneProvider;
73 /** The configuration. */
74 private final Configuration configuration;
76 /** All posts by their ID. */
77 private final Map<String, Post> allPosts = new HashMap<String, Post>();
79 /** All posts by their Sones. */
80 private final Map<String, Collection<Post>> sonePosts = new HashMap<String, Collection<Post>>();
82 /** All posts by their recipient. */
83 private final Map<String, Collection<Post>> recipientPosts = new HashMap<String, Collection<Post>>();
85 /** Whether posts are known. */
86 private final Set<String> knownPosts = new HashSet<String>();
88 /** All post replies by their ID. */
89 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
91 /** Replies sorted by Sone. */
92 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
95 public int compare(String leftString, String rightString) {
96 return leftString.compareTo(rightString);
98 }, PostReply.TIME_COMPARATOR);
100 /** Replies by post. */
101 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
103 /** Whether post replies are known. */
104 private final Set<String> knownPostReplies = new HashSet<String>();
106 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
107 private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
108 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
110 private final Map<String, Image> allImages = new HashMap<String, Image>();
113 * Creates a new memory database.
115 * @param soneProvider
117 * @param configuration
118 * The configuration for loading and saving elements
121 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
122 this.soneProvider = soneProvider;
123 this.configuration = configuration;
131 * Saves the database.
133 * @throws DatabaseException
134 * if an error occurs while saving
137 public void save() throws DatabaseException {
139 saveKnownPostReplies();
146 /** {@inheritDocs} */
148 protected void doStart() {
150 loadKnownPostReplies();
154 /** {@inheritDocs} */
156 protected void doStop() {
160 } catch (DatabaseException de1) {
166 // POSTPROVIDER METHODS
169 /** {@inheritDocs} */
171 public Optional<Post> getPost(String postId) {
172 lock.readLock().lock();
174 return fromNullable(allPosts.get(postId));
176 lock.readLock().unlock();
180 /** {@inheritDocs} */
182 public Collection<Post> getPosts(String soneId) {
183 return new HashSet<Post>(getPostsFrom(soneId));
186 /** {@inheritDocs} */
188 public Collection<Post> getDirectedPosts(String recipientId) {
189 lock.readLock().lock();
191 Collection<Post> posts = recipientPosts.get(recipientId);
192 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
194 lock.readLock().unlock();
199 // POSTBUILDERFACTORY METHODS
202 /** {@inheritDocs} */
204 public PostBuilder newPostBuilder() {
205 return new MemoryPostBuilder(this);
212 /** {@inheritDocs} */
214 public void storePost(Post post) {
215 checkNotNull(post, "post must not be null");
216 lock.writeLock().lock();
218 allPosts.put(post.getId(), post);
219 getPostsFrom(post.getSone().getId()).add(post);
220 if (post.getRecipientId().isPresent()) {
221 getPostsTo(post.getRecipientId().get()).add(post);
224 lock.writeLock().unlock();
228 /** {@inheritDocs} */
230 public void removePost(Post post) {
231 checkNotNull(post, "post must not be null");
232 lock.writeLock().lock();
234 allPosts.remove(post.getId());
235 getPostsFrom(post.getSone().getId()).remove(post);
236 if (post.getRecipientId().isPresent()) {
237 getPostsTo(post.getRecipientId().get()).remove(post);
239 post.getSone().removePost(post);
241 lock.writeLock().unlock();
245 /** {@inheritDocs} */
247 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
248 checkNotNull(sone, "sone must not be null");
249 /* verify that all posts are from the same Sone. */
250 for (Post post : posts) {
251 if (!sone.equals(post.getSone())) {
252 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
256 lock.writeLock().lock();
258 /* remove all posts by the Sone. */
259 getPostsFrom(sone.getId()).clear();
260 for (Post post : posts) {
261 allPosts.remove(post.getId());
262 if (post.getRecipientId().isPresent()) {
263 getPostsTo(post.getRecipientId().get()).remove(post);
268 getPostsFrom(sone.getId()).addAll(posts);
269 for (Post post : posts) {
270 allPosts.put(post.getId(), post);
271 if (post.getRecipientId().isPresent()) {
272 getPostsTo(post.getRecipientId().get()).add(post);
276 lock.writeLock().unlock();
280 /** {@inheritDocs} */
282 public void removePosts(Sone sone) {
283 checkNotNull(sone, "sone must not be null");
284 lock.writeLock().lock();
286 /* remove all posts by the Sone. */
287 getPostsFrom(sone.getId()).clear();
288 for (Post post : sone.getPosts()) {
289 allPosts.remove(post.getId());
290 if (post.getRecipientId().isPresent()) {
291 getPostsTo(post.getRecipientId().get()).remove(post);
295 lock.writeLock().unlock();
300 // POSTREPLYPROVIDER METHODS
303 /** {@inheritDocs} */
305 public Optional<PostReply> getPostReply(String id) {
306 lock.readLock().lock();
308 return fromNullable(allPostReplies.get(id));
310 lock.readLock().unlock();
314 /** {@inheritDocs} */
316 public List<PostReply> getReplies(String postId) {
317 lock.readLock().lock();
319 if (!postReplies.containsKey(postId)) {
320 return Collections.emptyList();
322 return new ArrayList<PostReply>(postReplies.get(postId));
324 lock.readLock().unlock();
329 // POSTREPLYBUILDERFACTORY METHODS
332 /** {@inheritDocs} */
334 public PostReplyBuilder newPostReplyBuilder() {
335 return new MemoryPostReplyBuilder(this, soneProvider);
339 // POSTREPLYSTORE METHODS
342 /** {@inheritDocs} */
344 public void storePostReply(PostReply postReply) {
345 lock.writeLock().lock();
347 allPostReplies.put(postReply.getId(), postReply);
348 if (postReplies.containsKey(postReply.getPostId())) {
349 postReplies.get(postReply.getPostId()).add(postReply);
351 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
352 replies.add(postReply);
353 postReplies.put(postReply.getPostId(), replies);
356 lock.writeLock().unlock();
360 /** {@inheritDocs} */
362 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
363 checkNotNull(sone, "sone must not be null");
364 /* verify that all posts are from the same Sone. */
365 for (PostReply postReply : postReplies) {
366 if (!sone.equals(postReply.getSone())) {
367 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
371 lock.writeLock().lock();
373 /* remove all post replies of the Sone. */
374 for (PostReply postReply : getRepliesFrom(sone.getId())) {
375 removePostReply(postReply);
377 for (PostReply postReply : postReplies) {
378 allPostReplies.put(postReply.getId(), postReply);
379 sonePostReplies.put(postReply.getSone().getId(), postReply);
380 if (this.postReplies.containsKey(postReply.getPostId())) {
381 this.postReplies.get(postReply.getPostId()).add(postReply);
383 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
384 replies.add(postReply);
385 this.postReplies.put(postReply.getPostId(), replies);
389 lock.writeLock().unlock();
393 /** {@inheritDocs} */
395 public void removePostReply(PostReply postReply) {
396 lock.writeLock().lock();
398 allPostReplies.remove(postReply.getId());
399 if (postReplies.containsKey(postReply.getPostId())) {
400 postReplies.get(postReply.getPostId()).remove(postReply);
401 if (postReplies.get(postReply.getPostId()).isEmpty()) {
402 postReplies.remove(postReply.getPostId());
406 lock.writeLock().unlock();
410 /** {@inheritDocs} */
412 public void removePostReplies(Sone sone) {
413 checkNotNull(sone, "sone must not be null");
415 lock.writeLock().lock();
417 for (PostReply postReply : sone.getReplies()) {
418 removePostReply(postReply);
421 lock.writeLock().unlock();
426 // ALBUMPROVDER METHODS
430 public Optional<Album> getAlbum(String albumId) {
431 lock.readLock().lock();
433 return fromNullable(allAlbums.get(albumId));
435 lock.readLock().unlock();
440 // ALBUMSTORE METHODS
444 public void storeAlbum(Album album) {
445 lock.writeLock().lock();
447 allAlbums.put(album.getId(), album);
448 albumChildren.put(album.getParent().getId(), album.getId());
450 lock.writeLock().unlock();
455 public void removeAlbum(Album album) {
456 lock.writeLock().lock();
458 allAlbums.remove(album.getId());
459 albumChildren.remove(album.getParent().getId(), album.getId());
461 lock.writeLock().unlock();
466 // IMAGEPROVIDER METHODS
470 public Optional<Image> getImage(String imageId) {
471 lock.readLock().lock();
473 return fromNullable(allImages.get(imageId));
475 lock.readLock().unlock();
480 // IMAGESTORE METHODS
484 public void storeImage(Image image) {
485 lock.writeLock().lock();
487 allImages.put(image.getId(), image);
488 albumImages.put(image.getAlbum().getId(), image.getId());
490 lock.writeLock().unlock();
495 public void removeImage(Image image) {
496 lock.writeLock().lock();
498 allImages.remove(image.getId());
499 albumImages.remove(image.getAlbum().getId(), image.getId());
501 lock.writeLock().unlock();
506 // PACKAGE-PRIVATE METHODS
510 * Returns whether the given post is known.
514 * @return {@code true} if the post is known, {@code false} otherwise
516 boolean isPostKnown(Post post) {
517 lock.readLock().lock();
519 return knownPosts.contains(post.getId());
521 lock.readLock().unlock();
526 * Sets whether the given post is known.
531 * {@code true} if the post is known, {@code false} otherwise
533 void setPostKnown(Post post, boolean known) {
534 lock.writeLock().lock();
537 knownPosts.add(post.getId());
539 knownPosts.remove(post.getId());
542 lock.writeLock().unlock();
547 * Returns whether the given post reply is known.
551 * @return {@code true} if the given post reply is known, {@code false}
554 boolean isPostReplyKnown(PostReply postReply) {
555 lock.readLock().lock();
557 return knownPostReplies.contains(postReply.getId());
559 lock.readLock().unlock();
564 * Sets whether the given post reply is known.
569 * {@code true} if the post reply is known, {@code false} otherwise
571 void setPostReplyKnown(PostReply postReply, boolean known) {
572 lock.writeLock().lock();
575 knownPostReplies.add(postReply.getId());
577 knownPostReplies.remove(postReply.getId());
580 lock.writeLock().unlock();
584 void moveUp(Album album) {
585 lock.writeLock().lock();
587 List<String> albums = albumChildren.get(album.getParent().getId());
588 int currentIndex = albums.indexOf(album.getId());
589 if (currentIndex == 0) {
592 albums.remove(album.getId());
593 albums.add(currentIndex - 1, album.getId());
595 lock.writeLock().unlock();
599 void moveDown(Album album) {
600 lock.writeLock().lock();
602 List<String> albums = albumChildren.get(album.getParent().getId());
603 int currentIndex = albums.indexOf(album.getId());
604 if (currentIndex == (albums.size() - 1)) {
607 albums.remove(album.getId());
608 albums.add(currentIndex + 1, album.getId());
610 lock.writeLock().unlock();
614 void moveUp(Image image) {
615 lock.writeLock().lock();
617 List<String> images = albumImages.get(image.getAlbum().getId());
618 int currentIndex = images.indexOf(image.getId());
619 if (currentIndex == 0) {
622 images.remove(image.getId());
623 images.add(currentIndex - 1, image.getId());
625 lock.writeLock().unlock();
629 void moveDown(Image image) {
630 lock.writeLock().lock();
632 List<String> images = albumChildren.get(image.getAlbum().getId());
633 int currentIndex = images.indexOf(image.getId());
634 if (currentIndex == (images.size() - 1)) {
637 images.remove(image.getId());
638 images.add(currentIndex + 1, image.getId());
640 lock.writeLock().unlock();
649 * Gets all posts for the given Sone, creating a new collection if there is
653 * The ID of the Sone to get the posts for
656 private Collection<Post> getPostsFrom(String soneId) {
657 Collection<Post> posts = null;
658 lock.readLock().lock();
660 posts = sonePosts.get(soneId);
662 lock.readLock().unlock();
668 posts = new HashSet<Post>();
669 lock.writeLock().lock();
671 sonePosts.put(soneId, posts);
673 lock.writeLock().unlock();
680 * Gets all posts that are directed the given Sone, creating a new collection
681 * if there is none yet.
684 * The ID of the Sone to get the posts for
687 private Collection<Post> getPostsTo(String recipientId) {
688 Collection<Post> posts = null;
689 lock.readLock().lock();
691 posts = recipientPosts.get(recipientId);
693 lock.readLock().unlock();
699 posts = new HashSet<Post>();
700 lock.writeLock().lock();
702 recipientPosts.put(recipientId, posts);
704 lock.writeLock().unlock();
710 /** Loads the known posts. */
711 private void loadKnownPosts() {
712 lock.writeLock().lock();
716 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
717 if (knownPostId == null) {
720 knownPosts.add(knownPostId);
723 lock.writeLock().unlock();
728 * Saves the known posts to the configuration.
730 * @throws DatabaseException
731 * if a configuration error occurs
733 private void saveKnownPosts() throws DatabaseException {
734 lock.readLock().lock();
737 for (String knownPostId : knownPosts) {
738 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
740 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
741 } catch (ConfigurationException ce1) {
742 throw new DatabaseException("Could not save database.", ce1);
744 lock.readLock().unlock();
749 * Returns all replies by the given Sone.
753 * @return The post replies of the Sone, sorted by time (newest first)
755 private Collection<PostReply> getRepliesFrom(String id) {
756 lock.readLock().lock();
758 if (sonePostReplies.containsKey(id)) {
759 return Collections.unmodifiableCollection(sonePostReplies.get(id));
761 return Collections.emptySet();
763 lock.readLock().unlock();
767 /** Loads the known post replies. */
768 private void loadKnownPostReplies() {
769 lock.writeLock().lock();
771 int replyCounter = 0;
773 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
774 if (knownReplyId == null) {
777 knownPostReplies.add(knownReplyId);
780 lock.writeLock().unlock();
785 * Saves the known post replies to the configuration.
787 * @throws DatabaseException
788 * if a configuration error occurs
790 private void saveKnownPostReplies() throws DatabaseException {
791 lock.readLock().lock();
793 int replyCounter = 0;
794 for (String knownReplyId : knownPostReplies) {
795 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
797 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
798 } catch (ConfigurationException ce1) {
799 throw new DatabaseException("Could not save database.", ce1);
801 lock.readLock().unlock();