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