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 java.util.logging.Logger.getLogger;
26 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Comparator;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
37 import java.util.concurrent.locks.ReadWriteLock;
38 import java.util.concurrent.locks.ReentrantReadWriteLock;
39 import java.util.logging.Level;
40 import java.util.logging.Logger;
42 import net.pterodactylus.sone.data.Album;
43 import net.pterodactylus.sone.data.Image;
44 import net.pterodactylus.sone.data.Post;
45 import net.pterodactylus.sone.data.PostReply;
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.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.SetMultimap;
61 import com.google.common.collect.SortedSetMultimap;
62 import com.google.common.collect.TreeMultimap;
63 import com.google.inject.Inject;
66 * Memory-based {@link Database} implementation.
68 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
70 public class MemoryDatabase implements Database {
72 private static final Logger logger = getLogger(MemoryDatabase.class.getName());
75 private final ReadWriteLock lock = new ReentrantReadWriteLock();
77 /** The configuration. */
78 private final Configuration configuration;
80 private final Map<String, Sone> sones = new HashMap<String, Sone>();
81 private final MemoryIdentityDatabase memoryIdentityDatabase;
82 private final MemoryPostDatabase memoryPostDatabase;
84 /** All post replies by their ID. */
85 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
86 private final SetMultimap<String, String> likedPostRepliesBySone = HashMultimap.create();
87 private final SetMultimap<String, String> postReplyLikingSones = HashMultimap.create();
89 /** Replies sorted by Sone. */
90 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
93 public int compare(String leftString, String rightString) {
94 return leftString.compareTo(rightString);
96 }, PostReply.TIME_COMPARATOR);
98 /** Replies by post. */
99 private final SortedSetMultimap<String, PostReply> postReplies = TreeMultimap.create(new Comparator<String>() {
102 public int compare(String leftString, String rightString) {
103 return leftString.compareTo(rightString);
105 }, PostReply.TIME_COMPARATOR);
107 /** Whether post replies are known. */
108 private final Set<String> knownPostReplies = new HashSet<String>();
110 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
111 private final ListMultimap<String, String> albumChildren = ArrayListMultimap.create();
112 private final ListMultimap<String, String> albumImages = ArrayListMultimap.create();
114 private final Map<String, Image> allImages = new HashMap<String, Image>();
117 * Creates a new memory database.
119 * @param configuration
120 * The configuration for loading and saving elements
123 public MemoryDatabase(Configuration configuration) {
124 this.configuration = configuration;
125 memoryPostDatabase = new MemoryPostDatabase(this, lock, configuration);
126 memoryIdentityDatabase = new MemoryIdentityDatabase(lock);
134 public void start() {
135 memoryPostDatabase.start();
136 loadKnownPostReplies();
142 memoryPostDatabase.stop();
143 configuration.save();
144 } catch (DatabaseException de1) {
145 logger.log(Level.WARNING, "Could not stop post database!", de1);
146 } catch (ConfigurationException ce1) {
147 logger.log(Level.WARNING, "Could not save configuration!", ce1);
152 public Optional<Identity> getIdentity(String identityId) {
153 return memoryIdentityDatabase.getIdentity(identityId);
157 public void storeIdentity(Identity identitiy) {
158 memoryIdentityDatabase.storeIdentity(identitiy);
162 public Function<String, Optional<Sone>> getSone() {
163 return new Function<String, Optional<Sone>>() {
165 public Optional<Sone> apply(String soneId) {
166 return (soneId == null) ? Optional.<Sone>absent() : getSone(soneId);
172 public Optional<Sone> getSone(String soneId) {
173 lock.readLock().lock();
175 return fromNullable(sones.get(soneId));
177 lock.readLock().unlock();
182 public Collection<Sone> getSones() {
183 lock.readLock().lock();
185 return Collections.unmodifiableCollection(sones.values());
187 lock.readLock().unlock();
192 public Collection<Sone> getLocalSones() {
193 lock.readLock().lock();
195 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
197 lock.readLock().unlock();
202 public Collection<Sone> getRemoteSones() {
203 lock.readLock().lock();
205 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
207 lock.readLock().unlock();
212 public void storeSone(Sone sone) {
213 lock.writeLock().lock();
215 sones.put(sone.getId(), sone);
217 lock.writeLock().unlock();
222 public SoneBuilder newSoneBuilder() {
223 return new DefaultSoneBuilder(this) {
225 public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
226 Sone sone = super.build(soneCreated);
227 lock.writeLock().lock();
229 sones.put(sone.getId(), sone);
231 lock.writeLock().unlock();
239 // POSTPROVIDER METHODS
243 public Function<String, Optional<Post>> getPost() {
244 return memoryPostDatabase.getPost();
248 public Optional<Post> getPost(String postId) {
249 return memoryPostDatabase.getPost(postId);
253 public Collection<Post> getPosts(String soneId) {
254 return memoryPostDatabase.getPosts(soneId);
258 public Collection<Post> getDirectedPosts(String recipientId) {
259 return memoryPostDatabase.getDirectedPosts(recipientId);
263 * Returns whether the given post is known.
267 * @return {@code true} if the post is known, {@code false} otherwise
270 public boolean isPostKnown(Post post) {
271 return memoryPostDatabase.isPostKnown(post);
275 * Sets whether the given post is known.
281 public void setPostKnown(Post post) {
282 memoryPostDatabase.setPostKnown(post);
286 public void likePost(Post post, Sone localSone) {
287 memoryPostDatabase.likePost(post, localSone);
291 public void unlikePost(Post post, Sone localSone) {
292 memoryPostDatabase.unlikePost(post, localSone);
295 public boolean isLiked(Post post, Sone sone) {
296 return memoryPostDatabase.isLiked(post, sone);
300 public Set<Sone> getLikes(Post post) {
301 return memoryPostDatabase.getLikes(post);
309 public void storePost(Post post) {
310 memoryPostDatabase.storePost(post);
314 public void removePost(Post post) {
315 memoryPostDatabase.removePost(post);
319 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
320 /* verify that all posts are from the same Sone. */
322 memoryPostDatabase.storePosts(sone, posts);
326 public void removePosts(Sone sone) {
327 memoryPostDatabase.removePosts(sone);
331 // POSTREPLYPROVIDER METHODS
335 public Optional<PostReply> getPostReply(String id) {
336 lock.readLock().lock();
338 return fromNullable(allPostReplies.get(id));
340 lock.readLock().unlock();
345 public List<PostReply> getReplies(String postId) {
346 lock.readLock().lock();
348 if (!postReplies.containsKey(postId)) {
351 return new ArrayList<PostReply>(postReplies.get(postId));
353 lock.readLock().unlock();
358 public void likePostReply(PostReply postReply, Sone localSone) {
359 lock.writeLock().lock();
361 likedPostRepliesBySone.put(localSone.getId(), postReply.getId());
362 postReplyLikingSones.put(postReply.getId(), localSone.getId());
364 lock.writeLock().unlock();
369 public void unlikePostReply(PostReply postReply, Sone localSone) {
370 lock.writeLock().lock();
372 likedPostRepliesBySone.remove(localSone.getId(), postReply.getId());
373 postReplyLikingSones.remove(postReply.getId(), localSone.getId());
375 lock.writeLock().unlock();
380 public boolean isLiked(PostReply postReply, Sone sone) {
381 lock.readLock().lock();
383 return postReplyLikingSones.containsEntry(postReply.getId(), sone.getId());
385 lock.readLock().unlock();
390 public Set<Sone> getLikes(PostReply postReply) {
391 lock.readLock().lock();
393 return from(postReplyLikingSones.get(postReply.getId())).transform(getSone()).transformAndConcat(this.<Sone>unwrap()).toSet();
395 lock.readLock().unlock();
400 // POSTREPLYSTORE METHODS
404 * Returns whether the given post reply is known.
408 * @return {@code true} if the given post reply is known, {@code false}
411 public boolean isPostReplyKnown(PostReply postReply) {
412 lock.readLock().lock();
414 return knownPostReplies.contains(postReply.getId());
416 lock.readLock().unlock();
421 public void setPostReplyKnown(PostReply postReply) {
422 lock.writeLock().lock();
424 knownPostReplies.add(postReply.getId());
426 lock.writeLock().unlock();
431 public void storePostReply(PostReply postReply) {
432 lock.writeLock().lock();
434 allPostReplies.put(postReply.getId(), postReply);
435 postReplies.put(postReply.getPostId(), postReply);
437 lock.writeLock().unlock();
442 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
443 checkNotNull(sone, "sone must not be null");
444 /* verify that all posts are from the same Sone. */
445 for (PostReply postReply : postReplies) {
446 if (!sone.equals(postReply.getSone())) {
447 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
451 lock.writeLock().lock();
453 /* remove all post replies of the Sone. */
454 for (PostReply postReply : getRepliesFrom(sone.getId())) {
455 removePostReply(postReply);
457 for (PostReply postReply : postReplies) {
458 allPostReplies.put(postReply.getId(), postReply);
459 sonePostReplies.put(postReply.getSone().getId(), postReply);
460 this.postReplies.put(postReply.getPostId(), postReply);
463 lock.writeLock().unlock();
468 public void removePostReply(PostReply postReply) {
469 lock.writeLock().lock();
471 allPostReplies.remove(postReply.getId());
472 postReplies.remove(postReply.getPostId(), postReply);
474 lock.writeLock().unlock();
479 public void removePostReplies(Sone sone) {
480 checkNotNull(sone, "sone must not be null");
482 lock.writeLock().lock();
484 for (PostReply postReply : sone.getReplies()) {
485 removePostReply(postReply);
488 lock.writeLock().unlock();
493 // ALBUMPROVDER METHODS
497 public Optional<Album> getAlbum(String albumId) {
498 lock.readLock().lock();
500 return fromNullable(allAlbums.get(albumId));
502 lock.readLock().unlock();
507 public List<Album> getAlbums(Album parent) {
508 lock.readLock().lock();
510 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
512 lock.readLock().unlock();
517 public void moveUp(Album album) {
518 lock.writeLock().lock();
520 List<String> albums = albumChildren.get(album.getParent().getId());
521 int currentIndex = albums.indexOf(album.getId());
522 if (currentIndex == 0) {
525 albums.remove(album.getId());
526 albums.add(currentIndex - 1, album.getId());
528 lock.writeLock().unlock();
533 public void moveDown(Album album) {
534 lock.writeLock().lock();
536 List<String> albums = albumChildren.get(album.getParent().getId());
537 int currentIndex = albums.indexOf(album.getId());
538 if (currentIndex == (albums.size() - 1)) {
541 albums.remove(album.getId());
542 albums.add(currentIndex + 1, album.getId());
544 lock.writeLock().unlock();
549 // ALBUMSTORE METHODS
553 public void storeAlbum(Album album) {
554 lock.writeLock().lock();
556 allAlbums.put(album.getId(), album);
557 if (!album.isRoot()) {
558 albumChildren.put(album.getParent().getId(), album.getId());
561 lock.writeLock().unlock();
566 public void removeAlbum(Album album) {
567 lock.writeLock().lock();
569 allAlbums.remove(album.getId());
570 albumChildren.remove(album.getParent().getId(), album.getId());
572 lock.writeLock().unlock();
577 // IMAGEPROVIDER METHODS
581 public Optional<Image> getImage(String imageId) {
582 lock.readLock().lock();
584 return fromNullable(allImages.get(imageId));
586 lock.readLock().unlock();
591 public List<Image> getImages(Album parent) {
592 lock.readLock().lock();
594 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
596 lock.readLock().unlock();
601 public void moveUp(Image image) {
602 lock.writeLock().lock();
604 List<String> images = albumImages.get(image.getAlbum().getId());
605 int currentIndex = images.indexOf(image.getId());
606 if (currentIndex == 0) {
609 images.remove(image.getId());
610 images.add(currentIndex - 1, image.getId());
612 lock.writeLock().unlock();
617 public void moveDown(Image image) {
618 lock.writeLock().lock();
620 List<String> images = albumChildren.get(image.getAlbum().getId());
621 int currentIndex = images.indexOf(image.getId());
622 if (currentIndex == (images.size() - 1)) {
625 images.remove(image.getId());
626 images.add(currentIndex + 1, image.getId());
628 lock.writeLock().unlock();
633 // IMAGESTORE METHODS
637 public void storeImage(Image image) {
638 lock.writeLock().lock();
640 allImages.put(image.getId(), image);
641 albumImages.put(image.getAlbum().getId(), image.getId());
643 lock.writeLock().unlock();
648 public void removeImage(Image image) {
649 lock.writeLock().lock();
651 allImages.remove(image.getId());
652 albumImages.remove(image.getAlbum().getId(), image.getId());
654 lock.writeLock().unlock();
663 * Returns all replies by the given Sone.
667 * @return The post replies of the Sone, sorted by time (newest first)
669 private Collection<PostReply> getRepliesFrom(String id) {
670 lock.readLock().lock();
672 if (sonePostReplies.containsKey(id)) {
673 return Collections.unmodifiableCollection(sonePostReplies.get(id));
675 return Collections.emptySet();
677 lock.readLock().unlock();
681 /** Loads the known post replies. */
682 private void loadKnownPostReplies() {
683 lock.writeLock().lock();
685 int replyCounter = 0;
687 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
688 if (knownReplyId == null) {
691 knownPostReplies.add(knownReplyId);
694 lock.writeLock().unlock();
699 * Saves the known post replies to the configuration.
701 * @throws DatabaseException
702 * if a configuration error occurs
704 private void saveKnownPostReplies() throws DatabaseException {
705 lock.readLock().lock();
707 int replyCounter = 0;
708 for (String knownReplyId : knownPostReplies) {
709 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
711 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
712 } catch (ConfigurationException ce1) {
713 throw new DatabaseException("Could not save database.", ce1);
715 lock.readLock().unlock();
719 private Function<String, Iterable<Album>> getAlbum() {
720 return new Function<String, Iterable<Album>>() {
722 public Iterable<Album> apply(String input) {
723 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
728 private Function<String, Iterable<Image>> getImage() {
729 return new Function<String, Iterable<Image>>() {
731 public Iterable<Image> apply(String input) {
732 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();
737 static <T> Function<Optional<T>, Iterable<T>> unwrap() {
738 return new Function<Optional<T>, Iterable<T>>() {
740 public Iterable<T> apply(Optional<T> input) {
741 return (input == null) ? Collections.<T>emptyList() : input.asSet();