Fix changed import.
[Sone.git] / src / main / java / net / pterodactylus / sone / database / memory / MemoryDatabase.java
1 /*
2  * Sone - MemoryDatabase.java - Copyright © 2013 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sone.database.memory;
19
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.unmodifiableCollection;
25 import static net.pterodactylus.sone.data.Reply.TIME_COMPARATOR;
26 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
27 import static net.pterodactylus.sone.data.Sone.toAllAlbums;
28 import static net.pterodactylus.sone.data.Sone.toAllImages;
29
30 import java.util.Collection;
31 import java.util.Comparator;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Set;
37 import java.util.concurrent.locks.ReadWriteLock;
38 import java.util.concurrent.locks.ReentrantReadWriteLock;
39
40 import net.pterodactylus.sone.data.Album;
41 import net.pterodactylus.sone.data.Image;
42 import net.pterodactylus.sone.data.Post;
43 import net.pterodactylus.sone.data.PostReply;
44 import net.pterodactylus.sone.data.Sone;
45 import net.pterodactylus.sone.data.impl.AlbumBuilderImpl;
46 import net.pterodactylus.sone.data.impl.ImageBuilderImpl;
47 import net.pterodactylus.sone.database.AlbumBuilder;
48 import net.pterodactylus.sone.database.Database;
49 import net.pterodactylus.sone.database.DatabaseException;
50 import net.pterodactylus.sone.database.ImageBuilder;
51 import net.pterodactylus.sone.database.PostBuilder;
52 import net.pterodactylus.sone.database.PostDatabase;
53 import net.pterodactylus.sone.database.PostReplyBuilder;
54 import net.pterodactylus.sone.database.SoneProvider;
55 import net.pterodactylus.util.config.Configuration;
56 import net.pterodactylus.util.config.ConfigurationException;
57
58 import com.google.common.base.Optional;
59 import com.google.common.base.Predicate;
60 import com.google.common.collect.HashMultimap;
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;
66 import com.google.inject.Singleton;
67
68 /**
69  * Memory-based {@link PostDatabase} implementation.
70  *
71  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
72  */
73 @Singleton
74 public class MemoryDatabase extends AbstractService implements Database {
75
76         /** The lock. */
77         private final ReadWriteLock lock = new ReentrantReadWriteLock();
78
79         /** The Sone provider. */
80         private final SoneProvider soneProvider;
81
82         /** The configuration. */
83         private final Configuration configuration;
84
85         private final Map<String, Sone> allSones = new HashMap<String, Sone>();
86
87         /** All posts by their ID. */
88         private final Map<String, Post> allPosts = new HashMap<String, Post>();
89
90         /** All posts by their Sones. */
91         private final Multimap<String, Post> sonePosts = HashMultimap.create();
92
93         /** Whether posts are known. */
94         private final Set<String> knownPosts = new HashSet<String>();
95
96         /** All post replies by their ID. */
97         private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
98
99         /** Replies sorted by Sone. */
100         private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
101
102                 @Override
103                 public int compare(String leftString, String rightString) {
104                         return leftString.compareTo(rightString);
105                 }
106         }, TIME_COMPARATOR);
107
108         /** Whether post replies are known. */
109         private final Set<String> knownPostReplies = new HashSet<String>();
110
111         private final Map<String, Album> allAlbums = new HashMap<String, Album>();
112         private final Multimap<String, Album> soneAlbums = HashMultimap.create();
113
114         private final Map<String, Image> allImages = new HashMap<String, Image>();
115         private final Multimap<String, Image> soneImages = HashMultimap.create();
116
117         /**
118          * Creates a new memory database.
119          *
120          * @param soneProvider
121          *              The Sone provider
122          * @param configuration
123          *              The configuration for loading and saving elements
124          */
125         @Inject
126         public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
127                 this.soneProvider = soneProvider;
128                 this.configuration = configuration;
129         }
130
131         //
132         // DATABASE METHODS
133         //
134
135         /**
136          * Saves the database.
137          *
138          * @throws DatabaseException
139          *              if an error occurs while saving
140          */
141         @Override
142         public void save() throws DatabaseException {
143                 saveKnownPosts();
144                 saveKnownPostReplies();
145         }
146
147         //
148         // SERVICE METHODS
149         //
150
151         /** {@inheritDocs} */
152         @Override
153         protected void doStart() {
154                 loadKnownPosts();
155                 loadKnownPostReplies();
156                 notifyStarted();
157         }
158
159         /** {@inheritDocs} */
160         @Override
161         protected void doStop() {
162                 try {
163                         save();
164                         notifyStopped();
165                 } catch (DatabaseException de1) {
166                         notifyFailed(de1);
167                 }
168         }
169
170         @Override
171         public void storeSone(Sone sone) {
172                 lock.writeLock().lock();
173                 try {
174                         Collection<Post> removedPosts = sonePosts.removeAll(sone.getId());
175                         for (Post removedPost : removedPosts) {
176                                 allPosts.remove(removedPost.getId());
177                         }
178                         Collection<PostReply> removedPostReplies =
179                                         sonePostReplies.removeAll(sone.getId());
180                         for (PostReply removedPostReply : removedPostReplies) {
181                                 allPostReplies.remove(removedPostReply.getId());
182                         }
183                         Collection<Album> removedAlbums =
184                                         soneAlbums.removeAll(sone.getId());
185                         for (Album removedAlbum : removedAlbums) {
186                                 allAlbums.remove(removedAlbum.getId());
187                         }
188                         Collection<Image> removedImages =
189                                         soneImages.removeAll(sone.getId());
190                         for (Image removedImage : removedImages) {
191                                 allImages.remove(removedImage.getId());
192                         }
193
194                         allSones.put(sone.getId(), sone);
195                         sonePosts.putAll(sone.getId(), sone.getPosts());
196                         for (Post post : sone.getPosts()) {
197                                 allPosts.put(post.getId(), post);
198                         }
199                         sonePostReplies.putAll(sone.getId(), sone.getReplies());
200                         for (PostReply postReply : sone.getReplies()) {
201                                 allPostReplies.put(postReply.getId(), postReply);
202                         }
203                         soneAlbums.putAll(sone.getId(), toAllAlbums.apply(sone));
204                         for (Album album : toAllAlbums.apply(sone)) {
205                                 allAlbums.put(album.getId(), album);
206                         }
207                         soneImages.putAll(sone.getId(), toAllImages.apply(sone));
208                         for (Image image : toAllImages.apply(sone)) {
209                                 allImages.put(image.getId(), image);
210                         }
211                 } finally {
212                         lock.writeLock().unlock();
213                 }
214         }
215
216         @Override
217         public Optional<Sone> getSone(String soneId) {
218                 lock.readLock().lock();
219                 try {
220                         return fromNullable(allSones.get(soneId));
221                 } finally {
222                         lock.readLock().unlock();
223                 }
224         }
225
226         @Override
227         public Collection<Sone> getSones() {
228                 lock.readLock().lock();
229                 try {
230                         return unmodifiableCollection(allSones.values());
231                 } finally {
232                         lock.readLock().unlock();
233                 }
234         }
235
236         @Override
237         public Collection<Sone> getLocalSones() {
238                 lock.readLock().lock();
239                 try {
240                         return from(allSones.values()).filter(LOCAL_SONE_FILTER).toSet();
241                 } finally {
242                         lock.readLock().unlock();
243                 }
244         }
245
246         @Override
247         public Collection<Sone> getRemoteSones() {
248                 lock.readLock().lock();
249                 try {
250                         return from(allSones.values())
251                                         .filter(not(LOCAL_SONE_FILTER)) .toSet();
252                 } finally {
253                         lock.readLock().unlock();
254                 }
255         }
256
257         //
258         // POSTPROVIDER METHODS
259         //
260
261         /** {@inheritDocs} */
262         @Override
263         public Optional<Post> getPost(String postId) {
264                 lock.readLock().lock();
265                 try {
266                         return fromNullable(allPosts.get(postId));
267                 } finally {
268                         lock.readLock().unlock();
269                 }
270         }
271
272         /** {@inheritDocs} */
273         @Override
274         public Collection<Post> getPosts(String soneId) {
275                 return new HashSet<Post>(getPostsFrom(soneId));
276         }
277
278         /** {@inheritDocs} */
279         @Override
280         public Collection<Post> getDirectedPosts(final String recipientId) {
281                 lock.readLock().lock();
282                 try {
283                         return from(sonePosts.values()).filter(new Predicate<Post>() {
284                                 @Override
285                                 public boolean apply(Post post) {
286                                         return post.getRecipientId().asSet().contains(recipientId);
287                                 }
288                         }).toSet();
289                 } finally {
290                         lock.readLock().unlock();
291                 }
292         }
293
294         //
295         // POSTBUILDERFACTORY METHODS
296         //
297
298         /** {@inheritDocs} */
299         @Override
300         public PostBuilder newPostBuilder() {
301                 return new MemoryPostBuilder(this, soneProvider);
302         }
303
304         //
305         // POSTSTORE METHODS
306         //
307
308         /** {@inheritDocs} */
309         @Override
310         public void storePost(Post post) {
311                 checkNotNull(post, "post must not be null");
312                 lock.writeLock().lock();
313                 try {
314                         allPosts.put(post.getId(), post);
315                         getPostsFrom(post.getSone().getId()).add(post);
316                 } finally {
317                         lock.writeLock().unlock();
318                 }
319         }
320
321         /** {@inheritDocs} */
322         @Override
323         public void removePost(Post post) {
324                 checkNotNull(post, "post must not be null");
325                 lock.writeLock().lock();
326                 try {
327                         allPosts.remove(post.getId());
328                         getPostsFrom(post.getSone().getId()).remove(post);
329                         post.getSone().removePost(post);
330                 } finally {
331                         lock.writeLock().unlock();
332                 }
333         }
334
335         /** {@inheritDocs} */
336         @Override
337         public void storePosts(Sone sone, Collection<Post> posts) throws IllegalArgumentException {
338                 checkNotNull(sone, "sone must not be null");
339                 /* verify that all posts are from the same Sone. */
340                 for (Post post : posts) {
341                         if (!sone.equals(post.getSone())) {
342                                 throw new IllegalArgumentException(String.format("Post from different Sone found: %s", post));
343                         }
344                 }
345
346                 lock.writeLock().lock();
347                 try {
348                         /* remove all posts by the Sone. */
349                         Collection<Post> oldPosts = getPostsFrom(sone.getId());
350                         for (Post post : oldPosts) {
351                                 allPosts.remove(post.getId());
352                         }
353
354                         /* add new posts. */
355                         getPostsFrom(sone.getId()).addAll(posts);
356                         for (Post post : posts) {
357                                 allPosts.put(post.getId(), post);
358                         }
359                 } finally {
360                         lock.writeLock().unlock();
361                 }
362         }
363
364         /** {@inheritDocs} */
365         @Override
366         public void removePosts(Sone sone) {
367                 checkNotNull(sone, "sone must not be null");
368                 lock.writeLock().lock();
369                 try {
370                         /* remove all posts by the Sone. */
371                         getPostsFrom(sone.getId()).clear();
372                         for (Post post : sone.getPosts()) {
373                                 allPosts.remove(post.getId());
374                         }
375                 } finally {
376                         lock.writeLock().unlock();
377                 }
378         }
379
380         //
381         // POSTREPLYPROVIDER METHODS
382         //
383
384         /** {@inheritDocs} */
385         @Override
386         public Optional<PostReply> getPostReply(String id) {
387                 lock.readLock().lock();
388                 try {
389                         return fromNullable(allPostReplies.get(id));
390                 } finally {
391                         lock.readLock().unlock();
392                 }
393         }
394
395         /** {@inheritDocs} */
396         @Override
397         public List<PostReply> getReplies(final String postId) {
398                 lock.readLock().lock();
399                 try {
400                         return from(allPostReplies.values())
401                                         .filter(new Predicate<PostReply>() {
402                                                 @Override
403                                                 public boolean apply(PostReply postReply) {
404                                                         return postReply.getPostId().equals(postId);
405                                                 }
406                                         }).toSortedList(TIME_COMPARATOR);
407                 } finally {
408                         lock.readLock().unlock();
409                 }
410         }
411
412         //
413         // POSTREPLYBUILDERFACTORY METHODS
414         //
415
416         /** {@inheritDocs} */
417         @Override
418         public PostReplyBuilder newPostReplyBuilder() {
419                 return new MemoryPostReplyBuilder(this, soneProvider);
420         }
421
422         //
423         // POSTREPLYSTORE METHODS
424         //
425
426         /** {@inheritDocs} */
427         @Override
428         public void storePostReply(PostReply postReply) {
429                 lock.writeLock().lock();
430                 try {
431                         allPostReplies.put(postReply.getId(), postReply);
432                 } finally {
433                         lock.writeLock().unlock();
434                 }
435         }
436
437         /** {@inheritDocs} */
438         @Override
439         public void storePostReplies(Sone sone, Collection<PostReply> postReplies) {
440                 checkNotNull(sone, "sone must not be null");
441                 /* verify that all posts are from the same Sone. */
442                 for (PostReply postReply : postReplies) {
443                         if (!sone.equals(postReply.getSone())) {
444                                 throw new IllegalArgumentException(String.format("PostReply from different Sone found: %s", postReply));
445                         }
446                 }
447
448                 lock.writeLock().lock();
449                 try {
450                         /* remove all post replies of the Sone. */
451                         for (PostReply postReply : getRepliesFrom(sone.getId())) {
452                                 removePostReply(postReply);
453                         }
454                         for (PostReply postReply : postReplies) {
455                                 allPostReplies.put(postReply.getId(), postReply);
456                                 sonePostReplies.put(postReply.getSone().getId(), postReply);
457                         }
458                 } finally {
459                         lock.writeLock().unlock();
460                 }
461         }
462
463         /** {@inheritDocs} */
464         @Override
465         public void removePostReply(PostReply postReply) {
466                 lock.writeLock().lock();
467                 try {
468                         allPostReplies.remove(postReply.getId());
469                 } finally {
470                         lock.writeLock().unlock();
471                 }
472         }
473
474         /** {@inheritDocs} */
475         @Override
476         public void removePostReplies(Sone sone) {
477                 checkNotNull(sone, "sone must not be null");
478
479                 lock.writeLock().lock();
480                 try {
481                         for (PostReply postReply : sone.getReplies()) {
482                                 removePostReply(postReply);
483                         }
484                 } finally {
485                         lock.writeLock().unlock();
486                 }
487         }
488
489         //
490         // ALBUMPROVDER METHODS
491         //
492
493         @Override
494         public Optional<Album> getAlbum(String albumId) {
495                 lock.readLock().lock();
496                 try {
497                         return fromNullable(allAlbums.get(albumId));
498                 } finally {
499                         lock.readLock().unlock();
500                 }
501         }
502
503         //
504         // ALBUMBUILDERFACTORY METHODS
505         //
506
507         @Override
508         public AlbumBuilder newAlbumBuilder() {
509                 return new AlbumBuilderImpl();
510         }
511
512         //
513         // ALBUMSTORE METHODS
514         //
515
516         @Override
517         public void storeAlbum(Album album) {
518                 lock.writeLock().lock();
519                 try {
520                         allAlbums.put(album.getId(), album);
521                         soneAlbums.put(album.getSone().getId(), album);
522                 } finally {
523                         lock.writeLock().unlock();
524                 }
525         }
526
527         @Override
528         public void removeAlbum(Album album) {
529                 lock.writeLock().lock();
530                 try {
531                         allAlbums.remove(album.getId());
532                         soneAlbums.remove(album.getSone().getId(), album);
533                 } finally {
534                         lock.writeLock().unlock();
535                 }
536         }
537
538         //
539         // IMAGEPROVIDER METHODS
540         //
541
542         @Override
543         public Optional<Image> getImage(String imageId) {
544                 lock.readLock().lock();
545                 try {
546                         return fromNullable(allImages.get(imageId));
547                 } finally {
548                         lock.readLock().unlock();
549                 }
550         }
551
552         //
553         // IMAGEBUILDERFACTORY METHODS
554         //
555
556         @Override
557         public ImageBuilder newImageBuilder() {
558                 return new ImageBuilderImpl();
559         }
560
561         //
562         // IMAGESTORE METHODS
563         //
564
565         @Override
566         public void storeImage(Image image) {
567                 lock.writeLock().lock();
568                 try {
569                         allImages.put(image.getId(), image);
570                         soneImages.put(image.getSone().getId(), image);
571                 } finally {
572                         lock.writeLock().unlock();
573                 }
574         }
575
576         @Override
577         public void removeImage(Image image) {
578                 lock.writeLock().lock();
579                 try {
580                         allImages.remove(image.getId());
581                         soneImages.remove(image.getSone().getId(), image);
582                 } finally {
583                         lock.writeLock().unlock();
584                 }
585         }
586
587         //
588         // PACKAGE-PRIVATE METHODS
589         //
590
591         /**
592          * Returns whether the given post is known.
593          *
594          * @param post
595          *              The post
596          * @return {@code true} if the post is known, {@code false} otherwise
597          */
598         boolean isPostKnown(Post post) {
599                 lock.readLock().lock();
600                 try {
601                         return knownPosts.contains(post.getId());
602                 } finally {
603                         lock.readLock().unlock();
604                 }
605         }
606
607         /**
608          * Sets whether the given post is known.
609          *
610          * @param post
611          *              The post
612          * @param known
613          *              {@code true} if the post is known, {@code false} otherwise
614          */
615         void setPostKnown(Post post, boolean known) {
616                 lock.writeLock().lock();
617                 try {
618                         if (known) {
619                                 knownPosts.add(post.getId());
620                         } else {
621                                 knownPosts.remove(post.getId());
622                         }
623                 } finally {
624                         lock.writeLock().unlock();
625                 }
626         }
627
628         /**
629          * Returns whether the given post reply is known.
630          *
631          * @param postReply
632          *              The post reply
633          * @return {@code true} if the given post reply is known, {@code false}
634          *         otherwise
635          */
636         boolean isPostReplyKnown(PostReply postReply) {
637                 lock.readLock().lock();
638                 try {
639                         return knownPostReplies.contains(postReply.getId());
640                 } finally {
641                         lock.readLock().unlock();
642                 }
643         }
644
645         /**
646          * Sets whether the given post reply is known.
647          *
648          * @param postReply
649          *              The post reply
650          * @param known
651          *              {@code true} if the post reply is known, {@code false} otherwise
652          */
653         void setPostReplyKnown(PostReply postReply, boolean known) {
654                 lock.writeLock().lock();
655                 try {
656                         if (known) {
657                                 knownPostReplies.add(postReply.getId());
658                         } else {
659                                 knownPostReplies.remove(postReply.getId());
660                         }
661                 } finally {
662                         lock.writeLock().unlock();
663                 }
664         }
665
666         //
667         // PRIVATE METHODS
668         //
669
670         /**
671          * Gets all posts for the given Sone, creating a new collection if there is
672          * none yet.
673          *
674          * @param soneId
675          *              The ID of the Sone to get the posts for
676          * @return All posts
677          */
678         private Collection<Post> getPostsFrom(String soneId) {
679                 lock.readLock().lock();
680                 try {
681                         return sonePosts.get(soneId);
682                 } finally {
683                         lock.readLock().unlock();
684                 }
685         }
686
687         /** Loads the known posts. */
688         private void loadKnownPosts() {
689                 lock.writeLock().lock();
690                 try {
691                         int postCounter = 0;
692                         while (true) {
693                                 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
694                                 if (knownPostId == null) {
695                                         break;
696                                 }
697                                 knownPosts.add(knownPostId);
698                         }
699                 } finally {
700                         lock.writeLock().unlock();
701                 }
702         }
703
704         /**
705          * Saves the known posts to the configuration.
706          *
707          * @throws DatabaseException
708          *              if a configuration error occurs
709          */
710         private void saveKnownPosts() throws DatabaseException {
711                 lock.readLock().lock();
712                 try {
713                         int postCounter = 0;
714                         for (String knownPostId : knownPosts) {
715                                 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
716                         }
717                         configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
718                 } catch (ConfigurationException ce1) {
719                         throw new DatabaseException("Could not save database.", ce1);
720                 } finally {
721                         lock.readLock().unlock();
722                 }
723         }
724
725         /**
726          * Returns all replies by the given Sone.
727          *
728          * @param id
729          *              The ID of the Sone
730          * @return The post replies of the Sone, sorted by time (newest first)
731          */
732         private Collection<PostReply> getRepliesFrom(String id) {
733                 lock.readLock().lock();
734                 try {
735                         return unmodifiableCollection(sonePostReplies.get(id));
736                 } finally {
737                         lock.readLock().unlock();
738                 }
739         }
740
741         /** Loads the known post replies. */
742         private void loadKnownPostReplies() {
743                 lock.writeLock().lock();
744                 try {
745                         int replyCounter = 0;
746                         while (true) {
747                                 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
748                                 if (knownReplyId == null) {
749                                         break;
750                                 }
751                                 knownPostReplies.add(knownReplyId);
752                         }
753                 } finally {
754                         lock.writeLock().unlock();
755                 }
756         }
757
758         /**
759          * Saves the known post replies to the configuration.
760          *
761          * @throws DatabaseException
762          *              if a configuration error occurs
763          */
764         private void saveKnownPostReplies() throws DatabaseException {
765                 lock.readLock().lock();
766                 try {
767                         int replyCounter = 0;
768                         for (String knownReplyId : knownPostReplies) {
769                                 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
770                         }
771                         configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
772                 } catch (ConfigurationException ce1) {
773                         throw new DatabaseException("Could not save database.", ce1);
774                 } finally {
775                         lock.readLock().unlock();
776                 }
777         }
778
779 }