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