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