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.data.impl.DefaultSoneBuilder;
48 import net.pterodactylus.sone.database.Database;
49 import net.pterodactylus.sone.database.DatabaseException;
50 import net.pterodactylus.sone.database.PostDatabase;
51 import net.pterodactylus.sone.database.SoneBuilder;
52 import net.pterodactylus.sone.freenet.wot.Identity;
53 import net.pterodactylus.util.config.Configuration;
54 import net.pterodactylus.util.config.ConfigurationException;
56 import com.google.common.base.Function;
57 import com.google.common.base.Optional;
58 import com.google.common.collect.ArrayListMultimap;
59 import com.google.common.collect.HashMultimap;
60 import com.google.common.collect.ListMultimap;
61 import com.google.common.collect.Maps;
62 import com.google.common.collect.Multimap;
63 import com.google.common.collect.SortedSetMultimap;
64 import com.google.common.collect.TreeMultimap;
65 import com.google.common.util.concurrent.AbstractService;
66 import com.google.inject.Inject;
69 * Memory-based {@link PostDatabase} implementation.
71 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
73 public class MemoryDatabase extends AbstractService implements Database {
76 private final ReadWriteLock lock = new ReentrantReadWriteLock();
78 /** The configuration. */
79 private final Configuration configuration;
81 private final Map<String, Identity> identities = Maps.newHashMap();
82 private final Map<String, Sone> sones = new HashMap<String, Sone>();
84 /** All posts by their ID. */
85 private final Map<String, Post> allPosts = new HashMap<String, Post>();
87 /** All posts by their Sones. */
88 private final Multimap<String, Post> sonePosts = HashMultimap.create();
90 /** All posts by their recipient. */
91 private final Multimap<String, Post> recipientPosts = HashMultimap.create();
93 /** Whether posts are known. */
94 private final Set<String> knownPosts = new HashSet<String>();
96 /** All post replies by their ID. */
97 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
99 /** Replies sorted by Sone. */
100 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
103 public int compare(String leftString, String rightString) {
104 return leftString.compareTo(rightString);
106 }, PostReply.TIME_COMPARATOR);
108 /** Replies by post. */
109 private final SortedSetMultimap<String, PostReply> postReplies = TreeMultimap.create(new Comparator<String>() {
112 public int compare(String leftString, String rightString) {
113 return leftString.compareTo(rightString);
115 }, PostReply.TIME_COMPARATOR);
117 /** Whether post replies are known. */
118 private final Set<String> knownPostReplies = new HashSet<String>();
120 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
121 private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
122 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
124 private final Map<String, Image> allImages = new HashMap<String, Image>();
127 * Creates a new memory database.
129 * @param configuration
130 * The configuration for loading and saving elements
133 public MemoryDatabase(Configuration configuration) {
134 this.configuration = configuration;
142 public void save() throws DatabaseException {
144 saveKnownPostReplies();
152 protected void doStart() {
154 loadKnownPostReplies();
159 protected void doStop() {
163 } catch (DatabaseException de1) {
169 public Optional<Identity> getIdentity(String identityId) {
170 lock.readLock().lock();
172 return fromNullable(identities.get(identityId));
174 lock.readLock().unlock();
179 public Optional<Sone> getSone(String soneId) {
180 lock.readLock().lock();
182 return fromNullable(sones.get(soneId));
184 lock.readLock().unlock();
189 public Collection<Sone> getSones() {
190 lock.readLock().lock();
192 return Collections.unmodifiableCollection(sones.values());
194 lock.readLock().unlock();
199 public Collection<Sone> getLocalSones() {
200 lock.readLock().lock();
202 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
204 lock.readLock().unlock();
209 public Collection<Sone> getRemoteSones() {
210 lock.readLock().lock();
212 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
214 lock.readLock().unlock();
219 public SoneBuilder newSoneBuilder() {
220 return new DefaultSoneBuilder(this) {
222 public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
223 Sone sone = super.build(soneCreated);
224 sones.put(sone.getId(), sone);
231 // POSTPROVIDER METHODS
235 public Optional<Post> getPost(String postId) {
236 lock.readLock().lock();
238 return fromNullable(allPosts.get(postId));
240 lock.readLock().unlock();
245 public Collection<Post> getPosts(String soneId) {
246 lock.readLock().lock();
248 return new HashSet<Post>(sonePosts.get(soneId));
250 lock.readLock().unlock();
255 public Collection<Post> getDirectedPosts(String recipientId) {
256 lock.readLock().lock();
258 Collection<Post> posts = recipientPosts.get(recipientId);
259 return (posts == null) ? Collections.<Post>emptySet() : new HashSet<Post>(posts);
261 lock.readLock().unlock();
270 public void storePost(Post post) {
271 checkNotNull(post, "post must not be null");
272 lock.writeLock().lock();
274 allPosts.put(post.getId(), post);
275 sonePosts.put(post.getSone().getId(), post);
276 if (post.getRecipientId().isPresent()) {
277 recipientPosts.put(post.getRecipientId().get(), post);
280 lock.writeLock().unlock();
285 public void removePost(Post post) {
286 checkNotNull(post, "post must not be null");
287 lock.writeLock().lock();
289 allPosts.remove(post.getId());
290 sonePosts.remove(post.getSone().getId(), post);
291 if (post.getRecipientId().isPresent()) {
292 recipientPosts.remove(post.getRecipientId().get(), post);
294 post.getSone().removePost(post);
296 lock.writeLock().unlock();
301 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
302 checkNotNull(sone, "sone must not be null");
303 /* verify that all posts are from the same Sone. */
304 for (Post post : posts) {
305 if (!sone.equals(post.getSone())) {
306 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
310 lock.writeLock().lock();
312 /* remove all posts by the Sone. */
313 sonePosts.removeAll(sone.getId());
314 for (Post post : posts) {
315 allPosts.remove(post.getId());
316 if (post.getRecipientId().isPresent()) {
317 recipientPosts.remove(post.getRecipientId().get(), post);
322 sonePosts.putAll(sone.getId(), posts);
323 for (Post post : posts) {
324 allPosts.put(post.getId(), post);
325 if (post.getRecipientId().isPresent()) {
326 recipientPosts.put(post.getRecipientId().get(), post);
330 lock.writeLock().unlock();
335 public void removePosts(Sone sone) {
336 checkNotNull(sone, "sone must not be null");
337 lock.writeLock().lock();
339 /* remove all posts by the Sone. */
340 sonePosts.removeAll(sone.getId());
341 for (Post post : sone.getPosts()) {
342 allPosts.remove(post.getId());
343 if (post.getRecipientId().isPresent()) {
344 recipientPosts.remove(post.getRecipientId().get(), post);
348 lock.writeLock().unlock();
353 // POSTREPLYPROVIDER METHODS
357 public Optional<PostReply> getPostReply(String id) {
358 lock.readLock().lock();
360 return fromNullable(allPostReplies.get(id));
362 lock.readLock().unlock();
367 public List<PostReply> getReplies(String postId) {
368 lock.readLock().lock();
370 if (!postReplies.containsKey(postId)) {
373 return new ArrayList<PostReply>(postReplies.get(postId));
375 lock.readLock().unlock();
380 // POSTREPLYSTORE METHODS
384 * Returns whether the given post reply is known.
388 * @return {@code true} if the given post reply is known, {@code false}
391 public boolean isPostReplyKnown(PostReply postReply) {
392 lock.readLock().lock();
394 return knownPostReplies.contains(postReply.getId());
396 lock.readLock().unlock();
401 public void setPostReplyKnown(PostReply postReply) {
402 lock.writeLock().lock();
404 knownPostReplies.add(postReply.getId());
406 lock.writeLock().unlock();
411 public void storePostReply(PostReply postReply) {
412 lock.writeLock().lock();
414 allPostReplies.put(postReply.getId(), postReply);
415 postReplies.put(postReply.getPostId(), postReply);
417 lock.writeLock().unlock();
422 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
423 checkNotNull(sone, "sone must not be null");
424 /* verify that all posts are from the same Sone. */
425 for (PostReply postReply : postReplies) {
426 if (!sone.equals(postReply.getSone())) {
427 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
431 lock.writeLock().lock();
433 /* remove all post replies of the Sone. */
434 for (PostReply postReply : getRepliesFrom(sone.getId())) {
435 removePostReply(postReply);
437 for (PostReply postReply : postReplies) {
438 allPostReplies.put(postReply.getId(), postReply);
439 sonePostReplies.put(postReply.getSone().getId(), postReply);
440 this.postReplies.put(postReply.getPostId(), postReply);
443 lock.writeLock().unlock();
448 public void removePostReply(PostReply postReply) {
449 lock.writeLock().lock();
451 allPostReplies.remove(postReply.getId());
452 postReplies.remove(postReply.getPostId(), postReply);
454 lock.writeLock().unlock();
459 public void removePostReplies(Sone sone) {
460 checkNotNull(sone, "sone must not be null");
462 lock.writeLock().lock();
464 for (PostReply postReply : sone.getReplies()) {
465 removePostReply(postReply);
468 lock.writeLock().unlock();
473 // ALBUMPROVDER METHODS
477 public Optional<Album> getAlbum(String albumId) {
478 lock.readLock().lock();
480 return fromNullable(allAlbums.get(albumId));
482 lock.readLock().unlock();
487 public List<Album> getAlbums(Album parent) {
488 lock.readLock().lock();
490 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
492 lock.readLock().unlock();
497 public void moveUp(Album album) {
498 lock.writeLock().lock();
500 List<String> albums = albumChildren.get(album.getParent().getId());
501 int currentIndex = albums.indexOf(album.getId());
502 if (currentIndex == 0) {
505 albums.remove(album.getId());
506 albums.add(currentIndex - 1, album.getId());
508 lock.writeLock().unlock();
513 public void moveDown(Album album) {
514 lock.writeLock().lock();
516 List<String> albums = albumChildren.get(album.getParent().getId());
517 int currentIndex = albums.indexOf(album.getId());
518 if (currentIndex == (albums.size() - 1)) {
521 albums.remove(album.getId());
522 albums.add(currentIndex + 1, album.getId());
524 lock.writeLock().unlock();
529 // ALBUMSTORE METHODS
533 public void storeAlbum(Album album) {
534 lock.writeLock().lock();
536 allAlbums.put(album.getId(), album);
537 albumChildren.put(album.getParent().getId(), album.getId());
539 lock.writeLock().unlock();
544 public void removeAlbum(Album album) {
545 lock.writeLock().lock();
547 allAlbums.remove(album.getId());
548 albumChildren.remove(album.getParent().getId(), album.getId());
550 lock.writeLock().unlock();
555 // IMAGEPROVIDER METHODS
559 public Optional<Image> getImage(String imageId) {
560 lock.readLock().lock();
562 return fromNullable(allImages.get(imageId));
564 lock.readLock().unlock();
569 public List<Image> getImages(Album parent) {
570 lock.readLock().lock();
572 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
574 lock.readLock().unlock();
579 public void moveUp(Image image) {
580 lock.writeLock().lock();
582 List<String> images = albumImages.get(image.getAlbum().getId());
583 int currentIndex = images.indexOf(image.getId());
584 if (currentIndex == 0) {
587 images.remove(image.getId());
588 images.add(currentIndex - 1, image.getId());
590 lock.writeLock().unlock();
595 public void moveDown(Image image) {
596 lock.writeLock().lock();
598 List<String> images = albumChildren.get(image.getAlbum().getId());
599 int currentIndex = images.indexOf(image.getId());
600 if (currentIndex == (images.size() - 1)) {
603 images.remove(image.getId());
604 images.add(currentIndex + 1, image.getId());
606 lock.writeLock().unlock();
611 // IMAGESTORE METHODS
615 public void storeImage(Image image) {
616 lock.writeLock().lock();
618 allImages.put(image.getId(), image);
619 albumImages.put(image.getAlbum().getId(), image.getId());
621 lock.writeLock().unlock();
626 public void removeImage(Image image) {
627 lock.writeLock().lock();
629 allImages.remove(image.getId());
630 albumImages.remove(image.getAlbum().getId(), image.getId());
632 lock.writeLock().unlock();
637 // PACKAGE-PRIVATE METHODS
641 * Returns whether the given post is known.
645 * @return {@code true} if the post is known, {@code false} otherwise
647 boolean isPostKnown(Post post) {
648 lock.readLock().lock();
650 return knownPosts.contains(post.getId());
652 lock.readLock().unlock();
657 * Sets whether the given post is known.
662 * {@code true} if the post is known, {@code false} otherwise
664 void setPostKnown(Post post, boolean known) {
665 lock.writeLock().lock();
668 knownPosts.add(post.getId());
670 knownPosts.remove(post.getId());
673 lock.writeLock().unlock();
681 /** Loads the known posts. */
682 private void loadKnownPosts() {
683 lock.writeLock().lock();
687 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
688 if (knownPostId == null) {
691 knownPosts.add(knownPostId);
694 lock.writeLock().unlock();
699 * Saves the known posts to the configuration.
701 * @throws DatabaseException
702 * if a configuration error occurs
704 private void saveKnownPosts() throws DatabaseException {
705 lock.readLock().lock();
708 for (String knownPostId : knownPosts) {
709 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
711 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
712 } catch (ConfigurationException ce1) {
713 throw new DatabaseException("Could not save database.", ce1);
715 lock.readLock().unlock();
720 * Returns all replies by the given Sone.
724 * @return The post replies of the Sone, sorted by time (newest first)
726 private Collection<PostReply> getRepliesFrom(String id) {
727 lock.readLock().lock();
729 if (sonePostReplies.containsKey(id)) {
730 return Collections.unmodifiableCollection(sonePostReplies.get(id));
732 return Collections.emptySet();
734 lock.readLock().unlock();
738 /** Loads the known post replies. */
739 private void loadKnownPostReplies() {
740 lock.writeLock().lock();
742 int replyCounter = 0;
744 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
745 if (knownReplyId == null) {
748 knownPostReplies.add(knownReplyId);
751 lock.writeLock().unlock();
756 * Saves the known post replies to the configuration.
758 * @throws DatabaseException
759 * if a configuration error occurs
761 private void saveKnownPostReplies() throws DatabaseException {
762 lock.readLock().lock();
764 int replyCounter = 0;
765 for (String knownReplyId : knownPostReplies) {
766 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
768 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
769 } catch (ConfigurationException ce1) {
770 throw new DatabaseException("Could not save database.", ce1);
772 lock.readLock().unlock();
776 private Function<String, Iterable<Album>> getAlbum() {
777 return new Function<String, Iterable<Album>>() {
779 public Iterable<Album> apply(String input) {
780 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
785 private Function<String, Iterable<Image>> getImage() {
786 return new Function<String, Iterable<Image>>() {
788 public Iterable<Image> apply(String input) {
789 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();