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 for (PostReply postReply : postReplies) {
381 allPostReplies.put(postReply.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();
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();
418 public void removePostReplies(Sone sone) {
419 checkNotNull(sone, "sone must not be null");
421 lock.writeLock().lock();
423 for (PostReply postReply : sone.getReplies()) {
424 removePostReply(postReply);
427 lock.writeLock().unlock();
432 // PACKAGE-PRIVATE METHODS
436 * Returns whether the given post is known.
440 * @return {@code true} if the post is known, {@code false} otherwise
442 boolean isPostKnown(Post post) {
443 lock.readLock().lock();
445 return knownPosts.contains(post.getId());
447 lock.readLock().unlock();
452 * Sets whether the given post is known.
457 * {@code true} if the post is known, {@code false} otherwise
459 void setPostKnown(Post post, boolean known) {
460 lock.writeLock().lock();
463 knownPosts.add(post.getId());
465 knownPosts.remove(post.getId());
468 lock.writeLock().unlock();
473 * Returns whether the given post reply is known.
477 * @return {@code true} if the given post reply is known, {@code false}
480 boolean isPostReplyKnown(PostReply postReply) {
481 lock.readLock().lock();
483 return knownPostReplies.contains(postReply.getId());
485 lock.readLock().unlock();
490 * Sets whether the given post reply is known.
495 * {@code true} if the post reply is known, {@code false}
498 void setPostReplyKnown(PostReply postReply, boolean known) {
499 lock.writeLock().lock();
502 knownPostReplies.add(postReply.getId());
504 knownPostReplies.remove(postReply.getId());
507 lock.writeLock().unlock();
516 * Gets all posts for the given Sone, creating a new collection if there is
520 * The ID of the Sone to get the posts for
523 private Collection<Post> getPostsFrom(String soneId) {
524 Collection<Post> posts = null;
525 lock.readLock().lock();
527 posts = sonePosts.get(soneId);
529 lock.readLock().unlock();
535 posts = new HashSet<Post>();
536 lock.writeLock().lock();
538 sonePosts.put(soneId, posts);
540 lock.writeLock().unlock();
547 * Gets all posts that are directed the given Sone, creating a new
548 * collection if there is none yet.
551 * The ID of the Sone to get the posts for
554 private Collection<Post> getPostsTo(String recipientId) {
555 Collection<Post> posts = null;
556 lock.readLock().lock();
558 posts = recipientPosts.get(recipientId);
560 lock.readLock().unlock();
566 posts = new HashSet<Post>();
567 lock.writeLock().lock();
569 recipientPosts.put(recipientId, posts);
571 lock.writeLock().unlock();
578 * Loads the known posts.
580 private void loadKnownPosts() {
581 lock.writeLock().lock();
585 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
586 if (knownPostId == null) {
589 knownPosts.add(knownPostId);
592 lock.writeLock().unlock();
597 * Saves the known posts to the configuration.
599 * @throws DatabaseException
600 * if a configuration error occurs
602 private void saveKnownPosts() throws DatabaseException {
603 lock.readLock().lock();
606 for (String knownPostId : knownPosts) {
607 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
609 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
610 } catch (ConfigurationException ce1) {
611 throw new DatabaseException("Could not save database.", ce1);
613 lock.readLock().unlock();
618 * Loads the known post replies.
620 private void loadKnownPostReplies() {
621 lock.writeLock().lock();
623 int replyCounter = 0;
625 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
626 if (knownReplyId == null) {
629 knownPostReplies.add(knownReplyId);
632 lock.writeLock().unlock();
637 * Saves the known post replies to the configuration.
639 * @throws DatabaseException
640 * if a configuration error occurs
642 private void saveKnownPostReplies() throws DatabaseException {
643 lock.readLock().lock();
645 int replyCounter = 0;
646 for (String knownReplyId : knownPostReplies) {
647 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
649 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
650 } catch (ConfigurationException ce1) {
651 throw new DatabaseException("Could not save database.", ce1);
653 lock.readLock().unlock();