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