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.*;
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();
135 /** {@inheritDocs} */
137 protected void doStart() {
139 loadKnownPostReplies();
143 /** {@inheritDocs} */
145 protected void doStop() {
149 } catch (DatabaseException de1) {
155 // POSTPROVIDER METHODS
158 /** {@inheritDocs} */
160 public Optional<Post> getPost(String postId) {
161 lock.readLock().lock();
163 return Optional.fromNullable(allPosts.get(postId));
165 lock.readLock().unlock();
169 /** {@inheritDocs} */
171 public Collection<Post> getPosts(String soneId) {
172 return new HashSet<Post>(getPostsFrom(soneId));
175 /** {@inheritDocs} */
177 public Collection<Post> getDirectedPosts(String recipientId) {
178 lock.readLock().lock();
180 Collection<Post> posts = recipientPosts.get(recipientId);
181 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
183 lock.readLock().unlock();
188 // POSTBUILDERFACTORY METHODS
191 /** {@inheritDocs} */
193 public PostBuilder newPostBuilder() {
194 return new MemoryPostBuilder(this, soneProvider);
201 /** {@inheritDocs} */
203 public void storePost(Post post) {
204 checkNotNull(post, "post must not be null");
205 lock.writeLock().lock();
207 allPosts.put(post.getId(), post);
208 getPostsFrom(post.getSone().getId()).add(post);
209 if (post.getRecipientId().isPresent()) {
210 getPostsTo(post.getRecipientId().get()).add(post);
213 lock.writeLock().unlock();
217 /** {@inheritDocs} */
219 public void removePost(Post post) {
220 checkNotNull(post, "post must not be null");
221 lock.writeLock().lock();
223 allPosts.remove(post.getId());
224 getPostsFrom(post.getSone().getId()).remove(post);
225 if (post.getRecipientId().isPresent()) {
226 getPostsTo(post.getRecipientId().get()).remove(post);
228 post.getSone().removePost(post);
230 lock.writeLock().unlock();
234 /** {@inheritDocs} */
236 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
237 checkNotNull(sone, "sone must not be null");
238 /* verify that all posts are from the same Sone. */
239 for (Post post : posts) {
240 if (!sone.equals(post.getSone())) {
241 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
245 lock.writeLock().lock();
247 /* remove all posts by the Sone. */
248 getPostsFrom(sone.getId()).clear();
249 for (Post post : posts) {
250 allPosts.remove(post.getId());
251 if (post.getRecipientId().isPresent()) {
252 getPostsTo(post.getRecipientId().get()).remove(post);
257 getPostsFrom(sone.getId()).addAll(posts);
258 for (Post post : posts) {
259 allPosts.put(post.getId(), post);
260 if (post.getRecipientId().isPresent()) {
261 getPostsTo(post.getRecipientId().get()).add(post);
265 lock.writeLock().unlock();
269 /** {@inheritDocs} */
271 public void removePosts(Sone sone) {
272 checkNotNull(sone, "sone must not be null");
273 lock.writeLock().lock();
275 /* remove all posts by the Sone. */
276 getPostsFrom(sone.getId()).clear();
277 for (Post post : sone.getPosts()) {
278 allPosts.remove(post.getId());
279 if (post.getRecipientId().isPresent()) {
280 getPostsTo(post.getRecipientId().get()).remove(post);
284 lock.writeLock().unlock();
289 // POSTREPLYPROVIDER METHODS
292 /** {@inheritDocs} */
294 public Optional<PostReply> getPostReply(String id) {
295 lock.readLock().lock();
297 return Optional.fromNullable(allPostReplies.get(id));
299 lock.readLock().unlock();
303 /** {@inheritDocs} */
305 public List<PostReply> getReplies(String postId) {
306 lock.readLock().lock();
308 if (!postReplies.containsKey(postId)) {
309 return Collections.emptyList();
311 return new ArrayList<PostReply>(postReplies.get(postId));
313 lock.readLock().unlock();
318 // POSTREPLYBUILDERFACTORY METHODS
321 /** {@inheritDocs} */
323 public PostReplyBuilder newPostReplyBuilder() {
324 return new MemoryPostReplyBuilder(this, soneProvider);
328 // POSTREPLYSTORE METHODS
331 /** {@inheritDocs} */
333 public void storePostReply(PostReply postReply) {
334 lock.writeLock().lock();
336 allPostReplies.put(postReply.getId(), postReply);
337 if (postReplies.containsKey(postReply.getPostId())) {
338 postReplies.get(postReply.getPostId()).add(postReply);
340 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
341 replies.add(postReply);
342 postReplies.put(postReply.getPostId(), replies);
345 lock.writeLock().unlock();
349 /** {@inheritDocs} */
351 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
352 checkNotNull(sone, "sone must not be null");
353 /* verify that all posts are from the same Sone. */
354 for (PostReply postReply : postReplies) {
355 if (!sone.equals(postReply.getSone())) {
356 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
360 lock.writeLock().lock();
362 /* remove all post replies of the Sone. */
363 for (PostReply postReply : getRepliesFrom(sone.getId())) {
364 removePostReply(postReply);
366 for (PostReply postReply : postReplies) {
367 allPostReplies.put(postReply.getId(), postReply);
368 sonePostReplies.put(postReply.getSone().getId(), postReply);
369 if (this.postReplies.containsKey(postReply.getPostId())) {
370 this.postReplies.get(postReply.getPostId()).add(postReply);
372 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
373 replies.add(postReply);
374 this.postReplies.put(postReply.getPostId(), replies);
378 lock.writeLock().unlock();
382 /** {@inheritDocs} */
384 public void removePostReply(PostReply postReply) {
385 lock.writeLock().lock();
387 allPostReplies.remove(postReply.getId());
388 if (postReplies.containsKey(postReply.getPostId())) {
389 postReplies.get(postReply.getPostId()).remove(postReply);
390 if (postReplies.get(postReply.getPostId()).isEmpty()) {
391 postReplies.remove(postReply.getPostId());
395 lock.writeLock().unlock();
399 /** {@inheritDocs} */
401 public void removePostReplies(Sone sone) {
402 checkNotNull(sone, "sone must not be null");
404 lock.writeLock().lock();
406 for (PostReply postReply : sone.getReplies()) {
407 removePostReply(postReply);
410 lock.writeLock().unlock();
415 // PACKAGE-PRIVATE METHODS
419 * Returns whether the given post is known.
423 * @return {@code true} if the post is known, {@code false} otherwise
425 boolean isPostKnown(Post post) {
426 lock.readLock().lock();
428 return knownPosts.contains(post.getId());
430 lock.readLock().unlock();
435 * Sets whether the given post is known.
440 * {@code true} if the post is known, {@code false} otherwise
442 void setPostKnown(Post post, boolean known) {
443 lock.writeLock().lock();
446 knownPosts.add(post.getId());
448 knownPosts.remove(post.getId());
451 lock.writeLock().unlock();
456 * Returns whether the given post reply is known.
460 * @return {@code true} if the given post reply is known, {@code false}
463 boolean isPostReplyKnown(PostReply postReply) {
464 lock.readLock().lock();
466 return knownPostReplies.contains(postReply.getId());
468 lock.readLock().unlock();
473 * Sets whether the given post reply is known.
478 * {@code true} if the post reply is known, {@code false} otherwise
480 void setPostReplyKnown(PostReply postReply, boolean known) {
481 lock.writeLock().lock();
484 knownPostReplies.add(postReply.getId());
486 knownPostReplies.remove(postReply.getId());
489 lock.writeLock().unlock();
498 * Gets all posts for the given Sone, creating a new collection if there is
502 * The ID of the Sone to get the posts for
505 private Collection<Post> getPostsFrom(String soneId) {
506 Collection<Post> posts = null;
507 lock.readLock().lock();
509 posts = sonePosts.get(soneId);
511 lock.readLock().unlock();
517 posts = new HashSet<Post>();
518 lock.writeLock().lock();
520 sonePosts.put(soneId, posts);
522 lock.writeLock().unlock();
529 * Gets all posts that are directed the given Sone, creating a new collection
530 * if there is none yet.
533 * The ID of the Sone to get the posts for
536 private Collection<Post> getPostsTo(String recipientId) {
537 Collection<Post> posts = null;
538 lock.readLock().lock();
540 posts = recipientPosts.get(recipientId);
542 lock.readLock().unlock();
548 posts = new HashSet<Post>();
549 lock.writeLock().lock();
551 recipientPosts.put(recipientId, posts);
553 lock.writeLock().unlock();
559 /** Loads the known posts. */
560 private void loadKnownPosts() {
561 lock.writeLock().lock();
565 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
566 if (knownPostId == null) {
569 knownPosts.add(knownPostId);
572 lock.writeLock().unlock();
577 * Saves the known posts to the configuration.
579 * @throws DatabaseException
580 * if a configuration error occurs
582 private void saveKnownPosts() throws DatabaseException {
583 lock.readLock().lock();
586 for (String knownPostId : knownPosts) {
587 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
589 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
590 } catch (ConfigurationException ce1) {
591 throw new DatabaseException("Could not save database.", ce1);
593 lock.readLock().unlock();
598 * Returns all replies by the given Sone.
602 * @return The post replies of the Sone, sorted by time (newest first)
604 private Collection<PostReply> getRepliesFrom(String id) {
605 lock.readLock().lock();
607 if (sonePostReplies.containsKey(id)) {
608 return Collections.unmodifiableCollection(sonePostReplies.get(id));
610 return Collections.emptySet();
612 lock.readLock().unlock();
616 /** Loads the known post replies. */
617 private void loadKnownPostReplies() {
618 lock.writeLock().lock();
620 int replyCounter = 0;
622 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
623 if (knownReplyId == null) {
626 knownPostReplies.add(knownReplyId);
629 lock.writeLock().unlock();
634 * Saves the known post replies to the configuration.
636 * @throws DatabaseException
637 * if a configuration error occurs
639 private void saveKnownPostReplies() throws DatabaseException {
640 lock.readLock().lock();
642 int replyCounter = 0;
643 for (String knownReplyId : knownPostReplies) {
644 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
646 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
647 } catch (ConfigurationException ce1) {
648 throw new DatabaseException("Could not save database.", ce1);
650 lock.readLock().unlock();