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.SetMultimap;
61 import com.google.common.collect.SortedSetMultimap;
62 import com.google.common.collect.TreeMultimap;
63 import com.google.common.util.concurrent.AbstractService;
64 import com.google.inject.Inject;
67 * Memory-based {@link PostDatabase} implementation.
69 * @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 configuration. */
77 private final Configuration configuration;
79 private final Map<String, Identity> identities = Maps.newHashMap();
80 private final Map<String, Sone> sones = new HashMap<String, Sone>();
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();
87 private final SetMultimap<String, String> likedPosts = HashMultimap.create();
89 /** All posts by their recipient. */
90 private final Multimap<String, Post> recipientPosts = HashMultimap.create();
92 /** Whether posts are known. */
93 private final Set<String> knownPosts = new HashSet<String>();
95 /** All post replies by their ID. */
96 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
98 /** Replies sorted by Sone. */
99 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
102 public int compare(String leftString, String rightString) {
103 return leftString.compareTo(rightString);
105 }, PostReply.TIME_COMPARATOR);
107 /** Replies by post. */
108 private final SortedSetMultimap<String, PostReply> postReplies = TreeMultimap.create(new Comparator<String>() {
111 public int compare(String leftString, String rightString) {
112 return leftString.compareTo(rightString);
114 }, PostReply.TIME_COMPARATOR);
116 /** Whether post replies are known. */
117 private final Set<String> knownPostReplies = new HashSet<String>();
119 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
120 private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
121 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
123 private final Map<String, Image> allImages = new HashMap<String, Image>();
126 * Creates a new memory database.
128 * @param configuration
129 * The configuration for loading and saving elements
132 public MemoryDatabase(Configuration configuration) {
133 this.configuration = configuration;
141 public void save() throws DatabaseException {
143 saveKnownPostReplies();
151 protected void doStart() {
153 loadKnownPostReplies();
158 protected void doStop() {
162 } catch (DatabaseException de1) {
168 public Optional<Identity> getIdentity(String identityId) {
169 lock.readLock().lock();
171 return fromNullable(identities.get(identityId));
173 lock.readLock().unlock();
178 public Function<String, Optional<Sone>> getSone() {
179 return new Function<String, Optional<Sone>>() {
181 public Optional<Sone> apply(String soneId) {
182 return (soneId == null) ? Optional.<Sone>absent() : getSone(soneId);
188 public Optional<Sone> getSone(String soneId) {
189 lock.readLock().lock();
191 return fromNullable(sones.get(soneId));
193 lock.readLock().unlock();
198 public Collection<Sone> getSones() {
199 lock.readLock().lock();
201 return Collections.unmodifiableCollection(sones.values());
203 lock.readLock().unlock();
208 public Collection<Sone> getLocalSones() {
209 lock.readLock().lock();
211 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
213 lock.readLock().unlock();
218 public Collection<Sone> getRemoteSones() {
219 lock.readLock().lock();
221 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
223 lock.readLock().unlock();
228 public SoneBuilder newSoneBuilder() {
229 return new DefaultSoneBuilder(this) {
231 public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
232 Sone sone = super.build(soneCreated);
233 lock.writeLock().lock();
235 sones.put(sone.getId(), sone);
237 lock.writeLock().unlock();
245 // POSTPROVIDER METHODS
249 public Function<String, Optional<Post>> getPost() {
250 return new Function<String, Optional<Post>>() {
252 public Optional<Post> apply(String postId) {
253 return (postId == null) ? Optional.<Post>absent() : getPost(postId);
259 public Optional<Post> getPost(String postId) {
260 lock.readLock().lock();
262 return fromNullable(allPosts.get(postId));
264 lock.readLock().unlock();
269 public Collection<Post> getPosts(String soneId) {
270 lock.readLock().lock();
272 return new HashSet<Post>(sonePosts.get(soneId));
274 lock.readLock().unlock();
279 public Collection<Post> getDirectedPosts(String recipientId) {
280 lock.readLock().lock();
282 Collection<Post> posts = recipientPosts.get(recipientId);
283 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
285 lock.readLock().unlock();
290 public void likePost(Post post, Sone localSone) {
291 lock.writeLock().lock();
293 likedPosts.put(localSone.getId(), post.getId());
295 lock.writeLock().unlock();
304 public void storePost(Post post) {
305 checkNotNull(post, "post must not be null");
306 lock.writeLock().lock();
308 allPosts.put(post.getId(), post);
309 sonePosts.put(post.getSone().getId(), post);
310 if (post.getRecipientId().isPresent()) {
311 recipientPosts.put(post.getRecipientId().get(), post);
314 lock.writeLock().unlock();
319 public void removePost(Post post) {
320 checkNotNull(post, "post must not be null");
321 lock.writeLock().lock();
323 allPosts.remove(post.getId());
324 sonePosts.remove(post.getSone().getId(), post);
325 if (post.getRecipientId().isPresent()) {
326 recipientPosts.remove(post.getRecipientId().get(), post);
328 post.getSone().removePost(post);
330 lock.writeLock().unlock();
335 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
336 checkNotNull(sone, "sone must not be null");
337 /* verify that all posts are from the same Sone. */
338 for (Post post : posts) {
339 if (!sone.equals(post.getSone())) {
340 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
344 lock.writeLock().lock();
346 /* remove all posts by the Sone. */
347 sonePosts.removeAll(sone.getId());
348 for (Post post : posts) {
349 allPosts.remove(post.getId());
350 if (post.getRecipientId().isPresent()) {
351 recipientPosts.remove(post.getRecipientId().get(), post);
356 sonePosts.putAll(sone.getId(), posts);
357 for (Post post : posts) {
358 allPosts.put(post.getId(), post);
359 if (post.getRecipientId().isPresent()) {
360 recipientPosts.put(post.getRecipientId().get(), post);
364 lock.writeLock().unlock();
369 public void removePosts(Sone sone) {
370 checkNotNull(sone, "sone must not be null");
371 lock.writeLock().lock();
373 /* remove all posts by the Sone. */
374 sonePosts.removeAll(sone.getId());
375 for (Post post : sone.getPosts()) {
376 allPosts.remove(post.getId());
377 if (post.getRecipientId().isPresent()) {
378 recipientPosts.remove(post.getRecipientId().get(), post);
382 lock.writeLock().unlock();
387 // POSTREPLYPROVIDER METHODS
391 public Optional<PostReply> getPostReply(String id) {
392 lock.readLock().lock();
394 return fromNullable(allPostReplies.get(id));
396 lock.readLock().unlock();
401 public List<PostReply> getReplies(String postId) {
402 lock.readLock().lock();
404 if (!postReplies.containsKey(postId)) {
407 return new ArrayList<PostReply>(postReplies.get(postId));
409 lock.readLock().unlock();
414 // POSTREPLYSTORE METHODS
418 * Returns whether the given post reply is known.
422 * @return {@code true} if the given post reply is known, {@code false}
425 public boolean isPostReplyKnown(PostReply postReply) {
426 lock.readLock().lock();
428 return knownPostReplies.contains(postReply.getId());
430 lock.readLock().unlock();
435 public void setPostReplyKnown(PostReply postReply) {
436 lock.writeLock().lock();
438 knownPostReplies.add(postReply.getId());
440 lock.writeLock().unlock();
445 public void storePostReply(PostReply postReply) {
446 lock.writeLock().lock();
448 allPostReplies.put(postReply.getId(), postReply);
449 postReplies.put(postReply.getPostId(), postReply);
451 lock.writeLock().unlock();
456 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
457 checkNotNull(sone, "sone must not be null");
458 /* verify that all posts are from the same Sone. */
459 for (PostReply postReply : postReplies) {
460 if (!sone.equals(postReply.getSone())) {
461 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
465 lock.writeLock().lock();
467 /* remove all post replies of the Sone. */
468 for (PostReply postReply : getRepliesFrom(sone.getId())) {
469 removePostReply(postReply);
471 for (PostReply postReply : postReplies) {
472 allPostReplies.put(postReply.getId(), postReply);
473 sonePostReplies.put(postReply.getSone().getId(), postReply);
474 this.postReplies.put(postReply.getPostId(), postReply);
477 lock.writeLock().unlock();
482 public void removePostReply(PostReply postReply) {
483 lock.writeLock().lock();
485 allPostReplies.remove(postReply.getId());
486 postReplies.remove(postReply.getPostId(), postReply);
488 lock.writeLock().unlock();
493 public void removePostReplies(Sone sone) {
494 checkNotNull(sone, "sone must not be null");
496 lock.writeLock().lock();
498 for (PostReply postReply : sone.getReplies()) {
499 removePostReply(postReply);
502 lock.writeLock().unlock();
507 // ALBUMPROVDER METHODS
511 public Optional<Album> getAlbum(String albumId) {
512 lock.readLock().lock();
514 return fromNullable(allAlbums.get(albumId));
516 lock.readLock().unlock();
521 public List<Album> getAlbums(Album parent) {
522 lock.readLock().lock();
524 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
526 lock.readLock().unlock();
531 public void moveUp(Album album) {
532 lock.writeLock().lock();
534 List<String> albums = albumChildren.get(album.getParent().getId());
535 int currentIndex = albums.indexOf(album.getId());
536 if (currentIndex == 0) {
539 albums.remove(album.getId());
540 albums.add(currentIndex - 1, album.getId());
542 lock.writeLock().unlock();
547 public void moveDown(Album album) {
548 lock.writeLock().lock();
550 List<String> albums = albumChildren.get(album.getParent().getId());
551 int currentIndex = albums.indexOf(album.getId());
552 if (currentIndex == (albums.size() - 1)) {
555 albums.remove(album.getId());
556 albums.add(currentIndex + 1, album.getId());
558 lock.writeLock().unlock();
563 // ALBUMSTORE METHODS
567 public void storeAlbum(Album album) {
568 lock.writeLock().lock();
570 allAlbums.put(album.getId(), album);
571 if (!album.isRoot()) {
572 albumChildren.put(album.getParent().getId(), album.getId());
575 lock.writeLock().unlock();
580 public void removeAlbum(Album album) {
581 lock.writeLock().lock();
583 allAlbums.remove(album.getId());
584 albumChildren.remove(album.getParent().getId(), album.getId());
586 lock.writeLock().unlock();
591 // IMAGEPROVIDER METHODS
595 public Optional<Image> getImage(String imageId) {
596 lock.readLock().lock();
598 return fromNullable(allImages.get(imageId));
600 lock.readLock().unlock();
605 public List<Image> getImages(Album parent) {
606 lock.readLock().lock();
608 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
610 lock.readLock().unlock();
615 public void moveUp(Image image) {
616 lock.writeLock().lock();
618 List<String> images = albumImages.get(image.getAlbum().getId());
619 int currentIndex = images.indexOf(image.getId());
620 if (currentIndex == 0) {
623 images.remove(image.getId());
624 images.add(currentIndex - 1, image.getId());
626 lock.writeLock().unlock();
631 public void moveDown(Image image) {
632 lock.writeLock().lock();
634 List<String> images = albumChildren.get(image.getAlbum().getId());
635 int currentIndex = images.indexOf(image.getId());
636 if (currentIndex == (images.size() - 1)) {
639 images.remove(image.getId());
640 images.add(currentIndex + 1, image.getId());
642 lock.writeLock().unlock();
647 // IMAGESTORE METHODS
651 public void storeImage(Image image) {
652 lock.writeLock().lock();
654 allImages.put(image.getId(), image);
655 albumImages.put(image.getAlbum().getId(), image.getId());
657 lock.writeLock().unlock();
662 public void removeImage(Image image) {
663 lock.writeLock().lock();
665 allImages.remove(image.getId());
666 albumImages.remove(image.getAlbum().getId(), image.getId());
668 lock.writeLock().unlock();
673 // PACKAGE-PRIVATE METHODS
677 * Returns whether the given post is known.
681 * @return {@code true} if the post is known, {@code false} otherwise
683 boolean isPostKnown(Post post) {
684 lock.readLock().lock();
686 return knownPosts.contains(post.getId());
688 lock.readLock().unlock();
693 * Sets whether the given post is known.
698 * {@code true} if the post is known, {@code false} otherwise
700 void setPostKnown(Post post, boolean known) {
701 lock.writeLock().lock();
704 knownPosts.add(post.getId());
706 knownPosts.remove(post.getId());
709 lock.writeLock().unlock();
717 /** Loads the known posts. */
718 private void loadKnownPosts() {
719 lock.writeLock().lock();
723 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
724 if (knownPostId == null) {
727 knownPosts.add(knownPostId);
730 lock.writeLock().unlock();
735 * Saves the known posts to the configuration.
737 * @throws DatabaseException
738 * if a configuration error occurs
740 private void saveKnownPosts() throws DatabaseException {
741 lock.readLock().lock();
744 for (String knownPostId : knownPosts) {
745 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
747 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
748 } catch (ConfigurationException ce1) {
749 throw new DatabaseException("Could not save database.", ce1);
751 lock.readLock().unlock();
756 * Returns all replies by the given Sone.
760 * @return The post replies of the Sone, sorted by time (newest first)
762 private Collection<PostReply> getRepliesFrom(String id) {
763 lock.readLock().lock();
765 if (sonePostReplies.containsKey(id)) {
766 return Collections.unmodifiableCollection(sonePostReplies.get(id));
768 return Collections.emptySet();
770 lock.readLock().unlock();
774 /** Loads the known post replies. */
775 private void loadKnownPostReplies() {
776 lock.writeLock().lock();
778 int replyCounter = 0;
780 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
781 if (knownReplyId == null) {
784 knownPostReplies.add(knownReplyId);
787 lock.writeLock().unlock();
792 * Saves the known post replies to the configuration.
794 * @throws DatabaseException
795 * if a configuration error occurs
797 private void saveKnownPostReplies() throws DatabaseException {
798 lock.readLock().lock();
800 int replyCounter = 0;
801 for (String knownReplyId : knownPostReplies) {
802 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
804 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
805 } catch (ConfigurationException ce1) {
806 throw new DatabaseException("Could not save database.", ce1);
808 lock.readLock().unlock();
812 private Function<String, Iterable<Album>> getAlbum() {
813 return new Function<String, Iterable<Album>>() {
815 public Iterable<Album> apply(String input) {
816 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
821 private Function<String, Iterable<Image>> getImage() {
822 return new Function<String, Iterable<Image>>() {
824 public Iterable<Image> apply(String input) {
825 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();