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.LocalSone;
54 import net.pterodactylus.sone.data.Post;
55 import net.pterodactylus.sone.data.PostReply;
56 import net.pterodactylus.sone.data.Profile;
57 import net.pterodactylus.sone.data.Profile.Field;
58 import net.pterodactylus.sone.data.Sone;
59 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
60 import net.pterodactylus.sone.data.impl.AlbumBuilderImpl;
61 import net.pterodactylus.sone.data.impl.ImageBuilderImpl;
62 import net.pterodactylus.sone.database.AlbumBuilder;
63 import net.pterodactylus.sone.database.Database;
64 import net.pterodactylus.sone.database.DatabaseException;
65 import net.pterodactylus.sone.database.ImageBuilder;
66 import net.pterodactylus.sone.database.PostBuilder;
67 import net.pterodactylus.sone.database.PostDatabase;
68 import net.pterodactylus.sone.database.PostReplyBuilder;
69 import net.pterodactylus.sone.database.SoneBuilder;
70 import net.pterodactylus.sone.database.SoneProvider;
71 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
72 import net.pterodactylus.sone.main.SonePlugin;
73 import net.pterodactylus.sone.utils.Optionals;
74 import net.pterodactylus.util.config.Configuration;
75 import net.pterodactylus.util.config.ConfigurationException;
77 import com.google.common.base.Function;
78 import com.google.common.base.Optional;
79 import com.google.common.base.Predicate;
80 import com.google.common.collect.FluentIterable;
81 import com.google.common.collect.HashMultimap;
82 import com.google.common.collect.Multimap;
83 import com.google.common.collect.SortedSetMultimap;
84 import com.google.common.collect.TreeMultimap;
85 import com.google.common.primitives.Longs;
86 import com.google.common.util.concurrent.AbstractService;
87 import com.google.inject.Inject;
88 import com.google.inject.Singleton;
91 * Memory-based {@link PostDatabase} implementation.
93 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
96 public class MemoryDatabase extends AbstractService implements Database {
98 private static final Logger logger = Logger.getLogger("Sone.Database.Memory");
99 private static final String LATEST_EDITION_PROPERTY = "Sone.LatestEdition";
101 private final ReadWriteLock lock = new ReentrantReadWriteLock();
103 /** The Sone provider. */
104 private final SoneProvider soneProvider;
106 /** The configuration. */
107 private final Configuration configuration;
108 private final ConfigurationLoader configurationLoader;
110 private final Set<String> localSones = new HashSet<String>();
111 private final Map<String, Sone> allSones = new HashMap<String, Sone>();
112 private final Map<String, String> lastInsertFingerprints = new HashMap<String, String>();
114 /** All post replies by their ID. */
115 private final Map<String, PostReply> allPostReplies = new HashMap<String, PostReply>();
117 /** Replies sorted by Sone. */
118 private final SortedSetMultimap<String, PostReply> sonePostReplies = TreeMultimap.create(new Comparator<String>() {
121 public int compare(String leftString, String rightString) {
122 return leftString.compareTo(rightString);
126 /** Whether post replies are known. */
127 private final Set<String> knownPostReplies = new HashSet<String>();
129 private final Map<String, Album> allAlbums = new HashMap<String, Album>();
130 private final Multimap<String, Album> soneAlbums = HashMultimap.create();
132 private final Map<String, Image> allImages = new HashMap<String, Image>();
133 private final Multimap<String, Image> soneImages = HashMultimap.create();
135 private final MemorySoneDatabase soneDatabase;
136 private final MemoryPostDatabase postDatabase;
137 private final MemoryBookmarkDatabase memoryBookmarkDatabase;
138 private final MemoryFriendDatabase memoryFriendDatabase;
141 * Creates a new memory database.
143 * @param soneProvider
145 * @param configuration
146 * The configuration for loading and saving elements
149 public MemoryDatabase(SoneProvider soneProvider, Configuration configuration) {
150 this.soneProvider = soneProvider;
151 this.configuration = configuration;
152 this.configurationLoader = new ConfigurationLoader(configuration);
153 soneDatabase = new MemorySoneDatabase(configurationLoader);
154 postDatabase = new MemoryPostDatabase(this, configurationLoader);
155 memoryBookmarkDatabase =
156 new MemoryBookmarkDatabase(this, configurationLoader);
157 memoryFriendDatabase = new MemoryFriendDatabase(configurationLoader);
165 public Optional<LocalSone> getLocalSone(String localSoneId) {
166 lock.readLock().lock();
168 if (!localSones.contains(localSoneId)) {
169 return Optional.absent();
171 return Optional.of((LocalSone) allSones.get(localSoneId));
173 lock.readLock().unlock();
178 public LocalSone registerLocalSone(OwnIdentity ownIdentity) {
179 final LocalSone localSone = loadLocalSone(ownIdentity);
180 localSones.add(ownIdentity.getId());
184 private LocalSone loadLocalSone(OwnIdentity ownIdentity) {
185 final SoneBuilder soneBuilder = newSoneBuilder().from(ownIdentity).using(
186 new Client("Sone", SonePlugin.VERSION.toString()));
188 loadElements(soneBuilder, ownIdentity.getId());
190 LocalSone localSone = soneBuilder.buildLocal();
192 localSone.setKnown(true);
193 localSone.setLatestEdition(
194 Optional.fromNullable(
195 Longs.tryParse(ownIdentity.getProperty(LATEST_EDITION_PROPERTY)))
200 private void loadElements(SoneBuilder soneBuilder, String soneId) {
201 long soneTime = configurationLoader.getLocalSoneTime(soneId);
202 if (soneTime == -1) {
205 soneBuilder.lastUpdated(soneTime);
207 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, soneId);
210 Set<Post> posts = configurationSoneParser.parsePosts(this);
211 soneBuilder.withPosts(posts);
212 for (Post post : posts) {
215 } catch (InvalidPostFound ipf) {
216 logger.log(Level.WARNING, "Invalid post found, aborting load!");
221 Set<PostReply> postReplies = configurationSoneParser.parsePostReplies(this);
222 soneBuilder.withPostReplies(postReplies);
223 for (PostReply reply : postReplies) {
224 reply.setKnown(true);
226 } catch (InvalidPostReplyFound iprf) {
227 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
232 private void loadSone(LocalSone sone) {
234 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone.getId());
235 Profile profile = configurationSoneParser.parseProfile(sone);
237 /* load post likes. */
238 Set<String> likedPostIds = configurationSoneParser.parseLikedPostIds();
240 /* load reply likes. */
241 Set<String> likedReplyIds = configurationSoneParser.parseLikedPostReplyIds();
244 List<Album> topLevelAlbums;
246 topLevelAlbums = configurationSoneParser.parseTopLevelAlbums(this, sone);
247 } catch (InvalidAlbumFound iaf) {
248 logger.log(Level.WARNING, "Invalid album found, aborting load!");
250 } catch (InvalidParentAlbumFound ipaf) {
251 logger.log(Level.WARNING,
252 format("Invalid parent album ID: %s", ipaf.getAlbumParentId()));
258 configurationSoneParser.parseImages(this, sone);
259 } catch (InvalidImageFound iif) {
260 logger.log(WARNING, "Invalid image found, aborting load!");
262 } catch (InvalidParentAlbumFound ipaf) {
263 logger.log(Level.WARNING,
264 format("Invalid album image (%s) encountered, aborting load!",
265 ipaf.getAlbumParentId()));
270 String sonePrefix = "Sone/" + sone.getId();
271 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
272 if (avatarId != null) {
273 final Map<String, Image> images = configurationSoneParser.getImages();
274 profile.setAvatar(images.get(avatarId));
278 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
279 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
280 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
281 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
282 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
283 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(
284 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars")
285 .getValue(ShowCustomAvatars.NEVER.name())));
287 /* if we’re still here, Sone was loaded successfully. */
288 lock.writeLock().lock();
290 updateSoneTime(sone, sone.getTime());
291 sone.setProfile(profile);
292 sone.setLikePostIds(likedPostIds);
293 sone.setLikeReplyIds(likedReplyIds);
295 String lastInsertFingerprint = configurationLoader.getLastInsertFingerprint(sone.getId());
296 lastInsertFingerprints.put(sone.getId(), lastInsertFingerprint);
298 allSones.put(sone.getId(), sone);
299 storePosts(sone.getId(), sone.getPosts());
300 storePostReplies(sone.getId(), sone.getReplies());
301 storeAlbums(sone.getId(), topLevelAlbums);
302 storeImages(sone.getId(), from(topLevelAlbums).transformAndConcat(Album.FLATTENER).transformAndConcat(Album.IMAGES).toList());
304 lock.writeLock().unlock();
307 logger.info(String.format("Sone loaded successfully: %s", sone));
311 public String getLastInsertFingerprint(Sone sone) {
312 lock.readLock().lock();
314 if (!lastInsertFingerprints.containsKey(sone.getId())) {
317 return lastInsertFingerprints.get(sone.getId());
319 lock.readLock().unlock();
324 public void setLastInsertFingerprint(Sone sone, String lastInsertFingerprint) {
325 lock.writeLock().lock();
327 lastInsertFingerprints.put(sone.getId(), lastInsertFingerprint);
329 lock.writeLock().unlock();
334 * Saves the database.
336 * @throws DatabaseException
337 * if an error occurs while saving
340 public void save() throws DatabaseException {
341 lock.writeLock().lock();
343 saveKnownPostReplies();
344 for (Sone localSone : from(localSones).transform(soneLoader()).transform(Optionals.<Sone>get())) {
348 lock.writeLock().unlock();
352 private synchronized void saveSone(Sone sone) {
353 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
355 /* save Sone into configuration. */
356 String sonePrefix = "Sone/" + sone.getId();
357 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
358 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(lastInsertFingerprints.get(sone.getId()));
361 Profile profile = sone.getProfile();
362 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
363 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
364 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
365 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
366 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
367 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
368 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
370 /* save profile fields. */
371 int fieldCounter = 0;
372 for (Field profileField : profile.getFields()) {
373 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
374 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
375 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
377 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
381 for (Post post : sone.getPosts()) {
382 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
383 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
384 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
385 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
386 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
388 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
391 int replyCounter = 0;
392 for (PostReply reply : sone.getReplies()) {
393 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
394 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
395 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
396 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
397 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
399 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
401 /* save post likes. */
402 int postLikeCounter = 0;
403 for (String postId : sone.getLikedPostIds()) {
404 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
406 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
408 /* save reply likes. */
409 int replyLikeCounter = 0;
410 for (String replyId : sone.getLikedReplyIds()) {
411 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
413 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
415 /* save albums. first, collect in a flat structure, top-level first. */
416 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
418 int albumCounter = 0;
419 for (Album album : albums) {
420 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
421 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
422 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
423 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
424 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
425 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
427 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
430 int imageCounter = 0;
431 for (Album album : albums) {
432 for (Image image : album.getImages()) {
433 if (!image.isInserted()) {
436 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
437 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
438 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
439 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
440 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
441 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
442 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
443 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
444 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
447 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
450 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
451 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
452 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
453 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
454 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
455 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
457 configuration.save();
459 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
460 } catch (ConfigurationException ce1) {
461 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
469 /** {@inheritDocs} */
471 protected void doStart() {
472 soneDatabase.start();
473 memoryFriendDatabase.start();
474 postDatabase.start();
475 memoryBookmarkDatabase.start();
476 loadKnownPostReplies();
480 /** {@inheritDocs} */
482 protected void doStop() {
485 memoryFriendDatabase.stop();
487 memoryBookmarkDatabase.stop();
490 } catch (DatabaseException de1) {
496 public SoneBuilder newSoneBuilder() {
497 return new MemorySoneBuilder(this);
501 public void storeSone(Sone sone) {
502 lock.writeLock().lock();
506 allSones.put(sone.getId(), sone);
507 storePosts(sone.getId(), sone.getPosts());
508 storePostReplies(sone.getId(), sone.getReplies());
509 storeAlbums(sone.getId(), toAllAlbums.apply(sone));
510 storeImages(sone.getId(), toAllImages.apply(sone));
512 lock.writeLock().unlock();
517 public boolean isSoneKnown(Sone sone) {
518 return soneDatabase.isKnownSone(sone.getId());
522 public void setSoneKnown(Sone sone) {
523 soneDatabase.setSoneKnown(sone.getId());
527 public void updateSoneTime(Sone sone, long soneTime) {
528 soneDatabase.updateSoneTime(sone.getId(), soneTime);
531 private void storePosts(String soneId, Collection<Post> posts) {
532 postDatabase.storePosts(soneId, posts);
535 private void storePostReplies(String soneId, Collection<PostReply> postReplies) {
536 sonePostReplies.putAll(soneId, postReplies);
537 for (PostReply postReply : postReplies) {
538 allPostReplies.put(postReply.getId(), postReply);
542 private void storeAlbums(String soneId, Collection<Album> albums) {
543 soneAlbums.putAll(soneId, albums);
544 for (Album album : albums) {
545 allAlbums.put(album.getId(), album);
549 private void storeImages(String soneId, Collection<Image> images) {
550 soneImages.putAll(soneId, images);
551 for (Image image : images) {
552 allImages.put(image.getId(), image);
557 public void removeSone(Sone sone) {
558 lock.writeLock().lock();
560 allSones.remove(sone.getId());
561 postDatabase.removePostsFor(sone.getId());
562 Collection<PostReply> removedPostReplies =
563 sonePostReplies.removeAll(sone.getId());
564 for (PostReply removedPostReply : removedPostReplies) {
565 allPostReplies.remove(removedPostReply.getId());
567 Collection<Album> removedAlbums =
568 soneAlbums.removeAll(sone.getId());
569 for (Album removedAlbum : removedAlbums) {
570 allAlbums.remove(removedAlbum.getId());
572 Collection<Image> removedImages =
573 soneImages.removeAll(sone.getId());
574 for (Image removedImage : removedImages) {
575 allImages.remove(removedImage.getId());
578 lock.writeLock().unlock();
583 public Function<String, Optional<Sone>> soneLoader() {
584 return new Function<String, Optional<Sone>>() {
586 public Optional<Sone> apply(String soneId) {
587 return getSone(soneId);
593 public Optional<Sone> getSone(String soneId) {
594 lock.readLock().lock();
596 return fromNullable(allSones.get(soneId));
598 lock.readLock().unlock();
603 public Collection<Sone> getSones() {
604 lock.readLock().lock();
606 return new HashSet<Sone>(allSones.values());
608 lock.readLock().unlock();
613 public Collection<LocalSone> getLocalSones() {
614 lock.readLock().lock();
616 return from(allSones.values()).filter(LOCAL_SONE_FILTER).transform(new Function<Sone, LocalSone>() {
618 public LocalSone apply(Sone sone) {
619 // FIXME – Sones will not always implement LocalSone
620 return (LocalSone) sone;
624 lock.readLock().unlock();
629 public Collection<Sone> getRemoteSones() {
630 lock.readLock().lock();
632 return from(allSones.values())
633 .filter(not(LOCAL_SONE_FILTER)) .toSet();
635 lock.readLock().unlock();
640 public Collection<String> getFriends(LocalSone localSone) {
641 if (!localSone.isLocal()) {
642 return Collections.emptySet();
644 return memoryFriendDatabase.getFriends(localSone.getId());
648 public Optional<Long> getSoneFollowingTime(String remoteSoneId) {
649 return memoryFriendDatabase.getSoneFollowingTime(remoteSoneId);
653 public boolean isFriend(LocalSone localSone, String friendSoneId) {
654 if (!localSone.isLocal()) {
657 return memoryFriendDatabase.isFriend(localSone.getId(), friendSoneId);
661 public void addFriend(LocalSone localSone, String friendSoneId) {
662 memoryFriendDatabase.addFriend(localSone.getId(), friendSoneId);
666 public void removeFriend(LocalSone localSone, String friendSoneId) {
667 memoryFriendDatabase.removeFriend(localSone.getId(), friendSoneId);
671 // POSTPROVIDER METHODS
674 /** {@inheritDocs} */
676 public Optional<Post> getPost(String postId) {
677 return postDatabase.getPost(postId);
680 /** {@inheritDocs} */
682 public Collection<Post> getPosts(String soneId) {
683 return new HashSet<Post>(getPostsFrom(soneId));
686 /** {@inheritDocs} */
688 public Collection<Post> getDirectedPosts(final String recipientId) {
689 return postDatabase.getDirectedPosts(recipientId);
693 // POSTBUILDERFACTORY METHODS
696 /** {@inheritDocs} */
698 public PostBuilder newPostBuilder() {
699 return new MemoryPostBuilder(this, soneProvider);
706 /** {@inheritDocs} */
708 public void storePost(Post post) {
709 checkNotNull(post, "post must not be null");
710 postDatabase.storePost(post);
713 /** {@inheritDocs} */
715 public void removePost(Post post) {
716 checkNotNull(post, "post must not be null");
717 postDatabase.removePost(post.getId());
721 // POSTREPLYPROVIDER METHODS
724 /** {@inheritDocs} */
726 public Optional<PostReply> getPostReply(String id) {
727 lock.readLock().lock();
729 return fromNullable(allPostReplies.get(id));
731 lock.readLock().unlock();
735 /** {@inheritDocs} */
737 public List<PostReply> getReplies(final String postId) {
738 lock.readLock().lock();
740 return from(allPostReplies.values())
741 .filter(new Predicate<PostReply>() {
743 public boolean apply(PostReply postReply) {
744 return postReply.getPostId().equals(postId);
746 }).toSortedList(TIME_COMPARATOR);
748 lock.readLock().unlock();
753 // POSTREPLYBUILDERFACTORY METHODS
756 /** {@inheritDocs} */
758 public PostReplyBuilder newPostReplyBuilder() {
759 return new MemoryPostReplyBuilder(this, soneProvider);
763 // POSTREPLYSTORE METHODS
766 /** {@inheritDocs} */
768 public void storePostReply(PostReply postReply) {
769 lock.writeLock().lock();
771 allPostReplies.put(postReply.getId(), postReply);
773 lock.writeLock().unlock();
777 /** {@inheritDocs} */
779 public void removePostReply(PostReply postReply) {
780 lock.writeLock().lock();
782 allPostReplies.remove(postReply.getId());
784 lock.writeLock().unlock();
789 // ALBUMPROVDER METHODS
793 public Optional<Album> getAlbum(String albumId) {
794 lock.readLock().lock();
796 return fromNullable(allAlbums.get(albumId));
798 lock.readLock().unlock();
803 // ALBUMBUILDERFACTORY METHODS
807 public AlbumBuilder newAlbumBuilder() {
808 return new AlbumBuilderImpl();
812 // ALBUMSTORE METHODS
816 public void storeAlbum(Album album) {
817 lock.writeLock().lock();
819 allAlbums.put(album.getId(), album);
820 soneAlbums.put(album.getSone().getId(), album);
822 lock.writeLock().unlock();
827 public void removeAlbum(Album album) {
828 lock.writeLock().lock();
830 allAlbums.remove(album.getId());
831 soneAlbums.remove(album.getSone().getId(), album);
833 lock.writeLock().unlock();
838 // IMAGEPROVIDER METHODS
842 public Optional<Image> getImage(String imageId) {
843 lock.readLock().lock();
845 return fromNullable(allImages.get(imageId));
847 lock.readLock().unlock();
852 // IMAGEBUILDERFACTORY METHODS
856 public ImageBuilder newImageBuilder() {
857 return new ImageBuilderImpl();
861 // IMAGESTORE METHODS
865 public void storeImage(Image image) {
866 lock.writeLock().lock();
868 allImages.put(image.getId(), image);
869 soneImages.put(image.getSone().getId(), image);
871 lock.writeLock().unlock();
876 public void removeImage(Image image) {
877 lock.writeLock().lock();
879 allImages.remove(image.getId());
880 soneImages.remove(image.getSone().getId(), image);
882 lock.writeLock().unlock();
887 public void bookmarkPost(Post post) {
888 memoryBookmarkDatabase.bookmarkPost(post);
892 public void unbookmarkPost(Post post) {
893 memoryBookmarkDatabase.unbookmarkPost(post);
897 public boolean isPostBookmarked(Post post) {
898 return memoryBookmarkDatabase.isPostBookmarked(post);
902 public Set<Post> getBookmarkedPosts() {
903 return memoryBookmarkDatabase.getBookmarkedPosts();
907 // PACKAGE-PRIVATE METHODS
911 * Returns whether the given post is known.
915 * @return {@code true} if the post is known, {@code false} otherwise
917 boolean isPostKnown(Post post) {
918 return postDatabase.isPostKnown(post.getId());
922 * Sets whether the given post is known.
927 * {@code true} if the post is known, {@code false} otherwise
929 void setPostKnown(Post post, boolean known) {
930 postDatabase.setPostKnown(post.getId(), known);
934 * Returns whether the given post reply is known.
938 * @return {@code true} if the given post reply is known, {@code false}
941 boolean isPostReplyKnown(PostReply postReply) {
942 lock.readLock().lock();
944 return knownPostReplies.contains(postReply.getId());
946 lock.readLock().unlock();
951 * Sets whether the given post reply is known.
956 * {@code true} if the post reply is known, {@code false} otherwise
958 void setPostReplyKnown(PostReply postReply, boolean known) {
959 lock.writeLock().lock();
962 knownPostReplies.add(postReply.getId());
964 knownPostReplies.remove(postReply.getId());
967 lock.writeLock().unlock();
976 * Gets all posts for the given Sone, creating a new collection if there is
980 * The ID of the Sone to get the posts for
983 private Collection<Post> getPostsFrom(String soneId) {
984 return postDatabase.getPostsFrom(soneId);
987 /** Loads the known post replies. */
988 private void loadKnownPostReplies() {
989 Set<String> knownPostReplies = configurationLoader.loadKnownPostReplies();
990 lock.writeLock().lock();
992 this.knownPostReplies.clear();
993 this.knownPostReplies.addAll(knownPostReplies);
995 lock.writeLock().unlock();
1000 * Saves the known post replies to the configuration.
1002 * @throws DatabaseException
1003 * if a configuration error occurs
1005 private void saveKnownPostReplies() throws DatabaseException {
1006 lock.readLock().lock();
1008 int replyCounter = 0;
1009 for (String knownReplyId : knownPostReplies) {
1010 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(
1013 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1014 } catch (ConfigurationException ce1) {
1015 throw new DatabaseException("Could not save database.", ce1);
1017 lock.readLock().unlock();