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.SortedSet;
37 import java.util.TreeSet;
38 import java.util.concurrent.locks.ReadWriteLock;
39 import java.util.concurrent.locks.ReentrantReadWriteLock;
41 import net.pterodactylus.sone.data.Album;
42 import net.pterodactylus.sone.data.Image;
43 import net.pterodactylus.sone.data.Post;
44 import net.pterodactylus.sone.data.PostReply;
45 import net.pterodactylus.sone.data.Reply;
46 import net.pterodactylus.sone.data.Sone;
47 import net.pterodactylus.sone.database.Database;
48 import net.pterodactylus.sone.database.DatabaseException;
49 import net.pterodactylus.sone.database.PostDatabase;
50 import net.pterodactylus.sone.database.SoneBuilder;
51 import net.pterodactylus.sone.freenet.wot.Identity;
52 import net.pterodactylus.util.config.Configuration;
53 import net.pterodactylus.util.config.ConfigurationException;
55 import com.google.common.base.Function;
56 import com.google.common.base.Optional;
57 import com.google.common.collect.ArrayListMultimap;
58 import com.google.common.collect.HashMultimap;
59 import com.google.common.collect.ListMultimap;
60 import com.google.common.collect.Maps;
61 import com.google.common.collect.Multimap;
62 import com.google.common.collect.SortedSetMultimap;
63 import com.google.common.collect.TreeMultimap;
64 import com.google.common.util.concurrent.AbstractService;
65 import com.google.inject.Inject;
68 * Memory-based {@link PostDatabase} implementation.
70 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
72 public class MemoryDatabase extends AbstractService implements Database {
75 private final ReadWriteLock lock = new ReentrantReadWriteLock();
77 /** The configuration. */
78 private final Configuration configuration;
80 private final Map<String, Identity> identities = Maps.newHashMap();
81 private final Map<String, Sone> sones = new HashMap<String, Sone>();
83 /** All posts by their ID. */
84 private final Map<String, Post> allPosts = new HashMap<String, Post>();
86 /** All posts by their Sones. */
87 private final Multimap<String, Post> sonePosts = 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 Optional<Sone> getSone(String soneId) {
179 lock.readLock().lock();
181 return fromNullable(sones.get(soneId));
183 lock.readLock().unlock();
188 public Collection<Sone> getSones() {
189 lock.readLock().lock();
191 return Collections.unmodifiableCollection(sones.values());
193 lock.readLock().unlock();
198 public Collection<Sone> getLocalSones() {
199 lock.readLock().lock();
201 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
203 lock.readLock().unlock();
208 public Collection<Sone> getRemoteSones() {
209 lock.readLock().lock();
211 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
213 lock.readLock().unlock();
218 public SoneBuilder newSoneBuilder() {
223 // POSTPROVIDER METHODS
227 public Optional<Post> getPost(String postId) {
228 lock.readLock().lock();
230 return fromNullable(allPosts.get(postId));
232 lock.readLock().unlock();
237 public Collection<Post> getPosts(String soneId) {
238 lock.readLock().lock();
240 return new HashSet<Post>(sonePosts.get(soneId));
242 lock.readLock().unlock();
247 public Collection<Post> getDirectedPosts(String recipientId) {
248 lock.readLock().lock();
250 Collection<Post> posts = recipientPosts.get(recipientId);
251 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
253 lock.readLock().unlock();
262 public void storePost(Post post) {
263 checkNotNull(post, "post must not be null");
264 lock.writeLock().lock();
266 allPosts.put(post.getId(), post);
267 sonePosts.put(post.getSone().getId(), post);
268 if (post.getRecipientId().isPresent()) {
269 recipientPosts.put(post.getRecipientId().get(), post);
272 lock.writeLock().unlock();
277 public void removePost(Post post) {
278 checkNotNull(post, "post must not be null");
279 lock.writeLock().lock();
281 allPosts.remove(post.getId());
282 sonePosts.remove(post.getSone().getId(), post);
283 if (post.getRecipientId().isPresent()) {
284 recipientPosts.remove(post.getRecipientId().get(), post);
286 post.getSone().removePost(post);
288 lock.writeLock().unlock();
293 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
294 checkNotNull(sone, "sone must not be null");
295 /* verify that all posts are from the same Sone. */
296 for (Post post : posts) {
297 if (!sone.equals(post.getSone())) {
298 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
302 lock.writeLock().lock();
304 /* remove all posts by the Sone. */
305 sonePosts.removeAll(sone.getId());
306 for (Post post : posts) {
307 allPosts.remove(post.getId());
308 if (post.getRecipientId().isPresent()) {
309 recipientPosts.remove(post.getRecipientId().get(), post);
314 sonePosts.putAll(sone.getId(), posts);
315 for (Post post : posts) {
316 allPosts.put(post.getId(), post);
317 if (post.getRecipientId().isPresent()) {
318 recipientPosts.put(post.getRecipientId().get(), post);
322 lock.writeLock().unlock();
327 public void removePosts(Sone sone) {
328 checkNotNull(sone, "sone must not be null");
329 lock.writeLock().lock();
331 /* remove all posts by the Sone. */
332 sonePosts.removeAll(sone.getId());
333 for (Post post : sone.getPosts()) {
334 allPosts.remove(post.getId());
335 if (post.getRecipientId().isPresent()) {
336 recipientPosts.remove(post.getRecipientId().get(), post);
340 lock.writeLock().unlock();
345 // POSTREPLYPROVIDER METHODS
349 public Optional<PostReply> getPostReply(String id) {
350 lock.readLock().lock();
352 return fromNullable(allPostReplies.get(id));
354 lock.readLock().unlock();
359 public List<PostReply> getReplies(String postId) {
360 lock.readLock().lock();
362 if (!postReplies.containsKey(postId)) {
365 return new ArrayList<PostReply>(postReplies.get(postId));
367 lock.readLock().unlock();
372 // POSTREPLYSTORE METHODS
376 * Returns whether the given post reply is known.
380 * @return {@code true} if the given post reply is known, {@code false}
383 public boolean isPostReplyKnown(PostReply postReply) {
384 lock.readLock().lock();
386 return knownPostReplies.contains(postReply.getId());
388 lock.readLock().unlock();
393 public void setPostReplyKnown(PostReply postReply) {
394 lock.writeLock().lock();
396 knownPostReplies.add(postReply.getId());
398 lock.writeLock().unlock();
403 public void storePostReply(PostReply postReply) {
404 lock.writeLock().lock();
406 allPostReplies.put(postReply.getId(), postReply);
407 postReplies.put(postReply.getPostId(), postReply);
409 lock.writeLock().unlock();
414 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
415 checkNotNull(sone, "sone must not be null");
416 /* verify that all posts are from the same Sone. */
417 for (PostReply postReply : postReplies) {
418 if (!sone.equals(postReply.getSone())) {
419 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
423 lock.writeLock().lock();
425 /* remove all post replies of the Sone. */
426 for (PostReply postReply : getRepliesFrom(sone.getId())) {
427 removePostReply(postReply);
429 for (PostReply postReply : postReplies) {
430 allPostReplies.put(postReply.getId(), postReply);
431 sonePostReplies.put(postReply.getSone().getId(), postReply);
432 this.postReplies.put(postReply.getPostId(), postReply);
435 lock.writeLock().unlock();
440 public void removePostReply(PostReply postReply) {
441 lock.writeLock().lock();
443 allPostReplies.remove(postReply.getId());
444 postReplies.remove(postReply.getPostId(), postReply);
446 lock.writeLock().unlock();
451 public void removePostReplies(Sone sone) {
452 checkNotNull(sone, "sone must not be null");
454 lock.writeLock().lock();
456 for (PostReply postReply : sone.getReplies()) {
457 removePostReply(postReply);
460 lock.writeLock().unlock();
465 // ALBUMPROVDER METHODS
469 public Optional<Album> getAlbum(String albumId) {
470 lock.readLock().lock();
472 return fromNullable(allAlbums.get(albumId));
474 lock.readLock().unlock();
479 public List<Album> getAlbums(Album parent) {
480 lock.readLock().lock();
482 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
484 lock.readLock().unlock();
489 public void moveUp(Album album) {
490 lock.writeLock().lock();
492 List<String> albums = albumChildren.get(album.getParent().getId());
493 int currentIndex = albums.indexOf(album.getId());
494 if (currentIndex == 0) {
497 albums.remove(album.getId());
498 albums.add(currentIndex - 1, album.getId());
500 lock.writeLock().unlock();
505 public void moveDown(Album album) {
506 lock.writeLock().lock();
508 List<String> albums = albumChildren.get(album.getParent().getId());
509 int currentIndex = albums.indexOf(album.getId());
510 if (currentIndex == (albums.size() - 1)) {
513 albums.remove(album.getId());
514 albums.add(currentIndex + 1, album.getId());
516 lock.writeLock().unlock();
521 // ALBUMSTORE METHODS
525 public void storeAlbum(Album album) {
526 lock.writeLock().lock();
528 allAlbums.put(album.getId(), album);
529 albumChildren.put(album.getParent().getId(), album.getId());
531 lock.writeLock().unlock();
536 public void removeAlbum(Album album) {
537 lock.writeLock().lock();
539 allAlbums.remove(album.getId());
540 albumChildren.remove(album.getParent().getId(), album.getId());
542 lock.writeLock().unlock();
547 // IMAGEPROVIDER METHODS
551 public Optional<Image> getImage(String imageId) {
552 lock.readLock().lock();
554 return fromNullable(allImages.get(imageId));
556 lock.readLock().unlock();
561 public List<Image> getImages(Album parent) {
562 lock.readLock().lock();
564 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
566 lock.readLock().unlock();
571 public void moveUp(Image image) {
572 lock.writeLock().lock();
574 List<String> images = albumImages.get(image.getAlbum().getId());
575 int currentIndex = images.indexOf(image.getId());
576 if (currentIndex == 0) {
579 images.remove(image.getId());
580 images.add(currentIndex - 1, image.getId());
582 lock.writeLock().unlock();
587 public void moveDown(Image image) {
588 lock.writeLock().lock();
590 List<String> images = albumChildren.get(image.getAlbum().getId());
591 int currentIndex = images.indexOf(image.getId());
592 if (currentIndex == (images.size() - 1)) {
595 images.remove(image.getId());
596 images.add(currentIndex + 1, image.getId());
598 lock.writeLock().unlock();
603 // IMAGESTORE METHODS
607 public void storeImage(Image image) {
608 lock.writeLock().lock();
610 allImages.put(image.getId(), image);
611 albumImages.put(image.getAlbum().getId(), image.getId());
613 lock.writeLock().unlock();
618 public void removeImage(Image image) {
619 lock.writeLock().lock();
621 allImages.remove(image.getId());
622 albumImages.remove(image.getAlbum().getId(), image.getId());
624 lock.writeLock().unlock();
629 // PACKAGE-PRIVATE METHODS
633 * Returns whether the given post is known.
637 * @return {@code true} if the post is known, {@code false} otherwise
639 boolean isPostKnown(Post post) {
640 lock.readLock().lock();
642 return knownPosts.contains(post.getId());
644 lock.readLock().unlock();
649 * Sets whether the given post is known.
654 * {@code true} if the post is known, {@code false} otherwise
656 void setPostKnown(Post post, boolean known) {
657 lock.writeLock().lock();
660 knownPosts.add(post.getId());
662 knownPosts.remove(post.getId());
665 lock.writeLock().unlock();
673 /** Loads the known posts. */
674 private void loadKnownPosts() {
675 lock.writeLock().lock();
679 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
680 if (knownPostId == null) {
683 knownPosts.add(knownPostId);
686 lock.writeLock().unlock();
691 * Saves the known posts to the configuration.
693 * @throws DatabaseException
694 * if a configuration error occurs
696 private void saveKnownPosts() throws DatabaseException {
697 lock.readLock().lock();
700 for (String knownPostId : knownPosts) {
701 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
703 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
704 } catch (ConfigurationException ce1) {
705 throw new DatabaseException("Could not save database.", ce1);
707 lock.readLock().unlock();
712 * Returns all replies by the given Sone.
716 * @return The post replies of the Sone, sorted by time (newest first)
718 private Collection<PostReply> getRepliesFrom(String id) {
719 lock.readLock().lock();
721 if (sonePostReplies.containsKey(id)) {
722 return Collections.unmodifiableCollection(sonePostReplies.get(id));
724 return Collections.emptySet();
726 lock.readLock().unlock();
730 /** Loads the known post replies. */
731 private void loadKnownPostReplies() {
732 lock.writeLock().lock();
734 int replyCounter = 0;
736 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
737 if (knownReplyId == null) {
740 knownPostReplies.add(knownReplyId);
743 lock.writeLock().unlock();
748 * Saves the known post replies to the configuration.
750 * @throws DatabaseException
751 * if a configuration error occurs
753 private void saveKnownPostReplies() throws DatabaseException {
754 lock.readLock().lock();
756 int replyCounter = 0;
757 for (String knownReplyId : knownPostReplies) {
758 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
760 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
761 } catch (ConfigurationException ce1) {
762 throw new DatabaseException("Could not save database.", ce1);
764 lock.readLock().unlock();
768 private Function<String, Iterable<Album>> getAlbum() {
769 return new Function<String, Iterable<Album>>() {
771 public Iterable<Album> apply(String input) {
772 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
777 private Function<String, Iterable<Image>> getImage() {
778 return new Function<String, Iterable<Image>>() {
780 public Iterable<Image> apply(String input) {
781 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();