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.base.Predicates.not;
23 import static com.google.common.collect.FluentIterable.from;
24 import static java.util.Collections.emptyList;
25 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.Comparator;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.List;
36 import java.util.concurrent.locks.ReadWriteLock;
37 import java.util.concurrent.locks.ReentrantReadWriteLock;
39 import net.pterodactylus.sone.data.Album;
40 import net.pterodactylus.sone.data.Image;
41 import net.pterodactylus.sone.data.Post;
42 import net.pterodactylus.sone.data.PostReply;
43 import net.pterodactylus.sone.data.Sone;
44 import net.pterodactylus.sone.data.impl.DefaultSoneBuilder;
45 import net.pterodactylus.sone.database.Database;
46 import net.pterodactylus.sone.database.DatabaseException;
47 import net.pterodactylus.sone.database.PostDatabase;
48 import net.pterodactylus.sone.database.SoneBuilder;
49 import net.pterodactylus.sone.freenet.wot.Identity;
50 import net.pterodactylus.util.config.Configuration;
51 import net.pterodactylus.util.config.ConfigurationException;
53 import com.google.common.base.Function;
54 import com.google.common.base.Optional;
55 import com.google.common.collect.ArrayListMultimap;
56 import com.google.common.collect.HashMultimap;
57 import com.google.common.collect.ListMultimap;
58 import com.google.common.collect.Maps;
59 import com.google.common.collect.Multimap;
60 import com.google.common.collect.SortedSetMultimap;
61 import com.google.common.collect.TreeMultimap;
62 import com.google.common.util.concurrent.AbstractService;
63 import com.google.inject.Inject;
66 * Memory-based {@link PostDatabase} implementation.
68 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
70 public class MemoryDatabase extends AbstractService implements Database {
73 private final ReadWriteLock lock = new ReentrantReadWriteLock();
75 /** The configuration. */
76 private final Configuration configuration;
78 private final Map<String, Identity> identities = Maps.newHashMap();
79 private final Map<String, Sone> sones = new HashMap<String, Sone>();
81 /** All posts by their ID. */
82 private final Map<String, Post> allPosts = new HashMap<String, Post>();
84 /** All posts by their Sones. */
85 private final Multimap<String, Post> sonePosts = HashMultimap.create();
87 /** All posts by their recipient. */
88 private final Multimap<String, Post> recipientPosts = HashMultimap.create();
90 /** Whether posts are known. */
91 private final Set<String> knownPosts = new HashSet<String>();
93 /** All post replies by their ID. */
94 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
96 /** Replies sorted by Sone. */
97 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
100 public int compare(String leftString, String rightString) {
101 return leftString.compareTo(rightString);
103 }, PostReply.TIME_COMPARATOR);
105 /** Replies by post. */
106 private final SortedSetMultimap<String, PostReply> postReplies = TreeMultimap.create(new Comparator<String>() {
109 public int compare(String leftString, String rightString) {
110 return leftString.compareTo(rightString);
112 }, PostReply.TIME_COMPARATOR);
114 /** Whether post replies are known. */
115 private final Set<String> knownPostReplies = new HashSet<String>();
117 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
118 private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
119 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
121 private final Map<String, Image> allImages = new HashMap<String, Image>();
124 * Creates a new memory database.
126 * @param configuration
127 * The configuration for loading and saving elements
130 public MemoryDatabase(Configuration configuration) {
131 this.configuration = configuration;
139 public void save() throws DatabaseException {
141 saveKnownPostReplies();
149 protected void doStart() {
151 loadKnownPostReplies();
156 protected void doStop() {
160 } catch (DatabaseException de1) {
166 public Optional<Identity> getIdentity(String identityId) {
167 lock.readLock().lock();
169 return fromNullable(identities.get(identityId));
171 lock.readLock().unlock();
176 public Optional<Sone> getSone(String soneId) {
177 lock.readLock().lock();
179 return fromNullable(sones.get(soneId));
181 lock.readLock().unlock();
186 public Collection<Sone> getSones() {
187 lock.readLock().lock();
189 return Collections.unmodifiableCollection(sones.values());
191 lock.readLock().unlock();
196 public Collection<Sone> getLocalSones() {
197 lock.readLock().lock();
199 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
201 lock.readLock().unlock();
206 public Collection<Sone> getRemoteSones() {
207 lock.readLock().lock();
209 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
211 lock.readLock().unlock();
216 public SoneBuilder newSoneBuilder() {
217 return new DefaultSoneBuilder(this) {
219 public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
220 Sone sone = super.build(soneCreated);
221 lock.writeLock().lock();
223 sones.put(sone.getId(), sone);
225 lock.writeLock().unlock();
233 // POSTPROVIDER METHODS
237 public Optional<Post> getPost(String postId) {
238 lock.readLock().lock();
240 return fromNullable(allPosts.get(postId));
242 lock.readLock().unlock();
247 public Collection<Post> getPosts(String soneId) {
248 lock.readLock().lock();
250 return new HashSet<Post>(sonePosts.get(soneId));
252 lock.readLock().unlock();
257 public Collection<Post> getDirectedPosts(String recipientId) {
258 lock.readLock().lock();
260 Collection<Post> posts = recipientPosts.get(recipientId);
261 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
263 lock.readLock().unlock();
272 public void storePost(Post post) {
273 checkNotNull(post, "post must not be null");
274 lock.writeLock().lock();
276 allPosts.put(post.getId(), post);
277 sonePosts.put(post.getSone().getId(), post);
278 if (post.getRecipientId().isPresent()) {
279 recipientPosts.put(post.getRecipientId().get(), post);
282 lock.writeLock().unlock();
287 public void removePost(Post post) {
288 checkNotNull(post, "post must not be null");
289 lock.writeLock().lock();
291 allPosts.remove(post.getId());
292 sonePosts.remove(post.getSone().getId(), post);
293 if (post.getRecipientId().isPresent()) {
294 recipientPosts.remove(post.getRecipientId().get(), post);
296 post.getSone().removePost(post);
298 lock.writeLock().unlock();
303 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
304 checkNotNull(sone, "sone must not be null");
305 /* verify that all posts are from the same Sone. */
306 for (Post post : posts) {
307 if (!sone.equals(post.getSone())) {
308 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
312 lock.writeLock().lock();
314 /* remove all posts by the Sone. */
315 sonePosts.removeAll(sone.getId());
316 for (Post post : posts) {
317 allPosts.remove(post.getId());
318 if (post.getRecipientId().isPresent()) {
319 recipientPosts.remove(post.getRecipientId().get(), post);
324 sonePosts.putAll(sone.getId(), posts);
325 for (Post post : posts) {
326 allPosts.put(post.getId(), post);
327 if (post.getRecipientId().isPresent()) {
328 recipientPosts.put(post.getRecipientId().get(), post);
332 lock.writeLock().unlock();
337 public void removePosts(Sone sone) {
338 checkNotNull(sone, "sone must not be null");
339 lock.writeLock().lock();
341 /* remove all posts by the Sone. */
342 sonePosts.removeAll(sone.getId());
343 for (Post post : sone.getPosts()) {
344 allPosts.remove(post.getId());
345 if (post.getRecipientId().isPresent()) {
346 recipientPosts.remove(post.getRecipientId().get(), post);
350 lock.writeLock().unlock();
355 // POSTREPLYPROVIDER METHODS
359 public Optional<PostReply> getPostReply(String id) {
360 lock.readLock().lock();
362 return fromNullable(allPostReplies.get(id));
364 lock.readLock().unlock();
369 public List<PostReply> getReplies(String postId) {
370 lock.readLock().lock();
372 if (!postReplies.containsKey(postId)) {
375 return new ArrayList<PostReply>(postReplies.get(postId));
377 lock.readLock().unlock();
382 // POSTREPLYSTORE METHODS
386 * Returns whether the given post reply is known.
390 * @return {@code true} if the given post reply is known, {@code false}
393 public boolean isPostReplyKnown(PostReply postReply) {
394 lock.readLock().lock();
396 return knownPostReplies.contains(postReply.getId());
398 lock.readLock().unlock();
403 public void setPostReplyKnown(PostReply postReply) {
404 lock.writeLock().lock();
406 knownPostReplies.add(postReply.getId());
408 lock.writeLock().unlock();
413 public void storePostReply(PostReply postReply) {
414 lock.writeLock().lock();
416 allPostReplies.put(postReply.getId(), postReply);
417 postReplies.put(postReply.getPostId(), postReply);
419 lock.writeLock().unlock();
424 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
425 checkNotNull(sone, "sone must not be null");
426 /* verify that all posts are from the same Sone. */
427 for (PostReply postReply : postReplies) {
428 if (!sone.equals(postReply.getSone())) {
429 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
433 lock.writeLock().lock();
435 /* remove all post replies of the Sone. */
436 for (PostReply postReply : getRepliesFrom(sone.getId())) {
437 removePostReply(postReply);
439 for (PostReply postReply : postReplies) {
440 allPostReplies.put(postReply.getId(), postReply);
441 sonePostReplies.put(postReply.getSone().getId(), postReply);
442 this.postReplies.put(postReply.getPostId(), postReply);
445 lock.writeLock().unlock();
450 public void removePostReply(PostReply postReply) {
451 lock.writeLock().lock();
453 allPostReplies.remove(postReply.getId());
454 postReplies.remove(postReply.getPostId(), postReply);
456 lock.writeLock().unlock();
461 public void removePostReplies(Sone sone) {
462 checkNotNull(sone, "sone must not be null");
464 lock.writeLock().lock();
466 for (PostReply postReply : sone.getReplies()) {
467 removePostReply(postReply);
470 lock.writeLock().unlock();
475 // ALBUMPROVDER METHODS
479 public Optional<Album> getAlbum(String albumId) {
480 lock.readLock().lock();
482 return fromNullable(allAlbums.get(albumId));
484 lock.readLock().unlock();
489 public List<Album> getAlbums(Album parent) {
490 lock.readLock().lock();
492 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
494 lock.readLock().unlock();
499 public void moveUp(Album album) {
500 lock.writeLock().lock();
502 List<String> albums = albumChildren.get(album.getParent().getId());
503 int currentIndex = albums.indexOf(album.getId());
504 if (currentIndex == 0) {
507 albums.remove(album.getId());
508 albums.add(currentIndex - 1, album.getId());
510 lock.writeLock().unlock();
515 public void moveDown(Album album) {
516 lock.writeLock().lock();
518 List<String> albums = albumChildren.get(album.getParent().getId());
519 int currentIndex = albums.indexOf(album.getId());
520 if (currentIndex == (albums.size() - 1)) {
523 albums.remove(album.getId());
524 albums.add(currentIndex + 1, album.getId());
526 lock.writeLock().unlock();
531 // ALBUMSTORE METHODS
535 public void storeAlbum(Album album) {
536 lock.writeLock().lock();
538 allAlbums.put(album.getId(), album);
539 if (!album.isRoot()) {
540 albumChildren.put(album.getParent().getId(), album.getId());
543 lock.writeLock().unlock();
548 public void removeAlbum(Album album) {
549 lock.writeLock().lock();
551 allAlbums.remove(album.getId());
552 albumChildren.remove(album.getParent().getId(), album.getId());
554 lock.writeLock().unlock();
559 // IMAGEPROVIDER METHODS
563 public Optional<Image> getImage(String imageId) {
564 lock.readLock().lock();
566 return fromNullable(allImages.get(imageId));
568 lock.readLock().unlock();
573 public List<Image> getImages(Album parent) {
574 lock.readLock().lock();
576 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
578 lock.readLock().unlock();
583 public void moveUp(Image image) {
584 lock.writeLock().lock();
586 List<String> images = albumImages.get(image.getAlbum().getId());
587 int currentIndex = images.indexOf(image.getId());
588 if (currentIndex == 0) {
591 images.remove(image.getId());
592 images.add(currentIndex - 1, image.getId());
594 lock.writeLock().unlock();
599 public void moveDown(Image image) {
600 lock.writeLock().lock();
602 List<String> images = albumChildren.get(image.getAlbum().getId());
603 int currentIndex = images.indexOf(image.getId());
604 if (currentIndex == (images.size() - 1)) {
607 images.remove(image.getId());
608 images.add(currentIndex + 1, image.getId());
610 lock.writeLock().unlock();
615 // IMAGESTORE METHODS
619 public void storeImage(Image image) {
620 lock.writeLock().lock();
622 allImages.put(image.getId(), image);
623 albumImages.put(image.getAlbum().getId(), image.getId());
625 lock.writeLock().unlock();
630 public void removeImage(Image image) {
631 lock.writeLock().lock();
633 allImages.remove(image.getId());
634 albumImages.remove(image.getAlbum().getId(), image.getId());
636 lock.writeLock().unlock();
641 // PACKAGE-PRIVATE METHODS
645 * Returns whether the given post is known.
649 * @return {@code true} if the post is known, {@code false} otherwise
651 boolean isPostKnown(Post post) {
652 lock.readLock().lock();
654 return knownPosts.contains(post.getId());
656 lock.readLock().unlock();
661 * Sets whether the given post is known.
666 * {@code true} if the post is known, {@code false} otherwise
668 void setPostKnown(Post post, boolean known) {
669 lock.writeLock().lock();
672 knownPosts.add(post.getId());
674 knownPosts.remove(post.getId());
677 lock.writeLock().unlock();
685 /** Loads the known posts. */
686 private void loadKnownPosts() {
687 lock.writeLock().lock();
691 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
692 if (knownPostId == null) {
695 knownPosts.add(knownPostId);
698 lock.writeLock().unlock();
703 * Saves the known posts to the configuration.
705 * @throws DatabaseException
706 * if a configuration error occurs
708 private void saveKnownPosts() throws DatabaseException {
709 lock.readLock().lock();
712 for (String knownPostId : knownPosts) {
713 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
715 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
716 } catch (ConfigurationException ce1) {
717 throw new DatabaseException("Could not save database.", ce1);
719 lock.readLock().unlock();
724 * Returns all replies by the given Sone.
728 * @return The post replies of the Sone, sorted by time (newest first)
730 private Collection<PostReply> getRepliesFrom(String id) {
731 lock.readLock().lock();
733 if (sonePostReplies.containsKey(id)) {
734 return Collections.unmodifiableCollection(sonePostReplies.get(id));
736 return Collections.emptySet();
738 lock.readLock().unlock();
742 /** Loads the known post replies. */
743 private void loadKnownPostReplies() {
744 lock.writeLock().lock();
746 int replyCounter = 0;
748 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
749 if (knownReplyId == null) {
752 knownPostReplies.add(knownReplyId);
755 lock.writeLock().unlock();
760 * Saves the known post replies to the configuration.
762 * @throws DatabaseException
763 * if a configuration error occurs
765 private void saveKnownPostReplies() throws DatabaseException {
766 lock.readLock().lock();
768 int replyCounter = 0;
769 for (String knownReplyId : knownPostReplies) {
770 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
772 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
773 } catch (ConfigurationException ce1) {
774 throw new DatabaseException("Could not save database.", ce1);
776 lock.readLock().unlock();
780 private Function<String, Iterable<Album>> getAlbum() {
781 return new Function<String, Iterable<Album>>() {
783 public Iterable<Album> apply(String input) {
784 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
789 private Function<String, Iterable<Image>> getImage() {
790 return new Function<String, Iterable<Image>>() {
792 public Iterable<Image> apply(String input) {
793 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();