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