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();
143 memoryPostDatabase.stop();
144 configuration.save();
145 } catch (DatabaseException de1) {
146 logger.log(Level.WARNING, "Could not stop post database!", de1);
147 } catch (ConfigurationException ce1) {
148 logger.log(Level.WARNING, "Could not save configuration!", ce1);
154 public Optional<Identity> getIdentity(String identityId) {
155 return memoryIdentityDatabase.getIdentity(identityId);
159 public void storeIdentity(Identity identitiy) {
160 memoryIdentityDatabase.storeIdentity(identitiy);
164 public Function<String, Optional<Sone>> getSone() {
165 return new Function<String, Optional<Sone>>() {
167 public Optional<Sone> apply(String soneId) {
168 return (soneId == null) ? Optional.<Sone>absent() : getSone(soneId);
174 public Optional<Sone> getSone(String soneId) {
175 lock.readLock().lock();
177 return fromNullable(sones.get(soneId));
179 lock.readLock().unlock();
184 public Collection<Sone> getSones() {
185 lock.readLock().lock();
187 return Collections.unmodifiableCollection(sones.values());
189 lock.readLock().unlock();
194 public Collection<Sone> getLocalSones() {
195 lock.readLock().lock();
197 return from(getSones()).filter(LOCAL_SONE_FILTER).toSet();
199 lock.readLock().unlock();
204 public Collection<Sone> getRemoteSones() {
205 lock.readLock().lock();
207 return from(getSones()).filter(not(LOCAL_SONE_FILTER)).toSet();
209 lock.readLock().unlock();
214 public void storeSone(Sone sone) {
215 lock.writeLock().lock();
217 sones.put(sone.getId(), sone);
219 lock.writeLock().unlock();
224 public SoneBuilder newSoneBuilder() {
225 return new DefaultSoneBuilder(this) {
227 public Sone build(Optional<SoneCreated> soneCreated) throws IllegalStateException {
228 Sone sone = super.build(soneCreated);
229 lock.writeLock().lock();
231 sones.put(sone.getId(), sone);
233 lock.writeLock().unlock();
241 // POSTPROVIDER METHODS
245 public Function<String, Optional<Post>> getPost() {
246 return memoryPostDatabase.getPost();
250 public Optional<Post> getPost(String postId) {
251 return memoryPostDatabase.getPost(postId);
255 public Collection<Post> getPosts(String soneId) {
256 return memoryPostDatabase.getPosts(soneId);
260 public Collection<Post> getDirectedPosts(String recipientId) {
261 return memoryPostDatabase.getDirectedPosts(recipientId);
265 * Returns whether the given post is known.
269 * @return {@code true} if the post is known, {@code false} otherwise
272 public boolean isPostKnown(Post post) {
273 return memoryPostDatabase.isPostKnown(post);
277 * Sets whether the given post is known.
283 public void setPostKnown(Post post) {
284 memoryPostDatabase.setPostKnown(post);
288 public void likePost(Post post, Sone localSone) {
289 memoryPostDatabase.likePost(post, localSone);
293 public void unlikePost(Post post, Sone localSone) {
294 memoryPostDatabase.unlikePost(post, localSone);
297 public boolean isLiked(Post post, Sone sone) {
298 return memoryPostDatabase.isLiked(post, sone);
302 public Set<Sone> getLikes(Post post) {
303 return memoryPostDatabase.getLikes(post);
311 public void storePost(Post post) {
312 memoryPostDatabase.storePost(post);
316 public void removePost(Post post) {
317 memoryPostDatabase.removePost(post);
321 public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
322 /* verify that all posts are from the same Sone. */
324 memoryPostDatabase.storePosts(sone, posts);
328 public void removePosts(Sone sone) {
329 memoryPostDatabase.removePosts(sone);
333 // POSTREPLYPROVIDER METHODS
337 public Optional<PostReply> getPostReply(String id) {
338 lock.readLock().lock();
340 return fromNullable(allPostReplies.get(id));
342 lock.readLock().unlock();
347 public List<PostReply> getReplies(String postId) {
348 lock.readLock().lock();
350 if (!postReplies.containsKey(postId)) {
353 return new ArrayList<PostReply>(postReplies.get(postId));
355 lock.readLock().unlock();
360 public void likePostReply(PostReply postReply, Sone localSone) {
361 lock.writeLock().lock();
363 likedPostRepliesBySone.put(localSone.getId(), postReply.getId());
364 postReplyLikingSones.put(postReply.getId(), localSone.getId());
366 lock.writeLock().unlock();
371 public void unlikePostReply(PostReply postReply, Sone localSone) {
372 lock.writeLock().lock();
374 likedPostRepliesBySone.remove(localSone.getId(), postReply.getId());
375 postReplyLikingSones.remove(postReply.getId(), localSone.getId());
377 lock.writeLock().unlock();
382 public boolean isLiked(PostReply postReply, Sone sone) {
383 lock.readLock().lock();
385 return postReplyLikingSones.containsEntry(postReply.getId(), sone.getId());
387 lock.readLock().unlock();
392 public Set<Sone> getLikes(PostReply postReply) {
393 lock.readLock().lock();
395 return from(postReplyLikingSones.get(postReply.getId())).transform(getSone()).transformAndConcat(this.<Sone>unwrap()).toSet();
397 lock.readLock().unlock();
402 // POSTREPLYSTORE METHODS
406 * Returns whether the given post reply is known.
410 * @return {@code true} if the given post reply is known, {@code false}
413 public boolean isPostReplyKnown(PostReply postReply) {
414 lock.readLock().lock();
416 return knownPostReplies.contains(postReply.getId());
418 lock.readLock().unlock();
423 public void setPostReplyKnown(PostReply postReply) {
424 lock.writeLock().lock();
426 knownPostReplies.add(postReply.getId());
428 lock.writeLock().unlock();
433 public void storePostReply(PostReply postReply) {
434 lock.writeLock().lock();
436 allPostReplies.put(postReply.getId(), postReply);
437 postReplies.put(postReply.getPostId(), postReply);
439 lock.writeLock().unlock();
444 public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
445 checkNotNull(sone, "sone must not be null");
446 /* verify that all posts are from the same Sone. */
447 for (PostReply postReply : postReplies) {
448 if (!sone.equals(postReply.getSone())) {
449 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
453 lock.writeLock().lock();
455 /* remove all post replies of the Sone. */
456 for (PostReply postReply : getRepliesFrom(sone.getId())) {
457 removePostReply(postReply);
459 for (PostReply postReply : postReplies) {
460 allPostReplies.put(postReply.getId(), postReply);
461 sonePostReplies.put(postReply.getSone().getId(), postReply);
462 this.postReplies.put(postReply.getPostId(), postReply);
465 lock.writeLock().unlock();
470 public void removePostReply(PostReply postReply) {
471 lock.writeLock().lock();
473 allPostReplies.remove(postReply.getId());
474 postReplies.remove(postReply.getPostId(), postReply);
476 lock.writeLock().unlock();
481 public void removePostReplies(Sone sone) {
482 checkNotNull(sone, "sone must not be null");
484 lock.writeLock().lock();
486 for (PostReply postReply : sone.getReplies()) {
487 removePostReply(postReply);
490 lock.writeLock().unlock();
495 // ALBUMPROVDER METHODS
499 public Optional<Album> getAlbum(String albumId) {
500 lock.readLock().lock();
502 return fromNullable(allAlbums.get(albumId));
504 lock.readLock().unlock();
509 public List<Album> getAlbums(Album parent) {
510 lock.readLock().lock();
512 return from(albumChildren.get(parent.getId())).transformAndConcat(getAlbum()).toList();
514 lock.readLock().unlock();
519 public void moveUp(Album album) {
520 lock.writeLock().lock();
522 List<String> albums = albumChildren.get(album.getParent().getId());
523 int currentIndex = albums.indexOf(album.getId());
524 if (currentIndex == 0) {
527 albums.remove(album.getId());
528 albums.add(currentIndex - 1, album.getId());
530 lock.writeLock().unlock();
535 public void moveDown(Album album) {
536 lock.writeLock().lock();
538 List<String> albums = albumChildren.get(album.getParent().getId());
539 int currentIndex = albums.indexOf(album.getId());
540 if (currentIndex == (albums.size() - 1)) {
543 albums.remove(album.getId());
544 albums.add(currentIndex + 1, album.getId());
546 lock.writeLock().unlock();
551 // ALBUMSTORE METHODS
555 public void storeAlbum(Album album) {
556 lock.writeLock().lock();
558 allAlbums.put(album.getId(), album);
559 if (!album.isRoot()) {
560 albumChildren.put(album.getParent().getId(), album.getId());
563 lock.writeLock().unlock();
568 public void removeAlbum(Album album) {
569 lock.writeLock().lock();
571 allAlbums.remove(album.getId());
572 albumChildren.remove(album.getParent().getId(), album.getId());
574 lock.writeLock().unlock();
579 // IMAGEPROVIDER METHODS
583 public Optional<Image> getImage(String imageId) {
584 lock.readLock().lock();
586 return fromNullable(allImages.get(imageId));
588 lock.readLock().unlock();
593 public List<Image> getImages(Album parent) {
594 lock.readLock().lock();
596 return from(albumImages.get(parent.getId())).transformAndConcat(getImage()).toList();
598 lock.readLock().unlock();
603 public void moveUp(Image image) {
604 lock.writeLock().lock();
606 List<String> images = albumImages.get(image.getAlbum().getId());
607 int currentIndex = images.indexOf(image.getId());
608 if (currentIndex == 0) {
611 images.remove(image.getId());
612 images.add(currentIndex - 1, image.getId());
614 lock.writeLock().unlock();
619 public void moveDown(Image image) {
620 lock.writeLock().lock();
622 List<String> images = albumChildren.get(image.getAlbum().getId());
623 int currentIndex = images.indexOf(image.getId());
624 if (currentIndex == (images.size() - 1)) {
627 images.remove(image.getId());
628 images.add(currentIndex + 1, image.getId());
630 lock.writeLock().unlock();
635 // IMAGESTORE METHODS
639 public void storeImage(Image image) {
640 lock.writeLock().lock();
642 allImages.put(image.getId(), image);
643 albumImages.put(image.getAlbum().getId(), image.getId());
645 lock.writeLock().unlock();
650 public void removeImage(Image image) {
651 lock.writeLock().lock();
653 allImages.remove(image.getId());
654 albumImages.remove(image.getAlbum().getId(), image.getId());
656 lock.writeLock().unlock();
665 * Returns all replies by the given Sone.
669 * @return The post replies of the Sone, sorted by time (newest first)
671 private Collection<PostReply> getRepliesFrom(String id) {
672 lock.readLock().lock();
674 if (sonePostReplies.containsKey(id)) {
675 return Collections.unmodifiableCollection(sonePostReplies.get(id));
677 return Collections.emptySet();
679 lock.readLock().unlock();
683 /** Loads the known post replies. */
684 private void loadKnownPostReplies() {
685 lock.writeLock().lock();
687 int replyCounter = 0;
689 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
690 if (knownReplyId == null) {
693 knownPostReplies.add(knownReplyId);
696 lock.writeLock().unlock();
701 * Saves the known post replies to the configuration.
703 * @throws DatabaseException
704 * if a configuration error occurs
706 private void saveKnownPostReplies() throws DatabaseException {
707 lock.readLock().lock();
709 int replyCounter = 0;
710 for (String knownReplyId : knownPostReplies) {
711 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
713 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
714 } catch (ConfigurationException ce1) {
715 throw new DatabaseException("Could not save database.", ce1);
717 lock.readLock().unlock();
721 private Function<String, Iterable<Album>> getAlbum() {
722 return new Function<String, Iterable<Album>>() {
724 public Iterable<Album> apply(String input) {
725 return (input == null) ? Collections.<Album>emptyList() : getAlbum(input).asSet();
730 private Function<String, Iterable<Image>> getImage() {
731 return new Function<String, Iterable<Image>>() {
733 public Iterable<Image> apply(String input) {
734 return (input == null) ? Collections.<Image>emptyList() : getImage(input).asSet();
739 static <T> Function<Optional<T>, Iterable<T>> unwrap() {
740 return new Function<Optional<T>, Iterable<T>>() {
742 public Iterable<T> apply(Optional<T> input) {
743 return (input == null) ? Collections.<T>emptyList() : input.asSet();