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;
22 import static com.google.common.collect.FluentIterable.from;
23 import static net.pterodactylus.sone.data.Reply.TIME_COMPARATOR;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.Comparator;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.List;
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.Sone;
42 import net.pterodactylus.sone.data.impl.AlbumBuilderImpl;
43 import net.pterodactylus.sone.data.impl.ImageBuilderImpl;
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.ImageBuilder;
48 import net.pterodactylus.sone.database.PostBuilder;
49 import net.pterodactylus.sone.database.PostDatabase;
50 import net.pterodactylus.sone.database.PostReplyBuilder;
51 import net.pterodactylus.sone.database.SoneProvider;
52 import net.pterodactylus.util.config.Configuration;
53 import net.pterodactylus.util.config.ConfigurationException;
55 import com.google.common.base.Optional;
56 import com.google.common.base.Predicate;
57 import com.google.common.collect.HashMultimap;
58 import com.google.common.collect.Multimap;
59 import com.google.common.collect.SortedSetMultimap;
60 import com.google.common.collect.TreeMultimap;
61 import com.google.common.util.concurrent.AbstractService;
62 import com.google.inject.Inject;
63 import com.google.inject.Singleton;
66 * Memory-based {@link PostDatabase} implementation.
68 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
71 public class MemoryDatabase extends AbstractService implements Database {
74 private final ReadWriteLock lock = new ReentrantReadWriteLock();
76 /** The Sone provider. */
77 private final SoneProvider soneProvider;
79 /** The configuration. */
80 private final Configuration configuration;
82 /** All posts by their ID. */
83 private final Map<String, Post> allPosts = new HashMap<String, Post>();
85 /** All posts by their Sones. */
86 private final Multimap<String, Post> sonePosts = HashMultimap.create();
88 /** Whether posts are known. */
89 private final Set<String> knownPosts = new HashSet<String>();
91 /** All post replies by their ID. */
92 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
94 /** Replies sorted by Sone. */
95 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
98 public int compare(String leftString, String rightString) {
99 return leftString.compareTo(rightString);
103 /** Replies by post. */
104 private final SortedSetMultimap<String, PostReply> postReplies = TreeMultimap.create(new Comparator<String>() {
107 public int compare(String leftString, String rightString) {
108 return leftString.compareTo(rightString);
112 /** Whether post replies are known. */
113 private final Set<String> knownPostReplies = new HashSet<String>();
115 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
116 private final Multimap<String, Album> soneAlbums = HashMultimap.create();
118 private final Map<String, Image> allImages = new HashMap<String, Image>();
119 private final Multimap<String, Image> soneImages = HashMultimap.create();
122 * Creates a new memory database.
124 * @param soneProvider
126 * @param configuration
127 * The configuration for loading and saving elements
130 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
131 this.soneProvider = soneProvider;
132 this.configuration = configuration;
140 * Saves the database.
142 * @throws DatabaseException
143 * if an error occurs while saving
146 public void save() throws DatabaseException {
148 saveKnownPostReplies();
155 /** {@inheritDocs} */
157 protected void doStart() {
159 loadKnownPostReplies();
163 /** {@inheritDocs} */
165 protected void doStop() {
169 } catch (DatabaseException de1) {
175 // POSTPROVIDER METHODS
178 /** {@inheritDocs} */
180 public Optional<Post> getPost(String postId) {
181 lock.readLock().lock();
183 return fromNullable(allPosts.get(postId));
185 lock.readLock().unlock();
189 /** {@inheritDocs} */
191 public Collection<Post> getPosts(String soneId) {
192 return new HashSet<Post>(getPostsFrom(soneId));
195 /** {@inheritDocs} */
197 public Collection<Post> getDirectedPosts(final String recipientId) {
198 lock.readLock().lock();
200 return from(sonePosts.values()).filter(new Predicate<Post>() {
202 public boolean apply(Post post) {
203 return post.getRecipientId().asSet().contains(recipientId);
207 lock.readLock().unlock();
212 // POSTBUILDERFACTORY METHODS
215 /** {@inheritDocs} */
217 public PostBuilder newPostBuilder() {
218 return new MemoryPostBuilder(this, soneProvider);
225 /** {@inheritDocs} */
227 public void storePost(Post post) {
228 checkNotNull(post, "post must not be null");
229 lock.writeLock().lock();
231 allPosts.put(post.getId(), post);
232 getPostsFrom(post.getSone().getId()).add(post);
234 lock.writeLock().unlock();
238 /** {@inheritDocs} */
240 public void removePost(Post post) {
241 checkNotNull(post, "post must not be null");
242 lock.writeLock().lock();
244 allPosts.remove(post.getId());
245 getPostsFrom(post.getSone().getId()).remove(post);
246 post.getSone().removePost(post);
248 lock.writeLock().unlock();
252 /** {@inheritDocs} */
254 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
255 checkNotNull(sone, "sone must not be null");
256 /* verify that all posts are from the same Sone. */
257 for (Post post : posts) {
258 if (!sone.equals(post.getSone())) {
259 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
263 lock.writeLock().lock();
265 /* remove all posts by the Sone. */
266 Collection<Post> oldPosts = getPostsFrom(sone.getId());
267 for (Post post : oldPosts) {
268 allPosts.remove(post.getId());
272 getPostsFrom(sone.getId()).addAll(posts);
273 for (Post post : posts) {
274 allPosts.put(post.getId(), post);
277 lock.writeLock().unlock();
281 /** {@inheritDocs} */
283 public void removePosts(Sone sone) {
284 checkNotNull(sone, "sone must not be null");
285 lock.writeLock().lock();
287 /* remove all posts by the Sone. */
288 getPostsFrom(sone.getId()).clear();
289 for (Post post : sone.getPosts()) {
290 allPosts.remove(post.getId());
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 postReplies.put(postReply.getPostId(), postReply);
348 lock.writeLock().unlock();
352 /** {@inheritDocs} */
354 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
355 checkNotNull(sone, "sone must not be null");
356 /* verify that all posts are from the same Sone. */
357 for (PostReply postReply : postReplies) {
358 if (!sone.equals(postReply.getSone())) {
359 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
363 lock.writeLock().lock();
365 /* remove all post replies of the Sone. */
366 for (PostReply postReply : getRepliesFrom(sone.getId())) {
367 removePostReply(postReply);
369 for (PostReply postReply : postReplies) {
370 allPostReplies.put(postReply.getId(), postReply);
371 sonePostReplies.put(postReply.getSone().getId(), postReply);
372 this.postReplies.put(postReply.getPostId(), postReply);
375 lock.writeLock().unlock();
379 /** {@inheritDocs} */
381 public void removePostReply(PostReply postReply) {
382 lock.writeLock().lock();
384 allPostReplies.remove(postReply.getId());
385 if (postReplies.containsKey(postReply.getPostId())) {
386 postReplies.get(postReply.getPostId()).remove(postReply);
389 lock.writeLock().unlock();
393 /** {@inheritDocs} */
395 public void removePostReplies(Sone sone) {
396 checkNotNull(sone, "sone must not be null");
398 lock.writeLock().lock();
400 for (PostReply postReply : sone.getReplies()) {
401 removePostReply(postReply);
404 lock.writeLock().unlock();
409 // ALBUMPROVDER METHODS
413 public Optional<Album> getAlbum(String albumId) {
414 lock.readLock().lock();
416 return fromNullable(allAlbums.get(albumId));
418 lock.readLock().unlock();
423 // ALBUMBUILDERFACTORY METHODS
427 public AlbumBuilder newAlbumBuilder() {
428 return new AlbumBuilderImpl();
432 // ALBUMSTORE METHODS
436 public void storeAlbum(Album album) {
437 lock.writeLock().lock();
439 allAlbums.put(album.getId(), album);
440 soneAlbums.put(album.getSone().getId(), album);
442 lock.writeLock().unlock();
447 public void removeAlbum(Album album) {
448 lock.writeLock().lock();
450 allAlbums.remove(album.getId());
451 soneAlbums.remove(album.getSone().getId(), album);
453 lock.writeLock().unlock();
458 // IMAGEPROVIDER METHODS
462 public Optional<Image> getImage(String imageId) {
463 lock.readLock().lock();
465 return fromNullable(allImages.get(imageId));
467 lock.readLock().unlock();
472 // IMAGEBUILDERFACTORY METHODS
476 public ImageBuilder newImageBuilder() {
477 return new ImageBuilderImpl();
481 // IMAGESTORE METHODS
485 public void storeImage(Image image) {
486 lock.writeLock().lock();
488 allImages.put(image.getId(), image);
489 soneImages.put(image.getSone().getId(), image);
491 lock.writeLock().unlock();
496 public void removeImage(Image image) {
497 lock.writeLock().lock();
499 allImages.remove(image.getId());
500 soneImages.remove(image.getSone().getId(), image);
502 lock.writeLock().unlock();
507 // PACKAGE-PRIVATE METHODS
511 * Returns whether the given post is known.
515 * @return {@code true} if the post is known, {@code false} otherwise
517 boolean isPostKnown(Post post) {
518 lock.readLock().lock();
520 return knownPosts.contains(post.getId());
522 lock.readLock().unlock();
527 * Sets whether the given post is known.
532 * {@code true} if the post is known, {@code false} otherwise
534 void setPostKnown(Post post, boolean known) {
535 lock.writeLock().lock();
538 knownPosts.add(post.getId());
540 knownPosts.remove(post.getId());
543 lock.writeLock().unlock();
548 * Returns whether the given post reply is known.
552 * @return {@code true} if the given post reply is known, {@code false}
555 boolean isPostReplyKnown(PostReply postReply) {
556 lock.readLock().lock();
558 return knownPostReplies.contains(postReply.getId());
560 lock.readLock().unlock();
565 * Sets whether the given post reply is known.
570 * {@code true} if the post reply is known, {@code false} otherwise
572 void setPostReplyKnown(PostReply postReply, boolean known) {
573 lock.writeLock().lock();
576 knownPostReplies.add(postReply.getId());
578 knownPostReplies.remove(postReply.getId());
581 lock.writeLock().unlock();
590 * Gets all posts for the given Sone, creating a new collection if there is
594 * The ID of the Sone to get the posts for
597 private Collection<Post> getPostsFrom(String soneId) {
598 lock.readLock().lock();
600 return sonePosts.get(soneId);
602 lock.readLock().unlock();
606 /** Loads the known posts. */
607 private void loadKnownPosts() {
608 lock.writeLock().lock();
612 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
613 if (knownPostId == null) {
616 knownPosts.add(knownPostId);
619 lock.writeLock().unlock();
624 * Saves the known posts to the configuration.
626 * @throws DatabaseException
627 * if a configuration error occurs
629 private void saveKnownPosts() throws DatabaseException {
630 lock.readLock().lock();
633 for (String knownPostId : knownPosts) {
634 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
636 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
637 } catch (ConfigurationException ce1) {
638 throw new DatabaseException("Could not save database.", ce1);
640 lock.readLock().unlock();
645 * Returns all replies by the given Sone.
649 * @return The post replies of the Sone, sorted by time (newest first)
651 private Collection<PostReply> getRepliesFrom(String id) {
652 lock.readLock().lock();
654 return Collections.unmodifiableCollection(sonePostReplies.get(id));
656 lock.readLock().unlock();
660 /** Loads the known post replies. */
661 private void loadKnownPostReplies() {
662 lock.writeLock().lock();
664 int replyCounter = 0;
666 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
667 if (knownReplyId == null) {
670 knownPostReplies.add(knownReplyId);
673 lock.writeLock().unlock();
678 * Saves the known post replies to the configuration.
680 * @throws DatabaseException
681 * if a configuration error occurs
683 private void saveKnownPostReplies() throws DatabaseException {
684 lock.readLock().lock();
686 int replyCounter = 0;
687 for (String knownReplyId : knownPostReplies) {
688 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
690 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
691 } catch (ConfigurationException ce1) {
692 throw new DatabaseException("Could not save database.", ce1);
694 lock.readLock().unlock();