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.data.impl.AlbumBuilderImpl;
44 import net.pterodactylus.sone.data.impl.ImageBuilderImpl;
45 import net.pterodactylus.sone.database.AlbumBuilder;
46 import net.pterodactylus.sone.database.Database;
47 import net.pterodactylus.sone.database.DatabaseException;
48 import net.pterodactylus.sone.database.ImageBuilder;
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.SoneProvider;
53 import net.pterodactylus.util.config.Configuration;
54 import net.pterodactylus.util.config.ConfigurationException;
56 import com.google.common.base.Optional;
57 import com.google.common.collect.HashMultimap;
58 import com.google.common.collect.Multimap;
59 import com.google.common.collect.SortedSetMultimap;
60 import com.google.common.collect.TreeMultimap;
61 import com.google.common.util.concurrent.AbstractService;
62 import com.google.inject.Inject;
65 * Memory-based {@link PostDatabase} implementation.
67 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
69 public class MemoryDatabase extends AbstractService implements Database {
72 private final ReadWriteLock lock = new ReentrantReadWriteLock();
74 /** The Sone provider. */
75 private final SoneProvider soneProvider;
77 /** The configuration. */
78 private final Configuration configuration;
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 Multimap<String, Post> sonePosts = HashMultimap.create();
86 /** All posts by their recipient. */
87 private final Multimap<String, Post> recipientPosts = HashMultimap.create();
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>();
112 private final Map<String, Image> allImages = new HashMap<String, Image>();
115 * Creates a new memory database.
117 * @param soneProvider
119 * @param configuration
120 * The configuration for loading and saving elements
123 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
124 this.soneProvider = soneProvider;
125 this.configuration = configuration;
133 * Saves the database.
135 * @throws DatabaseException
136 * if an error occurs while saving
139 public void save() throws DatabaseException {
141 saveKnownPostReplies();
148 /** {@inheritDocs} */
150 protected void doStart() {
152 loadKnownPostReplies();
156 /** {@inheritDocs} */
158 protected void doStop() {
162 } catch (DatabaseException de1) {
168 // POSTPROVIDER METHODS
171 /** {@inheritDocs} */
173 public Optional<Post> getPost(String postId) {
174 lock.readLock().lock();
176 return fromNullable(allPosts.get(postId));
178 lock.readLock().unlock();
182 /** {@inheritDocs} */
184 public Collection<Post> getPosts(String soneId) {
185 return new HashSet<Post>(getPostsFrom(soneId));
188 /** {@inheritDocs} */
190 public Collection<Post> getDirectedPosts(String recipientId) {
191 lock.readLock().lock();
193 Collection<Post> posts = recipientPosts.get(recipientId);
194 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
196 lock.readLock().unlock();
201 // POSTBUILDERFACTORY METHODS
204 /** {@inheritDocs} */
206 public PostBuilder newPostBuilder() {
207 return new MemoryPostBuilder(this, soneProvider);
214 /** {@inheritDocs} */
216 public void storePost(Post post) {
217 checkNotNull(post, "post must not be null");
218 lock.writeLock().lock();
220 allPosts.put(post.getId(), post);
221 getPostsFrom(post.getSone().getId()).add(post);
222 if (post.getRecipientId().isPresent()) {
223 getPostsTo(post.getRecipientId().get()).add(post);
226 lock.writeLock().unlock();
230 /** {@inheritDocs} */
232 public void removePost(Post post) {
233 checkNotNull(post, "post must not be null");
234 lock.writeLock().lock();
236 allPosts.remove(post.getId());
237 getPostsFrom(post.getSone().getId()).remove(post);
238 if (post.getRecipientId().isPresent()) {
239 getPostsTo(post.getRecipientId().get()).remove(post);
241 post.getSone().removePost(post);
243 lock.writeLock().unlock();
247 /** {@inheritDocs} */
249 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
250 checkNotNull(sone, "sone must not be null");
251 /* verify that all posts are from the same Sone. */
252 for (Post post : posts) {
253 if (!sone.equals(post.getSone())) {
254 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
258 lock.writeLock().lock();
260 /* remove all posts by the Sone. */
261 Collection<Post> oldPosts = getPostsFrom(sone.getId());
262 for (Post post : oldPosts) {
263 allPosts.remove(post.getId());
264 if (post.getRecipientId().isPresent()) {
265 getPostsTo(post.getRecipientId().get()).remove(post);
270 getPostsFrom(sone.getId()).addAll(posts);
271 for (Post post : posts) {
272 allPosts.put(post.getId(), post);
273 if (post.getRecipientId().isPresent()) {
274 getPostsTo(post.getRecipientId().get()).add(post);
278 lock.writeLock().unlock();
282 /** {@inheritDocs} */
284 public void removePosts(Sone sone) {
285 checkNotNull(sone, "sone must not be null");
286 lock.writeLock().lock();
288 /* remove all posts by the Sone. */
289 getPostsFrom(sone.getId()).clear();
290 for (Post post : sone.getPosts()) {
291 allPosts.remove(post.getId());
292 if (post.getRecipientId().isPresent()) {
293 getPostsTo(post.getRecipientId().get()).remove(post);
297 lock.writeLock().unlock();
302 // POSTREPLYPROVIDER METHODS
305 /** {@inheritDocs} */
307 public Optional<PostReply> getPostReply(String id) {
308 lock.readLock().lock();
310 return fromNullable(allPostReplies.get(id));
312 lock.readLock().unlock();
316 /** {@inheritDocs} */
318 public List<PostReply> getReplies(String postId) {
319 lock.readLock().lock();
321 if (!postReplies.containsKey(postId)) {
322 return Collections.emptyList();
324 return new ArrayList<PostReply>(postReplies.get(postId));
326 lock.readLock().unlock();
331 // POSTREPLYBUILDERFACTORY METHODS
334 /** {@inheritDocs} */
336 public PostReplyBuilder newPostReplyBuilder() {
337 return new MemoryPostReplyBuilder(this, soneProvider);
341 // POSTREPLYSTORE METHODS
344 /** {@inheritDocs} */
346 public void storePostReply(PostReply postReply) {
347 lock.writeLock().lock();
349 allPostReplies.put(postReply.getId(), postReply);
350 if (postReplies.containsKey(postReply.getPostId())) {
351 postReplies.get(postReply.getPostId()).add(postReply);
353 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
354 replies.add(postReply);
355 postReplies.put(postReply.getPostId(), replies);
358 lock.writeLock().unlock();
362 /** {@inheritDocs} */
364 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
365 checkNotNull(sone, "sone must not be null");
366 /* verify that all posts are from the same Sone. */
367 for (PostReply postReply : postReplies) {
368 if (!sone.equals(postReply.getSone())) {
369 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
373 lock.writeLock().lock();
375 /* remove all post replies of the Sone. */
376 for (PostReply postReply : getRepliesFrom(sone.getId())) {
377 removePostReply(postReply);
379 for (PostReply postReply : postReplies) {
380 allPostReplies.put(postReply.getId(), postReply);
381 sonePostReplies.put(postReply.getSone().getId(), postReply);
382 if (this.postReplies.containsKey(postReply.getPostId())) {
383 this.postReplies.get(postReply.getPostId()).add(postReply);
385 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
386 replies.add(postReply);
387 this.postReplies.put(postReply.getPostId(), replies);
391 lock.writeLock().unlock();
395 /** {@inheritDocs} */
397 public void removePostReply(PostReply postReply) {
398 lock.writeLock().lock();
400 allPostReplies.remove(postReply.getId());
401 if (postReplies.containsKey(postReply.getPostId())) {
402 postReplies.get(postReply.getPostId()).remove(postReply);
403 if (postReplies.get(postReply.getPostId()).isEmpty()) {
404 postReplies.remove(postReply.getPostId());
408 lock.writeLock().unlock();
412 /** {@inheritDocs} */
414 public void removePostReplies(Sone sone) {
415 checkNotNull(sone, "sone must not be null");
417 lock.writeLock().lock();
419 for (PostReply postReply : sone.getReplies()) {
420 removePostReply(postReply);
423 lock.writeLock().unlock();
428 // ALBUMPROVDER METHODS
432 public Optional<Album> getAlbum(String albumId) {
433 lock.readLock().lock();
435 return fromNullable(allAlbums.get(albumId));
437 lock.readLock().unlock();
442 // ALBUMBUILDERFACTORY METHODS
446 public AlbumBuilder newAlbumBuilder() {
447 return new AlbumBuilderImpl();
451 // ALBUMSTORE METHODS
455 public void storeAlbum(Album album) {
456 lock.writeLock().lock();
458 allAlbums.put(album.getId(), album);
460 lock.writeLock().unlock();
465 public void removeAlbum(Album album) {
466 lock.writeLock().lock();
468 allAlbums.remove(album.getId());
470 lock.writeLock().unlock();
475 // IMAGEPROVIDER METHODS
479 public Optional<Image> getImage(String imageId) {
480 lock.readLock().lock();
482 return fromNullable(allImages.get(imageId));
484 lock.readLock().unlock();
489 // IMAGEBUILDERFACTORY METHODS
493 public ImageBuilder newImageBuilder() {
494 return new ImageBuilderImpl();
498 // IMAGESTORE METHODS
502 public void storeImage(Image image) {
503 lock.writeLock().lock();
505 allImages.put(image.getId(), image);
507 lock.writeLock().unlock();
512 public void removeImage(Image image) {
513 lock.writeLock().lock();
515 allImages.remove(image.getId());
517 lock.writeLock().unlock();
522 // PACKAGE-PRIVATE METHODS
526 * Returns whether the given post is known.
530 * @return {@code true} if the post is known, {@code false} otherwise
532 boolean isPostKnown(Post post) {
533 lock.readLock().lock();
535 return knownPosts.contains(post.getId());
537 lock.readLock().unlock();
542 * Sets whether the given post is known.
547 * {@code true} if the post is known, {@code false} otherwise
549 void setPostKnown(Post post, boolean known) {
550 lock.writeLock().lock();
553 knownPosts.add(post.getId());
555 knownPosts.remove(post.getId());
558 lock.writeLock().unlock();
563 * Returns whether the given post reply is known.
567 * @return {@code true} if the given post reply is known, {@code false}
570 boolean isPostReplyKnown(PostReply postReply) {
571 lock.readLock().lock();
573 return knownPostReplies.contains(postReply.getId());
575 lock.readLock().unlock();
580 * Sets whether the given post reply is known.
585 * {@code true} if the post reply is known, {@code false} otherwise
587 void setPostReplyKnown(PostReply postReply, boolean known) {
588 lock.writeLock().lock();
591 knownPostReplies.add(postReply.getId());
593 knownPostReplies.remove(postReply.getId());
596 lock.writeLock().unlock();
605 * Gets all posts for the given Sone, creating a new collection if there is
609 * The ID of the Sone to get the posts for
612 private Collection<Post> getPostsFrom(String soneId) {
613 lock.readLock().lock();
615 return sonePosts.get(soneId);
617 lock.readLock().unlock();
622 * Gets all posts that are directed the given Sone, creating a new collection
623 * if there is none yet.
626 * The ID of the Sone to get the posts for
629 private Collection<Post> getPostsTo(String recipientId) {
630 lock.readLock().lock();
632 return recipientPosts.get(recipientId);
634 lock.readLock().unlock();
638 /** Loads the known posts. */
639 private void loadKnownPosts() {
640 lock.writeLock().lock();
644 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
645 if (knownPostId == null) {
648 knownPosts.add(knownPostId);
651 lock.writeLock().unlock();
656 * Saves the known posts to the configuration.
658 * @throws DatabaseException
659 * if a configuration error occurs
661 private void saveKnownPosts() throws DatabaseException {
662 lock.readLock().lock();
665 for (String knownPostId : knownPosts) {
666 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
668 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
669 } catch (ConfigurationException ce1) {
670 throw new DatabaseException("Could not save database.", ce1);
672 lock.readLock().unlock();
677 * Returns all replies by the given Sone.
681 * @return The post replies of the Sone, sorted by time (newest first)
683 private Collection<PostReply> getRepliesFrom(String id) {
684 lock.readLock().lock();
686 if (sonePostReplies.containsKey(id)) {
687 return Collections.unmodifiableCollection(sonePostReplies.get(id));
689 return Collections.emptySet();
691 lock.readLock().unlock();
695 /** Loads the known post replies. */
696 private void loadKnownPostReplies() {
697 lock.writeLock().lock();
699 int replyCounter = 0;
701 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
702 if (knownReplyId == null) {
705 knownPostReplies.add(knownReplyId);
708 lock.writeLock().unlock();
713 * Saves the known post replies to the configuration.
715 * @throws DatabaseException
716 * if a configuration error occurs
718 private void saveKnownPostReplies() throws DatabaseException {
719 lock.readLock().lock();
721 int replyCounter = 0;
722 for (String knownReplyId : knownPostReplies) {
723 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
725 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
726 } catch (ConfigurationException ce1) {
727 throw new DatabaseException("Could not save database.", ce1);
729 lock.readLock().unlock();