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.lang.String.format;
25 import static java.util.logging.Level.WARNING;
26 import static net.pterodactylus.sone.data.Reply.TIME_COMPARATOR;
27 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
28 import static net.pterodactylus.sone.data.Sone.toAllAlbums;
29 import static net.pterodactylus.sone.data.Sone.toAllImages;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.Comparator;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.List;
39 import java.util.concurrent.locks.ReadWriteLock;
40 import java.util.concurrent.locks.ReentrantReadWriteLock;
41 import java.util.logging.Level;
42 import java.util.logging.Logger;
44 import net.pterodactylus.sone.core.ConfigurationSoneParser;
45 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
47 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
48 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
49 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
50 import net.pterodactylus.sone.data.Album;
51 import net.pterodactylus.sone.data.Client;
52 import net.pterodactylus.sone.data.Image;
53 import net.pterodactylus.sone.data.Post;
54 import net.pterodactylus.sone.data.PostReply;
55 import net.pterodactylus.sone.data.Profile;
56 import net.pterodactylus.sone.data.Profile.Field;
57 import net.pterodactylus.sone.data.Sone;
58 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
59 import net.pterodactylus.sone.data.impl.AlbumBuilderImpl;
60 import net.pterodactylus.sone.data.impl.ImageBuilderImpl;
61 import net.pterodactylus.sone.database.AlbumBuilder;
62 import net.pterodactylus.sone.database.Database;
63 import net.pterodactylus.sone.database.DatabaseException;
64 import net.pterodactylus.sone.database.ImageBuilder;
65 import net.pterodactylus.sone.database.PostBuilder;
66 import net.pterodactylus.sone.database.PostDatabase;
67 import net.pterodactylus.sone.database.PostReplyBuilder;
68 import net.pterodactylus.sone.database.SoneBuilder;
69 import net.pterodactylus.sone.database.SoneProvider;
70 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
71 import net.pterodactylus.sone.main.SonePlugin;
72 import net.pterodactylus.sone.utils.Optionals;
73 import net.pterodactylus.util.config.Configuration;
74 import net.pterodactylus.util.config.ConfigurationException;
76 import com.google.common.base.Function;
77 import com.google.common.base.Optional;
78 import com.google.common.base.Predicate;
79 import com.google.common.collect.FluentIterable;
80 import com.google.common.collect.HashMultimap;
81 import com.google.common.collect.Multimap;
82 import com.google.common.collect.SortedSetMultimap;
83 import com.google.common.collect.TreeMultimap;
84 import com.google.common.primitives.Longs;
85 import com.google.common.util.concurrent.AbstractService;
86 import com.google.inject.Inject;
87 import com.google.inject.Singleton;
90 * Memory-based {@link PostDatabase} implementation.
92 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
95 public class MemoryDatabase extends AbstractService implements Database {
97 private static final Logger logger = Logger.getLogger("Sone.Database.Memory");
98 private static final String LATEST_EDITION_PROPERTY = "Sone.LatestEdition";
100 private final ReadWriteLock lock = new ReentrantReadWriteLock();
102 /** The Sone provider. */
103 private final SoneProvider soneProvider;
105 /** The configuration. */
106 private final Configuration configuration;
107 private final ConfigurationLoader configurationLoader;
109 private final Set<String> localSones = new HashSet<String>();
110 private final Map<String, Sone> allSones = new HashMap<String, Sone>();
111 private final Map<String, String> lastInsertFingerprints = new HashMap<String, String>();
113 /** All post replies by their ID. */
114 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
116 /** Replies sorted by Sone. */
117 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
120 public int compare(String leftString, String rightString) {
121 return leftString.compareTo(rightString);
125 /** Whether post replies are known. */
126 private final Set<String> knownPostReplies = new HashSet<String>();
128 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
129 private final Multimap<String, Album> soneAlbums = HashMultimap.create();
131 private final Map<String, Image> allImages = new HashMap<String, Image>();
132 private final Multimap<String, Image> soneImages = HashMultimap.create();
134 private final MemoryPostDatabase postDatabase;
135 private final MemoryBookmarkDatabase memoryBookmarkDatabase;
136 private final MemoryFriendDatabase memoryFriendDatabase;
139 * Creates a new memory database.
141 * @param soneProvider
143 * @param configuration
144 * The configuration for loading and saving elements
147 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
148 this.soneProvider = soneProvider;
149 this.configuration = configuration;
150 this.configurationLoader = new ConfigurationLoader(configuration);
151 postDatabase = new MemoryPostDatabase(this, configurationLoader);
152 memoryBookmarkDatabase =
153 new MemoryBookmarkDatabase(this, configurationLoader);
154 memoryFriendDatabase = new MemoryFriendDatabase(configurationLoader);
163 public Sone registerLocalSone(OwnIdentity ownIdentity) {
164 final Sone localSone = loadLocalSone(ownIdentity);
165 localSones.add(ownIdentity.getId());
169 private Sone loadLocalSone(OwnIdentity ownIdentity) {
170 Sone localSone = newSoneBuilder().local().from(ownIdentity).build();
171 localSone.setLatestEdition(
172 Optional.fromNullable(
173 Longs.tryParse(ownIdentity.getProperty(LATEST_EDITION_PROPERTY)))
175 localSone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
176 localSone.setKnown(true);
182 public void loadSone(Sone sone) {
183 long soneTime = configurationLoader.getLocalSoneTime(sone.getId());
184 if (soneTime == -1) {
189 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
190 Profile profile = configurationSoneParser.parseProfile();
193 Collection<Post> posts;
195 posts = configurationSoneParser.parsePosts(this);
196 } catch (InvalidPostFound ipf) {
197 logger.log(Level.WARNING, "Invalid post found, aborting load!");
202 Collection<PostReply> postReplies;
204 postReplies = configurationSoneParser.parsePostReplies(this);
205 } catch (InvalidPostReplyFound iprf) {
206 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
210 /* load post likes. */
211 Set<String> likedPostIds = configurationSoneParser.parseLikedPostIds();
213 /* load reply likes. */
214 Set<String> likedReplyIds = configurationSoneParser.parseLikedPostReplyIds();
217 List<Album> topLevelAlbums;
219 topLevelAlbums = configurationSoneParser.parseTopLevelAlbums(this);
220 } catch (InvalidAlbumFound iaf) {
221 logger.log(Level.WARNING, "Invalid album found, aborting load!");
223 } catch (InvalidParentAlbumFound ipaf) {
224 logger.log(Level.WARNING,
225 format("Invalid parent album ID: %s", ipaf.getAlbumParentId()));
231 configurationSoneParser.parseImages(this);
232 } catch (InvalidImageFound iif) {
233 logger.log(WARNING, "Invalid image found, aborting load!");
235 } catch (InvalidParentAlbumFound ipaf) {
236 logger.log(Level.WARNING,
237 format("Invalid album image (%s) encountered, aborting load!",
238 ipaf.getAlbumParentId()));
243 String sonePrefix = "Sone/" + sone.getId();
244 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
245 if (avatarId != null) {
246 final Map<String, Image> images = configurationSoneParser.getImages();
247 profile.setAvatar(images.get(avatarId));
251 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
252 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
253 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
254 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
255 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
256 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(
257 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars")
258 .getValue(ShowCustomAvatars.NEVER.name())));
260 /* if we’re still here, Sone was loaded successfully. */
261 lock.writeLock().lock();
263 sone.setTime(soneTime);
264 sone.setProfile(profile);
265 sone.setLikePostIds(likedPostIds);
266 sone.setLikeReplyIds(likedReplyIds);
268 String lastInsertFingerprint = configurationLoader.getLastInsertFingerprint(sone.getId());
269 lastInsertFingerprints.put(sone.getId(), lastInsertFingerprint);
271 allSones.put(sone.getId(), sone);
272 storePosts(sone.getId(), posts);
273 storePostReplies(sone.getId(), postReplies);
274 storeAlbums(sone.getId(), topLevelAlbums);
275 storeImages(sone.getId(), from(topLevelAlbums).transformAndConcat(Album.FLATTENER).transformAndConcat(Album.IMAGES).toList());
277 lock.writeLock().unlock();
279 for (Post post : posts) {
282 for (PostReply reply : postReplies) {
283 reply.setKnown(true);
286 logger.info(String.format("Sone loaded successfully: %s", sone));
290 public String getLastInsertFingerprint(Sone sone) {
291 lock.readLock().lock();
293 if (!lastInsertFingerprints.containsKey(sone.getId())) {
296 return lastInsertFingerprints.get(sone.getId());
298 lock.readLock().unlock();
303 public void setLastInsertFingerprint(Sone sone, String lastInsertFingerprint) {
304 lock.writeLock().lock();
306 lastInsertFingerprints.put(sone.getId(), lastInsertFingerprint);
308 lock.writeLock().unlock();
313 * Saves the database.
315 * @throws DatabaseException
316 * if an error occurs while saving
319 public void save() throws DatabaseException {
320 lock.writeLock().lock();
322 saveKnownPostReplies();
323 for (Sone localSone : from(localSones).transform(soneLoader()).transform(Optionals.<Sone>get())) {
327 lock.writeLock().unlock();
331 private synchronized void saveSone(Sone sone) {
332 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
334 /* save Sone into configuration. */
335 String sonePrefix = "Sone/" + sone.getId();
336 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
337 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(lastInsertFingerprints.get(sone.getId()));
340 Profile profile = sone.getProfile();
341 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
342 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
343 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
344 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
345 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
346 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
347 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
349 /* save profile fields. */
350 int fieldCounter = 0;
351 for (Field profileField : profile.getFields()) {
352 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
353 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
354 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
356 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
360 for (Post post : sone.getPosts()) {
361 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
362 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
363 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
364 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
365 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
367 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
370 int replyCounter = 0;
371 for (PostReply reply : sone.getReplies()) {
372 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
373 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
374 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
375 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
376 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
378 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
380 /* save post likes. */
381 int postLikeCounter = 0;
382 for (String postId : sone.getLikedPostIds()) {
383 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
385 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
387 /* save reply likes. */
388 int replyLikeCounter = 0;
389 for (String replyId : sone.getLikedReplyIds()) {
390 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
392 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
394 /* save albums. first, collect in a flat structure, top-level first. */
395 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
397 int albumCounter = 0;
398 for (Album album : albums) {
399 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
400 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
401 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
402 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
403 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
404 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
406 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
409 int imageCounter = 0;
410 for (Album album : albums) {
411 for (Image image : album.getImages()) {
412 if (!image.isInserted()) {
415 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
416 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
417 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
418 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
419 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
420 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
421 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
422 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
423 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
426 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
429 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
430 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
431 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
432 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
433 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
434 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
436 configuration.save();
438 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
439 } catch (ConfigurationException ce1) {
440 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
448 /** {@inheritDocs} */
450 protected void doStart() {
451 postDatabase.start();
452 memoryBookmarkDatabase.start();
453 loadKnownPostReplies();
457 /** {@inheritDocs} */
459 protected void doStop() {
462 memoryBookmarkDatabase.stop();
465 } catch (DatabaseException de1) {
471 public SoneBuilder newSoneBuilder() {
472 return new MemorySoneBuilder(this);
476 public void storeSone(Sone sone) {
477 lock.writeLock().lock();
481 allSones.put(sone.getId(), sone);
482 storePosts(sone.getId(), sone.getPosts());
483 storePostReplies(sone.getId(), sone.getReplies());
484 storeAlbums(sone.getId(), toAllAlbums.apply(sone));
485 storeImages(sone.getId(), toAllImages.apply(sone));
487 lock.writeLock().unlock();
491 private void storePosts(String soneId, Collection<Post> posts) {
492 postDatabase.storePosts(soneId, posts);
495 private void storePostReplies(String soneId, Collection<PostReply> postReplies) {
496 sonePostReplies.putAll(soneId, postReplies);
497 for (PostReply postReply : postReplies) {
498 allPostReplies.put(postReply.getId(), postReply);
502 private void storeAlbums(String soneId, Collection<Album> albums) {
503 soneAlbums.putAll(soneId, albums);
504 for (Album album : albums) {
505 allAlbums.put(album.getId(), album);
509 private void storeImages(String soneId, Collection<Image> images) {
510 soneImages.putAll(soneId, images);
511 for (Image image : images) {
512 allImages.put(image.getId(), image);
517 public void removeSone(Sone sone) {
518 lock.writeLock().lock();
520 allSones.remove(sone.getId());
521 postDatabase.removePostsFor(sone.getId());
522 Collection<PostReply> removedPostReplies =
523 sonePostReplies.removeAll(sone.getId());
524 for (PostReply removedPostReply : removedPostReplies) {
525 allPostReplies.remove(removedPostReply.getId());
527 Collection<Album> removedAlbums =
528 soneAlbums.removeAll(sone.getId());
529 for (Album removedAlbum : removedAlbums) {
530 allAlbums.remove(removedAlbum.getId());
532 Collection<Image> removedImages =
533 soneImages.removeAll(sone.getId());
534 for (Image removedImage : removedImages) {
535 allImages.remove(removedImage.getId());
538 lock.writeLock().unlock();
543 public Function<String, Optional<Sone>> soneLoader() {
544 return new Function<String, Optional<Sone>>() {
546 public Optional<Sone> apply(String soneId) {
547 return getSone(soneId);
553 public Optional<Sone> getSone(String soneId) {
554 lock.readLock().lock();
556 return fromNullable(allSones.get(soneId));
558 lock.readLock().unlock();
563 public Collection<Sone> getSones() {
564 lock.readLock().lock();
566 return new HashSet<Sone>(allSones.values());
568 lock.readLock().unlock();
573 public Collection<Sone> getLocalSones() {
574 lock.readLock().lock();
576 return from(allSones.values()).filter(LOCAL_SONE_FILTER).toSet();
578 lock.readLock().unlock();
583 public Collection<Sone> getRemoteSones() {
584 lock.readLock().lock();
586 return from(allSones.values())
587 .filter(not(LOCAL_SONE_FILTER)) .toSet();
589 lock.readLock().unlock();
594 public Collection<String> getFriends(Sone localSone) {
595 if (!localSone.isLocal()) {
596 return Collections.emptySet();
598 return memoryFriendDatabase.getFriends(localSone.getId());
602 public boolean isFriend(Sone localSone, String friendSoneId) {
603 if (!localSone.isLocal()) {
606 return memoryFriendDatabase.isFriend(localSone.getId(), friendSoneId);
610 public void addFriend(Sone localSone, String friendSoneId) {
611 if (!localSone.isLocal()) {
614 memoryFriendDatabase.addFriend(localSone.getId(), friendSoneId);
618 public void removeFriend(Sone localSone, String friendSoneId) {
619 if (!localSone.isLocal()) {
622 memoryFriendDatabase.removeFriend(localSone.getId(), friendSoneId);
626 // POSTPROVIDER METHODS
629 /** {@inheritDocs} */
631 public Optional<Post> getPost(String postId) {
632 return postDatabase.getPost(postId);
635 /** {@inheritDocs} */
637 public Collection<Post> getPosts(String soneId) {
638 return new HashSet<Post>(getPostsFrom(soneId));
641 /** {@inheritDocs} */
643 public Collection<Post> getDirectedPosts(final String recipientId) {
644 return postDatabase.getDirectedPosts(recipientId);
648 // POSTBUILDERFACTORY METHODS
651 /** {@inheritDocs} */
653 public PostBuilder newPostBuilder() {
654 return new MemoryPostBuilder(this, soneProvider);
661 /** {@inheritDocs} */
663 public void storePost(Post post) {
664 checkNotNull(post, "post must not be null");
665 postDatabase.storePost(post);
668 /** {@inheritDocs} */
670 public void removePost(Post post) {
671 checkNotNull(post, "post must not be null");
672 postDatabase.removePost(post.getId());
676 // POSTREPLYPROVIDER METHODS
679 /** {@inheritDocs} */
681 public Optional<PostReply> getPostReply(String id) {
682 lock.readLock().lock();
684 return fromNullable(allPostReplies.get(id));
686 lock.readLock().unlock();
690 /** {@inheritDocs} */
692 public List<PostReply> getReplies(final String postId) {
693 lock.readLock().lock();
695 return from(allPostReplies.values())
696 .filter(new Predicate<PostReply>() {
698 public boolean apply(PostReply postReply) {
699 return postReply.getPostId().equals(postId);
701 }).toSortedList(TIME_COMPARATOR);
703 lock.readLock().unlock();
708 // POSTREPLYBUILDERFACTORY METHODS
711 /** {@inheritDocs} */
713 public PostReplyBuilder newPostReplyBuilder() {
714 return new MemoryPostReplyBuilder(this, soneProvider);
718 // POSTREPLYSTORE METHODS
721 /** {@inheritDocs} */
723 public void storePostReply(PostReply postReply) {
724 lock.writeLock().lock();
726 allPostReplies.put(postReply.getId(), postReply);
728 lock.writeLock().unlock();
732 /** {@inheritDocs} */
734 public void removePostReply(PostReply postReply) {
735 lock.writeLock().lock();
737 allPostReplies.remove(postReply.getId());
739 lock.writeLock().unlock();
744 // ALBUMPROVDER METHODS
748 public Optional<Album> getAlbum(String albumId) {
749 lock.readLock().lock();
751 return fromNullable(allAlbums.get(albumId));
753 lock.readLock().unlock();
758 // ALBUMBUILDERFACTORY METHODS
762 public AlbumBuilder newAlbumBuilder() {
763 return new AlbumBuilderImpl();
767 // ALBUMSTORE METHODS
771 public void storeAlbum(Album album) {
772 lock.writeLock().lock();
774 allAlbums.put(album.getId(), album);
775 soneAlbums.put(album.getSone().getId(), album);
777 lock.writeLock().unlock();
782 public void removeAlbum(Album album) {
783 lock.writeLock().lock();
785 allAlbums.remove(album.getId());
786 soneAlbums.remove(album.getSone().getId(), album);
788 lock.writeLock().unlock();
793 // IMAGEPROVIDER METHODS
797 public Optional<Image> getImage(String imageId) {
798 lock.readLock().lock();
800 return fromNullable(allImages.get(imageId));
802 lock.readLock().unlock();
807 // IMAGEBUILDERFACTORY METHODS
811 public ImageBuilder newImageBuilder() {
812 return new ImageBuilderImpl();
816 // IMAGESTORE METHODS
820 public void storeImage(Image image) {
821 lock.writeLock().lock();
823 allImages.put(image.getId(), image);
824 soneImages.put(image.getSone().getId(), image);
826 lock.writeLock().unlock();
831 public void removeImage(Image image) {
832 lock.writeLock().lock();
834 allImages.remove(image.getId());
835 soneImages.remove(image.getSone().getId(), image);
837 lock.writeLock().unlock();
842 public void bookmarkPost(Post post) {
843 memoryBookmarkDatabase.bookmarkPost(post);
847 public void unbookmarkPost(Post post) {
848 memoryBookmarkDatabase.unbookmarkPost(post);
852 public boolean isPostBookmarked(Post post) {
853 return memoryBookmarkDatabase.isPostBookmarked(post);
857 public Set<Post> getBookmarkedPosts() {
858 return memoryBookmarkDatabase.getBookmarkedPosts();
862 // PACKAGE-PRIVATE METHODS
866 * Returns whether the given post is known.
870 * @return {@code true} if the post is known, {@code false} otherwise
872 boolean isPostKnown(Post post) {
873 return postDatabase.isPostKnown(post.getId());
877 * Sets whether the given post is known.
882 * {@code true} if the post is known, {@code false} otherwise
884 void setPostKnown(Post post, boolean known) {
885 postDatabase.setPostKnown(post.getId(), known);
889 * Returns whether the given post reply is known.
893 * @return {@code true} if the given post reply is known, {@code false}
896 boolean isPostReplyKnown(PostReply postReply) {
897 lock.readLock().lock();
899 return knownPostReplies.contains(postReply.getId());
901 lock.readLock().unlock();
906 * Sets whether the given post reply is known.
911 * {@code true} if the post reply is known, {@code false} otherwise
913 void setPostReplyKnown(PostReply postReply, boolean known) {
914 lock.writeLock().lock();
917 knownPostReplies.add(postReply.getId());
919 knownPostReplies.remove(postReply.getId());
922 lock.writeLock().unlock();
931 * Gets all posts for the given Sone, creating a new collection if there is
935 * The ID of the Sone to get the posts for
938 private Collection<Post> getPostsFrom(String soneId) {
939 return postDatabase.getPostsFrom(soneId);
942 /** Loads the known post replies. */
943 private void loadKnownPostReplies() {
944 Set<String> knownPostReplies = configurationLoader.loadKnownPostReplies();
945 lock.writeLock().lock();
947 this.knownPostReplies.clear();
948 this.knownPostReplies.addAll(knownPostReplies);
950 lock.writeLock().unlock();
955 * Saves the known post replies to the configuration.
957 * @throws DatabaseException
958 * if a configuration error occurs
960 private void saveKnownPostReplies() throws DatabaseException {
961 lock.readLock().lock();
963 int replyCounter = 0;
964 for (String knownReplyId : knownPostReplies) {
965 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(
968 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
969 } catch (ConfigurationException ce1) {
970 throw new DatabaseException("Could not save database.", ce1);
972 lock.readLock().unlock();