Implement album structure loading.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.java - Copyright © 2010 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.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
30
31 import net.pterodactylus.sone.core.Options.DefaultOption;
32 import net.pterodactylus.sone.core.Options.Option;
33 import net.pterodactylus.sone.core.Options.OptionWatcher;
34 import net.pterodactylus.sone.data.Album;
35 import net.pterodactylus.sone.data.Client;
36 import net.pterodactylus.sone.data.Image;
37 import net.pterodactylus.sone.data.Post;
38 import net.pterodactylus.sone.data.Profile;
39 import net.pterodactylus.sone.data.Profile.Field;
40 import net.pterodactylus.sone.data.Reply;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.sone.freenet.wot.Identity;
43 import net.pterodactylus.sone.freenet.wot.IdentityListener;
44 import net.pterodactylus.sone.freenet.wot.IdentityManager;
45 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
46 import net.pterodactylus.sone.freenet.wot.Trust;
47 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
48 import net.pterodactylus.sone.main.SonePlugin;
49 import net.pterodactylus.util.config.Configuration;
50 import net.pterodactylus.util.config.ConfigurationException;
51 import net.pterodactylus.util.logging.Logging;
52 import net.pterodactylus.util.number.Numbers;
53 import net.pterodactylus.util.validation.Validation;
54 import net.pterodactylus.util.version.Version;
55 import freenet.keys.FreenetURI;
56
57 /**
58  * The Sone core.
59  *
60  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
61  */
62 public class Core implements IdentityListener, UpdateListener {
63
64         /**
65          * Enumeration for the possible states of a {@link Sone}.
66          *
67          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
68          */
69         public enum SoneStatus {
70
71                 /** The Sone is unknown, i.e. not yet downloaded. */
72                 unknown,
73
74                 /** The Sone is idle, i.e. not being downloaded or inserted. */
75                 idle,
76
77                 /** The Sone is currently being inserted. */
78                 inserting,
79
80                 /** The Sone is currently being downloaded. */
81                 downloading,
82         }
83
84         /** The logger. */
85         private static final Logger logger = Logging.getLogger(Core.class);
86
87         /** The options. */
88         private final Options options = new Options();
89
90         /** The preferences. */
91         private final Preferences preferences = new Preferences(options);
92
93         /** The core listener manager. */
94         private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
95
96         /** The configuration. */
97         private Configuration configuration;
98
99         /** Whether we’re currently saving the configuration. */
100         private boolean storingConfiguration = false;
101
102         /** The identity manager. */
103         private final IdentityManager identityManager;
104
105         /** Interface to freenet. */
106         private final FreenetInterface freenetInterface;
107
108         /** The Sone downloader. */
109         private final SoneDownloader soneDownloader;
110
111         /** The update checker. */
112         private final UpdateChecker updateChecker;
113
114         /** Whether the core has been stopped. */
115         private volatile boolean stopped;
116
117         /** The Sones’ statuses. */
118         /* synchronize access on itself. */
119         private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
120
121         /** Locked local Sones. */
122         /* synchronize on itself. */
123         private final Set<Sone> lockedSones = new HashSet<Sone>();
124
125         /** Sone inserters. */
126         /* synchronize access on this on localSones. */
127         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
128
129         /** All local Sones. */
130         /* synchronize access on this on itself. */
131         private Map<String, Sone> localSones = new HashMap<String, Sone>();
132
133         /** All remote Sones. */
134         /* synchronize access on this on itself. */
135         private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
136
137         /** All new Sones. */
138         private Set<String> newSones = new HashSet<String>();
139
140         /** All known Sones. */
141         /* synchronize access on {@link #newSones}. */
142         private Set<String> knownSones = new HashSet<String>();
143
144         /** All posts. */
145         private Map<String, Post> posts = new HashMap<String, Post>();
146
147         /** All new posts. */
148         private Set<String> newPosts = new HashSet<String>();
149
150         /** All known posts. */
151         /* synchronize access on {@link #newPosts}. */
152         private Set<String> knownPosts = new HashSet<String>();
153
154         /** All replies. */
155         private Map<String, Reply> replies = new HashMap<String, Reply>();
156
157         /** All new replies. */
158         private Set<String> newReplies = new HashSet<String>();
159
160         /** All known replies. */
161         private Set<String> knownReplies = new HashSet<String>();
162
163         /** All bookmarked posts. */
164         /* synchronize access on itself. */
165         private Set<String> bookmarkedPosts = new HashSet<String>();
166
167         /** Trusted identities, sorted by own identities. */
168         private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
169
170         /** All known albums. */
171         private Map<String, Album> albums = new HashMap<String, Album>();
172
173         /** All known images. */
174         private Map<String, Image> images = new HashMap<String, Image>();
175
176         /**
177          * Creates a new core.
178          *
179          * @param configuration
180          *            The configuration of the core
181          * @param freenetInterface
182          *            The freenet interface
183          * @param identityManager
184          *            The identity manager
185          */
186         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
187                 this.configuration = configuration;
188                 this.freenetInterface = freenetInterface;
189                 this.identityManager = identityManager;
190                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
191                 this.updateChecker = new UpdateChecker(freenetInterface);
192         }
193
194         //
195         // LISTENER MANAGEMENT
196         //
197
198         /**
199          * Adds a new core listener.
200          *
201          * @param coreListener
202          *            The listener to add
203          */
204         public void addCoreListener(CoreListener coreListener) {
205                 coreListenerManager.addListener(coreListener);
206         }
207
208         /**
209          * Removes a core listener.
210          *
211          * @param coreListener
212          *            The listener to remove
213          */
214         public void removeCoreListener(CoreListener coreListener) {
215                 coreListenerManager.removeListener(coreListener);
216         }
217
218         //
219         // ACCESSORS
220         //
221
222         /**
223          * Sets the configuration to use. This will automatically save the current
224          * configuration to the given configuration.
225          *
226          * @param configuration
227          *            The new configuration to use
228          */
229         public void setConfiguration(Configuration configuration) {
230                 this.configuration = configuration;
231                 saveConfiguration();
232         }
233
234         /**
235          * Returns the options used by the core.
236          *
237          * @return The options of the core
238          */
239         public Preferences getPreferences() {
240                 return preferences;
241         }
242
243         /**
244          * Returns the identity manager used by the core.
245          *
246          * @return The identity manager
247          */
248         public IdentityManager getIdentityManager() {
249                 return identityManager;
250         }
251
252         /**
253          * Returns the update checker.
254          *
255          * @return The update checker
256          */
257         public UpdateChecker getUpdateChecker() {
258                 return updateChecker;
259         }
260
261         /**
262          * Returns the status of the given Sone.
263          *
264          * @param sone
265          *            The Sone to get the status for
266          * @return The status of the Sone
267          */
268         public SoneStatus getSoneStatus(Sone sone) {
269                 synchronized (soneStatuses) {
270                         return soneStatuses.get(sone);
271                 }
272         }
273
274         /**
275          * Sets the status of the given Sone.
276          *
277          * @param sone
278          *            The Sone to set the status of
279          * @param soneStatus
280          *            The status to set
281          */
282         public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
283                 synchronized (soneStatuses) {
284                         soneStatuses.put(sone, soneStatus);
285                 }
286         }
287
288         /**
289          * Returns whether the given Sone is currently locked.
290          *
291          * @param sone
292          *            The sone to check
293          * @return {@code true} if the Sone is locked, {@code false} if it is not
294          */
295         public boolean isLocked(Sone sone) {
296                 synchronized (lockedSones) {
297                         return lockedSones.contains(sone);
298                 }
299         }
300
301         /**
302          * Returns all Sones, remote and local.
303          *
304          * @return All Sones
305          */
306         public Set<Sone> getSones() {
307                 Set<Sone> allSones = new HashSet<Sone>();
308                 allSones.addAll(getLocalSones());
309                 allSones.addAll(getRemoteSones());
310                 return allSones;
311         }
312
313         /**
314          * Returns the Sone with the given ID, regardless whether it’s local or
315          * remote.
316          *
317          * @param id
318          *            The ID of the Sone to get
319          * @return The Sone with the given ID, or {@code null} if there is no such
320          *         Sone
321          */
322         public Sone getSone(String id) {
323                 return getSone(id, true);
324         }
325
326         /**
327          * Returns the Sone with the given ID, regardless whether it’s local or
328          * remote.
329          *
330          * @param id
331          *            The ID of the Sone to get
332          * @param create
333          *            {@code true} to create a new Sone if none exists,
334          *            {@code false} to return {@code null} if a Sone with the given
335          *            ID does not exist
336          * @return The Sone with the given ID, or {@code null} if there is no such
337          *         Sone
338          */
339         public Sone getSone(String id, boolean create) {
340                 if (isLocalSone(id)) {
341                         return getLocalSone(id);
342                 }
343                 return getRemoteSone(id, create);
344         }
345
346         /**
347          * Checks whether the core knows a Sone with the given ID.
348          *
349          * @param id
350          *            The ID of the Sone
351          * @return {@code true} if there is a Sone with the given ID, {@code false}
352          *         otherwise
353          */
354         public boolean hasSone(String id) {
355                 return isLocalSone(id) || isRemoteSone(id);
356         }
357
358         /**
359          * Returns whether the given Sone is a local Sone.
360          *
361          * @param sone
362          *            The Sone to check for its locality
363          * @return {@code true} if the given Sone is local, {@code false} otherwise
364          */
365         public boolean isLocalSone(Sone sone) {
366                 synchronized (localSones) {
367                         return localSones.containsKey(sone.getId());
368                 }
369         }
370
371         /**
372          * Returns whether the given ID is the ID of a local Sone.
373          *
374          * @param id
375          *            The Sone ID to check for its locality
376          * @return {@code true} if the given ID is a local Sone, {@code false}
377          *         otherwise
378          */
379         public boolean isLocalSone(String id) {
380                 synchronized (localSones) {
381                         return localSones.containsKey(id);
382                 }
383         }
384
385         /**
386          * Returns all local Sones.
387          *
388          * @return All local Sones
389          */
390         public Set<Sone> getLocalSones() {
391                 synchronized (localSones) {
392                         return new HashSet<Sone>(localSones.values());
393                 }
394         }
395
396         /**
397          * Returns the local Sone with the given ID.
398          *
399          * @param id
400          *            The ID of the Sone to get
401          * @return The Sone with the given ID
402          */
403         public Sone getLocalSone(String id) {
404                 return getLocalSone(id, true);
405         }
406
407         /**
408          * Returns the local Sone with the given ID, optionally creating a new Sone.
409          *
410          * @param id
411          *            The ID of the Sone
412          * @param create
413          *            {@code true} to create a new Sone if none exists,
414          *            {@code false} to return null if none exists
415          * @return The Sone with the given ID, or {@code null}
416          */
417         public Sone getLocalSone(String id, boolean create) {
418                 synchronized (localSones) {
419                         Sone sone = localSones.get(id);
420                         if ((sone == null) && create) {
421                                 sone = new Sone(id);
422                                 localSones.put(id, sone);
423                                 setSoneStatus(sone, SoneStatus.unknown);
424                         }
425                         return sone;
426                 }
427         }
428
429         /**
430          * Returns all remote Sones.
431          *
432          * @return All remote Sones
433          */
434         public Set<Sone> getRemoteSones() {
435                 synchronized (remoteSones) {
436                         return new HashSet<Sone>(remoteSones.values());
437                 }
438         }
439
440         /**
441          * Returns the remote Sone with the given ID.
442          *
443          * @param id
444          *            The ID of the remote Sone to get
445          * @return The Sone with the given ID
446          */
447         public Sone getRemoteSone(String id) {
448                 return getRemoteSone(id, true);
449         }
450
451         /**
452          * Returns the remote Sone with the given ID.
453          *
454          * @param id
455          *            The ID of the remote Sone to get
456          * @param create
457          *            {@code true} to always create a Sone, {@code false} to return
458          *            {@code null} if no Sone with the given ID exists
459          * @return The Sone with the given ID
460          */
461         public Sone getRemoteSone(String id, boolean create) {
462                 synchronized (remoteSones) {
463                         Sone sone = remoteSones.get(id);
464                         if ((sone == null) && create) {
465                                 sone = new Sone(id);
466                                 remoteSones.put(id, sone);
467                                 setSoneStatus(sone, SoneStatus.unknown);
468                         }
469                         return sone;
470                 }
471         }
472
473         /**
474          * Returns whether the given Sone is a remote Sone.
475          *
476          * @param sone
477          *            The Sone to check
478          * @return {@code true} if the given Sone is a remote Sone, {@code false}
479          *         otherwise
480          */
481         public boolean isRemoteSone(Sone sone) {
482                 synchronized (remoteSones) {
483                         return remoteSones.containsKey(sone.getId());
484                 }
485         }
486
487         /**
488          * Returns whether the Sone with the given ID is a remote Sone.
489          *
490          * @param id
491          *            The ID of the Sone to check
492          * @return {@code true} if the Sone with the given ID is a remote Sone,
493          *         {@code false} otherwise
494          */
495         public boolean isRemoteSone(String id) {
496                 synchronized (remoteSones) {
497                         return remoteSones.containsKey(id);
498                 }
499         }
500
501         /**
502          * Returns whether the Sone with the given ID is a new Sone.
503          *
504          * @param soneId
505          *            The ID of the sone to check for
506          * @return {@code true} if the given Sone is new, false otherwise
507          */
508         public boolean isNewSone(String soneId) {
509                 synchronized (newSones) {
510                         return !knownSones.contains(soneId) && newSones.contains(soneId);
511                 }
512         }
513
514         /**
515          * Returns whether the given Sone has been modified.
516          *
517          * @param sone
518          *            The Sone to check for modifications
519          * @return {@code true} if a modification has been detected in the Sone,
520          *         {@code false} otherwise
521          */
522         public boolean isModifiedSone(Sone sone) {
523                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
524         }
525
526         /**
527          * Returns whether the target Sone is trusted by the origin Sone.
528          *
529          * @param origin
530          *            The origin Sone
531          * @param target
532          *            The target Sone
533          * @return {@code true} if the target Sone is trusted by the origin Sone
534          */
535         public boolean isSoneTrusted(Sone origin, Sone target) {
536                 return trustedIdentities.containsKey(origin) && trustedIdentities.get(origin.getIdentity()).contains(target);
537         }
538
539         /**
540          * Returns the post with the given ID.
541          *
542          * @param postId
543          *            The ID of the post to get
544          * @return The post, or {@code null} if there is no such post
545          */
546         public Post getPost(String postId) {
547                 return getPost(postId, true);
548         }
549
550         /**
551          * Returns the post with the given ID, optionally creating a new post.
552          *
553          * @param postId
554          *            The ID of the post to get
555          * @param create
556          *            {@code true} it create a new post if no post with the given ID
557          *            exists, {@code false} to return {@code null}
558          * @return The post, or {@code null} if there is no such post
559          */
560         public Post getPost(String postId, boolean create) {
561                 synchronized (posts) {
562                         Post post = posts.get(postId);
563                         if ((post == null) && create) {
564                                 post = new Post(postId);
565                                 posts.put(postId, post);
566                         }
567                         return post;
568                 }
569         }
570
571         /**
572          * Returns whether the given post ID is new.
573          *
574          * @param postId
575          *            The post ID
576          * @return {@code true} if the post is considered to be new, {@code false}
577          *         otherwise
578          */
579         public boolean isNewPost(String postId) {
580                 synchronized (newPosts) {
581                         return !knownPosts.contains(postId) && newPosts.contains(postId);
582                 }
583         }
584
585         /**
586          * Returns the reply with the given ID. If there is no reply with the given
587          * ID yet, a new one is created.
588          *
589          * @param replyId
590          *            The ID of the reply to get
591          * @return The reply
592          */
593         public Reply getReply(String replyId) {
594                 return getReply(replyId, true);
595         }
596
597         /**
598          * Returns the reply with the given ID. If there is no reply with the given
599          * ID yet, a new one is created, unless {@code create} is false in which
600          * case {@code null} is returned.
601          *
602          * @param replyId
603          *            The ID of the reply to get
604          * @param create
605          *            {@code true} to always return a {@link Reply}, {@code false}
606          *            to return {@code null} if no reply can be found
607          * @return The reply, or {@code null} if there is no such reply
608          */
609         public Reply getReply(String replyId, boolean create) {
610                 synchronized (replies) {
611                         Reply reply = replies.get(replyId);
612                         if (create && (reply == null)) {
613                                 reply = new Reply(replyId);
614                                 replies.put(replyId, reply);
615                         }
616                         return reply;
617                 }
618         }
619
620         /**
621          * Returns all replies for the given post, order ascending by time.
622          *
623          * @param post
624          *            The post to get all replies for
625          * @return All replies for the given post
626          */
627         public List<Reply> getReplies(Post post) {
628                 Set<Sone> sones = getSones();
629                 List<Reply> replies = new ArrayList<Reply>();
630                 for (Sone sone : sones) {
631                         for (Reply reply : sone.getReplies()) {
632                                 if (reply.getPost().equals(post)) {
633                                         replies.add(reply);
634                                 }
635                         }
636                 }
637                 Collections.sort(replies, Reply.TIME_COMPARATOR);
638                 return replies;
639         }
640
641         /**
642          * Returns whether the reply with the given ID is new.
643          *
644          * @param replyId
645          *            The ID of the reply to check
646          * @return {@code true} if the reply is considered to be new, {@code false}
647          *         otherwise
648          */
649         public boolean isNewReply(String replyId) {
650                 synchronized (newReplies) {
651                         return !knownReplies.contains(replyId) && newReplies.contains(replyId);
652                 }
653         }
654
655         /**
656          * Returns all Sones that have liked the given post.
657          *
658          * @param post
659          *            The post to get the liking Sones for
660          * @return The Sones that like the given post
661          */
662         public Set<Sone> getLikes(Post post) {
663                 Set<Sone> sones = new HashSet<Sone>();
664                 for (Sone sone : getSones()) {
665                         if (sone.getLikedPostIds().contains(post.getId())) {
666                                 sones.add(sone);
667                         }
668                 }
669                 return sones;
670         }
671
672         /**
673          * Returns all Sones that have liked the given reply.
674          *
675          * @param reply
676          *            The reply to get the liking Sones for
677          * @return The Sones that like the given reply
678          */
679         public Set<Sone> getLikes(Reply reply) {
680                 Set<Sone> sones = new HashSet<Sone>();
681                 for (Sone sone : getSones()) {
682                         if (sone.getLikedReplyIds().contains(reply.getId())) {
683                                 sones.add(sone);
684                         }
685                 }
686                 return sones;
687         }
688
689         /**
690          * Returns whether the given post is bookmarked.
691          *
692          * @param post
693          *            The post to check
694          * @return {@code true} if the given post is bookmarked, {@code false}
695          *         otherwise
696          */
697         public boolean isBookmarked(Post post) {
698                 return isPostBookmarked(post.getId());
699         }
700
701         /**
702          * Returns whether the post with the given ID is bookmarked.
703          *
704          * @param id
705          *            The ID of the post to check
706          * @return {@code true} if the post with the given ID is bookmarked,
707          *         {@code false} otherwise
708          */
709         public boolean isPostBookmarked(String id) {
710                 synchronized (bookmarkedPosts) {
711                         return bookmarkedPosts.contains(id);
712                 }
713         }
714
715         /**
716          * Returns all currently known bookmarked posts.
717          *
718          * @return All bookmarked posts
719          */
720         public Set<Post> getBookmarkedPosts() {
721                 Set<Post> posts = new HashSet<Post>();
722                 synchronized (bookmarkedPosts) {
723                         for (String bookmarkedPostId : bookmarkedPosts) {
724                                 Post post = getPost(bookmarkedPostId, false);
725                                 if (post != null) {
726                                         posts.add(post);
727                                 }
728                         }
729                 }
730                 return posts;
731         }
732
733         /**
734          * Returns the album with the given ID, creating a new album if no album
735          * with the given ID can be found.
736          *
737          * @param albumId
738          *            The ID of the album
739          * @return The album with the given ID
740          */
741         public Album getAlbum(String albumId) {
742                 return getAlbum(albumId, true);
743         }
744
745         /**
746          * Returns the album with the given ID, optionally creating a new album if
747          * an album with the given ID can not be found.
748          *
749          * @param albumId
750          *            The ID of the album
751          * @param create
752          *            {@code true} to create a new album if none exists for the
753          *            given ID
754          * @return The album with the given ID, or {@code null} if no album with the
755          *         given ID exists and {@code create} is {@code false}
756          */
757         public Album getAlbum(String albumId, boolean create) {
758                 synchronized (albums) {
759                         Album album = albums.get(albumId);
760                         if (create && (album == null)) {
761                                 album = new Album(albumId);
762                                 albums.put(albumId, album);
763                         }
764                         return album;
765                 }
766         }
767
768         /**
769          * Returns the image with the given ID, creating it if necessary.
770          *
771          * @param imageId
772          *            The ID of the image
773          * @return The image with the given ID
774          */
775         public Image getImage(String imageId) {
776                 return getImage(imageId, true);
777         }
778
779         /**
780          * Returns the image with the given ID, optionally creating it if it does
781          * not exist.
782          *
783          * @param imageId
784          *            The ID of the image
785          * @param create
786          *            {@code true} to create an image if none exists with the given
787          *            ID
788          * @return The image with the given ID, or {@code null} if none exists and
789          *         none was created
790          */
791         public Image getImage(String imageId, boolean create) {
792                 synchronized (images) {
793                         Image image = images.get(imageId);
794                         if (create && (image == null)) {
795                                 image = new Image(imageId);
796                                 images.put(imageId, image);
797                         }
798                         return image;
799                 }
800         }
801
802         //
803         // ACTIONS
804         //
805
806         /**
807          * Locks the given Sone. A locked Sone will not be inserted by
808          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
809          * again.
810          *
811          * @param sone
812          *            The sone to lock
813          */
814         public void lockSone(Sone sone) {
815                 synchronized (lockedSones) {
816                         if (lockedSones.add(sone)) {
817                                 coreListenerManager.fireSoneLocked(sone);
818                         }
819                 }
820         }
821
822         /**
823          * Unlocks the given Sone.
824          *
825          * @see #lockSone(Sone)
826          * @param sone
827          *            The sone to unlock
828          */
829         public void unlockSone(Sone sone) {
830                 synchronized (lockedSones) {
831                         if (lockedSones.remove(sone)) {
832                                 coreListenerManager.fireSoneUnlocked(sone);
833                         }
834                 }
835         }
836
837         /**
838          * Adds a local Sone from the given ID which has to be the ID of an own
839          * identity.
840          *
841          * @param id
842          *            The ID of an own identity to add a Sone for
843          * @return The added (or already existing) Sone
844          */
845         public Sone addLocalSone(String id) {
846                 synchronized (localSones) {
847                         if (localSones.containsKey(id)) {
848                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
849                                 return localSones.get(id);
850                         }
851                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
852                         if (ownIdentity == null) {
853                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
854                                 return null;
855                         }
856                         return addLocalSone(ownIdentity);
857                 }
858         }
859
860         /**
861          * Adds a local Sone from the given own identity.
862          *
863          * @param ownIdentity
864          *            The own identity to create a Sone from
865          * @return The added (or already existing) Sone
866          */
867         public Sone addLocalSone(OwnIdentity ownIdentity) {
868                 if (ownIdentity == null) {
869                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
870                         return null;
871                 }
872                 synchronized (localSones) {
873                         final Sone sone;
874                         try {
875                                 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
876                         } catch (MalformedURLException mue1) {
877                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
878                                 return null;
879                         }
880                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
881                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
882                         /* TODO - load posts ’n stuff */
883                         localSones.put(ownIdentity.getId(), sone);
884                         final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
885                         soneInserters.put(sone, soneInserter);
886                         setSoneStatus(sone, SoneStatus.idle);
887                         loadSone(sone);
888                         if (!preferences.isSoneRescueMode()) {
889                                 soneInserter.start();
890                         }
891                         new Thread(new Runnable() {
892
893                                 @Override
894                                 @SuppressWarnings("synthetic-access")
895                                 public void run() {
896                                         if (!preferences.isSoneRescueMode()) {
897                                                 soneDownloader.fetchSone(sone);
898                                                 return;
899                                         }
900                                         logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
901                                         coreListenerManager.fireRescuingSone(sone);
902                                         lockSone(sone);
903                                         long edition = sone.getLatestEdition();
904                                         while (!stopped && (edition >= 0) && preferences.isSoneRescueMode()) {
905                                                 logger.log(Level.FINE, "Downloading edition " + edition + "…");
906                                                 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
907                                                 --edition;
908                                         }
909                                         logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
910                                         saveSone(sone);
911                                         coreListenerManager.fireRescuedSone(sone);
912                                         soneInserter.start();
913                                 }
914
915                         }, "Sone Downloader").start();
916                         return sone;
917                 }
918         }
919
920         /**
921          * Creates a new Sone for the given own identity.
922          *
923          * @param ownIdentity
924          *            The own identity to create a Sone for
925          * @return The created Sone
926          */
927         public Sone createSone(OwnIdentity ownIdentity) {
928                 try {
929                         ownIdentity.addContext("Sone");
930                 } catch (WebOfTrustException wote1) {
931                         logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
932                         return null;
933                 }
934                 Sone sone = addLocalSone(ownIdentity);
935                 return sone;
936         }
937
938         /**
939          * Adds the Sone of the given identity.
940          *
941          * @param identity
942          *            The identity whose Sone to add
943          * @return The added or already existing Sone
944          */
945         public Sone addRemoteSone(Identity identity) {
946                 if (identity == null) {
947                         logger.log(Level.WARNING, "Given Identity is null!");
948                         return null;
949                 }
950                 synchronized (remoteSones) {
951                         final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
952                         boolean newSone = sone.getRequestUri() == null;
953                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
954                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
955                         if (newSone) {
956                                 synchronized (newSones) {
957                                         newSone = !knownSones.contains(sone.getId());
958                                         if (newSone) {
959                                                 newSones.add(sone.getId());
960                                         }
961                                 }
962                                 if (newSone) {
963                                         coreListenerManager.fireNewSoneFound(sone);
964                                 }
965                         }
966                         remoteSones.put(identity.getId(), sone);
967                         soneDownloader.addSone(sone);
968                         setSoneStatus(sone, SoneStatus.unknown);
969                         new Thread(new Runnable() {
970
971                                 @Override
972                                 @SuppressWarnings("synthetic-access")
973                                 public void run() {
974                                         soneDownloader.fetchSone(sone);
975                                 }
976
977                         }, "Sone Downloader").start();
978                         return sone;
979                 }
980         }
981
982         /**
983          * Retrieves the trust relationship from the origin to the target. If the
984          * trust relationship can not be retrieved, {@code null} is returned.
985          *
986          * @see Identity#getTrust(OwnIdentity)
987          * @param origin
988          *            The origin of the trust tree
989          * @param target
990          *            The target of the trust
991          * @return The trust relationship
992          */
993         public Trust getTrust(Sone origin, Sone target) {
994                 if (!isLocalSone(origin)) {
995                         logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
996                         return null;
997                 }
998                 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
999         }
1000
1001         /**
1002          * Sets the trust value of the given origin Sone for the target Sone.
1003          *
1004          * @param origin
1005          *            The origin Sone
1006          * @param target
1007          *            The target Sone
1008          * @param trustValue
1009          *            The trust value (from {@code -100} to {@code 100})
1010          */
1011         public void setTrust(Sone origin, Sone target, int trustValue) {
1012                 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();
1013                 try {
1014                         ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1015                 } catch (WebOfTrustException wote1) {
1016                         logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1017                 }
1018         }
1019
1020         /**
1021          * Removes any trust assignment for the given target Sone.
1022          *
1023          * @param origin
1024          *            The trust origin
1025          * @param target
1026          *            The trust target
1027          */
1028         public void removeTrust(Sone origin, Sone target) {
1029                 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1030                 try {
1031                         ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1032                 } catch (WebOfTrustException wote1) {
1033                         logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1034                 }
1035         }
1036
1037         /**
1038          * Assigns the configured positive trust value for the given target.
1039          *
1040          * @param origin
1041          *            The trust origin
1042          * @param target
1043          *            The trust target
1044          */
1045         public void trustSone(Sone origin, Sone target) {
1046                 setTrust(origin, target, preferences.getPositiveTrust());
1047         }
1048
1049         /**
1050          * Assigns the configured negative trust value for the given target.
1051          *
1052          * @param origin
1053          *            The trust origin
1054          * @param target
1055          *            The trust target
1056          */
1057         public void distrustSone(Sone origin, Sone target) {
1058                 setTrust(origin, target, preferences.getNegativeTrust());
1059         }
1060
1061         /**
1062          * Removes the trust assignment for the given target.
1063          *
1064          * @param origin
1065          *            The trust origin
1066          * @param target
1067          *            The trust target
1068          */
1069         public void untrustSone(Sone origin, Sone target) {
1070                 removeTrust(origin, target);
1071         }
1072
1073         /**
1074          * Updates the stores Sone with the given Sone.
1075          *
1076          * @param sone
1077          *            The updated Sone
1078          */
1079         public void updateSone(Sone sone) {
1080                 if (hasSone(sone.getId())) {
1081                         boolean soneRescueMode = isLocalSone(sone) && preferences.isSoneRescueMode();
1082                         Sone storedSone = getSone(sone.getId());
1083                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1084                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1085                                 return;
1086                         }
1087                         synchronized (posts) {
1088                                 if (!soneRescueMode) {
1089                                         for (Post post : storedSone.getPosts()) {
1090                                                 posts.remove(post.getId());
1091                                                 if (!sone.getPosts().contains(post)) {
1092                                                         coreListenerManager.firePostRemoved(post);
1093                                                 }
1094                                         }
1095                                 }
1096                                 List<Post> storedPosts = storedSone.getPosts();
1097                                 synchronized (newPosts) {
1098                                         for (Post post : sone.getPosts()) {
1099                                                 post.setSone(storedSone);
1100                                                 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1101                                                         newPosts.add(post.getId());
1102                                                         coreListenerManager.fireNewPostFound(post);
1103                                                 }
1104                                                 posts.put(post.getId(), post);
1105                                         }
1106                                 }
1107                         }
1108                         synchronized (replies) {
1109                                 if (!soneRescueMode) {
1110                                         for (Reply reply : storedSone.getReplies()) {
1111                                                 replies.remove(reply.getId());
1112                                                 if (!sone.getReplies().contains(reply)) {
1113                                                         coreListenerManager.fireReplyRemoved(reply);
1114                                                 }
1115                                         }
1116                                 }
1117                                 Set<Reply> storedReplies = storedSone.getReplies();
1118                                 synchronized (newReplies) {
1119                                         for (Reply reply : sone.getReplies()) {
1120                                                 reply.setSone(storedSone);
1121                                                 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1122                                                         newReplies.add(reply.getId());
1123                                                         coreListenerManager.fireNewReplyFound(reply);
1124                                                 }
1125                                                 replies.put(reply.getId(), reply);
1126                                         }
1127                                 }
1128                         }
1129                         synchronized (storedSone) {
1130                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1131                                         storedSone.setTime(sone.getTime());
1132                                 }
1133                                 storedSone.setClient(sone.getClient());
1134                                 storedSone.setProfile(sone.getProfile());
1135                                 if (soneRescueMode) {
1136                                         for (Post post : sone.getPosts()) {
1137                                                 storedSone.addPost(post);
1138                                         }
1139                                         for (Reply reply : sone.getReplies()) {
1140                                                 storedSone.addReply(reply);
1141                                         }
1142                                         for (String likedPostId : sone.getLikedPostIds()) {
1143                                                 storedSone.addLikedPostId(likedPostId);
1144                                         }
1145                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1146                                                 storedSone.addLikedReplyId(likedReplyId);
1147                                         }
1148                                 } else {
1149                                         storedSone.setPosts(sone.getPosts());
1150                                         storedSone.setReplies(sone.getReplies());
1151                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1152                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1153                                 }
1154                                 storedSone.setLatestEdition(sone.getLatestEdition());
1155                         }
1156                 }
1157         }
1158
1159         /**
1160          * Deletes the given Sone. This will remove the Sone from the
1161          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1162          * and remove the context from its identity.
1163          *
1164          * @param sone
1165          *            The Sone to delete
1166          */
1167         public void deleteSone(Sone sone) {
1168                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1169                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1170                         return;
1171                 }
1172                 synchronized (localSones) {
1173                         if (!localSones.containsKey(sone.getId())) {
1174                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1175                                 return;
1176                         }
1177                         localSones.remove(sone.getId());
1178                         soneInserters.remove(sone).stop();
1179                 }
1180                 try {
1181                         ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1182                         ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1183                 } catch (WebOfTrustException wote1) {
1184                         logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1185                 }
1186                 try {
1187                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1188                 } catch (ConfigurationException ce1) {
1189                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1190                 }
1191         }
1192
1193         /**
1194          * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1195          * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1196          *
1197          * @param sone
1198          *            The Sone to mark as known
1199          */
1200         public void markSoneKnown(Sone sone) {
1201                 synchronized (newSones) {
1202                         if (newSones.remove(sone.getId())) {
1203                                 knownSones.add(sone.getId());
1204                                 coreListenerManager.fireMarkSoneKnown(sone);
1205                                 saveConfiguration();
1206                         }
1207                 }
1208         }
1209
1210         /**
1211          * Loads and updates the given Sone from the configuration. If any error is
1212          * encountered, loading is aborted and the given Sone is not changed.
1213          *
1214          * @param sone
1215          *            The Sone to load and update
1216          */
1217         public void loadSone(Sone sone) {
1218                 if (!isLocalSone(sone)) {
1219                         logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1220                         return;
1221                 }
1222
1223                 /* load Sone. */
1224                 String sonePrefix = "Sone/" + sone.getId();
1225                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1226                 if (soneTime == null) {
1227                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1228                         return;
1229                 }
1230                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1231
1232                 /* load profile. */
1233                 Profile profile = new Profile();
1234                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1235                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1236                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1237                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1238                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1239                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1240
1241                 /* load profile fields. */
1242                 while (true) {
1243                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1244                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1245                         if (fieldName == null) {
1246                                 break;
1247                         }
1248                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1249                         profile.addField(fieldName).setValue(fieldValue);
1250                 }
1251
1252                 /* load posts. */
1253                 Set<Post> posts = new HashSet<Post>();
1254                 while (true) {
1255                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1256                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1257                         if (postId == null) {
1258                                 break;
1259                         }
1260                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1261                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1262                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1263                         if ((postTime == 0) || (postText == null)) {
1264                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1265                                 return;
1266                         }
1267                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1268                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1269                                 post.setRecipient(getSone(postRecipientId));
1270                         }
1271                         posts.add(post);
1272                 }
1273
1274                 /* load replies. */
1275                 Set<Reply> replies = new HashSet<Reply>();
1276                 while (true) {
1277                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1278                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1279                         if (replyId == null) {
1280                                 break;
1281                         }
1282                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1283                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1284                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1285                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1286                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1287                                 return;
1288                         }
1289                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1290                 }
1291
1292                 /* load post likes. */
1293                 Set<String> likedPostIds = new HashSet<String>();
1294                 while (true) {
1295                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1296                         if (likedPostId == null) {
1297                                 break;
1298                         }
1299                         likedPostIds.add(likedPostId);
1300                 }
1301
1302                 /* load reply likes. */
1303                 Set<String> likedReplyIds = new HashSet<String>();
1304                 while (true) {
1305                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1306                         if (likedReplyId == null) {
1307                                 break;
1308                         }
1309                         likedReplyIds.add(likedReplyId);
1310                 }
1311
1312                 /* load friends. */
1313                 Set<String> friends = new HashSet<String>();
1314                 while (true) {
1315                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1316                         if (friendId == null) {
1317                                 break;
1318                         }
1319                         friends.add(friendId);
1320                 }
1321
1322                 /* load albums. */
1323                 Map<String, Album> albums = new HashMap<String, Album>();
1324                 List<Album> topLevelAlbums = new ArrayList<Album>();
1325                 while (true) {
1326                         String albumPrefix = sonePrefix + "/Albums/" + albums.size();
1327                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1328                         if (albumId == null) {
1329                                 break;
1330                         }
1331                         String albumName = configuration.getStringValue(albumPrefix + "/Name").getValue(null);
1332                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1333                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1334                         if ((albumName == null) || (albumDescription == null)) {
1335                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1336                                 return;
1337                         }
1338                         Album album = new Album(albumId).setSone(sone).setName(albumName).setDescription(albumDescription);
1339                         albums.put(albumId, album);
1340                         if (albumParentId != null) {
1341                                 Album parentAlbum = albums.get(albumParentId);
1342                                 if (parentAlbum == null) {
1343                                         logger.log(Level.WARNING, "Invalid parent album ID: " + albumParentId);
1344                                         return;
1345                                 }
1346                                 parentAlbum.addAlbum(album);
1347                         } else {
1348                                 topLevelAlbums.add(album);
1349                         }
1350                 }
1351
1352                 /* load options. */
1353                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1354                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1355
1356                 /* if we’re still here, Sone was loaded successfully. */
1357                 synchronized (sone) {
1358                         sone.setTime(soneTime);
1359                         sone.setProfile(profile);
1360                         sone.setPosts(posts);
1361                         sone.setReplies(replies);
1362                         sone.setLikePostIds(likedPostIds);
1363                         sone.setLikeReplyIds(likedReplyIds);
1364                         sone.setFriends(friends);
1365                         sone.setAlbums(topLevelAlbums);
1366                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1367                 }
1368                 synchronized (newSones) {
1369                         for (String friend : friends) {
1370                                 knownSones.add(friend);
1371                         }
1372                 }
1373                 synchronized (newPosts) {
1374                         for (Post post : posts) {
1375                                 knownPosts.add(post.getId());
1376                         }
1377                 }
1378                 synchronized (newReplies) {
1379                         for (Reply reply : replies) {
1380                                 knownReplies.add(reply.getId());
1381                         }
1382                 }
1383         }
1384
1385         /**
1386          * Saves the given Sone. This will persist all local settings for the given
1387          * Sone, such as the friends list and similar, private options.
1388          *
1389          * @param sone
1390          *            The Sone to save
1391          */
1392         public synchronized void saveSone(Sone sone) {
1393                 if (!isLocalSone(sone)) {
1394                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1395                         return;
1396                 }
1397                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1398                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1399                         return;
1400                 }
1401
1402                 logger.log(Level.INFO, "Saving Sone: %s", sone);
1403                 try {
1404                         ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1405
1406                         /* save Sone into configuration. */
1407                         String sonePrefix = "Sone/" + sone.getId();
1408                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1409                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1410
1411                         /* save profile. */
1412                         Profile profile = sone.getProfile();
1413                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1414                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1415                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1416                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1417                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1418                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1419
1420                         /* save profile fields. */
1421                         int fieldCounter = 0;
1422                         for (Field profileField : profile.getFields()) {
1423                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1424                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1425                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1426                         }
1427                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1428
1429                         /* save posts. */
1430                         int postCounter = 0;
1431                         for (Post post : sone.getPosts()) {
1432                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1433                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1434                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1435                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1436                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1437                         }
1438                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1439
1440                         /* save replies. */
1441                         int replyCounter = 0;
1442                         for (Reply reply : sone.getReplies()) {
1443                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1444                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1445                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1446                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1447                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1448                         }
1449                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1450
1451                         /* save post likes. */
1452                         int postLikeCounter = 0;
1453                         for (String postId : sone.getLikedPostIds()) {
1454                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1455                         }
1456                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1457
1458                         /* save reply likes. */
1459                         int replyLikeCounter = 0;
1460                         for (String replyId : sone.getLikedReplyIds()) {
1461                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1462                         }
1463                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1464
1465                         /* save friends. */
1466                         int friendCounter = 0;
1467                         for (String friendId : sone.getFriends()) {
1468                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1469                         }
1470                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1471
1472                         /* save albums. first, collect in a flat structure, top-level first. */
1473                         List<Album> albums = new ArrayList<Album>();
1474                         albums.addAll(sone.getAlbums());
1475                         int lastAlbumIndex = 0;
1476                         while (lastAlbumIndex < albums.size()) {
1477                                 int previousAlbumCount = albums.size();
1478                                 for (Album album : new ArrayList<Album>(albums.subList(lastAlbumIndex, albums.size()))) {
1479                                         albums.addAll(album.getAlbums());
1480                                 }
1481                                 lastAlbumIndex = previousAlbumCount;
1482                         }
1483
1484                         int albumCounter = 0;
1485                         for (Album album : albums) {
1486                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1487                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1488                                 configuration.getStringValue(albumPrefix + "/Name").setValue(album.getName());
1489                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1490                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
1491                         }
1492                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1493
1494                         /* save options. */
1495                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1496
1497                         configuration.save();
1498                         logger.log(Level.INFO, "Sone %s saved.", sone);
1499                 } catch (ConfigurationException ce1) {
1500                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1501                 } catch (WebOfTrustException wote1) {
1502                         logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1503                 }
1504         }
1505
1506         /**
1507          * Creates a new post.
1508          *
1509          * @param sone
1510          *            The Sone that creates the post
1511          * @param text
1512          *            The text of the post
1513          * @return The created post
1514          */
1515         public Post createPost(Sone sone, String text) {
1516                 return createPost(sone, System.currentTimeMillis(), text);
1517         }
1518
1519         /**
1520          * Creates a new post.
1521          *
1522          * @param sone
1523          *            The Sone that creates the post
1524          * @param time
1525          *            The time of the post
1526          * @param text
1527          *            The text of the post
1528          * @return The created post
1529          */
1530         public Post createPost(Sone sone, long time, String text) {
1531                 return createPost(sone, null, time, text);
1532         }
1533
1534         /**
1535          * Creates a new post.
1536          *
1537          * @param sone
1538          *            The Sone that creates the post
1539          * @param recipient
1540          *            The recipient Sone, or {@code null} if this post does not have
1541          *            a recipient
1542          * @param text
1543          *            The text of the post
1544          * @return The created post
1545          */
1546         public Post createPost(Sone sone, Sone recipient, String text) {
1547                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1548         }
1549
1550         /**
1551          * Creates a new post.
1552          *
1553          * @param sone
1554          *            The Sone that creates the post
1555          * @param recipient
1556          *            The recipient Sone, or {@code null} if this post does not have
1557          *            a recipient
1558          * @param time
1559          *            The time of the post
1560          * @param text
1561          *            The text of the post
1562          * @return The created post
1563          */
1564         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1565                 if (!isLocalSone(sone)) {
1566                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1567                         return null;
1568                 }
1569                 Post post = new Post(sone, time, text);
1570                 if (recipient != null) {
1571                         post.setRecipient(recipient);
1572                 }
1573                 synchronized (posts) {
1574                         posts.put(post.getId(), post);
1575                 }
1576                 synchronized (newPosts) {
1577                         knownPosts.add(post.getId());
1578                 }
1579                 sone.addPost(post);
1580                 saveSone(sone);
1581                 return post;
1582         }
1583
1584         /**
1585          * Deletes the given post.
1586          *
1587          * @param post
1588          *            The post to delete
1589          */
1590         public void deletePost(Post post) {
1591                 if (!isLocalSone(post.getSone())) {
1592                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1593                         return;
1594                 }
1595                 post.getSone().removePost(post);
1596                 synchronized (posts) {
1597                         posts.remove(post.getId());
1598                 }
1599                 saveSone(post.getSone());
1600         }
1601
1602         /**
1603          * Marks the given post as known, if it is currently a new post (according
1604          * to {@link #isNewPost(String)}).
1605          *
1606          * @param post
1607          *            The post to mark as known
1608          */
1609         public void markPostKnown(Post post) {
1610                 synchronized (newPosts) {
1611                         if (newPosts.remove(post.getId())) {
1612                                 knownPosts.add(post.getId());
1613                                 coreListenerManager.fireMarkPostKnown(post);
1614                                 saveConfiguration();
1615                         }
1616                 }
1617         }
1618
1619         /**
1620          * Bookmarks the given post.
1621          *
1622          * @param post
1623          *            The post to bookmark
1624          */
1625         public void bookmark(Post post) {
1626                 bookmarkPost(post.getId());
1627         }
1628
1629         /**
1630          * Bookmarks the post with the given ID.
1631          *
1632          * @param id
1633          *            The ID of the post to bookmark
1634          */
1635         public void bookmarkPost(String id) {
1636                 synchronized (bookmarkedPosts) {
1637                         bookmarkedPosts.add(id);
1638                 }
1639         }
1640
1641         /**
1642          * Removes the given post from the bookmarks.
1643          *
1644          * @param post
1645          *            The post to unbookmark
1646          */
1647         public void unbookmark(Post post) {
1648                 unbookmarkPost(post.getId());
1649         }
1650
1651         /**
1652          * Removes the post with the given ID from the bookmarks.
1653          *
1654          * @param id
1655          *            The ID of the post to unbookmark
1656          */
1657         public void unbookmarkPost(String id) {
1658                 synchronized (bookmarkedPosts) {
1659                         bookmarkedPosts.remove(id);
1660                 }
1661         }
1662
1663         /**
1664          * Creates a new reply.
1665          *
1666          * @param sone
1667          *            The Sone that creates the reply
1668          * @param post
1669          *            The post that this reply refers to
1670          * @param text
1671          *            The text of the reply
1672          * @return The created reply
1673          */
1674         public Reply createReply(Sone sone, Post post, String text) {
1675                 return createReply(sone, post, System.currentTimeMillis(), text);
1676         }
1677
1678         /**
1679          * Creates a new reply.
1680          *
1681          * @param sone
1682          *            The Sone that creates the reply
1683          * @param post
1684          *            The post that this reply refers to
1685          * @param time
1686          *            The time of the reply
1687          * @param text
1688          *            The text of the reply
1689          * @return The created reply
1690          */
1691         public Reply createReply(Sone sone, Post post, long time, String text) {
1692                 if (!isLocalSone(sone)) {
1693                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1694                         return null;
1695                 }
1696                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1697                 synchronized (replies) {
1698                         replies.put(reply.getId(), reply);
1699                 }
1700                 synchronized (newReplies) {
1701                         knownReplies.add(reply.getId());
1702                 }
1703                 sone.addReply(reply);
1704                 saveSone(sone);
1705                 return reply;
1706         }
1707
1708         /**
1709          * Deletes the given reply.
1710          *
1711          * @param reply
1712          *            The reply to delete
1713          */
1714         public void deleteReply(Reply reply) {
1715                 Sone sone = reply.getSone();
1716                 if (!isLocalSone(sone)) {
1717                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1718                         return;
1719                 }
1720                 synchronized (replies) {
1721                         replies.remove(reply.getId());
1722                 }
1723                 sone.removeReply(reply);
1724                 saveSone(sone);
1725         }
1726
1727         /**
1728          * Marks the given reply as known, if it is currently a new reply (according
1729          * to {@link #isNewReply(String)}).
1730          *
1731          * @param reply
1732          *            The reply to mark as known
1733          */
1734         public void markReplyKnown(Reply reply) {
1735                 synchronized (newReplies) {
1736                         if (newReplies.remove(reply.getId())) {
1737                                 knownReplies.add(reply.getId());
1738                                 coreListenerManager.fireMarkReplyKnown(reply);
1739                                 saveConfiguration();
1740                         }
1741                 }
1742         }
1743
1744         /**
1745          * Creates a new top-level album for the given Sone.
1746          *
1747          * @param sone
1748          *            The Sone to create the album for
1749          * @return The new album
1750          */
1751         public Album createAlbum(Sone sone) {
1752                 return createAlbum(sone, null);
1753         }
1754
1755         /**
1756          * Creates a new album for the given Sone.
1757          *
1758          * @param sone
1759          *            The Sone to create the album for
1760          * @param parent
1761          *            The parent of the album (may be {@code null} to create a
1762          *            top-level album)
1763          * @return The new album
1764          */
1765         public Album createAlbum(Sone sone, Album parent) {
1766                 Album album = new Album();
1767                 synchronized (albums) {
1768                         albums.put(album.getId(), album);
1769                 }
1770                 album.setSone(sone);
1771                 if (parent != null) {
1772                         parent.addAlbum(album);
1773                 } else {
1774                         sone.addAlbum(album);
1775                 }
1776                 return album;
1777         }
1778
1779         /**
1780          * Starts the core.
1781          */
1782         public void start() {
1783                 loadConfiguration();
1784                 updateChecker.addUpdateListener(this);
1785                 updateChecker.start();
1786         }
1787
1788         /**
1789          * Stops the core.
1790          */
1791         public void stop() {
1792                 synchronized (localSones) {
1793                         for (SoneInserter soneInserter : soneInserters.values()) {
1794                                 soneInserter.stop();
1795                         }
1796                 }
1797                 updateChecker.stop();
1798                 updateChecker.removeUpdateListener(this);
1799                 soneDownloader.stop();
1800                 saveConfiguration();
1801                 stopped = true;
1802         }
1803
1804         /**
1805          * Saves the current options.
1806          */
1807         public void saveConfiguration() {
1808                 synchronized (configuration) {
1809                         if (storingConfiguration) {
1810                                 logger.log(Level.FINE, "Already storing configuration…");
1811                                 return;
1812                         }
1813                         storingConfiguration = true;
1814                 }
1815
1816                 /* store the options first. */
1817                 try {
1818                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1819                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1820                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1821                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1822                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1823                         configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1824                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1825                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1826
1827                         /* save known Sones. */
1828                         int soneCounter = 0;
1829                         synchronized (newSones) {
1830                                 for (String knownSoneId : knownSones) {
1831                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1832                                 }
1833                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1834                         }
1835
1836                         /* save known posts. */
1837                         int postCounter = 0;
1838                         synchronized (newPosts) {
1839                                 for (String knownPostId : knownPosts) {
1840                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1841                                 }
1842                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1843                         }
1844
1845                         /* save known replies. */
1846                         int replyCounter = 0;
1847                         synchronized (newReplies) {
1848                                 for (String knownReplyId : knownReplies) {
1849                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1850                                 }
1851                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1852                         }
1853
1854                         /* save bookmarked posts. */
1855                         int bookmarkedPostCounter = 0;
1856                         synchronized (bookmarkedPosts) {
1857                                 for (String bookmarkedPostId : bookmarkedPosts) {
1858                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1859                                 }
1860                         }
1861                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1862
1863                         /* now save it. */
1864                         configuration.save();
1865
1866                 } catch (ConfigurationException ce1) {
1867                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1868                 } finally {
1869                         synchronized (configuration) {
1870                                 storingConfiguration = false;
1871                         }
1872                 }
1873         }
1874
1875         //
1876         // PRIVATE METHODS
1877         //
1878
1879         /**
1880          * Loads the configuration.
1881          */
1882         @SuppressWarnings("unchecked")
1883         private void loadConfiguration() {
1884                 /* create options. */
1885                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1886
1887                         @Override
1888                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1889                                 SoneInserter.setInsertionDelay(newValue);
1890                         }
1891
1892                 }));
1893                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75));
1894                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-100));
1895                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1896                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1897                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1898                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1899
1900                 /* read options from configuration. */
1901                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1902                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1903                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1904                 options.getBooleanOption("ClearOnNextRestart").set(null);
1905                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1906                 if (clearConfiguration) {
1907                         /* stop loading the configuration. */
1908                         return;
1909                 }
1910
1911                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1912                 options.getIntegerOption("PositiveTrust").set(configuration.getIntValue("Option/PositiveTrust").getValue(null));
1913                 options.getIntegerOption("NegativeTrust").set(configuration.getIntValue("Option/NegativeTrust").getValue(null));
1914                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1915                 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1916
1917                 /* load known Sones. */
1918                 int soneCounter = 0;
1919                 while (true) {
1920                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1921                         if (knownSoneId == null) {
1922                                 break;
1923                         }
1924                         synchronized (newSones) {
1925                                 knownSones.add(knownSoneId);
1926                         }
1927                 }
1928
1929                 /* load known posts. */
1930                 int postCounter = 0;
1931                 while (true) {
1932                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1933                         if (knownPostId == null) {
1934                                 break;
1935                         }
1936                         synchronized (newPosts) {
1937                                 knownPosts.add(knownPostId);
1938                         }
1939                 }
1940
1941                 /* load known replies. */
1942                 int replyCounter = 0;
1943                 while (true) {
1944                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1945                         if (knownReplyId == null) {
1946                                 break;
1947                         }
1948                         synchronized (newReplies) {
1949                                 knownReplies.add(knownReplyId);
1950                         }
1951                 }
1952
1953                 /* load bookmarked posts. */
1954                 int bookmarkedPostCounter = 0;
1955                 while (true) {
1956                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1957                         if (bookmarkedPostId == null) {
1958                                 break;
1959                         }
1960                         synchronized (bookmarkedPosts) {
1961                                 bookmarkedPosts.add(bookmarkedPostId);
1962                         }
1963                 }
1964
1965         }
1966
1967         /**
1968          * Generate a Sone URI from the given URI and latest edition.
1969          *
1970          * @param uriString
1971          *            The URI to derive the Sone URI from
1972          * @return The derived URI
1973          */
1974         private FreenetURI getSoneUri(String uriString) {
1975                 try {
1976                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1977                         return uri;
1978                 } catch (MalformedURLException mue1) {
1979                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1980                         return null;
1981                 }
1982         }
1983
1984         //
1985         // INTERFACE IdentityListener
1986         //
1987
1988         /**
1989          * {@inheritDoc}
1990          */
1991         @Override
1992         public void ownIdentityAdded(OwnIdentity ownIdentity) {
1993                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1994                 if (ownIdentity.hasContext("Sone")) {
1995                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1996                         addLocalSone(ownIdentity);
1997                 }
1998         }
1999
2000         /**
2001          * {@inheritDoc}
2002          */
2003         @Override
2004         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2005                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2006                 trustedIdentities.remove(ownIdentity);
2007         }
2008
2009         /**
2010          * {@inheritDoc}
2011          */
2012         @Override
2013         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2014                 logger.log(Level.FINEST, "Adding Identity: " + identity);
2015                 trustedIdentities.get(ownIdentity).add(identity);
2016                 addRemoteSone(identity);
2017         }
2018
2019         /**
2020          * {@inheritDoc}
2021          */
2022         @Override
2023         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2024                 new Thread(new Runnable() {
2025
2026                         @Override
2027                         @SuppressWarnings("synthetic-access")
2028                         public void run() {
2029                                 Sone sone = getRemoteSone(identity.getId());
2030                                 sone.setIdentity(identity);
2031                                 soneDownloader.addSone(sone);
2032                                 soneDownloader.fetchSone(sone);
2033                         }
2034                 }).start();
2035         }
2036
2037         /**
2038          * {@inheritDoc}
2039          */
2040         @Override
2041         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2042                 trustedIdentities.get(ownIdentity).remove(identity);
2043         }
2044
2045         //
2046         // INTERFACE UpdateListener
2047         //
2048
2049         /**
2050          * {@inheritDoc}
2051          */
2052         @Override
2053         public void updateFound(Version version, long releaseTime, long latestEdition) {
2054                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2055         }
2056
2057         /**
2058          * Convenience interface for external classes that want to access the core’s
2059          * configuration.
2060          *
2061          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2062          */
2063         public static class Preferences {
2064
2065                 /** The wrapped options. */
2066                 private final Options options;
2067
2068                 /**
2069                  * Creates a new preferences object wrapped around the given options.
2070                  *
2071                  * @param options
2072                  *            The options to wrap
2073                  */
2074                 public Preferences(Options options) {
2075                         this.options = options;
2076                 }
2077
2078                 /**
2079                  * Returns the insertion delay.
2080                  *
2081                  * @return The insertion delay
2082                  */
2083                 public int getInsertionDelay() {
2084                         return options.getIntegerOption("InsertionDelay").get();
2085                 }
2086
2087                 /**
2088                  * Sets the insertion delay
2089                  *
2090                  * @param insertionDelay
2091                  *            The new insertion delay, or {@code null} to restore it to
2092                  *            the default value
2093                  * @return This preferences
2094                  */
2095                 public Preferences setInsertionDelay(Integer insertionDelay) {
2096                         options.getIntegerOption("InsertionDelay").set(insertionDelay);
2097                         return this;
2098                 }
2099
2100                 /**
2101                  * Returns the positive trust.
2102                  *
2103                  * @return The positive trust
2104                  */
2105                 public int getPositiveTrust() {
2106                         return options.getIntegerOption("PositiveTrust").get();
2107                 }
2108
2109                 /**
2110                  * Sets the positive trust.
2111                  *
2112                  * @param positiveTrust
2113                  *            The new positive trust, or {@code null} to restore it to
2114                  *            the default vlaue
2115                  * @return This preferences
2116                  */
2117                 public Preferences setPositiveTrust(Integer positiveTrust) {
2118                         options.getIntegerOption("PositiveTrust").set(positiveTrust);
2119                         return this;
2120                 }
2121
2122                 /**
2123                  * Returns the negative trust.
2124                  *
2125                  * @return The negative trust
2126                  */
2127                 public int getNegativeTrust() {
2128                         return options.getIntegerOption("NegativeTrust").get();
2129                 }
2130
2131                 /**
2132                  * Sets the negative trust.
2133                  *
2134                  * @param negativeTrust
2135                  *            The negative trust, or {@code null} to restore it to the
2136                  *            default value
2137                  * @return The preferences
2138                  */
2139                 public Preferences setNegativeTrust(Integer negativeTrust) {
2140                         options.getIntegerOption("NegativeTrust").set(negativeTrust);
2141                         return this;
2142                 }
2143
2144                 /**
2145                  * Returns the trust comment. This is the comment that is set in the web
2146                  * of trust when a trust value is assigned to an identity.
2147                  *
2148                  * @return The trust comment
2149                  */
2150                 public String getTrustComment() {
2151                         return options.getStringOption("TrustComment").get();
2152                 }
2153
2154                 /**
2155                  * Sets the trust comment.
2156                  *
2157                  * @param trustComment
2158                  *            The trust comment, or {@code null} to restore it to the
2159                  *            default value
2160                  * @return This preferences
2161                  */
2162                 public Preferences setTrustComment(String trustComment) {
2163                         options.getStringOption("TrustComment").set(trustComment);
2164                         return this;
2165                 }
2166
2167                 /**
2168                  * Returns whether the rescue mode is active.
2169                  *
2170                  * @return {@code true} if the rescue mode is active, {@code false}
2171                  *         otherwise
2172                  */
2173                 public boolean isSoneRescueMode() {
2174                         return options.getBooleanOption("SoneRescueMode").get();
2175                 }
2176
2177                 /**
2178                  * Sets whether the rescue mode is active.
2179                  *
2180                  * @param soneRescueMode
2181                  *            {@code true} if the rescue mode is active, {@code false}
2182                  *            otherwise
2183                  * @return This preferences
2184                  */
2185                 public Preferences setSoneRescueMode(Boolean soneRescueMode) {
2186                         options.getBooleanOption("SoneRescueMode").set(soneRescueMode);
2187                         return this;
2188                 }
2189
2190                 /**
2191                  * Returns whether Sone should clear its settings on the next restart.
2192                  * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2193                  * to return {@code true} as well!
2194                  *
2195                  * @return {@code true} if Sone should clear its settings on the next
2196                  *         restart, {@code false} otherwise
2197                  */
2198                 public boolean isClearOnNextRestart() {
2199                         return options.getBooleanOption("ClearOnNextRestart").get();
2200                 }
2201
2202                 /**
2203                  * Sets whether Sone will clear its settings on the next restart.
2204                  *
2205                  * @param clearOnNextRestart
2206                  *            {@code true} if Sone should clear its settings on the next
2207                  *            restart, {@code false} otherwise
2208                  * @return This preferences
2209                  */
2210                 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2211                         options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2212                         return this;
2213                 }
2214
2215                 /**
2216                  * Returns whether Sone should really clear its settings on next
2217                  * restart. This is a confirmation option that needs to be set in
2218                  * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2219                  * settings on the next restart.
2220                  *
2221                  * @return {@code true} if Sone should really clear its settings on the
2222                  *         next restart, {@code false} otherwise
2223                  */
2224                 public boolean isReallyClearOnNextRestart() {
2225                         return options.getBooleanOption("ReallyClearOnNextRestart").get();
2226                 }
2227
2228                 /**
2229                  * Sets whether Sone should really clear its settings on the next
2230                  * restart.
2231                  *
2232                  * @param reallyClearOnNextRestart
2233                  *            {@code true} if Sone should really clear its settings on
2234                  *            the next restart, {@code false} otherwise
2235                  * @return This preferences
2236                  */
2237                 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2238                         options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);
2239                         return this;
2240                 }
2241
2242         }
2243
2244 }