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 public void storePostReply(PostReply postReply) {
351 lock.writeLock().lock();
353 allPostReplies.put(postReply.getId(), postReply);
354 if (postReplies.containsKey(postReply.getPostId())) {
355 postReplies.get(postReply.getPostId()).add(postReply);
357 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
358 replies.add(postReply);
359 postReplies.put(postReply.getPostId(), replies);
362 lock.writeLock().unlock();
367 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
368 checkNotNull(sone, "sone must not be null");
369 /* verify that all posts are from the same Sone. */
370 for (PostReply postReply : postReplies) {
371 if (!sone.equals(postReply.getSone())) {
372 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
376 lock.writeLock().lock();
378 /* remove all post replies of the Sone. */
379 for (PostReply postReply : getRepliesFrom(sone.getId())) {
380 removePostReply(postReply);
382 for (PostReply postReply : postReplies) {
383 allPostReplies.put(postReply.getId(), postReply);
384 sonePostReplies.put(postReply.getSone().getId(), postReply);
385 if (this.postReplies.containsKey(postReply.getPostId())) {
386 this.postReplies.get(postReply.getPostId()).add(postReply);
388 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
389 replies.add(postReply);
390 this.postReplies.put(postReply.getPostId(), replies);
394 lock.writeLock().unlock();
399 public void removePostReply(PostReply postReply) {
400 lock.writeLock().lock();
402 allPostReplies.remove(postReply.getId());
403 if (postReplies.containsKey(postReply.getPostId())) {
404 postReplies.get(postReply.getPostId()).remove(postReply);
405 if (postReplies.get(postReply.getPostId()).isEmpty()) {
406 postReplies.remove(postReply.getPostId());
410 lock.writeLock().unlock();
415 public void removePostReplies(Sone sone) {
416 checkNotNull(sone, "sone must not be null");
418 lock.writeLock().lock();
420 for (PostReply postReply : sone.getReplies()) {
421 removePostReply(postReply);
424 lock.writeLock().unlock();
429 // ALBUMPROVDER METHODS
433 public Optional<Album> getAlbum(String albumId) {
434 lock.readLock().lock();
436 return fromNullable(allAlbums.get(albumId));
438 lock.readLock().unlock();
443 public List<Album> getAlbums(Album parent) {
444 lock.readLock().lock();
446 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
448 lock.readLock().unlock();
453 public void moveUp(Album album) {
454 lock.writeLock().lock();
456 List<String> albums = albumChildren.get(album.getParent().getId());
457 int currentIndex = albums.indexOf(album.getId());
458 if (currentIndex == 0) {
461 albums.remove(album.getId());
462 albums.add(currentIndex - 1, album.getId());
464 lock.writeLock().unlock();
469 public void moveDown(Album album) {
470 lock.writeLock().lock();
472 List<String> albums = albumChildren.get(album.getParent().getId());
473 int currentIndex = albums.indexOf(album.getId());
474 if (currentIndex == (albums.size() - 1)) {
477 albums.remove(album.getId());
478 albums.add(currentIndex + 1, album.getId());
480 lock.writeLock().unlock();
485 // ALBUMSTORE METHODS
489 public void storeAlbum(Album album) {
490 lock.writeLock().lock();
492 allAlbums.put(album.getId(), album);
493 albumChildren.put(album.getParent().getId(), album.getId());
495 lock.writeLock().unlock();
500 public void removeAlbum(Album album) {
501 lock.writeLock().lock();
503 allAlbums.remove(album.getId());
504 albumChildren.remove(album.getParent().getId(), album.getId());
506 lock.writeLock().unlock();
511 // IMAGEPROVIDER METHODS
515 public Optional<Image> getImage(String imageId) {
516 lock.readLock().lock();
518 return fromNullable(allImages.get(imageId));
520 lock.readLock().unlock();
525 public List<Image> getImages(Album parent) {
526 lock.readLock().lock();
528 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
530 lock.readLock().unlock();
535 public void moveUp(Image image) {
536 lock.writeLock().lock();
538 List<String> images = albumImages.get(image.getAlbum().getId());
539 int currentIndex = images.indexOf(image.getId());
540 if (currentIndex == 0) {
543 images.remove(image.getId());
544 images.add(currentIndex - 1, image.getId());
546 lock.writeLock().unlock();
551 public void moveDown(Image image) {
552 lock.writeLock().lock();
554 List<String> images = albumChildren.get(image.getAlbum().getId());
555 int currentIndex = images.indexOf(image.getId());
556 if (currentIndex == (images.size() - 1)) {
559 images.remove(image.getId());
560 images.add(currentIndex + 1, image.getId());
562 lock.writeLock().unlock();
567 // IMAGESTORE METHODS
571 public void storeImage(Image image) {
572 lock.writeLock().lock();
574 allImages.put(image.getId(), image);
575 albumImages.put(image.getAlbum().getId(), image.getId());
577 lock.writeLock().unlock();
582 public void removeImage(Image image) {
583 lock.writeLock().lock();
585 allImages.remove(image.getId());
586 albumImages.remove(image.getAlbum().getId(), image.getId());
588 lock.writeLock().unlock();
593 // PACKAGE-PRIVATE METHODS
597 * Returns whether the given post is known.
601 * @return {@code true} if the post is known, {@code false} otherwise
603 boolean isPostKnown(Post post) {
604 lock.readLock().lock();
606 return knownPosts.contains(post.getId());
608 lock.readLock().unlock();
613 * Sets whether the given post is known.
618 * {@code true} if the post is known, {@code false} otherwise
620 void setPostKnown(Post post, boolean known) {
621 lock.writeLock().lock();
624 knownPosts.add(post.getId());
626 knownPosts.remove(post.getId());
629 lock.writeLock().unlock();
634 * Returns whether the given post reply is known.
638 * @return {@code true} if the given post reply is known, {@code false}
641 boolean isPostReplyKnown(PostReply postReply) {
642 lock.readLock().lock();
644 return knownPostReplies.contains(postReply.getId());
646 lock.readLock().unlock();
651 * Sets whether the given post reply is known.
656 * {@code true} if the post reply is known, {@code false} otherwise
658 void setPostReplyKnown(PostReply postReply, boolean known) {
659 lock.writeLock().lock();
662 knownPostReplies.add(postReply.getId());
664 knownPostReplies.remove(postReply.getId());
667 lock.writeLock().unlock();
676 * Gets all posts for the given Sone, creating a new collection if there is
680 * The ID of the Sone to get the posts for
683 private Collection<Post> getPostsFrom(String soneId) {
684 Collection<Post> posts = null;
685 lock.readLock().lock();
687 posts = sonePosts.get(soneId);
689 lock.readLock().unlock();
695 posts = new HashSet<Post>();
696 lock.writeLock().lock();
698 sonePosts.put(soneId, posts);
700 lock.writeLock().unlock();
707 * Gets all posts that are directed the given Sone, creating a new collection
708 * if there is none yet.
711 * The ID of the Sone to get the posts for
714 private Collection<Post> getPostsTo(String recipientId) {
715 Collection<Post> posts = null;
716 lock.readLock().lock();
718 posts = recipientPosts.get(recipientId);
720 lock.readLock().unlock();
726 posts = new HashSet<Post>();
727 lock.writeLock().lock();
729 recipientPosts.put(recipientId, posts);
731 lock.writeLock().unlock();
737 /** Loads the known posts. */
738 private void loadKnownPosts() {
739 lock.writeLock().lock();
743 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
744 if (knownPostId == null) {
747 knownPosts.add(knownPostId);
750 lock.writeLock().unlock();
755 * Saves the known posts to the configuration.
757 * @throws DatabaseException
758 * if a configuration error occurs
760 private void saveKnownPosts() throws DatabaseException {
761 lock.readLock().lock();
764 for (String knownPostId : knownPosts) {
765 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
767 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
768 } catch (ConfigurationException ce1) {
769 throw new DatabaseException("Could not save database.", ce1);
771 lock.readLock().unlock();
776 * Returns all replies by the given Sone.
780 * @return The post replies of the Sone, sorted by time (newest first)
782 private Collection<PostReply> getRepliesFrom(String id) {
783 lock.readLock().lock();
785 if (sonePostReplies.containsKey(id)) {
786 return Collections.unmodifiableCollection(sonePostReplies.get(id));
788 return Collections.emptySet();
790 lock.readLock().unlock();
794 /** Loads the known post replies. */
795 private void loadKnownPostReplies() {
796 lock.writeLock().lock();
798 int replyCounter = 0;
800 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
801 if (knownReplyId == null) {
804 knownPostReplies.add(knownReplyId);
807 lock.writeLock().unlock();
812 * Saves the known post replies to the configuration.
814 * @throws DatabaseException
815 * if a configuration error occurs
817 private void saveKnownPostReplies() throws DatabaseException {
818 lock.readLock().lock();
820 int replyCounter = 0;
821 for (String knownReplyId : knownPostReplies) {
822 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
824 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
825 } catch (ConfigurationException ce1) {
826 throw new DatabaseException("Could not save database.", ce1);
828 lock.readLock().unlock();
832 private Function<String, Iterable<Album>> getAlbum() {
833 return new Function<String, Iterable<Album>>() {
835 public Iterable<Album> apply(String input) {
836 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
841 private Function<String, Iterable<Image>> getImage() {
842 return new Function<String, Iterable<Image>>() {
844 public Iterable<Image> apply(String input) {
845 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();