53b67000d1ac96fb06ff0068561f41435b072b19
[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                 /* initialize options. */
1177                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1178
1179                 /* load Sone. */
1180                 String sonePrefix = "Sone/" + sone.getId();
1181                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1182                 if (soneTime == null) {
1183                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1184                         return;
1185                 }
1186                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1187
1188                 /* load profile. */
1189                 Profile profile = new Profile();
1190                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1191                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1192                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1193                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1194                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1195                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1196
1197                 /* load profile fields. */
1198                 while (true) {
1199                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1200                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1201                         if (fieldName == null) {
1202                                 break;
1203                         }
1204                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1205                         profile.addField(fieldName).setValue(fieldValue);
1206                 }
1207
1208                 /* load posts. */
1209                 Set<Post> posts = new HashSet<Post>();
1210                 while (true) {
1211                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1212                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1213                         if (postId == null) {
1214                                 break;
1215                         }
1216                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1217                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1218                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1219                         if ((postTime == 0) || (postText == null)) {
1220                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1221                                 return;
1222                         }
1223                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1224                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1225                                 post.setRecipient(getSone(postRecipientId));
1226                         }
1227                         posts.add(post);
1228                 }
1229
1230                 /* load replies. */
1231                 Set<Reply> replies = new HashSet<Reply>();
1232                 while (true) {
1233                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1234                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1235                         if (replyId == null) {
1236                                 break;
1237                         }
1238                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1239                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1240                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1241                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1242                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1243                                 return;
1244                         }
1245                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1246                 }
1247
1248                 /* load post likes. */
1249                 Set<String> likedPostIds = new HashSet<String>();
1250                 while (true) {
1251                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1252                         if (likedPostId == null) {
1253                                 break;
1254                         }
1255                         likedPostIds.add(likedPostId);
1256                 }
1257
1258                 /* load reply likes. */
1259                 Set<String> likedReplyIds = new HashSet<String>();
1260                 while (true) {
1261                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1262                         if (likedReplyId == null) {
1263                                 break;
1264                         }
1265                         likedReplyIds.add(likedReplyId);
1266                 }
1267
1268                 /* load friends. */
1269                 Set<String> friends = new HashSet<String>();
1270                 while (true) {
1271                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1272                         if (friendId == null) {
1273                                 break;
1274                         }
1275                         friends.add(friendId);
1276                 }
1277
1278                 /* load options. */
1279                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1280
1281                 /* if we’re still here, Sone was loaded successfully. */
1282                 synchronized (sone) {
1283                         sone.setTime(soneTime);
1284                         sone.setProfile(profile);
1285                         sone.setPosts(posts);
1286                         sone.setReplies(replies);
1287                         sone.setLikePostIds(likedPostIds);
1288                         sone.setLikeReplyIds(likedReplyIds);
1289                         sone.setFriends(friends);
1290                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1291                 }
1292                 synchronized (newSones) {
1293                         for (String friend : friends) {
1294                                 knownSones.add(friend);
1295                         }
1296                 }
1297                 synchronized (newPosts) {
1298                         for (Post post : posts) {
1299                                 knownPosts.add(post.getId());
1300                         }
1301                 }
1302                 synchronized (newReplies) {
1303                         for (Reply reply : replies) {
1304                                 knownReplies.add(reply.getId());
1305                         }
1306                 }
1307         }
1308
1309         /**
1310          * Saves the given Sone. This will persist all local settings for the given
1311          * Sone, such as the friends list and similar, private options.
1312          *
1313          * @param sone
1314          *            The Sone to save
1315          */
1316         public synchronized void saveSone(Sone sone) {
1317                 if (!isLocalSone(sone)) {
1318                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1319                         return;
1320                 }
1321                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1322                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1323                         return;
1324                 }
1325
1326                 logger.log(Level.INFO, "Saving Sone: %s", sone);
1327                 try {
1328                         ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1329
1330                         /* save Sone into configuration. */
1331                         String sonePrefix = "Sone/" + sone.getId();
1332                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1333                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1334
1335                         /* save profile. */
1336                         Profile profile = sone.getProfile();
1337                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1338                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1339                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1340                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1341                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1342                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1343
1344                         /* save profile fields. */
1345                         int fieldCounter = 0;
1346                         for (Field profileField : profile.getFields()) {
1347                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1348                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1349                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1350                         }
1351                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1352
1353                         /* save posts. */
1354                         int postCounter = 0;
1355                         for (Post post : sone.getPosts()) {
1356                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1357                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1358                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1359                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1360                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1361                         }
1362                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1363
1364                         /* save replies. */
1365                         int replyCounter = 0;
1366                         for (Reply reply : sone.getReplies()) {
1367                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1368                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1369                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1370                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1371                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1372                         }
1373                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1374
1375                         /* save post likes. */
1376                         int postLikeCounter = 0;
1377                         for (String postId : sone.getLikedPostIds()) {
1378                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1379                         }
1380                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1381
1382                         /* save reply likes. */
1383                         int replyLikeCounter = 0;
1384                         for (String replyId : sone.getLikedReplyIds()) {
1385                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1386                         }
1387                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1388
1389                         /* save friends. */
1390                         int friendCounter = 0;
1391                         for (String friendId : sone.getFriends()) {
1392                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1393                         }
1394                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1395
1396                         /* save options. */
1397                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1398
1399                         configuration.save();
1400                         logger.log(Level.INFO, "Sone %s saved.", sone);
1401                 } catch (ConfigurationException ce1) {
1402                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1403                 } catch (WebOfTrustException wote1) {
1404                         logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1405                 }
1406         }
1407
1408         /**
1409          * Creates a new post.
1410          *
1411          * @param sone
1412          *            The Sone that creates the post
1413          * @param text
1414          *            The text of the post
1415          * @return The created post
1416          */
1417         public Post createPost(Sone sone, String text) {
1418                 return createPost(sone, System.currentTimeMillis(), text);
1419         }
1420
1421         /**
1422          * Creates a new post.
1423          *
1424          * @param sone
1425          *            The Sone that creates the post
1426          * @param time
1427          *            The time of the post
1428          * @param text
1429          *            The text of the post
1430          * @return The created post
1431          */
1432         public Post createPost(Sone sone, long time, String text) {
1433                 return createPost(sone, null, time, text);
1434         }
1435
1436         /**
1437          * Creates a new post.
1438          *
1439          * @param sone
1440          *            The Sone that creates the post
1441          * @param recipient
1442          *            The recipient Sone, or {@code null} if this post does not have
1443          *            a recipient
1444          * @param text
1445          *            The text of the post
1446          * @return The created post
1447          */
1448         public Post createPost(Sone sone, Sone recipient, String text) {
1449                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1450         }
1451
1452         /**
1453          * Creates a new post.
1454          *
1455          * @param sone
1456          *            The Sone that creates the post
1457          * @param recipient
1458          *            The recipient Sone, or {@code null} if this post does not have
1459          *            a recipient
1460          * @param time
1461          *            The time of the post
1462          * @param text
1463          *            The text of the post
1464          * @return The created post
1465          */
1466         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1467                 if (!isLocalSone(sone)) {
1468                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1469                         return null;
1470                 }
1471                 Post post = new Post(sone, time, text);
1472                 if (recipient != null) {
1473                         post.setRecipient(recipient);
1474                 }
1475                 synchronized (posts) {
1476                         posts.put(post.getId(), post);
1477                 }
1478                 synchronized (newPosts) {
1479                         newPosts.add(post.getId());
1480                         coreListenerManager.fireNewPostFound(post);
1481                 }
1482                 sone.addPost(post);
1483                 saveSone(sone);
1484                 return post;
1485         }
1486
1487         /**
1488          * Deletes the given post.
1489          *
1490          * @param post
1491          *            The post to delete
1492          */
1493         public void deletePost(Post post) {
1494                 if (!isLocalSone(post.getSone())) {
1495                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1496                         return;
1497                 }
1498                 post.getSone().removePost(post);
1499                 synchronized (posts) {
1500                         posts.remove(post.getId());
1501                 }
1502                 coreListenerManager.firePostRemoved(post);
1503                 synchronized (newPosts) {
1504                         markPostKnown(post);
1505                         knownPosts.remove(post.getId());
1506                 }
1507                 saveSone(post.getSone());
1508         }
1509
1510         /**
1511          * Marks the given post as known, if it is currently a new post (according
1512          * to {@link #isNewPost(String)}).
1513          *
1514          * @param post
1515          *            The post to mark as known
1516          */
1517         public void markPostKnown(Post post) {
1518                 synchronized (newPosts) {
1519                         if (newPosts.remove(post.getId())) {
1520                                 knownPosts.add(post.getId());
1521                                 coreListenerManager.fireMarkPostKnown(post);
1522                                 saveConfiguration();
1523                         }
1524                 }
1525         }
1526
1527         /**
1528          * Bookmarks the given post.
1529          *
1530          * @param post
1531          *            The post to bookmark
1532          */
1533         public void bookmark(Post post) {
1534                 bookmarkPost(post.getId());
1535         }
1536
1537         /**
1538          * Bookmarks the post with the given ID.
1539          *
1540          * @param id
1541          *            The ID of the post to bookmark
1542          */
1543         public void bookmarkPost(String id) {
1544                 synchronized (bookmarkedPosts) {
1545                         bookmarkedPosts.add(id);
1546                 }
1547         }
1548
1549         /**
1550          * Removes the given post from the bookmarks.
1551          *
1552          * @param post
1553          *            The post to unbookmark
1554          */
1555         public void unbookmark(Post post) {
1556                 unbookmarkPost(post.getId());
1557         }
1558
1559         /**
1560          * Removes the post with the given ID from the bookmarks.
1561          *
1562          * @param id
1563          *            The ID of the post to unbookmark
1564          */
1565         public void unbookmarkPost(String id) {
1566                 synchronized (bookmarkedPosts) {
1567                         bookmarkedPosts.remove(id);
1568                 }
1569         }
1570
1571         /**
1572          * Creates a new reply.
1573          *
1574          * @param sone
1575          *            The Sone that creates the reply
1576          * @param post
1577          *            The post that this reply refers to
1578          * @param text
1579          *            The text of the reply
1580          * @return The created reply
1581          */
1582         public Reply createReply(Sone sone, Post post, String text) {
1583                 return createReply(sone, post, System.currentTimeMillis(), text);
1584         }
1585
1586         /**
1587          * Creates a new reply.
1588          *
1589          * @param sone
1590          *            The Sone that creates the reply
1591          * @param post
1592          *            The post that this reply refers to
1593          * @param time
1594          *            The time of the reply
1595          * @param text
1596          *            The text of the reply
1597          * @return The created reply
1598          */
1599         public Reply createReply(Sone sone, Post post, long time, String text) {
1600                 if (!isLocalSone(sone)) {
1601                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1602                         return null;
1603                 }
1604                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1605                 synchronized (replies) {
1606                         replies.put(reply.getId(), reply);
1607                 }
1608                 synchronized (newReplies) {
1609                         newReplies.add(reply.getId());
1610                         coreListenerManager.fireNewReplyFound(reply);
1611                 }
1612                 sone.addReply(reply);
1613                 saveSone(sone);
1614                 return reply;
1615         }
1616
1617         /**
1618          * Deletes the given reply.
1619          *
1620          * @param reply
1621          *            The reply to delete
1622          */
1623         public void deleteReply(Reply reply) {
1624                 Sone sone = reply.getSone();
1625                 if (!isLocalSone(sone)) {
1626                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1627                         return;
1628                 }
1629                 synchronized (replies) {
1630                         replies.remove(reply.getId());
1631                 }
1632                 synchronized (newReplies) {
1633                         markReplyKnown(reply);
1634                         knownReplies.remove(reply.getId());
1635                 }
1636                 sone.removeReply(reply);
1637                 saveSone(sone);
1638         }
1639
1640         /**
1641          * Marks the given reply as known, if it is currently a new reply (according
1642          * to {@link #isNewReply(String)}).
1643          *
1644          * @param reply
1645          *            The reply to mark as known
1646          */
1647         public void markReplyKnown(Reply reply) {
1648                 synchronized (newReplies) {
1649                         if (newReplies.remove(reply.getId())) {
1650                                 knownReplies.add(reply.getId());
1651                                 coreListenerManager.fireMarkReplyKnown(reply);
1652                                 saveConfiguration();
1653                         }
1654                 }
1655         }
1656
1657         /**
1658          * Starts the core.
1659          */
1660         public void start() {
1661                 loadConfiguration();
1662                 updateChecker.addUpdateListener(this);
1663                 updateChecker.start();
1664         }
1665
1666         /**
1667          * Stops the core.
1668          */
1669         public void stop() {
1670                 synchronized (localSones) {
1671                         for (SoneInserter soneInserter : soneInserters.values()) {
1672                                 soneInserter.stop();
1673                         }
1674                 }
1675                 updateChecker.stop();
1676                 updateChecker.removeUpdateListener(this);
1677                 soneDownloader.stop();
1678                 saveConfiguration();
1679                 stopped = true;
1680         }
1681
1682         /**
1683          * Saves the current options.
1684          */
1685         public void saveConfiguration() {
1686                 synchronized (configuration) {
1687                         if (storingConfiguration) {
1688                                 logger.log(Level.FINE, "Already storing configuration…");
1689                                 return;
1690                         }
1691                         storingConfiguration = true;
1692                 }
1693
1694                 /* store the options first. */
1695                 try {
1696                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1697                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1698                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1699                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1700                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1701                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1702                         configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1703                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1704                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1705
1706                         /* save known Sones. */
1707                         int soneCounter = 0;
1708                         synchronized (newSones) {
1709                                 for (String knownSoneId : knownSones) {
1710                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1711                                 }
1712                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1713                         }
1714
1715                         /* save known posts. */
1716                         int postCounter = 0;
1717                         synchronized (newPosts) {
1718                                 for (String knownPostId : knownPosts) {
1719                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1720                                 }
1721                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1722                         }
1723
1724                         /* save known replies. */
1725                         int replyCounter = 0;
1726                         synchronized (newReplies) {
1727                                 for (String knownReplyId : knownReplies) {
1728                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1729                                 }
1730                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1731                         }
1732
1733                         /* save bookmarked posts. */
1734                         int bookmarkedPostCounter = 0;
1735                         synchronized (bookmarkedPosts) {
1736                                 for (String bookmarkedPostId : bookmarkedPosts) {
1737                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1738                                 }
1739                         }
1740                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1741
1742                         /* now save it. */
1743                         configuration.save();
1744
1745                 } catch (ConfigurationException ce1) {
1746                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1747                 } finally {
1748                         synchronized (configuration) {
1749                                 storingConfiguration = false;
1750                         }
1751                 }
1752         }
1753
1754         //
1755         // PRIVATE METHODS
1756         //
1757
1758         /**
1759          * Loads the configuration.
1760          */
1761         @SuppressWarnings("unchecked")
1762         private void loadConfiguration() {
1763                 /* create options. */
1764                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1765
1766                         @Override
1767                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1768                                 SoneInserter.setInsertionDelay(newValue);
1769                         }
1770
1771                 }));
1772                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10));
1773                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75));
1774                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25));
1775                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1776                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1777                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1778                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1779
1780                 /* read options from configuration. */
1781                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1782                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1783                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1784                 options.getBooleanOption("ClearOnNextRestart").set(null);
1785                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1786                 if (clearConfiguration) {
1787                         /* stop loading the configuration. */
1788                         return;
1789                 }
1790
1791                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1792                 options.getIntegerOption("PostsPerPage").set(configuration.getIntValue("Option/PostsPerPage").getValue(null));
1793                 options.getIntegerOption("PositiveTrust").set(configuration.getIntValue("Option/PositiveTrust").getValue(null));
1794                 options.getIntegerOption("NegativeTrust").set(configuration.getIntValue("Option/NegativeTrust").getValue(null));
1795                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1796                 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1797
1798                 /* load known Sones. */
1799                 int soneCounter = 0;
1800                 while (true) {
1801                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1802                         if (knownSoneId == null) {
1803                                 break;
1804                         }
1805                         synchronized (newSones) {
1806                                 knownSones.add(knownSoneId);
1807                         }
1808                 }
1809
1810                 /* load known posts. */
1811                 int postCounter = 0;
1812                 while (true) {
1813                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1814                         if (knownPostId == null) {
1815                                 break;
1816                         }
1817                         synchronized (newPosts) {
1818                                 knownPosts.add(knownPostId);
1819                         }
1820                 }
1821
1822                 /* load known replies. */
1823                 int replyCounter = 0;
1824                 while (true) {
1825                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1826                         if (knownReplyId == null) {
1827                                 break;
1828                         }
1829                         synchronized (newReplies) {
1830                                 knownReplies.add(knownReplyId);
1831                         }
1832                 }
1833
1834                 /* load bookmarked posts. */
1835                 int bookmarkedPostCounter = 0;
1836                 while (true) {
1837                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1838                         if (bookmarkedPostId == null) {
1839                                 break;
1840                         }
1841                         synchronized (bookmarkedPosts) {
1842                                 bookmarkedPosts.add(bookmarkedPostId);
1843                         }
1844                 }
1845
1846         }
1847
1848         /**
1849          * Generate a Sone URI from the given URI and latest edition.
1850          *
1851          * @param uriString
1852          *            The URI to derive the Sone URI from
1853          * @return The derived URI
1854          */
1855         private FreenetURI getSoneUri(String uriString) {
1856                 try {
1857                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1858                         return uri;
1859                 } catch (MalformedURLException mue1) {
1860                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1861                         return null;
1862                 }
1863         }
1864
1865         //
1866         // INTERFACE IdentityListener
1867         //
1868
1869         /**
1870          * {@inheritDoc}
1871          */
1872         @Override
1873         public void ownIdentityAdded(OwnIdentity ownIdentity) {
1874                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1875                 if (ownIdentity.hasContext("Sone")) {
1876                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1877                         addLocalSone(ownIdentity);
1878                 }
1879         }
1880
1881         /**
1882          * {@inheritDoc}
1883          */
1884         @Override
1885         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1886                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1887                 trustedIdentities.remove(ownIdentity);
1888         }
1889
1890         /**
1891          * {@inheritDoc}
1892          */
1893         @Override
1894         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1895                 logger.log(Level.FINEST, "Adding Identity: " + identity);
1896                 trustedIdentities.get(ownIdentity).add(identity);
1897                 addRemoteSone(identity);
1898         }
1899
1900         /**
1901          * {@inheritDoc}
1902          */
1903         @Override
1904         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1905                 new Thread(new Runnable() {
1906
1907                         @Override
1908                         @SuppressWarnings("synthetic-access")
1909                         public void run() {
1910                                 Sone sone = getRemoteSone(identity.getId());
1911                                 sone.setIdentity(identity);
1912                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1913                                 soneDownloader.addSone(sone);
1914                                 soneDownloader.fetchSone(sone);
1915                         }
1916                 }).start();
1917         }
1918
1919         /**
1920          * {@inheritDoc}
1921          */
1922         @Override
1923         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
1924                 trustedIdentities.get(ownIdentity).remove(identity);
1925                 boolean foundIdentity = false;
1926                 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
1927                         if (trustedIdentity.getKey().equals(ownIdentity)) {
1928                                 continue;
1929                         }
1930                         if (trustedIdentity.getValue().contains(identity)) {
1931                                 foundIdentity = true;
1932                         }
1933                 }
1934                 if (foundIdentity) {
1935                         /* some local identity still trusts this identity, don’t remove. */
1936                         return;
1937                 }
1938                 Sone sone = getSone(identity.getId(), false);
1939                 if (sone == null) {
1940                         /* TODO - we don’t have the Sone anymore. should this happen? */
1941                         return;
1942                 }
1943                 synchronized (posts) {
1944                         synchronized (newPosts) {
1945                                 for (Post post : sone.getPosts()) {
1946                                         posts.remove(post.getId());
1947                                         newPosts.remove(post.getId());
1948                                         coreListenerManager.firePostRemoved(post);
1949                                 }
1950                         }
1951                 }
1952                 synchronized (replies) {
1953                         synchronized (newReplies) {
1954                                 for (Reply reply : sone.getReplies()) {
1955                                         replies.remove(reply.getId());
1956                                         newReplies.remove(reply.getId());
1957                                         coreListenerManager.fireReplyRemoved(reply);
1958                                 }
1959                         }
1960                 }
1961                 synchronized (remoteSones) {
1962                         remoteSones.remove(identity.getId());
1963                 }
1964                 synchronized (newSones) {
1965                         newSones.remove(identity.getId());
1966                 }
1967         }
1968
1969         //
1970         // INTERFACE UpdateListener
1971         //
1972
1973         /**
1974          * {@inheritDoc}
1975          */
1976         @Override
1977         public void updateFound(Version version, long releaseTime, long latestEdition) {
1978                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
1979         }
1980
1981         /**
1982          * Convenience interface for external classes that want to access the core’s
1983          * configuration.
1984          *
1985          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1986          */
1987         public static class Preferences {
1988
1989                 /** The wrapped options. */
1990                 private final Options options;
1991
1992                 /**
1993                  * Creates a new preferences object wrapped around the given options.
1994                  *
1995                  * @param options
1996                  *            The options to wrap
1997                  */
1998                 public Preferences(Options options) {
1999                         this.options = options;
2000                 }
2001
2002                 /**
2003                  * Returns the insertion delay.
2004                  *
2005                  * @return The insertion delay
2006                  */
2007                 public int getInsertionDelay() {
2008                         return options.getIntegerOption("InsertionDelay").get();
2009                 }
2010
2011                 /**
2012                  * Sets the insertion delay
2013                  *
2014                  * @param insertionDelay
2015                  *            The new insertion delay, or {@code null} to restore it to
2016                  *            the default value
2017                  * @return This preferences
2018                  */
2019                 public Preferences setInsertionDelay(Integer insertionDelay) {
2020                         options.getIntegerOption("InsertionDelay").set(insertionDelay);
2021                         return this;
2022                 }
2023
2024                 /**
2025                  * Returns the number of posts to show per page.
2026                  *
2027                  * @return The number of posts to show per page
2028                  */
2029                 public int getPostsPerPage() {
2030                         return options.getIntegerOption("PostsPerPage").get();
2031                 }
2032
2033                 /**
2034                  * Sets the number of posts to show per page.
2035                  *
2036                  * @param postsPerPage
2037                  *            The number of posts to show per page
2038                  * @return This preferences object
2039                  */
2040                 public Preferences setPostsPerPage(Integer postsPerPage) {
2041                         options.getIntegerOption("PostsPerPage").set(postsPerPage);
2042                         return this;
2043                 }
2044
2045                 /**
2046                  * Returns the positive trust.
2047                  *
2048                  * @return The positive trust
2049                  */
2050                 public int getPositiveTrust() {
2051                         return options.getIntegerOption("PositiveTrust").get();
2052                 }
2053
2054                 /**
2055                  * Sets the positive trust.
2056                  *
2057                  * @param positiveTrust
2058                  *            The new positive trust, or {@code null} to restore it to
2059                  *            the default vlaue
2060                  * @return This preferences
2061                  */
2062                 public Preferences setPositiveTrust(Integer positiveTrust) {
2063                         options.getIntegerOption("PositiveTrust").set(positiveTrust);
2064                         return this;
2065                 }
2066
2067                 /**
2068                  * Returns the negative trust.
2069                  *
2070                  * @return The negative trust
2071                  */
2072                 public int getNegativeTrust() {
2073                         return options.getIntegerOption("NegativeTrust").get();
2074                 }
2075
2076                 /**
2077                  * Sets the negative trust.
2078                  *
2079                  * @param negativeTrust
2080                  *            The negative trust, or {@code null} to restore it to the
2081                  *            default value
2082                  * @return The preferences
2083                  */
2084                 public Preferences setNegativeTrust(Integer negativeTrust) {
2085                         options.getIntegerOption("NegativeTrust").set(negativeTrust);
2086                         return this;
2087                 }
2088
2089                 /**
2090                  * Returns the trust comment. This is the comment that is set in the web
2091                  * of trust when a trust value is assigned to an identity.
2092                  *
2093                  * @return The trust comment
2094                  */
2095                 public String getTrustComment() {
2096                         return options.getStringOption("TrustComment").get();
2097                 }
2098
2099                 /**
2100                  * Sets the trust comment.
2101                  *
2102                  * @param trustComment
2103                  *            The trust comment, or {@code null} to restore it to the
2104                  *            default value
2105                  * @return This preferences
2106                  */
2107                 public Preferences setTrustComment(String trustComment) {
2108                         options.getStringOption("TrustComment").set(trustComment);
2109                         return this;
2110                 }
2111
2112                 /**
2113                  * Returns whether the rescue mode is active.
2114                  *
2115                  * @return {@code true} if the rescue mode is active, {@code false}
2116                  *         otherwise
2117                  */
2118                 public boolean isSoneRescueMode() {
2119                         return options.getBooleanOption("SoneRescueMode").get();
2120                 }
2121
2122                 /**
2123                  * Sets whether the rescue mode is active.
2124                  *
2125                  * @param soneRescueMode
2126                  *            {@code true} if the rescue mode is active, {@code false}
2127                  *            otherwise
2128                  * @return This preferences
2129                  */
2130                 public Preferences setSoneRescueMode(Boolean soneRescueMode) {
2131                         options.getBooleanOption("SoneRescueMode").set(soneRescueMode);
2132                         return this;
2133                 }
2134
2135                 /**
2136                  * Returns whether Sone should clear its settings on the next restart.
2137                  * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2138                  * to return {@code true} as well!
2139                  *
2140                  * @return {@code true} if Sone should clear its settings on the next
2141                  *         restart, {@code false} otherwise
2142                  */
2143                 public boolean isClearOnNextRestart() {
2144                         return options.getBooleanOption("ClearOnNextRestart").get();
2145                 }
2146
2147                 /**
2148                  * Sets whether Sone will clear its settings on the next restart.
2149                  *
2150                  * @param clearOnNextRestart
2151                  *            {@code true} if Sone should clear its settings on the next
2152                  *            restart, {@code false} otherwise
2153                  * @return This preferences
2154                  */
2155                 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2156                         options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2157                         return this;
2158                 }
2159
2160                 /**
2161                  * Returns whether Sone should really clear its settings on next
2162                  * restart. This is a confirmation option that needs to be set in
2163                  * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2164                  * settings on the next restart.
2165                  *
2166                  * @return {@code true} if Sone should really clear its settings on the
2167                  *         next restart, {@code false} otherwise
2168                  */
2169                 public boolean isReallyClearOnNextRestart() {
2170                         return options.getBooleanOption("ReallyClearOnNextRestart").get();
2171                 }
2172
2173                 /**
2174                  * Sets whether Sone should really clear its settings on the next
2175                  * restart.
2176                  *
2177                  * @param reallyClearOnNextRestart
2178                  *            {@code true} if Sone should really clear its settings on
2179                  *            the next restart, {@code false} otherwise
2180                  * @return This preferences
2181                  */
2182                 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2183                         options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);
2184                         return this;
2185                 }
2186
2187         }
2188
2189 }