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