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.HashMap;
26 import java.util.HashSet;
27 import java.util.List;
30 import java.util.SortedSet;
31 import java.util.TreeSet;
32 import java.util.concurrent.locks.ReadWriteLock;
33 import java.util.concurrent.locks.ReentrantReadWriteLock;
35 import net.pterodactylus.sone.data.Post;
36 import net.pterodactylus.sone.data.PostReply;
37 import net.pterodactylus.sone.data.Reply;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.sone.database.Database;
40 import net.pterodactylus.sone.database.DatabaseException;
41 import net.pterodactylus.sone.database.PostBuilder;
42 import net.pterodactylus.sone.database.PostDatabase;
43 import net.pterodactylus.sone.database.PostReplyBuilder;
44 import net.pterodactylus.sone.database.SoneProvider;
45 import net.pterodactylus.util.config.Configuration;
46 import net.pterodactylus.util.config.ConfigurationException;
48 import com.google.common.base.Optional;
49 import com.google.common.util.concurrent.AbstractService;
50 import com.google.inject.Inject;
53 * Memory-based {@link PostDatabase} implementation.
55 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
57 public class MemoryDatabase extends AbstractService implements Database {
60 private final ReadWriteLock lock = new ReentrantReadWriteLock();
62 /** The Sone provider. */
63 private final SoneProvider soneProvider;
65 /** The configuration. */
66 private final Configuration configuration;
68 /** All posts by their ID. */
69 private final Map<String, Post> allPosts = new HashMap<String, Post>();
71 /** All posts by their Sones. */
72 private final Map<String, Collection<Post>> sonePosts = new HashMap<String, Collection<Post>>();
74 /** All posts by their recipient. */
75 private final Map<String, Collection<Post>> recipientPosts = new HashMap<String, Collection<Post>>();
77 /** Whether posts are known. */
78 private final Set<String> knownPosts = new HashSet<String>();
80 /** All post replies by their ID. */
81 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
83 /** Replies by post. */
84 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
86 /** Whether post replies are known. */
87 private final Set<String> knownPostReplies = new HashSet<String>();
90 * Creates a new memory database.
94 * @param configuration
95 * The configuration for loading and saving elements
98 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
99 this.soneProvider = soneProvider;
100 this.configuration = configuration;
108 * Saves the database.
110 * @throws DatabaseException
111 * if an error occurs while saving
114 public void save() throws DatabaseException {
116 saveKnownPostReplies();
127 protected void doStart() {
129 loadKnownPostReplies();
137 protected void doStop() {
141 } catch (DatabaseException de1) {
147 // POSTPROVIDER METHODS
154 public Optional<Post> getPost(String postId) {
155 lock.readLock().lock();
157 return Optional.fromNullable(allPosts.get(postId));
159 lock.readLock().unlock();
167 public Collection<Post> getPosts(String soneId) {
168 return new HashSet<Post>(getPostsFrom(soneId));
175 public Collection<Post> getDirectedPosts(String recipientId) {
176 lock.readLock().lock();
178 Collection<Post> posts = recipientPosts.get(recipientId);
179 return (posts == null) ? Collections.<Post> emptySet() : new HashSet<Post>(posts);
181 lock.readLock().unlock();
186 // POSTBUILDERFACTORY METHODS
193 public PostBuilder newPostBuilder() {
194 return new MemoryPostBuilder(this, soneProvider);
205 public void storePost(Post post) {
206 checkNotNull(post, "post must not be null");
207 lock.writeLock().lock();
209 allPosts.put(post.getId(), post);
210 getPostsFrom(post.getSone().getId()).add(post);
211 if (post.getRecipientId().isPresent()) {
212 getPostsTo(post.getRecipientId().get()).add(post);
215 lock.writeLock().unlock();
223 public void removePost(Post post) {
224 checkNotNull(post, "post must not be null");
225 lock.writeLock().lock();
227 allPosts.remove(post.getId());
228 getPostsFrom(post.getSone().getId()).remove(post);
229 if (post.getRecipientId().isPresent()) {
230 getPostsTo(post.getRecipientId().get()).remove(post);
232 post.getSone().removePost(post);
234 lock.writeLock().unlock();
242 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
243 checkNotNull(sone, "sone must not be null");
244 /* verify that all posts are from the same Sone. */
245 for (Post post : posts) {
246 if (!sone.equals(post.getSone())) {
247 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
251 lock.writeLock().lock();
253 /* remove all posts by the Sone. */
254 getPostsFrom(sone.getId()).clear();
255 for (Post post : posts) {
256 allPosts.remove(post.getId());
257 if (post.getRecipientId().isPresent()) {
258 getPostsTo(post.getRecipientId().get()).remove(post);
263 getPostsFrom(sone.getId()).addAll(posts);
264 for (Post post : posts) {
265 allPosts.put(post.getId(), post);
266 if (post.getRecipientId().isPresent()) {
267 getPostsTo(post.getRecipientId().get()).add(post);
271 lock.writeLock().unlock();
279 public void removePosts(Sone sone) {
280 checkNotNull(sone, "sone must not be null");
281 lock.writeLock().lock();
283 /* remove all posts by the Sone. */
284 getPostsFrom(sone.getId()).clear();
285 for (Post post : sone.getPosts()) {
286 allPosts.remove(post.getId());
287 if (post.getRecipientId().isPresent()) {
288 getPostsTo(post.getRecipientId().get()).remove(post);
292 lock.writeLock().unlock();
297 // POSTREPLYPROVIDER METHODS
304 public Optional<PostReply> getPostReply(String id) {
305 lock.readLock().lock();
307 return Optional.fromNullable(allPostReplies.get(id));
309 lock.readLock().unlock();
317 public List<PostReply> getReplies(String postId) {
318 lock.readLock().lock();
320 if (!postReplies.containsKey(postId)) {
321 return Collections.emptyList();
323 return new ArrayList<PostReply>(postReplies.get(postId));
325 lock.readLock().unlock();
330 // POSTREPLYBUILDERFACTORY METHODS
337 public PostReplyBuilder newPostReplyBuilder() {
338 return new MemoryPostReplyBuilder(this, soneProvider);
342 // POSTREPLYSTORE METHODS
349 public void storePostReply(PostReply postReply) {
350 lock.writeLock().lock();
352 allPostReplies.put(postReply.getId(), postReply);
353 if (postReplies.containsKey(postReply.getPostId())) {
354 postReplies.get(postReply.getPostId()).add(postReply);
356 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
357 replies.add(postReply);
358 postReplies.put(postReply.getPostId(), replies);
361 lock.writeLock().unlock();
369 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
370 checkNotNull(sone, "sone must not be null");
371 /* verify that all posts are from the same Sone. */
372 for (PostReply postReply : postReplies) {
373 if (!sone.equals(postReply.getSone())) {
374 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
378 lock.writeLock().lock();
380 /* remove all post replies of the Sone. */
381 for (PostReply postReply : getRepliesFrom(sone.getId())) {
382 removePostReply(postReply);
384 for (PostReply postReply : postReplies) {
385 allPostReplies.put(postReply.getId(), postReply);
386 if (this.postReplies.containsKey(postReply.getPostId())) {
387 this.postReplies.get(postReply.getPostId()).add(postReply);
389 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
390 replies.add(postReply);
391 this.postReplies.put(postReply.getPostId(), replies);
395 lock.writeLock().unlock();
403 public void removePostReply(PostReply postReply) {
404 lock.writeLock().lock();
406 allPostReplies.remove(postReply.getId());
407 if (postReplies.containsKey(postReply.getPostId())) {
408 postReplies.get(postReply.getPostId()).remove(postReply);
409 if (postReplies.get(postReply.getPostId()).isEmpty()) {
410 postReplies.remove(postReply.getPostId());
414 lock.writeLock().unlock();
422 public void removePostReplies(Sone sone) {
423 checkNotNull(sone, "sone must not be null");
425 lock.writeLock().lock();
427 for (PostReply postReply : sone.getReplies()) {
428 removePostReply(postReply);
431 lock.writeLock().unlock();
436 // PACKAGE-PRIVATE METHODS
440 * Returns whether the given post is known.
444 * @return {@code true} if the post is known, {@code false} otherwise
446 boolean isPostKnown(Post post) {
447 lock.readLock().lock();
449 return knownPosts.contains(post.getId());
451 lock.readLock().unlock();
456 * Sets whether the given post is known.
461 * {@code true} if the post is known, {@code false} otherwise
463 void setPostKnown(Post post, boolean known) {
464 lock.writeLock().lock();
467 knownPosts.add(post.getId());
469 knownPosts.remove(post.getId());
472 lock.writeLock().unlock();
477 * Returns whether the given post reply is known.
481 * @return {@code true} if the given post reply is known, {@code false}
484 boolean isPostReplyKnown(PostReply postReply) {
485 lock.readLock().lock();
487 return knownPostReplies.contains(postReply.getId());
489 lock.readLock().unlock();
494 * Sets whether the given post reply is known.
499 * {@code true} if the post reply is known, {@code false}
502 void setPostReplyKnown(PostReply postReply, boolean known) {
503 lock.writeLock().lock();
506 knownPostReplies.add(postReply.getId());
508 knownPostReplies.remove(postReply.getId());
511 lock.writeLock().unlock();
520 * Gets all posts for the given Sone, creating a new collection if there is
524 * The ID of the Sone to get the posts for
527 private Collection<Post> getPostsFrom(String soneId) {
528 Collection<Post> posts = null;
529 lock.readLock().lock();
531 posts = sonePosts.get(soneId);
533 lock.readLock().unlock();
539 posts = new HashSet<Post>();
540 lock.writeLock().lock();
542 sonePosts.put(soneId, posts);
544 lock.writeLock().unlock();
551 * Gets all posts that are directed the given Sone, creating a new
552 * collection if there is none yet.
555 * The ID of the Sone to get the posts for
558 private Collection<Post> getPostsTo(String recipientId) {
559 Collection<Post> posts = null;
560 lock.readLock().lock();
562 posts = recipientPosts.get(recipientId);
564 lock.readLock().unlock();
570 posts = new HashSet<Post>();
571 lock.writeLock().lock();
573 recipientPosts.put(recipientId, posts);
575 lock.writeLock().unlock();
582 * Loads the known posts.
584 private void loadKnownPosts() {
585 lock.writeLock().lock();
589 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
590 if (knownPostId == null) {
593 knownPosts.add(knownPostId);
596 lock.writeLock().unlock();
601 * Saves the known posts to the configuration.
603 * @throws DatabaseException
604 * if a configuration error occurs
606 private void saveKnownPosts() throws DatabaseException {
607 lock.readLock().lock();
610 for (String knownPostId : knownPosts) {
611 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
613 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
614 } catch (ConfigurationException ce1) {
615 throw new DatabaseException("Could not save database.", ce1);
617 lock.readLock().unlock();
622 * Loads the known post replies.
624 private void loadKnownPostReplies() {
625 lock.writeLock().lock();
627 int replyCounter = 0;
629 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
630 if (knownReplyId == null) {
633 knownPostReplies.add(knownReplyId);
636 lock.writeLock().unlock();
641 * Saves the known post replies to the configuration.
643 * @throws DatabaseException
644 * if a configuration error occurs
646 private void saveKnownPostReplies() throws DatabaseException {
647 lock.readLock().lock();
649 int replyCounter = 0;
650 for (String knownReplyId : knownPostReplies) {
651 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
653 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
654 } catch (ConfigurationException ce1) {
655 throw new DatabaseException("Could not save database.", ce1);
657 lock.readLock().unlock();