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.Optional.fromNullable;
21 import static com.google.common.base.Preconditions.checkNotNull;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
32 import java.util.SortedSet;
33 import java.util.TreeSet;
34 import java.util.concurrent.locks.ReadWriteLock;
35 import java.util.concurrent.locks.ReentrantReadWriteLock;
37 import net.pterodactylus.sone.data.Post;
38 import net.pterodactylus.sone.data.PostReply;
39 import net.pterodactylus.sone.data.Reply;
40 import net.pterodactylus.sone.data.Sone;
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.collect.SortedSetMultimap;
52 import com.google.common.collect.TreeMultimap;
53 import com.google.common.util.concurrent.AbstractService;
54 import com.google.inject.Inject;
57 * Memory-based {@link PostDatabase} implementation.
59 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
61 public class MemoryDatabase extends AbstractService implements Database {
64 private final ReadWriteLock lock = new ReentrantReadWriteLock();
66 /** The Sone provider. */
67 private final SoneProvider soneProvider;
69 /** The configuration. */
70 private final Configuration configuration;
72 /** All posts by their ID. */
73 private final Map<String, Post> allPosts = new HashMap<String, Post>();
75 /** All posts by their Sones. */
76 private final Map<String, Collection<Post>> sonePosts = new HashMap<String, Collection<Post>>();
78 /** All posts by their recipient. */
79 private final Map<String, Collection<Post>> recipientPosts = new HashMap<String, Collection<Post>>();
81 /** Whether posts are known. */
82 private final Set<String> knownPosts = new HashSet<String>();
84 /** All post replies by their ID. */
85 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
87 /** Replies sorted by Sone. */
88 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
91 public int compare(String leftString, String rightString) {
92 return leftString.compareTo(rightString);
94 }, PostReply.TIME_COMPARATOR);
96 /** Replies by post. */
97 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
99 /** Whether post replies are known. */
100 private final Set<String> knownPostReplies = new HashSet<String>();
103 * Creates a new memory database.
105 * @param soneProvider
107 * @param configuration
108 * The configuration for loading and saving elements
111 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
112 this.soneProvider = soneProvider;
113 this.configuration = configuration;
121 * Saves the database.
123 * @throws DatabaseException
124 * if an error occurs while saving
127 public void save() throws DatabaseException {
129 saveKnownPostReplies();
136 /** {@inheritDocs} */
138 protected void doStart() {
140 loadKnownPostReplies();
144 /** {@inheritDocs} */
146 protected void doStop() {
150 } catch (DatabaseException de1) {
156 // POSTPROVIDER METHODS
159 /** {@inheritDocs} */
161 public Optional<Post> getPost(String postId) {
162 lock.readLock().lock();
164 return fromNullable(allPosts.get(postId));
166 lock.readLock().unlock();
170 /** {@inheritDocs} */
172 public Collection<Post> getPosts(String soneId) {
173 return new HashSet<Post>(getPostsFrom(soneId));
176 /** {@inheritDocs} */
178 public Collection<Post> getDirectedPosts(String recipientId) {
179 lock.readLock().lock();
181 Collection<Post> posts = recipientPosts.get(recipientId);
182 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
184 lock.readLock().unlock();
189 // POSTBUILDERFACTORY METHODS
192 /** {@inheritDocs} */
194 public PostBuilder newPostBuilder() {
195 return new MemoryPostBuilder(this, soneProvider);
202 /** {@inheritDocs} */
204 public void storePost(Post post) {
205 checkNotNull(post, "post must not be null");
206 lock.writeLock().lock();
208 allPosts.put(post.getId(), post);
209 getPostsFrom(post.getSone().getId()).add(post);
210 if (post.getRecipientId().isPresent()) {
211 getPostsTo(post.getRecipientId().get()).add(post);
214 lock.writeLock().unlock();
218 /** {@inheritDocs} */
220 public void removePost(Post post) {
221 checkNotNull(post, "post must not be null");
222 lock.writeLock().lock();
224 allPosts.remove(post.getId());
225 getPostsFrom(post.getSone().getId()).remove(post);
226 if (post.getRecipientId().isPresent()) {
227 getPostsTo(post.getRecipientId().get()).remove(post);
229 post.getSone().removePost(post);
231 lock.writeLock().unlock();
235 /** {@inheritDocs} */
237 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
238 checkNotNull(sone, "sone must not be null");
239 /* verify that all posts are from the same Sone. */
240 for (Post post : posts) {
241 if (!sone.equals(post.getSone())) {
242 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
246 lock.writeLock().lock();
248 /* remove all posts by the Sone. */
249 getPostsFrom(sone.getId()).clear();
250 for (Post post : posts) {
251 allPosts.remove(post.getId());
252 if (post.getRecipientId().isPresent()) {
253 getPostsTo(post.getRecipientId().get()).remove(post);
258 getPostsFrom(sone.getId()).addAll(posts);
259 for (Post post : posts) {
260 allPosts.put(post.getId(), post);
261 if (post.getRecipientId().isPresent()) {
262 getPostsTo(post.getRecipientId().get()).add(post);
266 lock.writeLock().unlock();
270 /** {@inheritDocs} */
272 public void removePosts(Sone sone) {
273 checkNotNull(sone, "sone must not be null");
274 lock.writeLock().lock();
276 /* remove all posts by the Sone. */
277 getPostsFrom(sone.getId()).clear();
278 for (Post post : sone.getPosts()) {
279 allPosts.remove(post.getId());
280 if (post.getRecipientId().isPresent()) {
281 getPostsTo(post.getRecipientId().get()).remove(post);
285 lock.writeLock().unlock();
290 // POSTREPLYPROVIDER METHODS
293 /** {@inheritDocs} */
295 public Optional<PostReply> getPostReply(String id) {
296 lock.readLock().lock();
298 return fromNullable(allPostReplies.get(id));
300 lock.readLock().unlock();
304 /** {@inheritDocs} */
306 public List<PostReply> getReplies(String postId) {
307 lock.readLock().lock();
309 if (!postReplies.containsKey(postId)) {
310 return Collections.emptyList();
312 return new ArrayList<PostReply>(postReplies.get(postId));
314 lock.readLock().unlock();
319 // POSTREPLYBUILDERFACTORY METHODS
322 /** {@inheritDocs} */
324 public PostReplyBuilder newPostReplyBuilder() {
325 return new MemoryPostReplyBuilder(this, soneProvider);
329 // POSTREPLYSTORE METHODS
332 /** {@inheritDocs} */
334 public void storePostReply(PostReply postReply) {
335 lock.writeLock().lock();
337 allPostReplies.put(postReply.getId(), postReply);
338 if (postReplies.containsKey(postReply.getPostId())) {
339 postReplies.get(postReply.getPostId()).add(postReply);
341 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
342 replies.add(postReply);
343 postReplies.put(postReply.getPostId(), replies);
346 lock.writeLock().unlock();
350 /** {@inheritDocs} */
352 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
353 checkNotNull(sone, "sone must not be null");
354 /* verify that all posts are from the same Sone. */
355 for (PostReply postReply : postReplies) {
356 if (!sone.equals(postReply.getSone())) {
357 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
361 lock.writeLock().lock();
363 /* remove all post replies of the Sone. */
364 for (PostReply postReply : getRepliesFrom(sone.getId())) {
365 removePostReply(postReply);
367 for (PostReply postReply : postReplies) {
368 allPostReplies.put(postReply.getId(), postReply);
369 sonePostReplies.put(postReply.getSone().getId(), postReply);
370 if (this.postReplies.containsKey(postReply.getPostId())) {
371 this.postReplies.get(postReply.getPostId()).add(postReply);
373 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
374 replies.add(postReply);
375 this.postReplies.put(postReply.getPostId(), replies);
379 lock.writeLock().unlock();
383 /** {@inheritDocs} */
385 public void removePostReply(PostReply postReply) {
386 lock.writeLock().lock();
388 allPostReplies.remove(postReply.getId());
389 if (postReplies.containsKey(postReply.getPostId())) {
390 postReplies.get(postReply.getPostId()).remove(postReply);
391 if (postReplies.get(postReply.getPostId()).isEmpty()) {
392 postReplies.remove(postReply.getPostId());
396 lock.writeLock().unlock();
400 /** {@inheritDocs} */
402 public void removePostReplies(Sone sone) {
403 checkNotNull(sone, "sone must not be null");
405 lock.writeLock().lock();
407 for (PostReply postReply : sone.getReplies()) {
408 removePostReply(postReply);
411 lock.writeLock().unlock();
416 // PACKAGE-PRIVATE METHODS
420 * Returns whether the given post is known.
424 * @return {@code true} if the post is known, {@code false} otherwise
426 boolean isPostKnown(Post post) {
427 lock.readLock().lock();
429 return knownPosts.contains(post.getId());
431 lock.readLock().unlock();
436 * Sets whether the given post is known.
441 * {@code true} if the post is known, {@code false} otherwise
443 void setPostKnown(Post post, boolean known) {
444 lock.writeLock().lock();
447 knownPosts.add(post.getId());
449 knownPosts.remove(post.getId());
452 lock.writeLock().unlock();
457 * Returns whether the given post reply is known.
461 * @return {@code true} if the given post reply is known, {@code false}
464 boolean isPostReplyKnown(PostReply postReply) {
465 lock.readLock().lock();
467 return knownPostReplies.contains(postReply.getId());
469 lock.readLock().unlock();
474 * Sets whether the given post reply is known.
479 * {@code true} if the post reply is known, {@code false} otherwise
481 void setPostReplyKnown(PostReply postReply, boolean known) {
482 lock.writeLock().lock();
485 knownPostReplies.add(postReply.getId());
487 knownPostReplies.remove(postReply.getId());
490 lock.writeLock().unlock();
499 * Gets all posts for the given Sone, creating a new collection if there is
503 * The ID of the Sone to get the posts for
506 private Collection<Post> getPostsFrom(String soneId) {
507 Collection<Post> posts = null;
508 lock.readLock().lock();
510 posts = sonePosts.get(soneId);
512 lock.readLock().unlock();
518 posts = new HashSet<Post>();
519 lock.writeLock().lock();
521 sonePosts.put(soneId, posts);
523 lock.writeLock().unlock();
530 * Gets all posts that are directed the given Sone, creating a new collection
531 * if there is none yet.
534 * The ID of the Sone to get the posts for
537 private Collection<Post> getPostsTo(String recipientId) {
538 Collection<Post> posts = null;
539 lock.readLock().lock();
541 posts = recipientPosts.get(recipientId);
543 lock.readLock().unlock();
549 posts = new HashSet<Post>();
550 lock.writeLock().lock();
552 recipientPosts.put(recipientId, posts);
554 lock.writeLock().unlock();
560 /** Loads the known posts. */
561 private void loadKnownPosts() {
562 lock.writeLock().lock();
566 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
567 if (knownPostId == null) {
570 knownPosts.add(knownPostId);
573 lock.writeLock().unlock();
578 * Saves the known posts to the configuration.
580 * @throws DatabaseException
581 * if a configuration error occurs
583 private void saveKnownPosts() throws DatabaseException {
584 lock.readLock().lock();
587 for (String knownPostId : knownPosts) {
588 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
590 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
591 } catch (ConfigurationException ce1) {
592 throw new DatabaseException("Could not save database.", ce1);
594 lock.readLock().unlock();
599 * Returns all replies by the given Sone.
603 * @return The post replies of the Sone, sorted by time (newest first)
605 private Collection<PostReply> getRepliesFrom(String id) {
606 lock.readLock().lock();
608 if (sonePostReplies.containsKey(id)) {
609 return Collections.unmodifiableCollection(sonePostReplies.get(id));
611 return Collections.emptySet();
613 lock.readLock().unlock();
617 /** Loads the known post replies. */
618 private void loadKnownPostReplies() {
619 lock.writeLock().lock();
621 int replyCounter = 0;
623 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
624 if (knownReplyId == null) {
627 knownPostReplies.add(knownReplyId);
630 lock.writeLock().unlock();
635 * Saves the known post replies to the configuration.
637 * @throws DatabaseException
638 * if a configuration error occurs
640 private void saveKnownPostReplies() throws DatabaseException {
641 lock.readLock().lock();
643 int replyCounter = 0;
644 for (String knownReplyId : knownPostReplies) {
645 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
647 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
648 } catch (ConfigurationException ce1) {
649 throw new DatabaseException("Could not save database.", ce1);
651 lock.readLock().unlock();