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.UUID;
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.data.impl.AbstractPostReplyBuilder;
41 import net.pterodactylus.sone.database.Database;
42 import net.pterodactylus.sone.database.DatabaseException;
43 import net.pterodactylus.sone.database.PostBuilder;
44 import net.pterodactylus.sone.database.PostDatabase;
45 import net.pterodactylus.sone.database.PostReplyBuilder;
46 import net.pterodactylus.sone.database.SoneProvider;
47 import net.pterodactylus.util.config.Configuration;
48 import net.pterodactylus.util.config.ConfigurationException;
50 import com.google.common.base.Optional;
51 import com.google.common.util.concurrent.AbstractService;
52 import com.google.inject.Inject;
55 * Memory-based {@link PostDatabase} implementation.
57 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
59 public class MemoryDatabase extends AbstractService implements Database {
62 private final ReadWriteLock lock = new ReentrantReadWriteLock();
64 /** The Sone provider. */
65 private final SoneProvider soneProvider;
67 /** The configuration. */
68 private final Configuration configuration;
70 /** All posts by their ID. */
71 private final Map<String, Post> allPosts = new HashMap<String, Post>();
73 /** All posts by their Sones. */
74 private final Map<String, Collection<Post>> sonePosts = new HashMap<String, Collection<Post>>();
76 /** All posts by their recipient. */
77 private final Map<String, Collection<Post>> recipientPosts = new HashMap<String, Collection<Post>>();
79 /** Whether posts are known. */
80 private final Set<String> knownPosts = new HashSet<String>();
82 /** All post replies by their ID. */
83 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
85 /** Replies by post. */
86 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
88 /** Whether post replies are known. */
89 private final Set<String> knownPostReplies = new HashSet<String>();
92 * Creates a new memory database.
96 * @param configuration
97 * The configuration for loading and saving elements
100 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
101 this.soneProvider = soneProvider;
102 this.configuration = configuration;
110 * Saves the database.
112 * @throws DatabaseException
113 * if an error occurs while saving
116 public void save() throws DatabaseException {
118 saveKnownPostReplies();
129 protected void doStart() {
131 loadKnownPostReplies();
139 protected void doStop() {
143 } catch (DatabaseException de1) {
149 // POSTPROVIDER METHODS
156 public Optional<Post> getPost(String postId) {
157 lock.readLock().lock();
159 return Optional.fromNullable(allPosts.get(postId));
161 lock.readLock().unlock();
169 public Collection<Post> getPosts(String soneId) {
170 return new HashSet<Post>(getPostsFrom(soneId));
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
195 public PostBuilder newPostBuilder() {
196 return new MemoryPostBuilder(this, soneProvider);
207 public void storePost(Post post) {
208 checkNotNull(post, "post must not be null");
209 lock.writeLock().lock();
211 allPosts.put(post.getId(), post);
212 getPostsFrom(post.getSone().getId()).add(post);
213 if (post.getRecipientId().isPresent()) {
214 getPostsTo(post.getRecipientId().get()).add(post);
217 lock.writeLock().unlock();
225 public void removePost(Post post) {
226 checkNotNull(post, "post must not be null");
227 lock.writeLock().lock();
229 allPosts.remove(post.getId());
230 getPostsFrom(post.getSone().getId()).remove(post);
231 if (post.getRecipientId().isPresent()) {
232 getPostsTo(post.getRecipientId().get()).remove(post);
234 post.getSone().removePost(post);
236 lock.writeLock().unlock();
244 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
245 checkNotNull(sone, "sone must not be null");
246 /* verify that all posts are from the same Sone. */
247 for (Post post : posts) {
248 if (!sone.equals(post.getSone())) {
249 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
253 lock.writeLock().lock();
255 /* remove all posts by the Sone. */
256 getPostsFrom(sone.getId()).clear();
257 for (Post post : posts) {
258 allPosts.remove(post.getId());
259 if (post.getRecipientId().isPresent()) {
260 getPostsTo(post.getRecipientId().get()).remove(post);
265 getPostsFrom(sone.getId()).addAll(posts);
266 for (Post post : posts) {
267 allPosts.put(post.getId(), post);
268 if (post.getRecipientId().isPresent()) {
269 getPostsTo(post.getRecipientId().get()).add(post);
273 lock.writeLock().unlock();
281 public void removePosts(Sone sone) {
282 checkNotNull(sone, "sone must not be null");
283 lock.writeLock().lock();
285 /* remove all posts by the Sone. */
286 getPostsFrom(sone.getId()).clear();
287 for (Post post : sone.getPosts()) {
288 allPosts.remove(post.getId());
289 if (post.getRecipientId().isPresent()) {
290 getPostsTo(post.getRecipientId().get()).remove(post);
294 lock.writeLock().unlock();
299 // POSTREPLYPROVIDER METHODS
306 public Optional<PostReply> getPostReply(String id) {
307 lock.readLock().lock();
309 return Optional.fromNullable(allPostReplies.get(id));
311 lock.readLock().unlock();
319 public List<PostReply> getReplies(String postId) {
320 lock.readLock().lock();
322 if (!postReplies.containsKey(postId)) {
323 return Collections.emptyList();
325 return new ArrayList<PostReply>(postReplies.get(postId));
327 lock.readLock().unlock();
332 // POSTREPLYBUILDERFACTORY METHODS
339 public PostReplyBuilder newPostReplyBuilder() {
340 return new MemoryPostReplyBuilder();
344 // POSTREPLYSTORE METHODS
351 public void storePostReply(PostReply postReply) {
352 lock.writeLock().lock();
354 allPostReplies.put(postReply.getId(), postReply);
355 if (postReplies.containsKey(postReply.getPostId())) {
356 postReplies.get(postReply.getPostId()).add(postReply);
358 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
359 replies.add(postReply);
360 postReplies.put(postReply.getPostId(), replies);
363 lock.writeLock().unlock();
371 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
372 checkNotNull(sone, "sone must not be null");
373 /* verify that all posts are from the same Sone. */
374 for (PostReply postReply : postReplies) {
375 if (!sone.equals(postReply.getSone())) {
376 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
380 lock.writeLock().lock();
382 for (PostReply postReply : postReplies) {
383 allPostReplies.put(postReply.getId(), postReply);
384 if (this.postReplies.containsKey(postReply.getPostId())) {
385 this.postReplies.get(postReply.getPostId()).add(postReply);
387 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
388 replies.add(postReply);
389 this.postReplies.put(postReply.getPostId(), replies);
393 lock.writeLock().unlock();
401 public void removePostReply(PostReply postReply) {
402 lock.writeLock().lock();
404 allPostReplies.remove(postReply.getId());
405 if (postReplies.containsKey(postReply.getPostId())) {
406 postReplies.get(postReply.getPostId()).remove(postReply);
407 if (postReplies.get(postReply.getPostId()).isEmpty()) {
408 postReplies.remove(postReply.getPostId());
412 lock.writeLock().unlock();
420 public void removePostReplies(Sone sone) {
421 checkNotNull(sone, "sone must not be null");
423 lock.writeLock().lock();
425 for (PostReply postReply : sone.getReplies()) {
426 removePostReply(postReply);
429 lock.writeLock().unlock();
434 // PACKAGE-PRIVATE METHODS
438 * Returns whether the given post is known.
442 * @return {@code true} if the post is known, {@code false} otherwise
444 boolean isPostKnown(Post post) {
445 lock.readLock().lock();
447 return knownPosts.contains(post.getId());
449 lock.readLock().unlock();
454 * Sets whether the given post is known.
459 * {@code true} if the post is known, {@code false} otherwise
461 void setPostKnown(Post post, boolean known) {
462 lock.writeLock().lock();
465 knownPosts.add(post.getId());
467 knownPosts.remove(post.getId());
470 lock.writeLock().unlock();
475 * Returns whether the given post reply is known.
479 * @return {@code true} if the given post reply is known, {@code false}
482 boolean isPostReplyKnown(PostReply postReply) {
483 lock.readLock().lock();
485 return knownPostReplies.contains(postReply.getId());
487 lock.readLock().unlock();
492 * Sets whether the given post reply is known.
497 * {@code true} if the post reply is known, {@code false}
500 void setPostReplyKnown(PostReply postReply, boolean known) {
501 lock.writeLock().lock();
504 knownPostReplies.add(postReply.getId());
506 knownPostReplies.remove(postReply.getId());
509 lock.writeLock().unlock();
518 * Gets all posts for the given Sone, creating a new collection if there is
522 * The ID of the Sone to get the posts for
525 private Collection<Post> getPostsFrom(String soneId) {
526 Collection<Post> posts = null;
527 lock.readLock().lock();
529 posts = sonePosts.get(soneId);
531 lock.readLock().unlock();
537 posts = new HashSet<Post>();
538 lock.writeLock().lock();
540 sonePosts.put(soneId, posts);
542 lock.writeLock().unlock();
549 * Gets all posts that are directed the given Sone, creating a new
550 * collection if there is none yet.
553 * The ID of the Sone to get the posts for
556 private Collection<Post> getPostsTo(String recipientId) {
557 Collection<Post> posts = null;
558 lock.readLock().lock();
560 posts = recipientPosts.get(recipientId);
562 lock.readLock().unlock();
568 posts = new HashSet<Post>();
569 lock.writeLock().lock();
571 recipientPosts.put(recipientId, posts);
573 lock.writeLock().unlock();
580 * Loads the known posts.
582 private void loadKnownPosts() {
583 lock.writeLock().lock();
587 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
588 if (knownPostId == null) {
591 knownPosts.add(knownPostId);
594 lock.writeLock().unlock();
599 * Saves the known posts to the configuration.
601 * @throws DatabaseException
602 * if a configuration error occurs
604 private void saveKnownPosts() throws DatabaseException {
605 lock.readLock().lock();
608 for (String knownPostId : knownPosts) {
609 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
611 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
612 } catch (ConfigurationException ce1) {
613 throw new DatabaseException("Could not save database.", ce1);
615 lock.readLock().unlock();
620 * Loads the known post replies.
622 private void loadKnownPostReplies() {
623 lock.writeLock().lock();
625 int replyCounter = 0;
627 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
628 if (knownReplyId == null) {
631 knownPostReplies.add(knownReplyId);
634 lock.writeLock().unlock();
639 * Saves the known post replies to the configuration.
641 * @throws DatabaseException
642 * if a configuration error occurs
644 private void saveKnownPostReplies() throws DatabaseException {
645 lock.readLock().lock();
647 int replyCounter = 0;
648 for (String knownReplyId : knownPostReplies) {
649 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
651 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
652 } catch (ConfigurationException ce1) {
653 throw new DatabaseException("Could not save database.", ce1);
655 lock.readLock().unlock();
660 * {@link PostReplyBuilder} implementation that creates
661 * {@link MemoryPostReply} objects.
663 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
665 private class MemoryPostReplyBuilder extends AbstractPostReplyBuilder {
671 public PostReply build() throws IllegalStateException {
674 PostReply postReply = new MemoryPostReply(MemoryDatabase.this, soneProvider, randomId ? UUID.randomUUID().toString() : id, senderId, currentTime ? System.currentTimeMillis() : time, text, postId);
675 postReply.setKnown(isPostReplyKnown(postReply));