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.Album;
38 import net.pterodactylus.sone.data.Image;
39 import net.pterodactylus.sone.data.Post;
40 import net.pterodactylus.sone.data.PostReply;
41 import net.pterodactylus.sone.data.Reply;
42 import net.pterodactylus.sone.data.Sone;
43 import net.pterodactylus.sone.data.impl.DefaultAlbumBuilder;
44 import net.pterodactylus.sone.database.AlbumBuilder;
45 import net.pterodactylus.sone.database.Database;
46 import net.pterodactylus.sone.database.DatabaseException;
47 import net.pterodactylus.sone.database.PostBuilder;
48 import net.pterodactylus.sone.database.PostDatabase;
49 import net.pterodactylus.sone.database.PostReplyBuilder;
50 import net.pterodactylus.sone.database.SoneProvider;
51 import net.pterodactylus.util.config.Configuration;
52 import net.pterodactylus.util.config.ConfigurationException;
54 import com.google.common.base.Optional;
55 import com.google.common.collect.SortedSetMultimap;
56 import com.google.common.collect.TreeMultimap;
57 import com.google.common.util.concurrent.AbstractService;
58 import com.google.inject.Inject;
61 * Memory-based {@link PostDatabase} implementation.
63 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
65 public class MemoryDatabase extends AbstractService implements Database {
68 private final ReadWriteLock lock = new ReentrantReadWriteLock();
70 /** The Sone provider. */
71 private final SoneProvider soneProvider;
73 /** The configuration. */
74 private final Configuration configuration;
76 /** All posts by their ID. */
77 private final Map<String, Post> allPosts = new HashMap<String, Post>();
79 /** All posts by their Sones. */
80 private final Map<String, Collection<Post>> sonePosts = new HashMap<String, Collection<Post>>();
82 /** All posts by their recipient. */
83 private final Map<String, Collection<Post>> recipientPosts = new HashMap<String, Collection<Post>>();
85 /** Whether posts are known. */
86 private final Set<String> knownPosts = new HashSet<String>();
88 /** All post replies by their ID. */
89 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
91 /** Replies sorted by Sone. */
92 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
95 public int compare(String leftString, String rightString) {
96 return leftString.compareTo(rightString);
98 }, PostReply.TIME_COMPARATOR);
100 /** Replies by post. */
101 private final Map<String, SortedSet<PostReply>> postReplies = new HashMap<String, SortedSet<PostReply>>();
103 /** Whether post replies are known. */
104 private final Set<String> knownPostReplies = new HashSet<String>();
106 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
108 private final Map<String, Image> allImages = new HashMap<String, Image>();
111 * Creates a new memory database.
113 * @param soneProvider
115 * @param configuration
116 * The configuration for loading and saving elements
119 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
120 this.soneProvider = soneProvider;
121 this.configuration = configuration;
129 * Saves the database.
131 * @throws DatabaseException
132 * if an error occurs while saving
135 public void save() throws DatabaseException {
137 saveKnownPostReplies();
144 /** {@inheritDocs} */
146 protected void doStart() {
148 loadKnownPostReplies();
152 /** {@inheritDocs} */
154 protected void doStop() {
158 } catch (DatabaseException de1) {
164 // POSTPROVIDER METHODS
167 /** {@inheritDocs} */
169 public Optional<Post> getPost(String postId) {
170 lock.readLock().lock();
172 return fromNullable(allPosts.get(postId));
174 lock.readLock().unlock();
178 /** {@inheritDocs} */
180 public Collection<Post> getPosts(String soneId) {
181 return new HashSet<Post>(getPostsFrom(soneId));
184 /** {@inheritDocs} */
186 public Collection<Post> getDirectedPosts(String recipientId) {
187 lock.readLock().lock();
189 Collection<Post> posts = recipientPosts.get(recipientId);
190 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
192 lock.readLock().unlock();
197 // POSTBUILDERFACTORY METHODS
200 /** {@inheritDocs} */
202 public PostBuilder newPostBuilder() {
203 return new MemoryPostBuilder(this, soneProvider);
210 /** {@inheritDocs} */
212 public void storePost(Post post) {
213 checkNotNull(post, "post must not be null");
214 lock.writeLock().lock();
216 allPosts.put(post.getId(), post);
217 getPostsFrom(post.getSone().getId()).add(post);
218 if (post.getRecipientId().isPresent()) {
219 getPostsTo(post.getRecipientId().get()).add(post);
222 lock.writeLock().unlock();
226 /** {@inheritDocs} */
228 public void removePost(Post post) {
229 checkNotNull(post, "post must not be null");
230 lock.writeLock().lock();
232 allPosts.remove(post.getId());
233 getPostsFrom(post.getSone().getId()).remove(post);
234 if (post.getRecipientId().isPresent()) {
235 getPostsTo(post.getRecipientId().get()).remove(post);
237 post.getSone().removePost(post);
239 lock.writeLock().unlock();
243 /** {@inheritDocs} */
245 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
246 checkNotNull(sone, "sone must not be null");
247 /* verify that all posts are from the same Sone. */
248 for (Post post : posts) {
249 if (!sone.equals(post.getSone())) {
250 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
254 lock.writeLock().lock();
256 /* remove all posts by the Sone. */
257 getPostsFrom(sone.getId()).clear();
258 for (Post post : posts) {
259 allPosts.remove(post.getId());
260 if (post.getRecipientId().isPresent()) {
261 getPostsTo(post.getRecipientId().get()).remove(post);
266 getPostsFrom(sone.getId()).addAll(posts);
267 for (Post post : posts) {
268 allPosts.put(post.getId(), post);
269 if (post.getRecipientId().isPresent()) {
270 getPostsTo(post.getRecipientId().get()).add(post);
274 lock.writeLock().unlock();
278 /** {@inheritDocs} */
280 public void removePosts(Sone sone) {
281 checkNotNull(sone, "sone must not be null");
282 lock.writeLock().lock();
284 /* remove all posts by the Sone. */
285 getPostsFrom(sone.getId()).clear();
286 for (Post post : sone.getPosts()) {
287 allPosts.remove(post.getId());
288 if (post.getRecipientId().isPresent()) {
289 getPostsTo(post.getRecipientId().get()).remove(post);
293 lock.writeLock().unlock();
298 // POSTREPLYPROVIDER METHODS
301 /** {@inheritDocs} */
303 public Optional<PostReply> getPostReply(String id) {
304 lock.readLock().lock();
306 return fromNullable(allPostReplies.get(id));
308 lock.readLock().unlock();
312 /** {@inheritDocs} */
314 public List<PostReply> getReplies(String postId) {
315 lock.readLock().lock();
317 if (!postReplies.containsKey(postId)) {
318 return Collections.emptyList();
320 return new ArrayList<PostReply>(postReplies.get(postId));
322 lock.readLock().unlock();
327 // POSTREPLYBUILDERFACTORY METHODS
330 /** {@inheritDocs} */
332 public PostReplyBuilder newPostReplyBuilder() {
333 return new MemoryPostReplyBuilder(this, soneProvider);
337 // POSTREPLYSTORE METHODS
340 /** {@inheritDocs} */
342 public void storePostReply(PostReply postReply) {
343 lock.writeLock().lock();
345 allPostReplies.put(postReply.getId(), postReply);
346 if (postReplies.containsKey(postReply.getPostId())) {
347 postReplies.get(postReply.getPostId()).add(postReply);
349 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
350 replies.add(postReply);
351 postReplies.put(postReply.getPostId(), replies);
354 lock.writeLock().unlock();
358 /** {@inheritDocs} */
360 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
361 checkNotNull(sone, "sone must not be null");
362 /* verify that all posts are from the same Sone. */
363 for (PostReply postReply : postReplies) {
364 if (!sone.equals(postReply.getSone())) {
365 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
369 lock.writeLock().lock();
371 /* remove all post replies of the Sone. */
372 for (PostReply postReply : getRepliesFrom(sone.getId())) {
373 removePostReply(postReply);
375 for (PostReply postReply : postReplies) {
376 allPostReplies.put(postReply.getId(), postReply);
377 sonePostReplies.put(postReply.getSone().getId(), postReply);
378 if (this.postReplies.containsKey(postReply.getPostId())) {
379 this.postReplies.get(postReply.getPostId()).add(postReply);
381 TreeSet<PostReply> replies = new TreeSet<PostReply>(Reply.TIME_COMPARATOR);
382 replies.add(postReply);
383 this.postReplies.put(postReply.getPostId(), replies);
387 lock.writeLock().unlock();
391 /** {@inheritDocs} */
393 public void removePostReply(PostReply postReply) {
394 lock.writeLock().lock();
396 allPostReplies.remove(postReply.getId());
397 if (postReplies.containsKey(postReply.getPostId())) {
398 postReplies.get(postReply.getPostId()).remove(postReply);
399 if (postReplies.get(postReply.getPostId()).isEmpty()) {
400 postReplies.remove(postReply.getPostId());
404 lock.writeLock().unlock();
408 /** {@inheritDocs} */
410 public void removePostReplies(Sone sone) {
411 checkNotNull(sone, "sone must not be null");
413 lock.writeLock().lock();
415 for (PostReply postReply : sone.getReplies()) {
416 removePostReply(postReply);
419 lock.writeLock().unlock();
424 // ALBUMPROVDER METHODS
428 public Optional<Album> getAlbum(String albumId) {
429 lock.readLock().lock();
431 return fromNullable(allAlbums.get(albumId));
433 lock.readLock().unlock();
438 // ALBUMBUILDERFACTORY METHODS
442 public AlbumBuilder newAlbumBuilder() {
443 return new DefaultAlbumBuilder();
447 // ALBUMSTORE METHODS
451 public void storeAlbum(Album album) {
452 lock.writeLock().lock();
454 allAlbums.put(album.getId(), album);
456 lock.writeLock().unlock();
461 public void removeAlbum(Album album) {
462 lock.writeLock().lock();
464 allAlbums.remove(album.getId());
466 lock.writeLock().unlock();
471 // IMAGEPROVIDER METHODS
475 public Optional<Image> getImage(String imageId) {
476 lock.readLock().lock();
478 return fromNullable(allImages.get(imageId));
480 lock.readLock().unlock();
485 // IMAGESTORE METHODS
489 public void storeImage(Image image) {
490 lock.writeLock().lock();
492 allImages.put(image.getId(), image);
494 lock.writeLock().unlock();
499 public void removeImage(Image image) {
500 lock.writeLock().lock();
502 allImages.remove(image.getId());
504 lock.writeLock().unlock();
509 // PACKAGE-PRIVATE METHODS
513 * Returns whether the given post is known.
517 * @return {@code true} if the post is known, {@code false} otherwise
519 boolean isPostKnown(Post post) {
520 lock.readLock().lock();
522 return knownPosts.contains(post.getId());
524 lock.readLock().unlock();
529 * Sets whether the given post is known.
534 * {@code true} if the post is known, {@code false} otherwise
536 void setPostKnown(Post post, boolean known) {
537 lock.writeLock().lock();
540 knownPosts.add(post.getId());
542 knownPosts.remove(post.getId());
545 lock.writeLock().unlock();
550 * Returns whether the given post reply is known.
554 * @return {@code true} if the given post reply is known, {@code false}
557 boolean isPostReplyKnown(PostReply postReply) {
558 lock.readLock().lock();
560 return knownPostReplies.contains(postReply.getId());
562 lock.readLock().unlock();
567 * Sets whether the given post reply is known.
572 * {@code true} if the post reply is known, {@code false} otherwise
574 void setPostReplyKnown(PostReply postReply, boolean known) {
575 lock.writeLock().lock();
578 knownPostReplies.add(postReply.getId());
580 knownPostReplies.remove(postReply.getId());
583 lock.writeLock().unlock();
592 * Gets all posts for the given Sone, creating a new collection if there is
596 * The ID of the Sone to get the posts for
599 private Collection<Post> getPostsFrom(String soneId) {
600 Collection<Post> posts = null;
601 lock.readLock().lock();
603 posts = sonePosts.get(soneId);
605 lock.readLock().unlock();
611 posts = new HashSet<Post>();
612 lock.writeLock().lock();
614 sonePosts.put(soneId, posts);
616 lock.writeLock().unlock();
623 * Gets all posts that are directed the given Sone, creating a new collection
624 * if there is none yet.
627 * The ID of the Sone to get the posts for
630 private Collection<Post> getPostsTo(String recipientId) {
631 Collection<Post> posts = null;
632 lock.readLock().lock();
634 posts = recipientPosts.get(recipientId);
636 lock.readLock().unlock();
642 posts = new HashSet<Post>();
643 lock.writeLock().lock();
645 recipientPosts.put(recipientId, posts);
647 lock.writeLock().unlock();
653 /** Loads the known posts. */
654 private void loadKnownPosts() {
655 lock.writeLock().lock();
659 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
660 if (knownPostId == null) {
663 knownPosts.add(knownPostId);
666 lock.writeLock().unlock();
671 * Saves the known posts to the configuration.
673 * @throws DatabaseException
674 * if a configuration error occurs
676 private void saveKnownPosts() throws DatabaseException {
677 lock.readLock().lock();
680 for (String knownPostId : knownPosts) {
681 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
683 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
684 } catch (ConfigurationException ce1) {
685 throw new DatabaseException("Could not save database.", ce1);
687 lock.readLock().unlock();
692 * Returns all replies by the given Sone.
696 * @return The post replies of the Sone, sorted by time (newest first)
698 private Collection<PostReply> getRepliesFrom(String id) {
699 lock.readLock().lock();
701 if (sonePostReplies.containsKey(id)) {
702 return Collections.unmodifiableCollection(sonePostReplies.get(id));
704 return Collections.emptySet();
706 lock.readLock().unlock();
710 /** Loads the known post replies. */
711 private void loadKnownPostReplies() {
712 lock.writeLock().lock();
714 int replyCounter = 0;
716 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
717 if (knownReplyId == null) {
720 knownPostReplies.add(knownReplyId);
723 lock.writeLock().unlock();
728 * Saves the known post replies to the configuration.
730 * @throws DatabaseException
731 * if a configuration error occurs
733 private void saveKnownPostReplies() throws DatabaseException {
734 lock.readLock().lock();
736 int replyCounter = 0;
737 for (String knownReplyId : knownPostReplies) {
738 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
740 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
741 } catch (ConfigurationException ce1) {
742 throw new DatabaseException("Could not save database.", ce1);
744 lock.readLock().unlock();