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.Preconditions.checkNotNull;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.Comparator;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.List;
31 import java.util.SortedSet;
32 import java.util.TreeSet;
33 import java.util.concurrent.locks.ReadWriteLock;
34 import java.util.concurrent.locks.ReentrantReadWriteLock;
36 import net.pterodactylus.sone.data.Post;
37 import net.pterodactylus.sone.data.PostReply;
38 import net.pterodactylus.sone.data.Reply;
39 import net.pterodactylus.sone.data.Sone;
40 import net.pterodactylus.sone.database.Database;
41 import net.pterodactylus.sone.database.DatabaseException;
42 import net.pterodactylus.sone.database.PostBuilder;
43 import net.pterodactylus.sone.database.PostDatabase;
44 import net.pterodactylus.sone.database.PostReplyBuilder;
45 import net.pterodactylus.sone.database.SoneProvider;
46 import net.pterodactylus.util.config.Configuration;
47 import net.pterodactylus.util.config.ConfigurationException;
49 import com.google.common.base.Optional;
50 import com.google.common.collect.SortedSetMultimap;
51 import com.google.common.collect.TreeMultimap;
52 import com.google.common.util.concurrent.AbstractService;
53 import com.google.inject.Inject;
56 * Memory-based {@link PostDatabase} implementation.
58 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
60 public class MemoryDatabase extends AbstractService implements Database {
63 private final ReadWriteLock lock = new ReentrantReadWriteLock();
65 /** The Sone provider. */
66 private final SoneProvider soneProvider;
68 /** The configuration. */
69 private final Configuration configuration;
71 /** All posts by their ID. */
72 private final Map<String, Post> allPosts = new HashMap<String, Post>();
74 /** All posts by their Sones. */
75 private final Map<String, Collection<Post>> sonePosts = new HashMap<String, Collection<Post>>();
77 /** All posts by their recipient. */
78 private final Map<String, Collection<Post>> recipientPosts = new HashMap<String, Collection<Post>>();
80 /** Whether posts are known. */
81 private final Set<String> knownPosts = new HashSet<String>();
83 /** All post replies by their ID. */
84 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
86 /** Replies sorted by Sone. */
87 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
90 public int compare(String leftString, String rightString) {
91 return leftString.compareTo(rightString);
93 }, PostReply.TIME_COMPARATOR);
95 /** Replies by post. */
96 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
98 /** Whether post replies are known. */
99 private final Set<String> knownPostReplies = new HashSet<String>();
102 * Creates a new memory database.
104 * @param soneProvider
106 * @param configuration
107 * The configuration for loading and saving elements
110 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
111 this.soneProvider = soneProvider;
112 this.configuration = configuration;
120 * Saves the database.
122 * @throws DatabaseException
123 * if an error occurs while saving
126 public void save() throws DatabaseException {
128 saveKnownPostReplies();
139 protected void doStart() {
141 loadKnownPostReplies();
149 protected void doStop() {
153 } catch (DatabaseException de1) {
159 // POSTPROVIDER METHODS
166 public Optional<Post> getPost(String postId) {
167 lock.readLock().lock();
169 return Optional.fromNullable(allPosts.get(postId));
171 lock.readLock().unlock();
179 public Collection<Post> getPosts(String soneId) {
180 return new HashSet<Post>(getPostsFrom(soneId));
187 public Collection<Post> getDirectedPosts(String recipientId) {
188 lock.readLock().lock();
190 Collection<Post> posts = recipientPosts.get(recipientId);
191 return (posts == null) ? Collections.<Post> emptySet() : new HashSet<Post>(posts);
193 lock.readLock().unlock();
198 // POSTBUILDERFACTORY METHODS
205 public PostBuilder newPostBuilder() {
206 return new MemoryPostBuilder(this, soneProvider);
217 public void storePost(Post post) {
218 checkNotNull(post, "post must not be null");
219 lock.writeLock().lock();
221 allPosts.put(post.getId(), post);
222 getPostsFrom(post.getSone().getId()).add(post);
223 if (post.getRecipientId().isPresent()) {
224 getPostsTo(post.getRecipientId().get()).add(post);
227 lock.writeLock().unlock();
235 public void removePost(Post post) {
236 checkNotNull(post, "post must not be null");
237 lock.writeLock().lock();
239 allPosts.remove(post.getId());
240 getPostsFrom(post.getSone().getId()).remove(post);
241 if (post.getRecipientId().isPresent()) {
242 getPostsTo(post.getRecipientId().get()).remove(post);
244 post.getSone().removePost(post);
246 lock.writeLock().unlock();
254 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
255 checkNotNull(sone, "sone must not be null");
256 /* verify that all posts are from the same Sone. */
257 for (Post post : posts) {
258 if (!sone.equals(post.getSone())) {
259 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
263 lock.writeLock().lock();
265 /* remove all posts by the Sone. */
266 getPostsFrom(sone.getId()).clear();
267 for (Post post : posts) {
268 allPosts.remove(post.getId());
269 if (post.getRecipientId().isPresent()) {
270 getPostsTo(post.getRecipientId().get()).remove(post);
275 getPostsFrom(sone.getId()).addAll(posts);
276 for (Post post : posts) {
277 allPosts.put(post.getId(), post);
278 if (post.getRecipientId().isPresent()) {
279 getPostsTo(post.getRecipientId().get()).add(post);
283 lock.writeLock().unlock();
291 public void removePosts(Sone sone) {
292 checkNotNull(sone, "sone must not be null");
293 lock.writeLock().lock();
295 /* remove all posts by the Sone. */
296 getPostsFrom(sone.getId()).clear();
297 for (Post post : sone.getPosts()) {
298 allPosts.remove(post.getId());
299 if (post.getRecipientId().isPresent()) {
300 getPostsTo(post.getRecipientId().get()).remove(post);
304 lock.writeLock().unlock();
309 // POSTREPLYPROVIDER METHODS
316 public Optional<PostReply> getPostReply(String id) {
317 lock.readLock().lock();
319 return Optional.fromNullable(allPostReplies.get(id));
321 lock.readLock().unlock();
329 public List<PostReply> getReplies(String postId) {
330 lock.readLock().lock();
332 if (!postReplies.containsKey(postId)) {
333 return Collections.emptyList();
335 return new ArrayList<PostReply>(postReplies.get(postId));
337 lock.readLock().unlock();
342 // POSTREPLYBUILDERFACTORY METHODS
349 public PostReplyBuilder newPostReplyBuilder() {
350 return new MemoryPostReplyBuilder(this, soneProvider);
354 // POSTREPLYSTORE METHODS
361 public void storePostReply(PostReply postReply) {
362 lock.writeLock().lock();
364 allPostReplies.put(postReply.getId(), postReply);
365 if (postReplies.containsKey(postReply.getPostId())) {
366 postReplies.get(postReply.getPostId()).add(postReply);
368 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
369 replies.add(postReply);
370 postReplies.put(postReply.getPostId(), replies);
373 lock.writeLock().unlock();
381 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
382 checkNotNull(sone, "sone must not be null");
383 /* verify that all posts are from the same Sone. */
384 for (PostReply postReply : postReplies) {
385 if (!sone.equals(postReply.getSone())) {
386 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
390 lock.writeLock().lock();
392 /* remove all post replies of the Sone. */
393 for (PostReply postReply : getRepliesFrom(sone.getId())) {
394 removePostReply(postReply);
396 for (PostReply postReply : postReplies) {
397 allPostReplies.put(postReply.getId(), postReply);
398 sonePostReplies.put(postReply.getSone().getId(), postReply);
399 if (this.postReplies.containsKey(postReply.getPostId())) {
400 this.postReplies.get(postReply.getPostId()).add(postReply);
402 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
403 replies.add(postReply);
404 this.postReplies.put(postReply.getPostId(), replies);
408 lock.writeLock().unlock();
416 public void removePostReply(PostReply postReply) {
417 lock.writeLock().lock();
419 allPostReplies.remove(postReply.getId());
420 if (postReplies.containsKey(postReply.getPostId())) {
421 postReplies.get(postReply.getPostId()).remove(postReply);
422 if (postReplies.get(postReply.getPostId()).isEmpty()) {
423 postReplies.remove(postReply.getPostId());
427 lock.writeLock().unlock();
435 public void removePostReplies(Sone sone) {
436 checkNotNull(sone, "sone must not be null");
438 lock.writeLock().lock();
440 for (PostReply postReply : sone.getReplies()) {
441 removePostReply(postReply);
444 lock.writeLock().unlock();
449 // PACKAGE-PRIVATE METHODS
453 * Returns whether the given post is known.
457 * @return {@code true} if the post is known, {@code false} otherwise
459 boolean isPostKnown(Post post) {
460 lock.readLock().lock();
462 return knownPosts.contains(post.getId());
464 lock.readLock().unlock();
469 * Sets whether the given post is known.
474 * {@code true} if the post is known, {@code false} otherwise
476 void setPostKnown(Post post, boolean known) {
477 lock.writeLock().lock();
480 knownPosts.add(post.getId());
482 knownPosts.remove(post.getId());
485 lock.writeLock().unlock();
490 * Returns whether the given post reply is known.
494 * @return {@code true} if the given post reply is known, {@code false}
497 boolean isPostReplyKnown(PostReply postReply) {
498 lock.readLock().lock();
500 return knownPostReplies.contains(postReply.getId());
502 lock.readLock().unlock();
507 * Sets whether the given post reply is known.
512 * {@code true} if the post reply is known, {@code false}
515 void setPostReplyKnown(PostReply postReply, boolean known) {
516 lock.writeLock().lock();
519 knownPostReplies.add(postReply.getId());
521 knownPostReplies.remove(postReply.getId());
524 lock.writeLock().unlock();
533 * Gets all posts for the given Sone, creating a new collection if there is
537 * The ID of the Sone to get the posts for
540 private Collection<Post> getPostsFrom(String soneId) {
541 Collection<Post> posts = null;
542 lock.readLock().lock();
544 posts = sonePosts.get(soneId);
546 lock.readLock().unlock();
552 posts = new HashSet<Post>();
553 lock.writeLock().lock();
555 sonePosts.put(soneId, posts);
557 lock.writeLock().unlock();
564 * Gets all posts that are directed the given Sone, creating a new
565 * collection if there is none yet.
568 * The ID of the Sone to get the posts for
571 private Collection<Post> getPostsTo(String recipientId) {
572 Collection<Post> posts = null;
573 lock.readLock().lock();
575 posts = recipientPosts.get(recipientId);
577 lock.readLock().unlock();
583 posts = new HashSet<Post>();
584 lock.writeLock().lock();
586 recipientPosts.put(recipientId, posts);
588 lock.writeLock().unlock();
595 * Loads the known posts.
597 private void loadKnownPosts() {
598 lock.writeLock().lock();
602 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
603 if (knownPostId == null) {
606 knownPosts.add(knownPostId);
609 lock.writeLock().unlock();
614 * Saves the known posts to the configuration.
616 * @throws DatabaseException
617 * if a configuration error occurs
619 private void saveKnownPosts() throws DatabaseException {
620 lock.readLock().lock();
623 for (String knownPostId : knownPosts) {
624 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
626 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
627 } catch (ConfigurationException ce1) {
628 throw new DatabaseException("Could not save database.", ce1);
630 lock.readLock().unlock();
635 * Returns all replies by the given Sone.
639 * @return The post replies of the Sone, sorted by time (newest first)
641 private Collection<PostReply> getRepliesFrom(String id) {
642 lock.readLock().lock();
644 if (sonePostReplies.containsKey(id)) {
645 return Collections.unmodifiableCollection(sonePostReplies.get(id));
647 return Collections.emptySet();
649 lock.readLock().unlock();
653 /** Loads the known post replies. */
654 private void loadKnownPostReplies() {
655 lock.writeLock().lock();
657 int replyCounter = 0;
659 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
660 if (knownReplyId == null) {
663 knownPostReplies.add(knownReplyId);
666 lock.writeLock().unlock();
671 * Saves the known post replies to the configuration.
673 * @throws DatabaseException
674 * if a configuration error occurs
676 private void saveKnownPostReplies() throws DatabaseException {
677 lock.readLock().lock();
679 int replyCounter = 0;
680 for (String knownReplyId : knownPostReplies) {
681 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
683 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
684 } catch (ConfigurationException ce1) {
685 throw new DatabaseException("Could not save database.", ce1);
687 lock.readLock().unlock();