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