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