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 /** 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>();
107 private final Multimap<String, Album> soneAlbums = HashMultimap.create();
109 private final Map<String, Image> allImages = new HashMap<String, Image>();
110 private final Multimap<String, Image> soneImages = HashMultimap.create();
113 * Creates a new memory database.
115 * @param soneProvider
117 * @param configuration
118 * The configuration for loading and saving elements
121 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
122 this.soneProvider = soneProvider;
123 this.configuration = configuration;
131 * Saves the database.
133 * @throws DatabaseException
134 * if an error occurs while saving
137 public void save() throws DatabaseException {
139 saveKnownPostReplies();
146 /** {@inheritDocs} */
148 protected void doStart() {
150 loadKnownPostReplies();
154 /** {@inheritDocs} */
156 protected void doStop() {
160 } catch (DatabaseException de1) {
166 // POSTPROVIDER METHODS
169 /** {@inheritDocs} */
171 public Optional<Post> getPost(String postId) {
172 lock.readLock().lock();
174 return fromNullable(allPosts.get(postId));
176 lock.readLock().unlock();
180 /** {@inheritDocs} */
182 public Collection<Post> getPosts(String soneId) {
183 return new HashSet<Post>(getPostsFrom(soneId));
186 /** {@inheritDocs} */
188 public Collection<Post> getDirectedPosts(final String recipientId) {
189 lock.readLock().lock();
191 return from(sonePosts.values()).filter(new Predicate<Post>() {
193 public boolean apply(Post post) {
194 return post.getRecipientId().asSet().contains(recipientId);
198 lock.readLock().unlock();
203 // POSTBUILDERFACTORY METHODS
206 /** {@inheritDocs} */
208 public PostBuilder newPostBuilder() {
209 return new MemoryPostBuilder(this, soneProvider);
216 /** {@inheritDocs} */
218 public void storePost(Post post) {
219 checkNotNull(post, "post must not be null");
220 lock.writeLock().lock();
222 allPosts.put(post.getId(), post);
223 getPostsFrom(post.getSone().getId()).add(post);
225 lock.writeLock().unlock();
229 /** {@inheritDocs} */
231 public void removePost(Post post) {
232 checkNotNull(post, "post must not be null");
233 lock.writeLock().lock();
235 allPosts.remove(post.getId());
236 getPostsFrom(post.getSone().getId()).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 Collection<Post> oldPosts = getPostsFrom(sone.getId());
258 for (Post post : oldPosts) {
259 allPosts.remove(post.getId());
263 getPostsFrom(sone.getId()).addAll(posts);
264 for (Post post : posts) {
265 allPosts.put(post.getId(), post);
268 lock.writeLock().unlock();
272 /** {@inheritDocs} */
274 public void removePosts(Sone sone) {
275 checkNotNull(sone, "sone must not be null");
276 lock.writeLock().lock();
278 /* remove all posts by the Sone. */
279 getPostsFrom(sone.getId()).clear();
280 for (Post post : sone.getPosts()) {
281 allPosts.remove(post.getId());
284 lock.writeLock().unlock();
289 // POSTREPLYPROVIDER METHODS
292 /** {@inheritDocs} */
294 public Optional<PostReply> getPostReply(String id) {
295 lock.readLock().lock();
297 return fromNullable(allPostReplies.get(id));
299 lock.readLock().unlock();
303 /** {@inheritDocs} */
305 public List<PostReply> getReplies(final String postId) {
306 lock.readLock().lock();
308 return from(allPostReplies.values())
309 .filter(new Predicate<PostReply>() {
311 public boolean apply(PostReply postReply) {
312 return postReply.getPostId().equals(postId);
314 }).toSortedList(TIME_COMPARATOR);
316 lock.readLock().unlock();
321 // POSTREPLYBUILDERFACTORY METHODS
324 /** {@inheritDocs} */
326 public PostReplyBuilder newPostReplyBuilder() {
327 return new MemoryPostReplyBuilder(this, soneProvider);
331 // POSTREPLYSTORE METHODS
334 /** {@inheritDocs} */
336 public void storePostReply(PostReply postReply) {
337 lock.writeLock().lock();
339 allPostReplies.put(postReply.getId(), postReply);
341 lock.writeLock().unlock();
345 /** {@inheritDocs} */
347 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
348 checkNotNull(sone, "sone must not be null");
349 /* verify that all posts are from the same Sone. */
350 for (PostReply postReply : postReplies) {
351 if (!sone.equals(postReply.getSone())) {
352 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
356 lock.writeLock().lock();
358 /* remove all post replies of the Sone. */
359 for (PostReply postReply : getRepliesFrom(sone.getId())) {
360 removePostReply(postReply);
362 for (PostReply postReply : postReplies) {
363 allPostReplies.put(postReply.getId(), postReply);
364 sonePostReplies.put(postReply.getSone().getId(), postReply);
367 lock.writeLock().unlock();
371 /** {@inheritDocs} */
373 public void removePostReply(PostReply postReply) {
374 lock.writeLock().lock();
376 allPostReplies.remove(postReply.getId());
378 lock.writeLock().unlock();
382 /** {@inheritDocs} */
384 public void removePostReplies(Sone sone) {
385 checkNotNull(sone, "sone must not be null");
387 lock.writeLock().lock();
389 for (PostReply postReply : sone.getReplies()) {
390 removePostReply(postReply);
393 lock.writeLock().unlock();
398 // ALBUMPROVDER METHODS
402 public Optional<Album> getAlbum(String albumId) {
403 lock.readLock().lock();
405 return fromNullable(allAlbums.get(albumId));
407 lock.readLock().unlock();
412 // ALBUMBUILDERFACTORY METHODS
416 public AlbumBuilder newAlbumBuilder() {
417 return new AlbumBuilderImpl();
421 // ALBUMSTORE METHODS
425 public void storeAlbum(Album album) {
426 lock.writeLock().lock();
428 allAlbums.put(album.getId(), album);
429 soneAlbums.put(album.getSone().getId(), album);
431 lock.writeLock().unlock();
436 public void removeAlbum(Album album) {
437 lock.writeLock().lock();
439 allAlbums.remove(album.getId());
440 soneAlbums.remove(album.getSone().getId(), album);
442 lock.writeLock().unlock();
447 // IMAGEPROVIDER METHODS
451 public Optional<Image> getImage(String imageId) {
452 lock.readLock().lock();
454 return fromNullable(allImages.get(imageId));
456 lock.readLock().unlock();
461 // IMAGEBUILDERFACTORY METHODS
465 public ImageBuilder newImageBuilder() {
466 return new ImageBuilderImpl();
470 // IMAGESTORE METHODS
474 public void storeImage(Image image) {
475 lock.writeLock().lock();
477 allImages.put(image.getId(), image);
478 soneImages.put(image.getSone().getId(), image);
480 lock.writeLock().unlock();
485 public void removeImage(Image image) {
486 lock.writeLock().lock();
488 allImages.remove(image.getId());
489 soneImages.remove(image.getSone().getId(), image);
491 lock.writeLock().unlock();
496 // PACKAGE-PRIVATE METHODS
500 * Returns whether the given post is known.
504 * @return {@code true} if the post is known, {@code false} otherwise
506 boolean isPostKnown(Post post) {
507 lock.readLock().lock();
509 return knownPosts.contains(post.getId());
511 lock.readLock().unlock();
516 * Sets whether the given post is known.
521 * {@code true} if the post is known, {@code false} otherwise
523 void setPostKnown(Post post, boolean known) {
524 lock.writeLock().lock();
527 knownPosts.add(post.getId());
529 knownPosts.remove(post.getId());
532 lock.writeLock().unlock();
537 * Returns whether the given post reply is known.
541 * @return {@code true} if the given post reply is known, {@code false}
544 boolean isPostReplyKnown(PostReply postReply) {
545 lock.readLock().lock();
547 return knownPostReplies.contains(postReply.getId());
549 lock.readLock().unlock();
554 * Sets whether the given post reply is known.
559 * {@code true} if the post reply is known, {@code false} otherwise
561 void setPostReplyKnown(PostReply postReply, boolean known) {
562 lock.writeLock().lock();
565 knownPostReplies.add(postReply.getId());
567 knownPostReplies.remove(postReply.getId());
570 lock.writeLock().unlock();
579 * Gets all posts for the given Sone, creating a new collection if there is
583 * The ID of the Sone to get the posts for
586 private Collection<Post> getPostsFrom(String soneId) {
587 lock.readLock().lock();
589 return sonePosts.get(soneId);
591 lock.readLock().unlock();
595 /** Loads the known posts. */
596 private void loadKnownPosts() {
597 lock.writeLock().lock();
601 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
602 if (knownPostId == null) {
605 knownPosts.add(knownPostId);
608 lock.writeLock().unlock();
613 * Saves the known posts to the configuration.
615 * @throws DatabaseException
616 * if a configuration error occurs
618 private void saveKnownPosts() throws DatabaseException {
619 lock.readLock().lock();
622 for (String knownPostId : knownPosts) {
623 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
625 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
626 } catch (ConfigurationException ce1) {
627 throw new DatabaseException("Could not save database.", ce1);
629 lock.readLock().unlock();
634 * Returns all replies by the given Sone.
638 * @return The post replies of the Sone, sorted by time (newest first)
640 private Collection<PostReply> getRepliesFrom(String id) {
641 lock.readLock().lock();
643 return Collections.unmodifiableCollection(sonePostReplies.get(id));
645 lock.readLock().unlock();
649 /** Loads the known post replies. */
650 private void loadKnownPostReplies() {
651 lock.writeLock().lock();
653 int replyCounter = 0;
655 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
656 if (knownReplyId == null) {
659 knownPostReplies.add(knownReplyId);
662 lock.writeLock().unlock();
667 * Saves the known post replies to the configuration.
669 * @throws DatabaseException
670 * if a configuration error occurs
672 private void saveKnownPostReplies() throws DatabaseException {
673 lock.readLock().lock();
675 int replyCounter = 0;
676 for (String knownReplyId : knownPostReplies) {
677 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
679 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
680 } catch (ConfigurationException ce1) {
681 throw new DatabaseException("Could not save database.", ce1);
683 lock.readLock().unlock();