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