Convert “Sone removed” into EventBus-based event.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.java - Copyright © 2010–2012 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.core;
19
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.Set;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
34
35 import net.pterodactylus.sone.core.Options.DefaultOption;
36 import net.pterodactylus.sone.core.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
39 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
40 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
41 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
42 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
43 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
44 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
45 import net.pterodactylus.sone.data.Album;
46 import net.pterodactylus.sone.data.Client;
47 import net.pterodactylus.sone.data.Image;
48 import net.pterodactylus.sone.data.Post;
49 import net.pterodactylus.sone.data.PostReply;
50 import net.pterodactylus.sone.data.Profile;
51 import net.pterodactylus.sone.data.Profile.Field;
52 import net.pterodactylus.sone.data.Reply;
53 import net.pterodactylus.sone.data.Sone;
54 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
55 import net.pterodactylus.sone.data.Sone.SoneStatus;
56 import net.pterodactylus.sone.data.TemporaryImage;
57 import net.pterodactylus.sone.data.impl.PostImpl;
58 import net.pterodactylus.sone.fcp.FcpInterface;
59 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
60 import net.pterodactylus.sone.freenet.wot.Identity;
61 import net.pterodactylus.sone.freenet.wot.IdentityListener;
62 import net.pterodactylus.sone.freenet.wot.IdentityManager;
63 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
64 import net.pterodactylus.sone.main.SonePlugin;
65 import net.pterodactylus.util.config.Configuration;
66 import net.pterodactylus.util.config.ConfigurationException;
67 import net.pterodactylus.util.logging.Logging;
68 import net.pterodactylus.util.number.Numbers;
69 import net.pterodactylus.util.service.AbstractService;
70 import net.pterodactylus.util.thread.NamedThreadFactory;
71 import net.pterodactylus.util.thread.Ticker;
72 import net.pterodactylus.util.validation.EqualityValidator;
73 import net.pterodactylus.util.validation.IntegerRangeValidator;
74 import net.pterodactylus.util.validation.OrValidator;
75 import net.pterodactylus.util.validation.Validation;
76 import net.pterodactylus.util.version.Version;
77
78 import com.google.common.base.Predicate;
79 import com.google.common.collect.Collections2;
80 import com.google.common.eventbus.EventBus;
81 import com.google.inject.Inject;
82
83 import freenet.keys.FreenetURI;
84
85 /**
86  * The Sone core.
87  *
88  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
89  */
90 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
91
92         /** The logger. */
93         private static final Logger logger = Logging.getLogger(Core.class);
94
95         /** The start time. */
96         private final long startupTime = System.currentTimeMillis();
97
98         /** The options. */
99         private final Options options = new Options();
100
101         /** The preferences. */
102         private final Preferences preferences = new Preferences(options);
103
104         /** The core listener manager. */
105         private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
106
107         /** The event bus. */
108         private final EventBus eventBus;
109
110         /** The configuration. */
111         private Configuration configuration;
112
113         /** Whether we’re currently saving the configuration. */
114         private boolean storingConfiguration = false;
115
116         /** The identity manager. */
117         private final IdentityManager identityManager;
118
119         /** Interface to freenet. */
120         private final FreenetInterface freenetInterface;
121
122         /** The Sone downloader. */
123         private final SoneDownloader soneDownloader;
124
125         /** The image inserter. */
126         private final ImageInserter imageInserter;
127
128         /** Sone downloader thread-pool. */
129         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
130
131         /** The update checker. */
132         private final UpdateChecker updateChecker;
133
134         /** The trust updater. */
135         private final WebOfTrustUpdater webOfTrustUpdater;
136
137         /** The FCP interface. */
138         private volatile FcpInterface fcpInterface;
139
140         /** The times Sones were followed. */
141         private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
142
143         /** Locked local Sones. */
144         /* synchronize on itself. */
145         private final Set<Sone> lockedSones = new HashSet<Sone>();
146
147         /** Sone inserters. */
148         /* synchronize access on this on sones. */
149         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
150
151         /** Sone rescuers. */
152         /* synchronize access on this on sones. */
153         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
154
155         /** All Sones. */
156         /* synchronize access on this on itself. */
157         private final Map<String, Sone> sones = new HashMap<String, Sone>();
158
159         /** All known Sones. */
160         private final Set<String> knownSones = new HashSet<String>();
161
162         /** All posts. */
163         private final Map<String, Post> posts = new HashMap<String, Post>();
164
165         /** All known posts. */
166         private final Set<String> knownPosts = new HashSet<String>();
167
168         /** All replies. */
169         private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
170
171         /** All known replies. */
172         private final Set<String> knownReplies = new HashSet<String>();
173
174         /** All bookmarked posts. */
175         /* synchronize access on itself. */
176         private final Set<String> bookmarkedPosts = new HashSet<String>();
177
178         /** Trusted identities, sorted by own identities. */
179         private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
180
181         /** All known albums. */
182         private final Map<String, Album> albums = new HashMap<String, Album>();
183
184         /** All known images. */
185         private final Map<String, Image> images = new HashMap<String, Image>();
186
187         /** All temporary images. */
188         private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
189
190         /** Ticker for threads that mark own elements as known. */
191         private final Ticker localElementTicker = new Ticker();
192
193         /** The time the configuration was last touched. */
194         private volatile long lastConfigurationUpdate;
195
196         /**
197          * Creates a new core.
198          *
199          * @param configuration
200          *            The configuration of the core
201          * @param freenetInterface
202          *            The freenet interface
203          * @param identityManager
204          *            The identity manager
205          * @param webOfTrustUpdater
206          *            The WebOfTrust updater
207          * @param eventBus
208          *            The event bus
209          */
210         @Inject
211         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
212                 super("Sone Core");
213                 this.configuration = configuration;
214                 this.freenetInterface = freenetInterface;
215                 this.identityManager = identityManager;
216                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
217                 this.imageInserter = new ImageInserter(this, freenetInterface);
218                 this.updateChecker = new UpdateChecker(freenetInterface);
219                 this.webOfTrustUpdater = webOfTrustUpdater;
220                 this.eventBus = eventBus;
221         }
222
223         //
224         // LISTENER MANAGEMENT
225         //
226
227         /**
228          * Adds a new core listener.
229          *
230          * @param coreListener
231          *            The listener to add
232          */
233         public void addCoreListener(CoreListener coreListener) {
234                 coreListenerManager.addListener(coreListener);
235         }
236
237         /**
238          * Removes a core listener.
239          *
240          * @param coreListener
241          *            The listener to remove
242          */
243         public void removeCoreListener(CoreListener coreListener) {
244                 coreListenerManager.removeListener(coreListener);
245         }
246
247         //
248         // ACCESSORS
249         //
250
251         /**
252          * Returns the time Sone was started.
253          *
254          * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
255          */
256         public long getStartupTime() {
257                 return startupTime;
258         }
259
260         /**
261          * Sets the configuration to use. This will automatically save the current
262          * configuration to the given configuration.
263          *
264          * @param configuration
265          *            The new configuration to use
266          */
267         public void setConfiguration(Configuration configuration) {
268                 this.configuration = configuration;
269                 touchConfiguration();
270         }
271
272         /**
273          * Returns the options used by the core.
274          *
275          * @return The options of the core
276          */
277         public Preferences getPreferences() {
278                 return preferences;
279         }
280
281         /**
282          * Returns the identity manager used by the core.
283          *
284          * @return The identity manager
285          */
286         public IdentityManager getIdentityManager() {
287                 return identityManager;
288         }
289
290         /**
291          * Returns the update checker.
292          *
293          * @return The update checker
294          */
295         public UpdateChecker getUpdateChecker() {
296                 return updateChecker;
297         }
298
299         /**
300          * Sets the FCP interface to use.
301          *
302          * @param fcpInterface
303          *            The FCP interface to use
304          */
305         public void setFcpInterface(FcpInterface fcpInterface) {
306                 this.fcpInterface = fcpInterface;
307         }
308
309         /**
310          * Returns the Sone rescuer for the given local Sone.
311          *
312          * @param sone
313          *            The local Sone to get the rescuer for
314          * @return The Sone rescuer for the given Sone
315          */
316         public SoneRescuer getSoneRescuer(Sone sone) {
317                 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
318                 synchronized (sones) {
319                         SoneRescuer soneRescuer = soneRescuers.get(sone);
320                         if (soneRescuer == null) {
321                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
322                                 soneRescuers.put(sone, soneRescuer);
323                                 soneRescuer.start();
324                         }
325                         return soneRescuer;
326                 }
327         }
328
329         /**
330          * Returns whether the given Sone is currently locked.
331          *
332          * @param sone
333          *            The sone to check
334          * @return {@code true} if the Sone is locked, {@code false} if it is not
335          */
336         public boolean isLocked(Sone sone) {
337                 synchronized (lockedSones) {
338                         return lockedSones.contains(sone);
339                 }
340         }
341
342         /**
343          * Returns all Sones, remote and local.
344          *
345          * @return All Sones
346          */
347         public Set<Sone> getSones() {
348                 return new HashSet<Sone>(sones.values());
349         }
350
351         /**
352          * Returns the Sone with the given ID, regardless whether it’s local or
353          * remote.
354          *
355          * @param id
356          *            The ID of the Sone to get
357          * @return The Sone with the given ID, or {@code null} if there is no such
358          *         Sone
359          */
360         public Sone getSone(String id) {
361                 return getSone(id, true);
362         }
363
364         /**
365          * Returns the Sone with the given ID, regardless whether it’s local or
366          * remote.
367          *
368          * @param id
369          *            The ID of the Sone to get
370          * @param create
371          *            {@code true} to create a new Sone if none exists,
372          *            {@code false} to return {@code null} if a Sone with the given
373          *            ID does not exist
374          * @return The Sone with the given ID, or {@code null} if there is no such
375          *         Sone
376          */
377         @Override
378         public Sone getSone(String id, boolean create) {
379                 synchronized (sones) {
380                         if (!sones.containsKey(id)) {
381                                 Sone sone = new Sone(id, false);
382                                 sones.put(id, sone);
383                         }
384                         return sones.get(id);
385                 }
386         }
387
388         /**
389          * Checks whether the core knows a Sone with the given ID.
390          *
391          * @param id
392          *            The ID of the Sone
393          * @return {@code true} if there is a Sone with the given ID, {@code false}
394          *         otherwise
395          */
396         public boolean hasSone(String id) {
397                 synchronized (sones) {
398                         return sones.containsKey(id);
399                 }
400         }
401
402         /**
403          * Returns all local Sones.
404          *
405          * @return All local Sones
406          */
407         public Collection<Sone> getLocalSones() {
408                 synchronized (sones) {
409                         return Collections2.filter(sones.values(), new Predicate<Sone>() {
410
411                                 @Override
412                                 public boolean apply(Sone sone) {
413                                         return sone.isLocal();
414                                 }
415                         });
416                 }
417         }
418
419         /**
420          * Returns the local Sone with the given ID, optionally creating a new Sone.
421          *
422          * @param id
423          *            The ID of the Sone
424          * @param create
425          *            {@code true} to create a new Sone if none exists,
426          *            {@code false} to return null if none exists
427          * @return The Sone with the given ID, or {@code null}
428          */
429         public Sone getLocalSone(String id, boolean create) {
430                 synchronized (sones) {
431                         Sone sone = sones.get(id);
432                         if ((sone == null) && create) {
433                                 sone = new Sone(id, true);
434                                 sones.put(id, sone);
435                         }
436                         if ((sone != null) && !sone.isLocal()) {
437                                 sone = new Sone(id, true);
438                                 sones.put(id, sone);
439                         }
440                         return sone;
441                 }
442         }
443
444         /**
445          * Returns all remote Sones.
446          *
447          * @return All remote Sones
448          */
449         public Collection<Sone> getRemoteSones() {
450                 synchronized (sones) {
451                         return Collections2.filter(sones.values(), new Predicate<Sone>() {
452
453                                 @Override
454                                 public boolean apply(Sone sone) {
455                                         return !sone.isLocal();
456                                 }
457                         });
458                 }
459         }
460
461         /**
462          * Returns the remote Sone with the given ID.
463          *
464          * @param id
465          *            The ID of the remote Sone to get
466          * @param create
467          *            {@code true} to always create a Sone, {@code false} to return
468          *            {@code null} if no Sone with the given ID exists
469          * @return The Sone with the given ID
470          */
471         public Sone getRemoteSone(String id, boolean create) {
472                 synchronized (sones) {
473                         Sone sone = sones.get(id);
474                         if ((sone == null) && create && (id != null) && (id.length() == 43)) {
475                                 sone = new Sone(id, false);
476                                 sones.put(id, sone);
477                         }
478                         return sone;
479                 }
480         }
481
482         /**
483          * Returns whether the given Sone has been modified.
484          *
485          * @param sone
486          *            The Sone to check for modifications
487          * @return {@code true} if a modification has been detected in the Sone,
488          *         {@code false} otherwise
489          */
490         public boolean isModifiedSone(Sone sone) {
491                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
492         }
493
494         /**
495          * Returns the time when the given was first followed by any local Sone.
496          *
497          * @param sone
498          *            The Sone to get the time for
499          * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
500          *         been followed, or {@link Long#MAX_VALUE}
501          */
502         public long getSoneFollowingTime(Sone sone) {
503                 synchronized (soneFollowingTimes) {
504                         if (soneFollowingTimes.containsKey(sone)) {
505                                 return soneFollowingTimes.get(sone);
506                         }
507                         return Long.MAX_VALUE;
508                 }
509         }
510
511         /**
512          * Returns whether the target Sone is trusted by the origin Sone.
513          *
514          * @param origin
515          *            The origin Sone
516          * @param target
517          *            The target Sone
518          * @return {@code true} if the target Sone is trusted by the origin Sone
519          */
520         public boolean isSoneTrusted(Sone origin, Sone target) {
521                 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
522                 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
523         }
524
525         /**
526          * Returns the post with the given ID.
527          *
528          * @param postId
529          *            The ID of the post to get
530          * @return The post with the given ID, or a new post with the given ID
531          */
532         public Post getPost(String postId) {
533                 return getPost(postId, true);
534         }
535
536         /**
537          * Returns the post with the given ID, optionally creating a new post.
538          *
539          * @param postId
540          *            The ID of the post to get
541          * @param create
542          *            {@code true} it create a new post if no post with the given ID
543          *            exists, {@code false} to return {@code null}
544          * @return The post, or {@code null} if there is no such post
545          */
546         @Override
547         public Post getPost(String postId, boolean create) {
548                 synchronized (posts) {
549                         Post post = posts.get(postId);
550                         if ((post == null) && create) {
551                                 post = new PostImpl(postId);
552                                 posts.put(postId, post);
553                         }
554                         return post;
555                 }
556         }
557
558         /**
559          * Returns all posts that have the given Sone as recipient.
560          *
561          * @see Post#getRecipient()
562          * @param recipient
563          *            The recipient of the posts
564          * @return All posts that have the given Sone as recipient
565          */
566         public Set<Post> getDirectedPosts(Sone recipient) {
567                 Validation.begin().isNotNull("Recipient", recipient).check();
568                 Set<Post> directedPosts = new HashSet<Post>();
569                 synchronized (posts) {
570                         for (Post post : posts.values()) {
571                                 if (recipient.equals(post.getRecipient())) {
572                                         directedPosts.add(post);
573                                 }
574                         }
575                 }
576                 return directedPosts;
577         }
578
579         /**
580          * Returns the reply with the given ID. If there is no reply with the given
581          * ID yet, a new one is created, unless {@code create} is false in which
582          * case {@code null} is returned.
583          *
584          * @param replyId
585          *            The ID of the reply to get
586          * @param create
587          *            {@code true} to always return a {@link Reply}, {@code false}
588          *            to return {@code null} if no reply can be found
589          * @return The reply, or {@code null} if there is no such reply
590          */
591         public PostReply getPostReply(String replyId, boolean create) {
592                 synchronized (replies) {
593                         PostReply reply = replies.get(replyId);
594                         if (create && (reply == null)) {
595                                 reply = new PostReply(replyId);
596                                 replies.put(replyId, reply);
597                         }
598                         return reply;
599                 }
600         }
601
602         /**
603          * Returns all replies for the given post, order ascending by time.
604          *
605          * @param post
606          *            The post to get all replies for
607          * @return All replies for the given post
608          */
609         public List<PostReply> getReplies(Post post) {
610                 Set<Sone> sones = getSones();
611                 List<PostReply> replies = new ArrayList<PostReply>();
612                 for (Sone sone : sones) {
613                         for (PostReply reply : sone.getReplies()) {
614                                 if (reply.getPost().equals(post)) {
615                                         replies.add(reply);
616                                 }
617                         }
618                 }
619                 Collections.sort(replies, Reply.TIME_COMPARATOR);
620                 return replies;
621         }
622
623         /**
624          * Returns all Sones that have liked the given post.
625          *
626          * @param post
627          *            The post to get the liking Sones for
628          * @return The Sones that like the given post
629          */
630         public Set<Sone> getLikes(Post post) {
631                 Set<Sone> sones = new HashSet<Sone>();
632                 for (Sone sone : getSones()) {
633                         if (sone.getLikedPostIds().contains(post.getId())) {
634                                 sones.add(sone);
635                         }
636                 }
637                 return sones;
638         }
639
640         /**
641          * Returns all Sones that have liked the given reply.
642          *
643          * @param reply
644          *            The reply to get the liking Sones for
645          * @return The Sones that like the given reply
646          */
647         public Set<Sone> getLikes(PostReply reply) {
648                 Set<Sone> sones = new HashSet<Sone>();
649                 for (Sone sone : getSones()) {
650                         if (sone.getLikedReplyIds().contains(reply.getId())) {
651                                 sones.add(sone);
652                         }
653                 }
654                 return sones;
655         }
656
657         /**
658          * Returns whether the given post is bookmarked.
659          *
660          * @param post
661          *            The post to check
662          * @return {@code true} if the given post is bookmarked, {@code false}
663          *         otherwise
664          */
665         public boolean isBookmarked(Post post) {
666                 return isPostBookmarked(post.getId());
667         }
668
669         /**
670          * Returns whether the post with the given ID is bookmarked.
671          *
672          * @param id
673          *            The ID of the post to check
674          * @return {@code true} if the post with the given ID is bookmarked,
675          *         {@code false} otherwise
676          */
677         public boolean isPostBookmarked(String id) {
678                 synchronized (bookmarkedPosts) {
679                         return bookmarkedPosts.contains(id);
680                 }
681         }
682
683         /**
684          * Returns all currently known bookmarked posts.
685          *
686          * @return All bookmarked posts
687          */
688         public Set<Post> getBookmarkedPosts() {
689                 Set<Post> posts = new HashSet<Post>();
690                 synchronized (bookmarkedPosts) {
691                         for (String bookmarkedPostId : bookmarkedPosts) {
692                                 Post post = getPost(bookmarkedPostId, false);
693                                 if (post != null) {
694                                         posts.add(post);
695                                 }
696                         }
697                 }
698                 return posts;
699         }
700
701         /**
702          * Returns the album with the given ID, creating a new album if no album
703          * with the given ID can be found.
704          *
705          * @param albumId
706          *            The ID of the album
707          * @return The album with the given ID
708          */
709         public Album getAlbum(String albumId) {
710                 return getAlbum(albumId, true);
711         }
712
713         /**
714          * Returns the album with the given ID, optionally creating a new album if
715          * an album with the given ID can not be found.
716          *
717          * @param albumId
718          *            The ID of the album
719          * @param create
720          *            {@code true} to create a new album if none exists for the
721          *            given ID
722          * @return The album with the given ID, or {@code null} if no album with the
723          *         given ID exists and {@code create} is {@code false}
724          */
725         public Album getAlbum(String albumId, boolean create) {
726                 synchronized (albums) {
727                         Album album = albums.get(albumId);
728                         if (create && (album == null)) {
729                                 album = new Album(albumId);
730                                 albums.put(albumId, album);
731                         }
732                         return album;
733                 }
734         }
735
736         /**
737          * Returns the image with the given ID, creating it if necessary.
738          *
739          * @param imageId
740          *            The ID of the image
741          * @return The image with the given ID
742          */
743         public Image getImage(String imageId) {
744                 return getImage(imageId, true);
745         }
746
747         /**
748          * Returns the image with the given ID, optionally creating it if it does
749          * not exist.
750          *
751          * @param imageId
752          *            The ID of the image
753          * @param create
754          *            {@code true} to create an image if none exists with the given
755          *            ID
756          * @return The image with the given ID, or {@code null} if none exists and
757          *         none was created
758          */
759         public Image getImage(String imageId, boolean create) {
760                 synchronized (images) {
761                         Image image = images.get(imageId);
762                         if (create && (image == null)) {
763                                 image = new Image(imageId);
764                                 images.put(imageId, image);
765                         }
766                         return image;
767                 }
768         }
769
770         /**
771          * Returns the temporary image with the given ID.
772          *
773          * @param imageId
774          *            The ID of the temporary image
775          * @return The temporary image, or {@code null} if there is no temporary
776          *         image with the given ID
777          */
778         public TemporaryImage getTemporaryImage(String imageId) {
779                 synchronized (temporaryImages) {
780                         return temporaryImages.get(imageId);
781                 }
782         }
783
784         //
785         // ACTIONS
786         //
787
788         /**
789          * Locks the given Sone. A locked Sone will not be inserted by
790          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
791          * again.
792          *
793          * @param sone
794          *            The sone to lock
795          */
796         public void lockSone(Sone sone) {
797                 synchronized (lockedSones) {
798                         if (lockedSones.add(sone)) {
799                                 coreListenerManager.fireSoneLocked(sone);
800                         }
801                 }
802         }
803
804         /**
805          * Unlocks the given Sone.
806          *
807          * @see #lockSone(Sone)
808          * @param sone
809          *            The sone to unlock
810          */
811         public void unlockSone(Sone sone) {
812                 synchronized (lockedSones) {
813                         if (lockedSones.remove(sone)) {
814                                 coreListenerManager.fireSoneUnlocked(sone);
815                         }
816                 }
817         }
818
819         /**
820          * Adds a local Sone from the given own identity.
821          *
822          * @param ownIdentity
823          *            The own identity to create a Sone from
824          * @return The added (or already existing) Sone
825          */
826         public Sone addLocalSone(OwnIdentity ownIdentity) {
827                 if (ownIdentity == null) {
828                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
829                         return null;
830                 }
831                 synchronized (sones) {
832                         final Sone sone;
833                         try {
834                                 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
835                         } catch (MalformedURLException mue1) {
836                                 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
837                                 return null;
838                         }
839                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
840                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
841                         sone.setKnown(true);
842                         /* TODO - load posts ’n stuff */
843                         sones.put(ownIdentity.getId(), sone);
844                         final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
845                         soneInserter.addSoneInsertListener(this);
846                         soneInserters.put(sone, soneInserter);
847                         sone.setStatus(SoneStatus.idle);
848                         loadSone(sone);
849                         soneInserter.start();
850                         return sone;
851                 }
852         }
853
854         /**
855          * Creates a new Sone for the given own identity.
856          *
857          * @param ownIdentity
858          *            The own identity to create a Sone for
859          * @return The created Sone
860          */
861         public Sone createSone(OwnIdentity ownIdentity) {
862                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
863                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
864                         return null;
865                 }
866                 Sone sone = addLocalSone(ownIdentity);
867                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
868                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
869                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
870                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
871                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
872                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
873
874                 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
875                 touchConfiguration();
876                 return sone;
877         }
878
879         /**
880          * Adds the Sone of the given identity.
881          *
882          * @param identity
883          *            The identity whose Sone to add
884          * @return The added or already existing Sone
885          */
886         public Sone addRemoteSone(Identity identity) {
887                 if (identity == null) {
888                         logger.log(Level.WARNING, "Given Identity is null!");
889                         return null;
890                 }
891                 synchronized (sones) {
892                         final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
893                         boolean newSone = sone.getRequestUri() == null;
894                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
895                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
896                         if (newSone) {
897                                 synchronized (knownSones) {
898                                         newSone = !knownSones.contains(sone.getId());
899                                 }
900                                 sone.setKnown(!newSone);
901                                 if (newSone) {
902                                         eventBus.post(new NewSoneFoundEvent(sone));
903                                         for (Sone localSone : getLocalSones()) {
904                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
905                                                         followSone(localSone, sone);
906                                                 }
907                                         }
908                                 }
909                         }
910                         soneDownloader.addSone(sone);
911                         soneDownloaders.execute(new Runnable() {
912
913                                 @Override
914                                 @SuppressWarnings("synthetic-access")
915                                 public void run() {
916                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
917                                 }
918
919                         });
920                         return sone;
921                 }
922         }
923
924         /**
925          * Lets the given local Sone follow the Sone with the given ID.
926          *
927          * @param sone
928          *            The local Sone that should follow another Sone
929          * @param soneId
930          *            The ID of the Sone to follow
931          */
932         public void followSone(Sone sone, String soneId) {
933                 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
934                 Sone followedSone = getSone(soneId, true);
935                 if (followedSone == null) {
936                         logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
937                         return;
938                 }
939                 followSone(sone, getSone(soneId));
940         }
941
942         /**
943          * Lets the given local Sone follow the other given Sone. If the given Sone
944          * was not followed by any local Sone before, this will mark all elements of
945          * the followed Sone as read that have been created before the current
946          * moment.
947          *
948          * @param sone
949          *            The local Sone that should follow the other Sone
950          * @param followedSone
951          *            The Sone that should be followed
952          */
953         public void followSone(Sone sone, Sone followedSone) {
954                 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
955                 sone.addFriend(followedSone.getId());
956                 synchronized (soneFollowingTimes) {
957                         if (!soneFollowingTimes.containsKey(followedSone)) {
958                                 long now = System.currentTimeMillis();
959                                 soneFollowingTimes.put(followedSone, now);
960                                 for (Post post : followedSone.getPosts()) {
961                                         if (post.getTime() < now) {
962                                                 markPostKnown(post);
963                                         }
964                                 }
965                                 for (PostReply reply : followedSone.getReplies()) {
966                                         if (reply.getTime() < now) {
967                                                 markReplyKnown(reply);
968                                         }
969                                 }
970                         }
971                 }
972                 touchConfiguration();
973         }
974
975         /**
976          * Lets the given local Sone unfollow the Sone with the given ID.
977          *
978          * @param sone
979          *            The local Sone that should unfollow another Sone
980          * @param soneId
981          *            The ID of the Sone being unfollowed
982          */
983         public void unfollowSone(Sone sone, String soneId) {
984                 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
985                 unfollowSone(sone, getSone(soneId, false));
986         }
987
988         /**
989          * Lets the given local Sone unfollow the other given Sone. If the given
990          * local Sone is the last local Sone that followed the given Sone, its
991          * following time will be removed.
992          *
993          * @param sone
994          *            The local Sone that should unfollow another Sone
995          * @param unfollowedSone
996          *            The Sone being unfollowed
997          */
998         public void unfollowSone(Sone sone, Sone unfollowedSone) {
999                 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1000                 sone.removeFriend(unfollowedSone.getId());
1001                 boolean unfollowedSoneStillFollowed = false;
1002                 for (Sone localSone : getLocalSones()) {
1003                         unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1004                 }
1005                 if (!unfollowedSoneStillFollowed) {
1006                         synchronized (soneFollowingTimes) {
1007                                 soneFollowingTimes.remove(unfollowedSone);
1008                         }
1009                 }
1010                 touchConfiguration();
1011         }
1012
1013         /**
1014          * Sets the trust value of the given origin Sone for the target Sone.
1015          *
1016          * @param origin
1017          *            The origin Sone
1018          * @param target
1019          *            The target Sone
1020          * @param trustValue
1021          *            The trust value (from {@code -100} to {@code 100})
1022          */
1023         public void setTrust(Sone origin, Sone target, int trustValue) {
1024                 Validation.begin().isNotNull("Trust Origin", origin).check().isInstanceOf("Trust Origin", origin.getIdentity(), OwnIdentity.class).isNotNull("Trust Target", target).isLessOrEqual("Trust Value", trustValue, 100).isGreaterOrEqual("Trust Value", trustValue, -100).check();
1025                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1026         }
1027
1028         /**
1029          * Removes any trust assignment for the given target Sone.
1030          *
1031          * @param origin
1032          *            The trust origin
1033          * @param target
1034          *            The trust target
1035          */
1036         public void removeTrust(Sone origin, Sone target) {
1037                 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1038                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1039         }
1040
1041         /**
1042          * Assigns the configured positive trust value for the given target.
1043          *
1044          * @param origin
1045          *            The trust origin
1046          * @param target
1047          *            The trust target
1048          */
1049         public void trustSone(Sone origin, Sone target) {
1050                 setTrust(origin, target, preferences.getPositiveTrust());
1051         }
1052
1053         /**
1054          * Assigns the configured negative trust value for the given target.
1055          *
1056          * @param origin
1057          *            The trust origin
1058          * @param target
1059          *            The trust target
1060          */
1061         public void distrustSone(Sone origin, Sone target) {
1062                 setTrust(origin, target, preferences.getNegativeTrust());
1063         }
1064
1065         /**
1066          * Removes the trust assignment for the given target.
1067          *
1068          * @param origin
1069          *            The trust origin
1070          * @param target
1071          *            The trust target
1072          */
1073         public void untrustSone(Sone origin, Sone target) {
1074                 removeTrust(origin, target);
1075         }
1076
1077         /**
1078          * Updates the stored Sone with the given Sone.
1079          *
1080          * @param sone
1081          *            The updated Sone
1082          */
1083         public void updateSone(Sone sone) {
1084                 updateSone(sone, false);
1085         }
1086
1087         /**
1088          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1089          * {@code true}, an older Sone than the current Sone can be given to restore
1090          * an old state.
1091          *
1092          * @param sone
1093          *            The Sone to update
1094          * @param soneRescueMode
1095          *            {@code true} if the stored Sone should be updated regardless
1096          *            of the age of the given Sone
1097          */
1098         public void updateSone(Sone sone, boolean soneRescueMode) {
1099                 if (hasSone(sone.getId())) {
1100                         Sone storedSone = getSone(sone.getId());
1101                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1102                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1103                                 return;
1104                         }
1105                         synchronized (posts) {
1106                                 if (!soneRescueMode) {
1107                                         for (Post post : storedSone.getPosts()) {
1108                                                 posts.remove(post.getId());
1109                                                 if (!sone.getPosts().contains(post)) {
1110                                                         coreListenerManager.firePostRemoved(post);
1111                                                 }
1112                                         }
1113                                 }
1114                                 List<Post> storedPosts = storedSone.getPosts();
1115                                 synchronized (knownPosts) {
1116                                         for (Post post : sone.getPosts()) {
1117                                                 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1118                                                 if (!storedPosts.contains(post)) {
1119                                                         if (post.getTime() < getSoneFollowingTime(sone)) {
1120                                                                 knownPosts.add(post.getId());
1121                                                                 post.setKnown(true);
1122                                                         } else if (!knownPosts.contains(post.getId())) {
1123                                                                 eventBus.post(new NewPostFoundEvent(post));
1124                                                         }
1125                                                 }
1126                                                 posts.put(post.getId(), post);
1127                                         }
1128                                 }
1129                         }
1130                         synchronized (replies) {
1131                                 if (!soneRescueMode) {
1132                                         for (PostReply reply : storedSone.getReplies()) {
1133                                                 replies.remove(reply.getId());
1134                                                 if (!sone.getReplies().contains(reply)) {
1135                                                         coreListenerManager.fireReplyRemoved(reply);
1136                                                 }
1137                                         }
1138                                 }
1139                                 Set<PostReply> storedReplies = storedSone.getReplies();
1140                                 synchronized (knownReplies) {
1141                                         for (PostReply reply : sone.getReplies()) {
1142                                                 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1143                                                 if (!storedReplies.contains(reply)) {
1144                                                         if (reply.getTime() < getSoneFollowingTime(sone)) {
1145                                                                 knownReplies.add(reply.getId());
1146                                                                 reply.setKnown(true);
1147                                                         } else if (!knownReplies.contains(reply.getId())) {
1148                                                                 eventBus.post(new NewPostReplyFoundEvent(reply));
1149                                                         }
1150                                                 }
1151                                                 replies.put(reply.getId(), reply);
1152                                         }
1153                                 }
1154                         }
1155                         synchronized (albums) {
1156                                 synchronized (images) {
1157                                         for (Album album : storedSone.getAlbums()) {
1158                                                 albums.remove(album.getId());
1159                                                 for (Image image : album.getImages()) {
1160                                                         images.remove(image.getId());
1161                                                 }
1162                                         }
1163                                         for (Album album : sone.getAlbums()) {
1164                                                 albums.put(album.getId(), album);
1165                                                 for (Image image : album.getImages()) {
1166                                                         images.put(image.getId(), image);
1167                                                 }
1168                                         }
1169                                 }
1170                         }
1171                         synchronized (storedSone) {
1172                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1173                                         storedSone.setTime(sone.getTime());
1174                                 }
1175                                 storedSone.setClient(sone.getClient());
1176                                 storedSone.setProfile(sone.getProfile());
1177                                 if (soneRescueMode) {
1178                                         for (Post post : sone.getPosts()) {
1179                                                 storedSone.addPost(post);
1180                                         }
1181                                         for (PostReply reply : sone.getReplies()) {
1182                                                 storedSone.addReply(reply);
1183                                         }
1184                                         for (String likedPostId : sone.getLikedPostIds()) {
1185                                                 storedSone.addLikedPostId(likedPostId);
1186                                         }
1187                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1188                                                 storedSone.addLikedReplyId(likedReplyId);
1189                                         }
1190                                         for (Album album : sone.getAlbums()) {
1191                                                 storedSone.addAlbum(album);
1192                                         }
1193                                 } else {
1194                                         storedSone.setPosts(sone.getPosts());
1195                                         storedSone.setReplies(sone.getReplies());
1196                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1197                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1198                                         storedSone.setAlbums(sone.getAlbums());
1199                                 }
1200                                 storedSone.setLatestEdition(sone.getLatestEdition());
1201                         }
1202                 }
1203         }
1204
1205         /**
1206          * Deletes the given Sone. This will remove the Sone from the
1207          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1208          * remove the context from its identity.
1209          *
1210          * @param sone
1211          *            The Sone to delete
1212          */
1213         public void deleteSone(Sone sone) {
1214                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1215                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1216                         return;
1217                 }
1218                 synchronized (sones) {
1219                         if (!getLocalSones().contains(sone)) {
1220                                 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1221                                 return;
1222                         }
1223                         sones.remove(sone.getId());
1224                         SoneInserter soneInserter = soneInserters.remove(sone);
1225                         soneInserter.removeSoneInsertListener(this);
1226                         soneInserter.stop();
1227                 }
1228                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1229                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1230                 try {
1231                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1232                 } catch (ConfigurationException ce1) {
1233                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1234                 }
1235         }
1236
1237         /**
1238          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1239          * known} before, a {@link MarkSoneKnownEvent} is fired.
1240          *
1241          * @param sone
1242          *            The Sone to mark as known
1243          */
1244         public void markSoneKnown(Sone sone) {
1245                 if (!sone.isKnown()) {
1246                         sone.setKnown(true);
1247                         synchronized (knownSones) {
1248                                 knownSones.add(sone.getId());
1249                         }
1250                         eventBus.post(new MarkSoneKnownEvent(sone));
1251                         touchConfiguration();
1252                 }
1253         }
1254
1255         /**
1256          * Loads and updates the given Sone from the configuration. If any error is
1257          * encountered, loading is aborted and the given Sone is not changed.
1258          *
1259          * @param sone
1260          *            The Sone to load and update
1261          */
1262         public void loadSone(Sone sone) {
1263                 if (!sone.isLocal()) {
1264                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1265                         return;
1266                 }
1267
1268                 /* initialize options. */
1269                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1270                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1271                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1272                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1273                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1274                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1275
1276                 /* load Sone. */
1277                 String sonePrefix = "Sone/" + sone.getId();
1278                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1279                 if (soneTime == null) {
1280                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1281                         return;
1282                 }
1283                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1284
1285                 /* load profile. */
1286                 Profile profile = new Profile(sone);
1287                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1288                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1289                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1290                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1291                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1292                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1293
1294                 /* load profile fields. */
1295                 while (true) {
1296                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1297                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1298                         if (fieldName == null) {
1299                                 break;
1300                         }
1301                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1302                         profile.addField(fieldName).setValue(fieldValue);
1303                 }
1304
1305                 /* load posts. */
1306                 Set<Post> posts = new HashSet<Post>();
1307                 while (true) {
1308                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1309                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1310                         if (postId == null) {
1311                                 break;
1312                         }
1313                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1314                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1315                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1316                         if ((postTime == 0) || (postText == null)) {
1317                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1318                                 return;
1319                         }
1320                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1321                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1322                                 post.setRecipient(getSone(postRecipientId));
1323                         }
1324                         posts.add(post);
1325                 }
1326
1327                 /* load replies. */
1328                 Set<PostReply> replies = new HashSet<PostReply>();
1329                 while (true) {
1330                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1331                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1332                         if (replyId == null) {
1333                                 break;
1334                         }
1335                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1336                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1337                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1338                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1339                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1340                                 return;
1341                         }
1342                         replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1343                 }
1344
1345                 /* load post likes. */
1346                 Set<String> likedPostIds = new HashSet<String>();
1347                 while (true) {
1348                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1349                         if (likedPostId == null) {
1350                                 break;
1351                         }
1352                         likedPostIds.add(likedPostId);
1353                 }
1354
1355                 /* load reply likes. */
1356                 Set<String> likedReplyIds = new HashSet<String>();
1357                 while (true) {
1358                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1359                         if (likedReplyId == null) {
1360                                 break;
1361                         }
1362                         likedReplyIds.add(likedReplyId);
1363                 }
1364
1365                 /* load friends. */
1366                 Set<String> friends = new HashSet<String>();
1367                 while (true) {
1368                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1369                         if (friendId == null) {
1370                                 break;
1371                         }
1372                         friends.add(friendId);
1373                 }
1374
1375                 /* load albums. */
1376                 List<Album> topLevelAlbums = new ArrayList<Album>();
1377                 int albumCounter = 0;
1378                 while (true) {
1379                         String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1380                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1381                         if (albumId == null) {
1382                                 break;
1383                         }
1384                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1385                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1386                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1387                         String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1388                         if ((albumTitle == null) || (albumDescription == null)) {
1389                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1390                                 return;
1391                         }
1392                         Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1393                         if (albumParentId != null) {
1394                                 Album parentAlbum = getAlbum(albumParentId, false);
1395                                 if (parentAlbum == null) {
1396                                         logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1397                                         return;
1398                                 }
1399                                 parentAlbum.addAlbum(album);
1400                         } else {
1401                                 if (!topLevelAlbums.contains(album)) {
1402                                         topLevelAlbums.add(album);
1403                                 }
1404                         }
1405                 }
1406
1407                 /* load images. */
1408                 int imageCounter = 0;
1409                 while (true) {
1410                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1411                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1412                         if (imageId == null) {
1413                                 break;
1414                         }
1415                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1416                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1417                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1418                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1419                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1420                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1421                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1422                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1423                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1424                                 return;
1425                         }
1426                         Album album = getAlbum(albumId, false);
1427                         if (album == null) {
1428                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1429                                 return;
1430                         }
1431                         Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1432                         image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1433                         album.addImage(image);
1434                 }
1435
1436                 /* load avatar. */
1437                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1438                 if (avatarId != null) {
1439                         profile.setAvatar(getImage(avatarId, false));
1440                 }
1441
1442                 /* load options. */
1443                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1444                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1445                 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1446                 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1447                 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1448                 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1449
1450                 /* if we’re still here, Sone was loaded successfully. */
1451                 synchronized (sone) {
1452                         sone.setTime(soneTime);
1453                         sone.setProfile(profile);
1454                         sone.setPosts(posts);
1455                         sone.setReplies(replies);
1456                         sone.setLikePostIds(likedPostIds);
1457                         sone.setLikeReplyIds(likedReplyIds);
1458                         for (String friendId : friends) {
1459                                 followSone(sone, friendId);
1460                         }
1461                         sone.setAlbums(topLevelAlbums);
1462                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1463                 }
1464                 synchronized (knownSones) {
1465                         for (String friend : friends) {
1466                                 knownSones.add(friend);
1467                         }
1468                 }
1469                 synchronized (knownPosts) {
1470                         for (Post post : posts) {
1471                                 knownPosts.add(post.getId());
1472                         }
1473                 }
1474                 synchronized (knownReplies) {
1475                         for (PostReply reply : replies) {
1476                                 knownReplies.add(reply.getId());
1477                         }
1478                 }
1479         }
1480
1481         /**
1482          * Creates a new post.
1483          *
1484          * @param sone
1485          *            The Sone that creates the post
1486          * @param text
1487          *            The text of the post
1488          * @return The created post
1489          */
1490         public Post createPost(Sone sone, String text) {
1491                 return createPost(sone, System.currentTimeMillis(), text);
1492         }
1493
1494         /**
1495          * Creates a new post.
1496          *
1497          * @param sone
1498          *            The Sone that creates the post
1499          * @param time
1500          *            The time of the post
1501          * @param text
1502          *            The text of the post
1503          * @return The created post
1504          */
1505         public Post createPost(Sone sone, long time, String text) {
1506                 return createPost(sone, null, time, text);
1507         }
1508
1509         /**
1510          * Creates a new post.
1511          *
1512          * @param sone
1513          *            The Sone that creates the post
1514          * @param recipient
1515          *            The recipient Sone, or {@code null} if this post does not have
1516          *            a recipient
1517          * @param text
1518          *            The text of the post
1519          * @return The created post
1520          */
1521         public Post createPost(Sone sone, Sone recipient, String text) {
1522                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1523         }
1524
1525         /**
1526          * Creates a new post.
1527          *
1528          * @param sone
1529          *            The Sone that creates the post
1530          * @param recipient
1531          *            The recipient Sone, or {@code null} if this post does not have
1532          *            a recipient
1533          * @param time
1534          *            The time of the post
1535          * @param text
1536          *            The text of the post
1537          * @return The created post
1538          */
1539         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1540                 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1541                 if (!sone.isLocal()) {
1542                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1543                         return null;
1544                 }
1545                 final Post post = new PostImpl(sone, time, text);
1546                 if (recipient != null) {
1547                         post.setRecipient(recipient);
1548                 }
1549                 synchronized (posts) {
1550                         posts.put(post.getId(), post);
1551                 }
1552                 eventBus.post(new NewPostFoundEvent(post));
1553                 sone.addPost(post);
1554                 touchConfiguration();
1555                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1556
1557                         /**
1558                          * {@inheritDoc}
1559                          */
1560                         @Override
1561                         public void run() {
1562                                 markPostKnown(post);
1563                         }
1564                 }, "Mark " + post + " read.");
1565                 return post;
1566         }
1567
1568         /**
1569          * Deletes the given post.
1570          *
1571          * @param post
1572          *            The post to delete
1573          */
1574         public void deletePost(Post post) {
1575                 if (!post.getSone().isLocal()) {
1576                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1577                         return;
1578                 }
1579                 post.getSone().removePost(post);
1580                 synchronized (posts) {
1581                         posts.remove(post.getId());
1582                 }
1583                 coreListenerManager.firePostRemoved(post);
1584                 markPostKnown(post);
1585                 touchConfiguration();
1586         }
1587
1588         /**
1589          * Marks the given post as known, if it is currently not a known post
1590          * (according to {@link Post#isKnown()}).
1591          *
1592          * @param post
1593          *            The post to mark as known
1594          */
1595         public void markPostKnown(Post post) {
1596                 post.setKnown(true);
1597                 synchronized (knownPosts) {
1598                         eventBus.post(new MarkPostKnownEvent(post));
1599                         if (knownPosts.add(post.getId())) {
1600                                 touchConfiguration();
1601                         }
1602                 }
1603                 for (PostReply reply : getReplies(post)) {
1604                         markReplyKnown(reply);
1605                 }
1606         }
1607
1608         /**
1609          * Bookmarks the given post.
1610          *
1611          * @param post
1612          *            The post to bookmark
1613          */
1614         public void bookmark(Post post) {
1615                 bookmarkPost(post.getId());
1616         }
1617
1618         /**
1619          * Bookmarks the post with the given ID.
1620          *
1621          * @param id
1622          *            The ID of the post to bookmark
1623          */
1624         public void bookmarkPost(String id) {
1625                 synchronized (bookmarkedPosts) {
1626                         bookmarkedPosts.add(id);
1627                 }
1628         }
1629
1630         /**
1631          * Removes the given post from the bookmarks.
1632          *
1633          * @param post
1634          *            The post to unbookmark
1635          */
1636         public void unbookmark(Post post) {
1637                 unbookmarkPost(post.getId());
1638         }
1639
1640         /**
1641          * Removes the post with the given ID from the bookmarks.
1642          *
1643          * @param id
1644          *            The ID of the post to unbookmark
1645          */
1646         public void unbookmarkPost(String id) {
1647                 synchronized (bookmarkedPosts) {
1648                         bookmarkedPosts.remove(id);
1649                 }
1650         }
1651
1652         /**
1653          * Creates a new reply.
1654          *
1655          * @param sone
1656          *            The Sone that creates the reply
1657          * @param post
1658          *            The post that this reply refers to
1659          * @param text
1660          *            The text of the reply
1661          * @return The created reply
1662          */
1663         public PostReply createReply(Sone sone, Post post, String text) {
1664                 return createReply(sone, post, System.currentTimeMillis(), text);
1665         }
1666
1667         /**
1668          * Creates a new reply.
1669          *
1670          * @param sone
1671          *            The Sone that creates the reply
1672          * @param post
1673          *            The post that this reply refers to
1674          * @param time
1675          *            The time of the reply
1676          * @param text
1677          *            The text of the reply
1678          * @return The created reply
1679          */
1680         public PostReply createReply(Sone sone, Post post, long time, String text) {
1681                 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1682                 if (!sone.isLocal()) {
1683                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1684                         return null;
1685                 }
1686                 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1687                 synchronized (replies) {
1688                         replies.put(reply.getId(), reply);
1689                 }
1690                 synchronized (knownReplies) {
1691                         eventBus.post(new NewPostReplyFoundEvent(reply));
1692                 }
1693                 sone.addReply(reply);
1694                 touchConfiguration();
1695                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1696
1697                         /**
1698                          * {@inheritDoc}
1699                          */
1700                         @Override
1701                         public void run() {
1702                                 markReplyKnown(reply);
1703                         }
1704                 }, "Mark " + reply + " read.");
1705                 return reply;
1706         }
1707
1708         /**
1709          * Deletes the given reply.
1710          *
1711          * @param reply
1712          *            The reply to delete
1713          */
1714         public void deleteReply(PostReply reply) {
1715                 Sone sone = reply.getSone();
1716                 if (!sone.isLocal()) {
1717                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1718                         return;
1719                 }
1720                 synchronized (replies) {
1721                         replies.remove(reply.getId());
1722                 }
1723                 synchronized (knownReplies) {
1724                         markReplyKnown(reply);
1725                         knownReplies.remove(reply.getId());
1726                 }
1727                 sone.removeReply(reply);
1728                 touchConfiguration();
1729         }
1730
1731         /**
1732          * Marks the given reply as known, if it is currently not a known reply
1733          * (according to {@link Reply#isKnown()}).
1734          *
1735          * @param reply
1736          *            The reply to mark as known
1737          */
1738         public void markReplyKnown(PostReply reply) {
1739                 reply.setKnown(true);
1740                 synchronized (knownReplies) {
1741                         eventBus.post(new MarkPostReplyKnownEvent(reply));
1742                         if (knownReplies.add(reply.getId())) {
1743                                 touchConfiguration();
1744                         }
1745                 }
1746         }
1747
1748         /**
1749          * Creates a new top-level album for the given Sone.
1750          *
1751          * @param sone
1752          *            The Sone to create the album for
1753          * @return The new album
1754          */
1755         public Album createAlbum(Sone sone) {
1756                 return createAlbum(sone, null);
1757         }
1758
1759         /**
1760          * Creates a new album for the given Sone.
1761          *
1762          * @param sone
1763          *            The Sone to create the album for
1764          * @param parent
1765          *            The parent of the album (may be {@code null} to create a
1766          *            top-level album)
1767          * @return The new album
1768          */
1769         public Album createAlbum(Sone sone, Album parent) {
1770                 Album album = new Album();
1771                 synchronized (albums) {
1772                         albums.put(album.getId(), album);
1773                 }
1774                 album.setSone(sone);
1775                 if (parent != null) {
1776                         parent.addAlbum(album);
1777                 } else {
1778                         sone.addAlbum(album);
1779                 }
1780                 return album;
1781         }
1782
1783         /**
1784          * Deletes the given album. The owner of the album has to be a local Sone,
1785          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1786          *
1787          * @param album
1788          *            The album to remove
1789          */
1790         public void deleteAlbum(Album album) {
1791                 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1792                 if (!album.isEmpty()) {
1793                         return;
1794                 }
1795                 if (album.getParent() == null) {
1796                         album.getSone().removeAlbum(album);
1797                 } else {
1798                         album.getParent().removeAlbum(album);
1799                 }
1800                 synchronized (albums) {
1801                         albums.remove(album.getId());
1802                 }
1803                 touchConfiguration();
1804         }
1805
1806         /**
1807          * Creates a new image.
1808          *
1809          * @param sone
1810          *            The Sone creating the image
1811          * @param album
1812          *            The album the image will be inserted into
1813          * @param temporaryImage
1814          *            The temporary image to create the image from
1815          * @return The newly created image
1816          */
1817         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1818                 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", sone.isLocal()).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1819                 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1820                 album.addImage(image);
1821                 synchronized (images) {
1822                         images.put(image.getId(), image);
1823                 }
1824                 imageInserter.insertImage(temporaryImage, image);
1825                 return image;
1826         }
1827
1828         /**
1829          * Deletes the given image. This method will also delete a matching
1830          * temporary image.
1831          *
1832          * @see #deleteTemporaryImage(TemporaryImage)
1833          * @param image
1834          *            The image to delete
1835          */
1836         public void deleteImage(Image image) {
1837                 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1838                 deleteTemporaryImage(image.getId());
1839                 image.getAlbum().removeImage(image);
1840                 synchronized (images) {
1841                         images.remove(image.getId());
1842                 }
1843                 touchConfiguration();
1844         }
1845
1846         /**
1847          * Creates a new temporary image.
1848          *
1849          * @param mimeType
1850          *            The MIME type of the temporary image
1851          * @param imageData
1852          *            The encoded data of the image
1853          * @return The temporary image
1854          */
1855         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1856                 TemporaryImage temporaryImage = new TemporaryImage();
1857                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1858                 synchronized (temporaryImages) {
1859                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1860                 }
1861                 return temporaryImage;
1862         }
1863
1864         /**
1865          * Deletes the given temporary image.
1866          *
1867          * @param temporaryImage
1868          *            The temporary image to delete
1869          */
1870         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1871                 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1872                 deleteTemporaryImage(temporaryImage.getId());
1873         }
1874
1875         /**
1876          * Deletes the temporary image with the given ID.
1877          *
1878          * @param imageId
1879          *            The ID of the temporary image to delete
1880          */
1881         public void deleteTemporaryImage(String imageId) {
1882                 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1883                 synchronized (temporaryImages) {
1884                         temporaryImages.remove(imageId);
1885                 }
1886                 Image image = getImage(imageId, false);
1887                 if (image != null) {
1888                         imageInserter.cancelImageInsert(image);
1889                 }
1890         }
1891
1892         /**
1893          * Notifies the core that the configuration, either of the core or of a
1894          * single local Sone, has changed, and that the configuration should be
1895          * saved.
1896          */
1897         public void touchConfiguration() {
1898                 lastConfigurationUpdate = System.currentTimeMillis();
1899         }
1900
1901         //
1902         // SERVICE METHODS
1903         //
1904
1905         /**
1906          * Starts the core.
1907          */
1908         @Override
1909         public void serviceStart() {
1910                 loadConfiguration();
1911                 updateChecker.addUpdateListener(this);
1912                 updateChecker.start();
1913                 identityManager.addIdentityListener(this);
1914                 identityManager.start();
1915                 webOfTrustUpdater.init();
1916                 webOfTrustUpdater.start();
1917         }
1918
1919         /**
1920          * {@inheritDoc}
1921          */
1922         @Override
1923         public void serviceRun() {
1924                 long lastSaved = System.currentTimeMillis();
1925                 while (!shouldStop()) {
1926                         sleep(1000);
1927                         long now = System.currentTimeMillis();
1928                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1929                                 for (Sone localSone : getLocalSones()) {
1930                                         saveSone(localSone);
1931                                 }
1932                                 saveConfiguration();
1933                                 lastSaved = now;
1934                         }
1935                 }
1936         }
1937
1938         /**
1939          * Stops the core.
1940          */
1941         @Override
1942         public void serviceStop() {
1943                 synchronized (sones) {
1944                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1945                                 soneInserter.getValue().removeSoneInsertListener(this);
1946                                 soneInserter.getValue().stop();
1947                                 saveSone(soneInserter.getKey());
1948                         }
1949                 }
1950                 saveConfiguration();
1951                 webOfTrustUpdater.stop();
1952                 updateChecker.stop();
1953                 updateChecker.removeUpdateListener(this);
1954                 soneDownloader.stop();
1955                 identityManager.removeIdentityListener(this);
1956                 identityManager.stop();
1957         }
1958
1959         //
1960         // PRIVATE METHODS
1961         //
1962
1963         /**
1964          * Saves the given Sone. This will persist all local settings for the given
1965          * Sone, such as the friends list and similar, private options.
1966          *
1967          * @param sone
1968          *            The Sone to save
1969          */
1970         private synchronized void saveSone(Sone sone) {
1971                 if (!sone.isLocal()) {
1972                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1973                         return;
1974                 }
1975                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1976                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1977                         return;
1978                 }
1979
1980                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1981                 try {
1982                         /* save Sone into configuration. */
1983                         String sonePrefix = "Sone/" + sone.getId();
1984                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1985                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1986
1987                         /* save profile. */
1988                         Profile profile = sone.getProfile();
1989                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1990                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1991                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1992                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1993                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1994                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1995                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1996
1997                         /* save profile fields. */
1998                         int fieldCounter = 0;
1999                         for (Field profileField : profile.getFields()) {
2000                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2001                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2002                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2003                         }
2004                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2005
2006                         /* save posts. */
2007                         int postCounter = 0;
2008                         for (Post post : sone.getPosts()) {
2009                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2010                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2011                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2012                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2013                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2014                         }
2015                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2016
2017                         /* save replies. */
2018                         int replyCounter = 0;
2019                         for (PostReply reply : sone.getReplies()) {
2020                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2021                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2022                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2023                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2024                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2025                         }
2026                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2027
2028                         /* save post likes. */
2029                         int postLikeCounter = 0;
2030                         for (String postId : sone.getLikedPostIds()) {
2031                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2032                         }
2033                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2034
2035                         /* save reply likes. */
2036                         int replyLikeCounter = 0;
2037                         for (String replyId : sone.getLikedReplyIds()) {
2038                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2039                         }
2040                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2041
2042                         /* save friends. */
2043                         int friendCounter = 0;
2044                         for (String friendId : sone.getFriends()) {
2045                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2046                         }
2047                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2048
2049                         /* save albums. first, collect in a flat structure, top-level first. */
2050                         List<Album> albums = sone.getAllAlbums();
2051
2052                         int albumCounter = 0;
2053                         for (Album album : albums) {
2054                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2055                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2056                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2057                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2058                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2059                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2060                         }
2061                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2062
2063                         /* save images. */
2064                         int imageCounter = 0;
2065                         for (Album album : albums) {
2066                                 for (Image image : album.getImages()) {
2067                                         if (!image.isInserted()) {
2068                                                 continue;
2069                                         }
2070                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2071                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2072                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2073                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2074                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2075                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2076                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2077                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2078                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2079                                 }
2080                         }
2081                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2082
2083                         /* save options. */
2084                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2085                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2086                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2087                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2088                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2089                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2090
2091                         configuration.save();
2092
2093                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2094
2095                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2096                 } catch (ConfigurationException ce1) {
2097                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2098                 }
2099         }
2100
2101         /**
2102          * Saves the current options.
2103          */
2104         private void saveConfiguration() {
2105                 synchronized (configuration) {
2106                         if (storingConfiguration) {
2107                                 logger.log(Level.FINE, "Already storing configuration…");
2108                                 return;
2109                         }
2110                         storingConfiguration = true;
2111                 }
2112
2113                 /* store the options first. */
2114                 try {
2115                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2116                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2117                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2118                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2119                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2120                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2121                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2122                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2123                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2124                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2125                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2126                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2127
2128                         /* save known Sones. */
2129                         int soneCounter = 0;
2130                         synchronized (knownSones) {
2131                                 for (String knownSoneId : knownSones) {
2132                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2133                                 }
2134                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2135                         }
2136
2137                         /* save Sone following times. */
2138                         soneCounter = 0;
2139                         synchronized (soneFollowingTimes) {
2140                                 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2141                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2142                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2143                                         ++soneCounter;
2144                                 }
2145                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2146                         }
2147
2148                         /* save known posts. */
2149                         int postCounter = 0;
2150                         synchronized (knownPosts) {
2151                                 for (String knownPostId : knownPosts) {
2152                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2153                                 }
2154                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2155                         }
2156
2157                         /* save known replies. */
2158                         int replyCounter = 0;
2159                         synchronized (knownReplies) {
2160                                 for (String knownReplyId : knownReplies) {
2161                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2162                                 }
2163                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2164                         }
2165
2166                         /* save bookmarked posts. */
2167                         int bookmarkedPostCounter = 0;
2168                         synchronized (bookmarkedPosts) {
2169                                 for (String bookmarkedPostId : bookmarkedPosts) {
2170                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2171                                 }
2172                         }
2173                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2174
2175                         /* now save it. */
2176                         configuration.save();
2177
2178                 } catch (ConfigurationException ce1) {
2179                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2180                 } finally {
2181                         synchronized (configuration) {
2182                                 storingConfiguration = false;
2183                         }
2184                 }
2185         }
2186
2187         /**
2188          * Loads the configuration.
2189          */
2190         @SuppressWarnings("unchecked")
2191         private void loadConfiguration() {
2192                 /* create options. */
2193                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2194
2195                         @Override
2196                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2197                                 SoneInserter.setInsertionDelay(newValue);
2198                         }
2199
2200                 }));
2201                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2202                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2203                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2204                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2205                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2206                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2207                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2208                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2209                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2210
2211                         @Override
2212                         @SuppressWarnings("synthetic-access")
2213                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2214                                 fcpInterface.setActive(newValue);
2215                         }
2216                 }));
2217                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2218
2219                         @Override
2220                         @SuppressWarnings("synthetic-access")
2221                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2222                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2223                         }
2224
2225                 }));
2226
2227                 loadConfigurationValue("InsertionDelay");
2228                 loadConfigurationValue("PostsPerPage");
2229                 loadConfigurationValue("ImagesPerPage");
2230                 loadConfigurationValue("CharactersPerPost");
2231                 loadConfigurationValue("PostCutOffLength");
2232                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2233                 loadConfigurationValue("PositiveTrust");
2234                 loadConfigurationValue("NegativeTrust");
2235                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2236                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2237                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2238
2239                 /* load known Sones. */
2240                 int soneCounter = 0;
2241                 while (true) {
2242                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2243                         if (knownSoneId == null) {
2244                                 break;
2245                         }
2246                         synchronized (knownSones) {
2247                                 knownSones.add(knownSoneId);
2248                         }
2249                 }
2250
2251                 /* load Sone following times. */
2252                 soneCounter = 0;
2253                 while (true) {
2254                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2255                         if (soneId == null) {
2256                                 break;
2257                         }
2258                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2259                         Sone followedSone = getSone(soneId);
2260                         if (followedSone == null) {
2261                                 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2262                         } else {
2263                                 synchronized (soneFollowingTimes) {
2264                                         soneFollowingTimes.put(getSone(soneId), time);
2265                                 }
2266                         }
2267                         ++soneCounter;
2268                 }
2269
2270                 /* load known posts. */
2271                 int postCounter = 0;
2272                 while (true) {
2273                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2274                         if (knownPostId == null) {
2275                                 break;
2276                         }
2277                         synchronized (knownPosts) {
2278                                 knownPosts.add(knownPostId);
2279                         }
2280                 }
2281
2282                 /* load known replies. */
2283                 int replyCounter = 0;
2284                 while (true) {
2285                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2286                         if (knownReplyId == null) {
2287                                 break;
2288                         }
2289                         synchronized (knownReplies) {
2290                                 knownReplies.add(knownReplyId);
2291                         }
2292                 }
2293
2294                 /* load bookmarked posts. */
2295                 int bookmarkedPostCounter = 0;
2296                 while (true) {
2297                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2298                         if (bookmarkedPostId == null) {
2299                                 break;
2300                         }
2301                         synchronized (bookmarkedPosts) {
2302                                 bookmarkedPosts.add(bookmarkedPostId);
2303                         }
2304                 }
2305
2306         }
2307
2308         /**
2309          * Loads an {@link Integer} configuration value for the option with the
2310          * given name, logging validation failures.
2311          *
2312          * @param optionName
2313          *            The name of the option to load
2314          */
2315         private void loadConfigurationValue(String optionName) {
2316                 try {
2317                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2318                 } catch (IllegalArgumentException iae1) {
2319                         logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2320                 }
2321         }
2322
2323         /**
2324          * Generate a Sone URI from the given URI and latest edition.
2325          *
2326          * @param uriString
2327          *            The URI to derive the Sone URI from
2328          * @return The derived URI
2329          */
2330         private static FreenetURI getSoneUri(String uriString) {
2331                 try {
2332                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2333                         return uri;
2334                 } catch (MalformedURLException mue1) {
2335                         logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2336                         return null;
2337                 }
2338         }
2339
2340         //
2341         // INTERFACE IdentityListener
2342         //
2343
2344         /**
2345          * {@inheritDoc}
2346          */
2347         @Override
2348         public void ownIdentityAdded(OwnIdentity ownIdentity) {
2349                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2350                 if (ownIdentity.hasContext("Sone")) {
2351                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2352                         addLocalSone(ownIdentity);
2353                 }
2354         }
2355
2356         /**
2357          * {@inheritDoc}
2358          */
2359         @Override
2360         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2361                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2362                 trustedIdentities.remove(ownIdentity);
2363         }
2364
2365         /**
2366          * {@inheritDoc}
2367          */
2368         @Override
2369         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2370                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2371                 trustedIdentities.get(ownIdentity).add(identity);
2372                 addRemoteSone(identity);
2373         }
2374
2375         /**
2376          * {@inheritDoc}
2377          */
2378         @Override
2379         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2380                 soneDownloaders.execute(new Runnable() {
2381
2382                         @Override
2383                         @SuppressWarnings("synthetic-access")
2384                         public void run() {
2385                                 Sone sone = getRemoteSone(identity.getId(), false);
2386                                 sone.setIdentity(identity);
2387                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2388                                 soneDownloader.addSone(sone);
2389                                 soneDownloader.fetchSone(sone);
2390                         }
2391                 });
2392         }
2393
2394         /**
2395          * {@inheritDoc}
2396          */
2397         @Override
2398         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2399                 trustedIdentities.get(ownIdentity).remove(identity);
2400                 boolean foundIdentity = false;
2401                 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2402                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2403                                 continue;
2404                         }
2405                         if (trustedIdentity.getValue().contains(identity)) {
2406                                 foundIdentity = true;
2407                         }
2408                 }
2409                 if (foundIdentity) {
2410                         /* some local identity still trusts this identity, don’t remove. */
2411                         return;
2412                 }
2413                 Sone sone = getSone(identity.getId(), false);
2414                 if (sone == null) {
2415                         /* TODO - we don’t have the Sone anymore. should this happen? */
2416                         return;
2417                 }
2418                 synchronized (posts) {
2419                         synchronized (knownPosts) {
2420                                 for (Post post : sone.getPosts()) {
2421                                         posts.remove(post.getId());
2422                                         coreListenerManager.firePostRemoved(post);
2423                                 }
2424                         }
2425                 }
2426                 synchronized (replies) {
2427                         synchronized (knownReplies) {
2428                                 for (PostReply reply : sone.getReplies()) {
2429                                         replies.remove(reply.getId());
2430                                         coreListenerManager.fireReplyRemoved(reply);
2431                                 }
2432                         }
2433                 }
2434                 synchronized (sones) {
2435                         sones.remove(identity.getId());
2436                 }
2437                 eventBus.post(new SoneRemovedEvent(sone));
2438         }
2439
2440         //
2441         // INTERFACE UpdateListener
2442         //
2443
2444         /**
2445          * {@inheritDoc}
2446          */
2447         @Override
2448         public void updateFound(Version version, long releaseTime, long latestEdition) {
2449                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2450         }
2451
2452         //
2453         // INTERFACE ImageInsertListener
2454         //
2455
2456         /**
2457          * {@inheritDoc}
2458          */
2459         @Override
2460         public void insertStarted(Sone sone) {
2461                 coreListenerManager.fireSoneInserting(sone);
2462         }
2463
2464         /**
2465          * {@inheritDoc}
2466          */
2467         @Override
2468         public void insertFinished(Sone sone, long insertDuration) {
2469                 coreListenerManager.fireSoneInserted(sone, insertDuration);
2470         }
2471
2472         /**
2473          * {@inheritDoc}
2474          */
2475         @Override
2476         public void insertAborted(Sone sone, Throwable cause) {
2477                 coreListenerManager.fireSoneInsertAborted(sone, cause);
2478         }
2479
2480         //
2481         // SONEINSERTLISTENER METHODS
2482         //
2483
2484         /**
2485          * {@inheritDoc}
2486          */
2487         @Override
2488         public void imageInsertStarted(Image image) {
2489                 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2490                 coreListenerManager.fireImageInsertStarted(image);
2491         }
2492
2493         /**
2494          * {@inheritDoc}
2495          */
2496         @Override
2497         public void imageInsertAborted(Image image) {
2498                 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2499                 coreListenerManager.fireImageInsertAborted(image);
2500         }
2501
2502         /**
2503          * {@inheritDoc}
2504          */
2505         @Override
2506         public void imageInsertFinished(Image image, FreenetURI key) {
2507                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2508                 image.setKey(key.toString());
2509                 deleteTemporaryImage(image.getId());
2510                 touchConfiguration();
2511                 coreListenerManager.fireImageInsertFinished(image);
2512         }
2513
2514         /**
2515          * {@inheritDoc}
2516          */
2517         @Override
2518         public void imageInsertFailed(Image image, Throwable cause) {
2519                 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2520                 coreListenerManager.fireImageInsertFailed(image, cause);
2521         }
2522
2523         /**
2524          * Convenience interface for external classes that want to access the core’s
2525          * configuration.
2526          *
2527          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2528          */
2529         public static class Preferences {
2530
2531                 /** The wrapped options. */
2532                 private final Options options;
2533
2534                 /**
2535                  * Creates a new preferences object wrapped around the given options.
2536                  *
2537                  * @param options
2538                  *            The options to wrap
2539                  */
2540                 public Preferences(Options options) {
2541                         this.options = options;
2542                 }
2543
2544                 /**
2545                  * Returns the insertion delay.
2546                  *
2547                  * @return The insertion delay
2548                  */
2549                 public int getInsertionDelay() {
2550                         return options.getIntegerOption("InsertionDelay").get();
2551                 }
2552
2553                 /**
2554                  * Validates the given insertion delay.
2555                  *
2556                  * @param insertionDelay
2557                  *            The insertion delay to validate
2558                  * @return {@code true} if the given insertion delay was valid,
2559                  *         {@code false} otherwise
2560                  */
2561                 public boolean validateInsertionDelay(Integer insertionDelay) {
2562                         return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2563                 }
2564
2565                 /**
2566                  * Sets the insertion delay
2567                  *
2568                  * @param insertionDelay
2569                  *            The new insertion delay, or {@code null} to restore it to
2570                  *            the default value
2571                  * @return This preferences
2572                  */
2573                 public Preferences setInsertionDelay(Integer insertionDelay) {
2574                         options.getIntegerOption("InsertionDelay").set(insertionDelay);
2575                         return this;
2576                 }
2577
2578                 /**
2579                  * Returns the number of posts to show per page.
2580                  *
2581                  * @return The number of posts to show per page
2582                  */
2583                 public int getPostsPerPage() {
2584                         return options.getIntegerOption("PostsPerPage").get();
2585                 }
2586
2587                 /**
2588                  * Validates the number of posts per page.
2589                  *
2590                  * @param postsPerPage
2591                  *            The number of posts per page
2592                  * @return {@code true} if the number of posts per page was valid,
2593                  *         {@code false} otherwise
2594                  */
2595                 public boolean validatePostsPerPage(Integer postsPerPage) {
2596                         return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2597                 }
2598
2599                 /**
2600                  * Sets the number of posts to show per page.
2601                  *
2602                  * @param postsPerPage
2603                  *            The number of posts to show per page
2604                  * @return This preferences object
2605                  */
2606                 public Preferences setPostsPerPage(Integer postsPerPage) {
2607                         options.getIntegerOption("PostsPerPage").set(postsPerPage);
2608                         return this;
2609                 }
2610
2611                 /**
2612                  * Returns the number of images to show per page.
2613                  *
2614                  * @return The number of images to show per page
2615                  */
2616                 public int getImagesPerPage() {
2617                         return options.getIntegerOption("ImagesPerPage").get();
2618                 }
2619
2620                 /**
2621                  * Validates the number of images per page.
2622                  *
2623                  * @param imagesPerPage
2624                  *            The number of images per page
2625                  * @return {@code true} if the number of images per page was valid,
2626                  *         {@code false} otherwise
2627                  */
2628                 public boolean validateImagesPerPage(Integer imagesPerPage) {
2629                         return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2630                 }
2631
2632                 /**
2633                  * Sets the number of images per page.
2634                  *
2635                  * @param imagesPerPage
2636                  *            The number of images per page
2637                  * @return This preferences object
2638                  */
2639                 public Preferences setImagesPerPage(Integer imagesPerPage) {
2640                         options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2641                         return this;
2642                 }
2643
2644                 /**
2645                  * Returns the number of characters per post, or <code>-1</code> if the
2646                  * posts should not be cut off.
2647                  *
2648                  * @return The numbers of characters per post
2649                  */
2650                 public int getCharactersPerPost() {
2651                         return options.getIntegerOption("CharactersPerPost").get();
2652                 }
2653
2654                 /**
2655                  * Validates the number of characters per post.
2656                  *
2657                  * @param charactersPerPost
2658                  *            The number of characters per post
2659                  * @return {@code true} if the number of characters per post was valid,
2660                  *         {@code false} otherwise
2661                  */
2662                 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2663                         return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2664                 }
2665
2666                 /**
2667                  * Sets the number of characters per post.
2668                  *
2669                  * @param charactersPerPost
2670                  *            The number of characters per post, or <code>-1</code> to
2671                  *            not cut off the posts
2672                  * @return This preferences objects
2673                  */
2674                 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2675                         options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2676                         return this;
2677                 }
2678
2679                 /**
2680                  * Returns the number of characters the shortened post should have.
2681                  *
2682                  * @return The number of characters of the snippet
2683                  */
2684                 public int getPostCutOffLength() {
2685                         return options.getIntegerOption("PostCutOffLength").get();
2686                 }
2687
2688                 /**
2689                  * Validates the number of characters after which to cut off the post.
2690                  *
2691                  * @param postCutOffLength
2692                  *            The number of characters of the snippet
2693                  * @return {@code true} if the number of characters of the snippet is
2694                  *         valid, {@code false} otherwise
2695                  */
2696                 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2697                         return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2698                 }
2699
2700                 /**
2701                  * Sets the number of characters the shortened post should have.
2702                  *
2703                  * @param postCutOffLength
2704                  *            The number of characters of the snippet
2705                  * @return This preferences
2706                  */
2707                 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2708                         options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2709                         return this;
2710                 }
2711
2712                 /**
2713                  * Returns whether Sone requires full access to be even visible.
2714                  *
2715                  * @return {@code true} if Sone requires full access, {@code false}
2716                  *         otherwise
2717                  */
2718                 public boolean isRequireFullAccess() {
2719                         return options.getBooleanOption("RequireFullAccess").get();
2720                 }
2721
2722                 /**
2723                  * Sets whether Sone requires full access to be even visible.
2724                  *
2725                  * @param requireFullAccess
2726                  *            {@code true} if Sone requires full access, {@code false}
2727                  *            otherwise
2728                  */
2729                 public void setRequireFullAccess(Boolean requireFullAccess) {
2730                         options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2731                 }
2732
2733                 /**
2734                  * Returns the positive trust.
2735                  *
2736                  * @return The positive trust
2737                  */
2738                 public int getPositiveTrust() {
2739                         return options.getIntegerOption("PositiveTrust").get();
2740                 }
2741
2742                 /**
2743                  * Validates the positive trust.
2744                  *
2745                  * @param positiveTrust
2746                  *            The positive trust to validate
2747                  * @return {@code true} if the positive trust was valid, {@code false}
2748                  *         otherwise
2749                  */
2750                 public boolean validatePositiveTrust(Integer positiveTrust) {
2751                         return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2752                 }
2753
2754                 /**
2755                  * Sets the positive trust.
2756                  *
2757                  * @param positiveTrust
2758                  *            The new positive trust, or {@code null} to restore it to
2759                  *            the default vlaue
2760                  * @return This preferences
2761                  */
2762                 public Preferences setPositiveTrust(Integer positiveTrust) {
2763                         options.getIntegerOption("PositiveTrust").set(positiveTrust);
2764                         return this;
2765                 }
2766
2767                 /**
2768                  * Returns the negative trust.
2769                  *
2770                  * @return The negative trust
2771                  */
2772                 public int getNegativeTrust() {
2773                         return options.getIntegerOption("NegativeTrust").get();
2774                 }
2775
2776                 /**
2777                  * Validates the negative trust.
2778                  *
2779                  * @param negativeTrust
2780                  *            The negative trust to validate
2781                  * @return {@code true} if the negative trust was valid, {@code false}
2782                  *         otherwise
2783                  */
2784                 public boolean validateNegativeTrust(Integer negativeTrust) {
2785                         return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2786                 }
2787
2788                 /**
2789                  * Sets the negative trust.
2790                  *
2791                  * @param negativeTrust
2792                  *            The negative trust, or {@code null} to restore it to the
2793                  *            default value
2794                  * @return The preferences
2795                  */
2796                 public Preferences setNegativeTrust(Integer negativeTrust) {
2797                         options.getIntegerOption("NegativeTrust").set(negativeTrust);
2798                         return this;
2799                 }
2800
2801                 /**
2802                  * Returns the trust comment. This is the comment that is set in the web
2803                  * of trust when a trust value is assigned to an identity.
2804                  *
2805                  * @return The trust comment
2806                  */
2807                 public String getTrustComment() {
2808                         return options.getStringOption("TrustComment").get();
2809                 }
2810
2811                 /**
2812                  * Sets the trust comment.
2813                  *
2814                  * @param trustComment
2815                  *            The trust comment, or {@code null} to restore it to the
2816                  *            default value
2817                  * @return This preferences
2818                  */
2819                 public Preferences setTrustComment(String trustComment) {
2820                         options.getStringOption("TrustComment").set(trustComment);
2821                         return this;
2822                 }
2823
2824                 /**
2825                  * Returns whether the {@link FcpInterface FCP interface} is currently
2826                  * active.
2827                  *
2828                  * @see FcpInterface#setActive(boolean)
2829                  * @return {@code true} if the FCP interface is currently active,
2830                  *         {@code false} otherwise
2831                  */
2832                 public boolean isFcpInterfaceActive() {
2833                         return options.getBooleanOption("ActivateFcpInterface").get();
2834                 }
2835
2836                 /**
2837                  * Sets whether the {@link FcpInterface FCP interface} is currently
2838                  * active.
2839                  *
2840                  * @see FcpInterface#setActive(boolean)
2841                  * @param fcpInterfaceActive
2842                  *            {@code true} to activate the FCP interface, {@code false}
2843                  *            to deactivate the FCP interface
2844                  * @return This preferences object
2845                  */
2846                 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2847                         options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2848                         return this;
2849                 }
2850
2851                 /**
2852                  * Returns the action level for which full access to the FCP interface
2853                  * is required.
2854                  *
2855                  * @return The action level for which full access to the FCP interface
2856                  *         is required
2857                  */
2858                 public FullAccessRequired getFcpFullAccessRequired() {
2859                         return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2860                 }
2861
2862                 /**
2863                  * Sets the action level for which full access to the FCP interface is
2864                  * required
2865                  *
2866                  * @param fcpFullAccessRequired
2867                  *            The action level
2868                  * @return This preferences
2869                  */
2870                 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2871                         options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2872                         return this;
2873                 }
2874
2875         }
2876
2877 }