Convert “new post reply found” into EventBus-based event.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.java - Copyright © 2010–2012 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.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.Set;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
34
35 import net.pterodactylus.sone.core.Options.DefaultOption;
36 import net.pterodactylus.sone.core.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
39 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
40 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
41 import net.pterodactylus.sone.data.Album;
42 import net.pterodactylus.sone.data.Client;
43 import net.pterodactylus.sone.data.Image;
44 import net.pterodactylus.sone.data.Post;
45 import net.pterodactylus.sone.data.PostReply;
46 import net.pterodactylus.sone.data.Profile;
47 import net.pterodactylus.sone.data.Profile.Field;
48 import net.pterodactylus.sone.data.Reply;
49 import net.pterodactylus.sone.data.Sone;
50 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
51 import net.pterodactylus.sone.data.Sone.SoneStatus;
52 import net.pterodactylus.sone.data.TemporaryImage;
53 import net.pterodactylus.sone.data.impl.PostImpl;
54 import net.pterodactylus.sone.fcp.FcpInterface;
55 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
56 import net.pterodactylus.sone.freenet.wot.Identity;
57 import net.pterodactylus.sone.freenet.wot.IdentityListener;
58 import net.pterodactylus.sone.freenet.wot.IdentityManager;
59 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
60 import net.pterodactylus.sone.main.SonePlugin;
61 import net.pterodactylus.util.config.Configuration;
62 import net.pterodactylus.util.config.ConfigurationException;
63 import net.pterodactylus.util.logging.Logging;
64 import net.pterodactylus.util.number.Numbers;
65 import net.pterodactylus.util.service.AbstractService;
66 import net.pterodactylus.util.thread.NamedThreadFactory;
67 import net.pterodactylus.util.thread.Ticker;
68 import net.pterodactylus.util.validation.EqualityValidator;
69 import net.pterodactylus.util.validation.IntegerRangeValidator;
70 import net.pterodactylus.util.validation.OrValidator;
71 import net.pterodactylus.util.validation.Validation;
72 import net.pterodactylus.util.version.Version;
73
74 import com.google.common.base.Predicate;
75 import com.google.common.collect.Collections2;
76 import com.google.common.eventbus.EventBus;
77 import com.google.inject.Inject;
78
79 import freenet.keys.FreenetURI;
80
81 /**
82  * The Sone core.
83  *
84  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
85  */
86 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
87
88         /** The logger. */
89         private static final Logger logger = Logging.getLogger(Core.class);
90
91         /** The start time. */
92         private final long startupTime = System.currentTimeMillis();
93
94         /** The options. */
95         private final Options options = new Options();
96
97         /** The preferences. */
98         private final Preferences preferences = new Preferences(options);
99
100         /** The core listener manager. */
101         private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
102
103         /** The event bus. */
104         private final EventBus eventBus;
105
106         /** The configuration. */
107         private Configuration configuration;
108
109         /** Whether we’re currently saving the configuration. */
110         private boolean storingConfiguration = false;
111
112         /** The identity manager. */
113         private final IdentityManager identityManager;
114
115         /** Interface to freenet. */
116         private final FreenetInterface freenetInterface;
117
118         /** The Sone downloader. */
119         private final SoneDownloader soneDownloader;
120
121         /** The image inserter. */
122         private final ImageInserter imageInserter;
123
124         /** Sone downloader thread-pool. */
125         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
126
127         /** The update checker. */
128         private final UpdateChecker updateChecker;
129
130         /** The trust updater. */
131         private final WebOfTrustUpdater webOfTrustUpdater;
132
133         /** The FCP interface. */
134         private volatile FcpInterface fcpInterface;
135
136         /** The times Sones were followed. */
137         private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
138
139         /** Locked local Sones. */
140         /* synchronize on itself. */
141         private final Set<Sone> lockedSones = new HashSet<Sone>();
142
143         /** Sone inserters. */
144         /* synchronize access on this on sones. */
145         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
146
147         /** Sone rescuers. */
148         /* synchronize access on this on sones. */
149         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
150
151         /** All Sones. */
152         /* synchronize access on this on itself. */
153         private final Map<String, Sone> sones = new HashMap<String, Sone>();
154
155         /** All known Sones. */
156         private final Set<String> knownSones = new HashSet<String>();
157
158         /** All posts. */
159         private final Map<String, Post> posts = new HashMap<String, Post>();
160
161         /** All known posts. */
162         private final Set<String> knownPosts = new HashSet<String>();
163
164         /** All replies. */
165         private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
166
167         /** All known replies. */
168         private final Set<String> knownReplies = new HashSet<String>();
169
170         /** All bookmarked posts. */
171         /* synchronize access on itself. */
172         private final Set<String> bookmarkedPosts = new HashSet<String>();
173
174         /** Trusted identities, sorted by own identities. */
175         private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
176
177         /** All known albums. */
178         private final Map<String, Album> albums = new HashMap<String, Album>();
179
180         /** All known images. */
181         private final Map<String, Image> images = new HashMap<String, Image>();
182
183         /** All temporary images. */
184         private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
185
186         /** Ticker for threads that mark own elements as known. */
187         private final Ticker localElementTicker = new Ticker();
188
189         /** The time the configuration was last touched. */
190         private volatile long lastConfigurationUpdate;
191
192         /**
193          * Creates a new core.
194          *
195          * @param configuration
196          *            The configuration of the core
197          * @param freenetInterface
198          *            The freenet interface
199          * @param identityManager
200          *            The identity manager
201          * @param webOfTrustUpdater
202          *            The WebOfTrust updater
203          * @param eventBus
204          *            The event bus
205          */
206         @Inject
207         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
208                 super("Sone Core");
209                 this.configuration = configuration;
210                 this.freenetInterface = freenetInterface;
211                 this.identityManager = identityManager;
212                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
213                 this.imageInserter = new ImageInserter(this, freenetInterface);
214                 this.updateChecker = new UpdateChecker(freenetInterface);
215                 this.webOfTrustUpdater = webOfTrustUpdater;
216                 this.eventBus = eventBus;
217         }
218
219         //
220         // LISTENER MANAGEMENT
221         //
222
223         /**
224          * Adds a new core listener.
225          *
226          * @param coreListener
227          *            The listener to add
228          */
229         public void addCoreListener(CoreListener coreListener) {
230                 coreListenerManager.addListener(coreListener);
231         }
232
233         /**
234          * Removes a core listener.
235          *
236          * @param coreListener
237          *            The listener to remove
238          */
239         public void removeCoreListener(CoreListener coreListener) {
240                 coreListenerManager.removeListener(coreListener);
241         }
242
243         //
244         // ACCESSORS
245         //
246
247         /**
248          * Returns the time Sone was started.
249          *
250          * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
251          */
252         public long getStartupTime() {
253                 return startupTime;
254         }
255
256         /**
257          * Sets the configuration to use. This will automatically save the current
258          * configuration to the given configuration.
259          *
260          * @param configuration
261          *            The new configuration to use
262          */
263         public void setConfiguration(Configuration configuration) {
264                 this.configuration = configuration;
265                 touchConfiguration();
266         }
267
268         /**
269          * Returns the options used by the core.
270          *
271          * @return The options of the core
272          */
273         public Preferences getPreferences() {
274                 return preferences;
275         }
276
277         /**
278          * Returns the identity manager used by the core.
279          *
280          * @return The identity manager
281          */
282         public IdentityManager getIdentityManager() {
283                 return identityManager;
284         }
285
286         /**
287          * Returns the update checker.
288          *
289          * @return The update checker
290          */
291         public UpdateChecker getUpdateChecker() {
292                 return updateChecker;
293         }
294
295         /**
296          * Sets the FCP interface to use.
297          *
298          * @param fcpInterface
299          *            The FCP interface to use
300          */
301         public void setFcpInterface(FcpInterface fcpInterface) {
302                 this.fcpInterface = fcpInterface;
303         }
304
305         /**
306          * Returns the Sone rescuer for the given local Sone.
307          *
308          * @param sone
309          *            The local Sone to get the rescuer for
310          * @return The Sone rescuer for the given Sone
311          */
312         public SoneRescuer getSoneRescuer(Sone sone) {
313                 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
314                 synchronized (sones) {
315                         SoneRescuer soneRescuer = soneRescuers.get(sone);
316                         if (soneRescuer == null) {
317                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
318                                 soneRescuers.put(sone, soneRescuer);
319                                 soneRescuer.start();
320                         }
321                         return soneRescuer;
322                 }
323         }
324
325         /**
326          * Returns whether the given Sone is currently locked.
327          *
328          * @param sone
329          *            The sone to check
330          * @return {@code true} if the Sone is locked, {@code false} if it is not
331          */
332         public boolean isLocked(Sone sone) {
333                 synchronized (lockedSones) {
334                         return lockedSones.contains(sone);
335                 }
336         }
337
338         /**
339          * Returns all Sones, remote and local.
340          *
341          * @return All Sones
342          */
343         public Set<Sone> getSones() {
344                 return new HashSet<Sone>(sones.values());
345         }
346
347         /**
348          * Returns the Sone with the given ID, regardless whether it’s local or
349          * remote.
350          *
351          * @param id
352          *            The ID of the Sone to get
353          * @return The Sone with the given ID, or {@code null} if there is no such
354          *         Sone
355          */
356         public Sone getSone(String id) {
357                 return getSone(id, true);
358         }
359
360         /**
361          * Returns the Sone with the given ID, regardless whether it’s local or
362          * remote.
363          *
364          * @param id
365          *            The ID of the Sone to get
366          * @param create
367          *            {@code true} to create a new Sone if none exists,
368          *            {@code false} to return {@code null} if a Sone with the given
369          *            ID does not exist
370          * @return The Sone with the given ID, or {@code null} if there is no such
371          *         Sone
372          */
373         @Override
374         public Sone getSone(String id, boolean create) {
375                 synchronized (sones) {
376                         if (!sones.containsKey(id)) {
377                                 Sone sone = new Sone(id, false);
378                                 sones.put(id, sone);
379                         }
380                         return sones.get(id);
381                 }
382         }
383
384         /**
385          * Checks whether the core knows a Sone with the given ID.
386          *
387          * @param id
388          *            The ID of the Sone
389          * @return {@code true} if there is a Sone with the given ID, {@code false}
390          *         otherwise
391          */
392         public boolean hasSone(String id) {
393                 synchronized (sones) {
394                         return sones.containsKey(id);
395                 }
396         }
397
398         /**
399          * Returns all local Sones.
400          *
401          * @return All local Sones
402          */
403         public Collection<Sone> getLocalSones() {
404                 synchronized (sones) {
405                         return Collections2.filter(sones.values(), new Predicate<Sone>() {
406
407                                 @Override
408                                 public boolean apply(Sone sone) {
409                                         return sone.isLocal();
410                                 }
411                         });
412                 }
413         }
414
415         /**
416          * Returns the local Sone with the given ID, optionally creating a new Sone.
417          *
418          * @param id
419          *            The ID of the Sone
420          * @param create
421          *            {@code true} to create a new Sone if none exists,
422          *            {@code false} to return null if none exists
423          * @return The Sone with the given ID, or {@code null}
424          */
425         public Sone getLocalSone(String id, boolean create) {
426                 synchronized (sones) {
427                         Sone sone = sones.get(id);
428                         if ((sone == null) && create) {
429                                 sone = new Sone(id, true);
430                                 sones.put(id, sone);
431                         }
432                         if ((sone != null) && !sone.isLocal()) {
433                                 sone = new Sone(id, true);
434                                 sones.put(id, sone);
435                         }
436                         return sone;
437                 }
438         }
439
440         /**
441          * Returns all remote Sones.
442          *
443          * @return All remote Sones
444          */
445         public Collection<Sone> getRemoteSones() {
446                 synchronized (sones) {
447                         return Collections2.filter(sones.values(), new Predicate<Sone>() {
448
449                                 @Override
450                                 public boolean apply(Sone sone) {
451                                         return !sone.isLocal();
452                                 }
453                         });
454                 }
455         }
456
457         /**
458          * Returns the remote Sone with the given ID.
459          *
460          * @param id
461          *            The ID of the remote Sone to get
462          * @param create
463          *            {@code true} to always create a Sone, {@code false} to return
464          *            {@code null} if no Sone with the given ID exists
465          * @return The Sone with the given ID
466          */
467         public Sone getRemoteSone(String id, boolean create) {
468                 synchronized (sones) {
469                         Sone sone = sones.get(id);
470                         if ((sone == null) && create && (id != null) && (id.length() == 43)) {
471                                 sone = new Sone(id, false);
472                                 sones.put(id, sone);
473                         }
474                         return sone;
475                 }
476         }
477
478         /**
479          * Returns whether the given Sone has been modified.
480          *
481          * @param sone
482          *            The Sone to check for modifications
483          * @return {@code true} if a modification has been detected in the Sone,
484          *         {@code false} otherwise
485          */
486         public boolean isModifiedSone(Sone sone) {
487                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
488         }
489
490         /**
491          * Returns the time when the given was first followed by any local Sone.
492          *
493          * @param sone
494          *            The Sone to get the time for
495          * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
496          *         been followed, or {@link Long#MAX_VALUE}
497          */
498         public long getSoneFollowingTime(Sone sone) {
499                 synchronized (soneFollowingTimes) {
500                         if (soneFollowingTimes.containsKey(sone)) {
501                                 return soneFollowingTimes.get(sone);
502                         }
503                         return Long.MAX_VALUE;
504                 }
505         }
506
507         /**
508          * Returns whether the target Sone is trusted by the origin Sone.
509          *
510          * @param origin
511          *            The origin Sone
512          * @param target
513          *            The target Sone
514          * @return {@code true} if the target Sone is trusted by the origin Sone
515          */
516         public boolean isSoneTrusted(Sone origin, Sone target) {
517                 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
518                 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
519         }
520
521         /**
522          * Returns the post with the given ID.
523          *
524          * @param postId
525          *            The ID of the post to get
526          * @return The post with the given ID, or a new post with the given ID
527          */
528         public Post getPost(String postId) {
529                 return getPost(postId, true);
530         }
531
532         /**
533          * Returns the post with the given ID, optionally creating a new post.
534          *
535          * @param postId
536          *            The ID of the post to get
537          * @param create
538          *            {@code true} it create a new post if no post with the given ID
539          *            exists, {@code false} to return {@code null}
540          * @return The post, or {@code null} if there is no such post
541          */
542         @Override
543         public Post getPost(String postId, boolean create) {
544                 synchronized (posts) {
545                         Post post = posts.get(postId);
546                         if ((post == null) && create) {
547                                 post = new PostImpl(postId);
548                                 posts.put(postId, post);
549                         }
550                         return post;
551                 }
552         }
553
554         /**
555          * Returns all posts that have the given Sone as recipient.
556          *
557          * @see Post#getRecipient()
558          * @param recipient
559          *            The recipient of the posts
560          * @return All posts that have the given Sone as recipient
561          */
562         public Set<Post> getDirectedPosts(Sone recipient) {
563                 Validation.begin().isNotNull("Recipient", recipient).check();
564                 Set<Post> directedPosts = new HashSet<Post>();
565                 synchronized (posts) {
566                         for (Post post : posts.values()) {
567                                 if (recipient.equals(post.getRecipient())) {
568                                         directedPosts.add(post);
569                                 }
570                         }
571                 }
572                 return directedPosts;
573         }
574
575         /**
576          * Returns the reply with the given ID. If there is no reply with the given
577          * ID yet, a new one is created, unless {@code create} is false in which
578          * case {@code null} is returned.
579          *
580          * @param replyId
581          *            The ID of the reply to get
582          * @param create
583          *            {@code true} to always return a {@link Reply}, {@code false}
584          *            to return {@code null} if no reply can be found
585          * @return The reply, or {@code null} if there is no such reply
586          */
587         public PostReply getPostReply(String replyId, boolean create) {
588                 synchronized (replies) {
589                         PostReply reply = replies.get(replyId);
590                         if (create && (reply == null)) {
591                                 reply = new PostReply(replyId);
592                                 replies.put(replyId, reply);
593                         }
594                         return reply;
595                 }
596         }
597
598         /**
599          * Returns all replies for the given post, order ascending by time.
600          *
601          * @param post
602          *            The post to get all replies for
603          * @return All replies for the given post
604          */
605         public List<PostReply> getReplies(Post post) {
606                 Set<Sone> sones = getSones();
607                 List<PostReply> replies = new ArrayList<PostReply>();
608                 for (Sone sone : sones) {
609                         for (PostReply reply : sone.getReplies()) {
610                                 if (reply.getPost().equals(post)) {
611                                         replies.add(reply);
612                                 }
613                         }
614                 }
615                 Collections.sort(replies, Reply.TIME_COMPARATOR);
616                 return replies;
617         }
618
619         /**
620          * Returns all Sones that have liked the given post.
621          *
622          * @param post
623          *            The post to get the liking Sones for
624          * @return The Sones that like the given post
625          */
626         public Set<Sone> getLikes(Post post) {
627                 Set<Sone> sones = new HashSet<Sone>();
628                 for (Sone sone : getSones()) {
629                         if (sone.getLikedPostIds().contains(post.getId())) {
630                                 sones.add(sone);
631                         }
632                 }
633                 return sones;
634         }
635
636         /**
637          * Returns all Sones that have liked the given reply.
638          *
639          * @param reply
640          *            The reply to get the liking Sones for
641          * @return The Sones that like the given reply
642          */
643         public Set<Sone> getLikes(PostReply reply) {
644                 Set<Sone> sones = new HashSet<Sone>();
645                 for (Sone sone : getSones()) {
646                         if (sone.getLikedReplyIds().contains(reply.getId())) {
647                                 sones.add(sone);
648                         }
649                 }
650                 return sones;
651         }
652
653         /**
654          * Returns whether the given post is bookmarked.
655          *
656          * @param post
657          *            The post to check
658          * @return {@code true} if the given post is bookmarked, {@code false}
659          *         otherwise
660          */
661         public boolean isBookmarked(Post post) {
662                 return isPostBookmarked(post.getId());
663         }
664
665         /**
666          * Returns whether the post with the given ID is bookmarked.
667          *
668          * @param id
669          *            The ID of the post to check
670          * @return {@code true} if the post with the given ID is bookmarked,
671          *         {@code false} otherwise
672          */
673         public boolean isPostBookmarked(String id) {
674                 synchronized (bookmarkedPosts) {
675                         return bookmarkedPosts.contains(id);
676                 }
677         }
678
679         /**
680          * Returns all currently known bookmarked posts.
681          *
682          * @return All bookmarked posts
683          */
684         public Set<Post> getBookmarkedPosts() {
685                 Set<Post> posts = new HashSet<Post>();
686                 synchronized (bookmarkedPosts) {
687                         for (String bookmarkedPostId : bookmarkedPosts) {
688                                 Post post = getPost(bookmarkedPostId, false);
689                                 if (post != null) {
690                                         posts.add(post);
691                                 }
692                         }
693                 }
694                 return posts;
695         }
696
697         /**
698          * Returns the album with the given ID, creating a new album if no album
699          * with the given ID can be found.
700          *
701          * @param albumId
702          *            The ID of the album
703          * @return The album with the given ID
704          */
705         public Album getAlbum(String albumId) {
706                 return getAlbum(albumId, true);
707         }
708
709         /**
710          * Returns the album with the given ID, optionally creating a new album if
711          * an album with the given ID can not be found.
712          *
713          * @param albumId
714          *            The ID of the album
715          * @param create
716          *            {@code true} to create a new album if none exists for the
717          *            given ID
718          * @return The album with the given ID, or {@code null} if no album with the
719          *         given ID exists and {@code create} is {@code false}
720          */
721         public Album getAlbum(String albumId, boolean create) {
722                 synchronized (albums) {
723                         Album album = albums.get(albumId);
724                         if (create && (album == null)) {
725                                 album = new Album(albumId);
726                                 albums.put(albumId, album);
727                         }
728                         return album;
729                 }
730         }
731
732         /**
733          * Returns the image with the given ID, creating it if necessary.
734          *
735          * @param imageId
736          *            The ID of the image
737          * @return The image with the given ID
738          */
739         public Image getImage(String imageId) {
740                 return getImage(imageId, true);
741         }
742
743         /**
744          * Returns the image with the given ID, optionally creating it if it does
745          * not exist.
746          *
747          * @param imageId
748          *            The ID of the image
749          * @param create
750          *            {@code true} to create an image if none exists with the given
751          *            ID
752          * @return The image with the given ID, or {@code null} if none exists and
753          *         none was created
754          */
755         public Image getImage(String imageId, boolean create) {
756                 synchronized (images) {
757                         Image image = images.get(imageId);
758                         if (create && (image == null)) {
759                                 image = new Image(imageId);
760                                 images.put(imageId, image);
761                         }
762                         return image;
763                 }
764         }
765
766         /**
767          * Returns the temporary image with the given ID.
768          *
769          * @param imageId
770          *            The ID of the temporary image
771          * @return The temporary image, or {@code null} if there is no temporary
772          *         image with the given ID
773          */
774         public TemporaryImage getTemporaryImage(String imageId) {
775                 synchronized (temporaryImages) {
776                         return temporaryImages.get(imageId);
777                 }
778         }
779
780         //
781         // ACTIONS
782         //
783
784         /**
785          * Locks the given Sone. A locked Sone will not be inserted by
786          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
787          * again.
788          *
789          * @param sone
790          *            The sone to lock
791          */
792         public void lockSone(Sone sone) {
793                 synchronized (lockedSones) {
794                         if (lockedSones.add(sone)) {
795                                 coreListenerManager.fireSoneLocked(sone);
796                         }
797                 }
798         }
799
800         /**
801          * Unlocks the given Sone.
802          *
803          * @see #lockSone(Sone)
804          * @param sone
805          *            The sone to unlock
806          */
807         public void unlockSone(Sone sone) {
808                 synchronized (lockedSones) {
809                         if (lockedSones.remove(sone)) {
810                                 coreListenerManager.fireSoneUnlocked(sone);
811                         }
812                 }
813         }
814
815         /**
816          * Adds a local Sone from the given own identity.
817          *
818          * @param ownIdentity
819          *            The own identity to create a Sone from
820          * @return The added (or already existing) Sone
821          */
822         public Sone addLocalSone(OwnIdentity ownIdentity) {
823                 if (ownIdentity == null) {
824                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
825                         return null;
826                 }
827                 synchronized (sones) {
828                         final Sone sone;
829                         try {
830                                 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
831                         } catch (MalformedURLException mue1) {
832                                 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
833                                 return null;
834                         }
835                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
836                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
837                         sone.setKnown(true);
838                         /* TODO - load posts ’n stuff */
839                         sones.put(ownIdentity.getId(), sone);
840                         final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
841                         soneInserter.addSoneInsertListener(this);
842                         soneInserters.put(sone, soneInserter);
843                         sone.setStatus(SoneStatus.idle);
844                         loadSone(sone);
845                         soneInserter.start();
846                         return sone;
847                 }
848         }
849
850         /**
851          * Creates a new Sone for the given own identity.
852          *
853          * @param ownIdentity
854          *            The own identity to create a Sone for
855          * @return The created Sone
856          */
857         public Sone createSone(OwnIdentity ownIdentity) {
858                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
859                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
860                         return null;
861                 }
862                 Sone sone = addLocalSone(ownIdentity);
863                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
864                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
865                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
866                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
867                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
868                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
869
870                 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
871                 touchConfiguration();
872                 return sone;
873         }
874
875         /**
876          * Adds the Sone of the given identity.
877          *
878          * @param identity
879          *            The identity whose Sone to add
880          * @return The added or already existing Sone
881          */
882         public Sone addRemoteSone(Identity identity) {
883                 if (identity == null) {
884                         logger.log(Level.WARNING, "Given Identity is null!");
885                         return null;
886                 }
887                 synchronized (sones) {
888                         final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
889                         boolean newSone = sone.getRequestUri() == null;
890                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
891                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
892                         if (newSone) {
893                                 synchronized (knownSones) {
894                                         newSone = !knownSones.contains(sone.getId());
895                                 }
896                                 sone.setKnown(!newSone);
897                                 if (newSone) {
898                                         eventBus.post(new NewSoneFoundEvent(sone));
899                                         for (Sone localSone : getLocalSones()) {
900                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
901                                                         followSone(localSone, sone);
902                                                 }
903                                         }
904                                 }
905                         }
906                         soneDownloader.addSone(sone);
907                         soneDownloaders.execute(new Runnable() {
908
909                                 @Override
910                                 @SuppressWarnings("synthetic-access")
911                                 public void run() {
912                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
913                                 }
914
915                         });
916                         return sone;
917                 }
918         }
919
920         /**
921          * Lets the given local Sone follow the Sone with the given ID.
922          *
923          * @param sone
924          *            The local Sone that should follow another Sone
925          * @param soneId
926          *            The ID of the Sone to follow
927          */
928         public void followSone(Sone sone, String soneId) {
929                 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
930                 Sone followedSone = getSone(soneId, true);
931                 if (followedSone == null) {
932                         logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
933                         return;
934                 }
935                 followSone(sone, getSone(soneId));
936         }
937
938         /**
939          * Lets the given local Sone follow the other given Sone. If the given Sone
940          * was not followed by any local Sone before, this will mark all elements of
941          * the followed Sone as read that have been created before the current
942          * moment.
943          *
944          * @param sone
945          *            The local Sone that should follow the other Sone
946          * @param followedSone
947          *            The Sone that should be followed
948          */
949         public void followSone(Sone sone, Sone followedSone) {
950                 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
951                 sone.addFriend(followedSone.getId());
952                 synchronized (soneFollowingTimes) {
953                         if (!soneFollowingTimes.containsKey(followedSone)) {
954                                 long now = System.currentTimeMillis();
955                                 soneFollowingTimes.put(followedSone, now);
956                                 for (Post post : followedSone.getPosts()) {
957                                         if (post.getTime() < now) {
958                                                 markPostKnown(post);
959                                         }
960                                 }
961                                 for (PostReply reply : followedSone.getReplies()) {
962                                         if (reply.getTime() < now) {
963                                                 markReplyKnown(reply);
964                                         }
965                                 }
966                         }
967                 }
968                 touchConfiguration();
969         }
970
971         /**
972          * Lets the given local Sone unfollow the Sone with the given ID.
973          *
974          * @param sone
975          *            The local Sone that should unfollow another Sone
976          * @param soneId
977          *            The ID of the Sone being unfollowed
978          */
979         public void unfollowSone(Sone sone, String soneId) {
980                 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
981                 unfollowSone(sone, getSone(soneId, false));
982         }
983
984         /**
985          * Lets the given local Sone unfollow the other given Sone. If the given
986          * local Sone is the last local Sone that followed the given Sone, its
987          * following time will be removed.
988          *
989          * @param sone
990          *            The local Sone that should unfollow another Sone
991          * @param unfollowedSone
992          *            The Sone being unfollowed
993          */
994         public void unfollowSone(Sone sone, Sone unfollowedSone) {
995                 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
996                 sone.removeFriend(unfollowedSone.getId());
997                 boolean unfollowedSoneStillFollowed = false;
998                 for (Sone localSone : getLocalSones()) {
999                         unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1000                 }
1001                 if (!unfollowedSoneStillFollowed) {
1002                         synchronized (soneFollowingTimes) {
1003                                 soneFollowingTimes.remove(unfollowedSone);
1004                         }
1005                 }
1006                 touchConfiguration();
1007         }
1008
1009         /**
1010          * Sets the trust value of the given origin Sone for the target Sone.
1011          *
1012          * @param origin
1013          *            The origin Sone
1014          * @param target
1015          *            The target Sone
1016          * @param trustValue
1017          *            The trust value (from {@code -100} to {@code 100})
1018          */
1019         public void setTrust(Sone origin, Sone target, int trustValue) {
1020                 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();
1021                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1022         }
1023
1024         /**
1025          * Removes any trust assignment for the given target Sone.
1026          *
1027          * @param origin
1028          *            The trust origin
1029          * @param target
1030          *            The trust target
1031          */
1032         public void removeTrust(Sone origin, Sone target) {
1033                 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1034                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1035         }
1036
1037         /**
1038          * Assigns the configured positive trust value for the given target.
1039          *
1040          * @param origin
1041          *            The trust origin
1042          * @param target
1043          *            The trust target
1044          */
1045         public void trustSone(Sone origin, Sone target) {
1046                 setTrust(origin, target, preferences.getPositiveTrust());
1047         }
1048
1049         /**
1050          * Assigns the configured negative trust value for the given target.
1051          *
1052          * @param origin
1053          *            The trust origin
1054          * @param target
1055          *            The trust target
1056          */
1057         public void distrustSone(Sone origin, Sone target) {
1058                 setTrust(origin, target, preferences.getNegativeTrust());
1059         }
1060
1061         /**
1062          * Removes the trust assignment for the given target.
1063          *
1064          * @param origin
1065          *            The trust origin
1066          * @param target
1067          *            The trust target
1068          */
1069         public void untrustSone(Sone origin, Sone target) {
1070                 removeTrust(origin, target);
1071         }
1072
1073         /**
1074          * Updates the stored Sone with the given Sone.
1075          *
1076          * @param sone
1077          *            The updated Sone
1078          */
1079         public void updateSone(Sone sone) {
1080                 updateSone(sone, false);
1081         }
1082
1083         /**
1084          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1085          * {@code true}, an older Sone than the current Sone can be given to restore
1086          * an old state.
1087          *
1088          * @param sone
1089          *            The Sone to update
1090          * @param soneRescueMode
1091          *            {@code true} if the stored Sone should be updated regardless
1092          *            of the age of the given Sone
1093          */
1094         public void updateSone(Sone sone, boolean soneRescueMode) {
1095                 if (hasSone(sone.getId())) {
1096                         Sone storedSone = getSone(sone.getId());
1097                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1098                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1099                                 return;
1100                         }
1101                         synchronized (posts) {
1102                                 if (!soneRescueMode) {
1103                                         for (Post post : storedSone.getPosts()) {
1104                                                 posts.remove(post.getId());
1105                                                 if (!sone.getPosts().contains(post)) {
1106                                                         coreListenerManager.firePostRemoved(post);
1107                                                 }
1108                                         }
1109                                 }
1110                                 List<Post> storedPosts = storedSone.getPosts();
1111                                 synchronized (knownPosts) {
1112                                         for (Post post : sone.getPosts()) {
1113                                                 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1114                                                 if (!storedPosts.contains(post)) {
1115                                                         if (post.getTime() < getSoneFollowingTime(sone)) {
1116                                                                 knownPosts.add(post.getId());
1117                                                                 post.setKnown(true);
1118                                                         } else if (!knownPosts.contains(post.getId())) {
1119                                                                 eventBus.post(new NewPostFoundEvent(post));
1120                                                         }
1121                                                 }
1122                                                 posts.put(post.getId(), post);
1123                                         }
1124                                 }
1125                         }
1126                         synchronized (replies) {
1127                                 if (!soneRescueMode) {
1128                                         for (PostReply reply : storedSone.getReplies()) {
1129                                                 replies.remove(reply.getId());
1130                                                 if (!sone.getReplies().contains(reply)) {
1131                                                         coreListenerManager.fireReplyRemoved(reply);
1132                                                 }
1133                                         }
1134                                 }
1135                                 Set<PostReply> storedReplies = storedSone.getReplies();
1136                                 synchronized (knownReplies) {
1137                                         for (PostReply reply : sone.getReplies()) {
1138                                                 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1139                                                 if (!storedReplies.contains(reply)) {
1140                                                         if (reply.getTime() < getSoneFollowingTime(sone)) {
1141                                                                 knownReplies.add(reply.getId());
1142                                                                 reply.setKnown(true);
1143                                                         } else if (!knownReplies.contains(reply.getId())) {
1144                                                                 eventBus.post(new NewPostReplyFoundEvent(reply));
1145                                                         }
1146                                                 }
1147                                                 replies.put(reply.getId(), reply);
1148                                         }
1149                                 }
1150                         }
1151                         synchronized (albums) {
1152                                 synchronized (images) {
1153                                         for (Album album : storedSone.getAlbums()) {
1154                                                 albums.remove(album.getId());
1155                                                 for (Image image : album.getImages()) {
1156                                                         images.remove(image.getId());
1157                                                 }
1158                                         }
1159                                         for (Album album : sone.getAlbums()) {
1160                                                 albums.put(album.getId(), album);
1161                                                 for (Image image : album.getImages()) {
1162                                                         images.put(image.getId(), image);
1163                                                 }
1164                                         }
1165                                 }
1166                         }
1167                         synchronized (storedSone) {
1168                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1169                                         storedSone.setTime(sone.getTime());
1170                                 }
1171                                 storedSone.setClient(sone.getClient());
1172                                 storedSone.setProfile(sone.getProfile());
1173                                 if (soneRescueMode) {
1174                                         for (Post post : sone.getPosts()) {
1175                                                 storedSone.addPost(post);
1176                                         }
1177                                         for (PostReply reply : sone.getReplies()) {
1178                                                 storedSone.addReply(reply);
1179                                         }
1180                                         for (String likedPostId : sone.getLikedPostIds()) {
1181                                                 storedSone.addLikedPostId(likedPostId);
1182                                         }
1183                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1184                                                 storedSone.addLikedReplyId(likedReplyId);
1185                                         }
1186                                         for (Album album : sone.getAlbums()) {
1187                                                 storedSone.addAlbum(album);
1188                                         }
1189                                 } else {
1190                                         storedSone.setPosts(sone.getPosts());
1191                                         storedSone.setReplies(sone.getReplies());
1192                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1193                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1194                                         storedSone.setAlbums(sone.getAlbums());
1195                                 }
1196                                 storedSone.setLatestEdition(sone.getLatestEdition());
1197                         }
1198                 }
1199         }
1200
1201         /**
1202          * Deletes the given Sone. This will remove the Sone from the
1203          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1204          * remove the context from its identity.
1205          *
1206          * @param sone
1207          *            The Sone to delete
1208          */
1209         public void deleteSone(Sone sone) {
1210                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1211                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1212                         return;
1213                 }
1214                 synchronized (sones) {
1215                         if (!getLocalSones().contains(sone)) {
1216                                 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1217                                 return;
1218                         }
1219                         sones.remove(sone.getId());
1220                         SoneInserter soneInserter = soneInserters.remove(sone);
1221                         soneInserter.removeSoneInsertListener(this);
1222                         soneInserter.stop();
1223                 }
1224                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1225                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1226                 try {
1227                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1228                 } catch (ConfigurationException ce1) {
1229                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1230                 }
1231         }
1232
1233         /**
1234          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1235          * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1236          *
1237          * @param sone
1238          *            The Sone to mark as known
1239          */
1240         public void markSoneKnown(Sone sone) {
1241                 if (!sone.isKnown()) {
1242                         sone.setKnown(true);
1243                         synchronized (knownSones) {
1244                                 knownSones.add(sone.getId());
1245                         }
1246                         coreListenerManager.fireMarkSoneKnown(sone);
1247                         touchConfiguration();
1248                 }
1249         }
1250
1251         /**
1252          * Loads and updates the given Sone from the configuration. If any error is
1253          * encountered, loading is aborted and the given Sone is not changed.
1254          *
1255          * @param sone
1256          *            The Sone to load and update
1257          */
1258         public void loadSone(Sone sone) {
1259                 if (!sone.isLocal()) {
1260                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1261                         return;
1262                 }
1263
1264                 /* initialize options. */
1265                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1266                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1267                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1268                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1269                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1270                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1271
1272                 /* load Sone. */
1273                 String sonePrefix = "Sone/" + sone.getId();
1274                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1275                 if (soneTime == null) {
1276                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1277                         return;
1278                 }
1279                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1280
1281                 /* load profile. */
1282                 Profile profile = new Profile(sone);
1283                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1284                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1285                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1286                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1287                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1288                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1289
1290                 /* load profile fields. */
1291                 while (true) {
1292                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1293                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1294                         if (fieldName == null) {
1295                                 break;
1296                         }
1297                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1298                         profile.addField(fieldName).setValue(fieldValue);
1299                 }
1300
1301                 /* load posts. */
1302                 Set<Post> posts = new HashSet<Post>();
1303                 while (true) {
1304                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1305                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1306                         if (postId == null) {
1307                                 break;
1308                         }
1309                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1310                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1311                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1312                         if ((postTime == 0) || (postText == null)) {
1313                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1314                                 return;
1315                         }
1316                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1317                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1318                                 post.setRecipient(getSone(postRecipientId));
1319                         }
1320                         posts.add(post);
1321                 }
1322
1323                 /* load replies. */
1324                 Set<PostReply> replies = new HashSet<PostReply>();
1325                 while (true) {
1326                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1327                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1328                         if (replyId == null) {
1329                                 break;
1330                         }
1331                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1332                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1333                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1334                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1335                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1336                                 return;
1337                         }
1338                         replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1339                 }
1340
1341                 /* load post likes. */
1342                 Set<String> likedPostIds = new HashSet<String>();
1343                 while (true) {
1344                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1345                         if (likedPostId == null) {
1346                                 break;
1347                         }
1348                         likedPostIds.add(likedPostId);
1349                 }
1350
1351                 /* load reply likes. */
1352                 Set<String> likedReplyIds = new HashSet<String>();
1353                 while (true) {
1354                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1355                         if (likedReplyId == null) {
1356                                 break;
1357                         }
1358                         likedReplyIds.add(likedReplyId);
1359                 }
1360
1361                 /* load friends. */
1362                 Set<String> friends = new HashSet<String>();
1363                 while (true) {
1364                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1365                         if (friendId == null) {
1366                                 break;
1367                         }
1368                         friends.add(friendId);
1369                 }
1370
1371                 /* load albums. */
1372                 List<Album> topLevelAlbums = new ArrayList<Album>();
1373                 int albumCounter = 0;
1374                 while (true) {
1375                         String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1376                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1377                         if (albumId == null) {
1378                                 break;
1379                         }
1380                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1381                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1382                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1383                         String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1384                         if ((albumTitle == null) || (albumDescription == null)) {
1385                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1386                                 return;
1387                         }
1388                         Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1389                         if (albumParentId != null) {
1390                                 Album parentAlbum = getAlbum(albumParentId, false);
1391                                 if (parentAlbum == null) {
1392                                         logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1393                                         return;
1394                                 }
1395                                 parentAlbum.addAlbum(album);
1396                         } else {
1397                                 if (!topLevelAlbums.contains(album)) {
1398                                         topLevelAlbums.add(album);
1399                                 }
1400                         }
1401                 }
1402
1403                 /* load images. */
1404                 int imageCounter = 0;
1405                 while (true) {
1406                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1407                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1408                         if (imageId == null) {
1409                                 break;
1410                         }
1411                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1412                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1413                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1414                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1415                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1416                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1417                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1418                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1419                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1420                                 return;
1421                         }
1422                         Album album = getAlbum(albumId, false);
1423                         if (album == null) {
1424                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1425                                 return;
1426                         }
1427                         Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1428                         image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1429                         album.addImage(image);
1430                 }
1431
1432                 /* load avatar. */
1433                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1434                 if (avatarId != null) {
1435                         profile.setAvatar(getImage(avatarId, false));
1436                 }
1437
1438                 /* load options. */
1439                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1440                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1441                 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1442                 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1443                 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1444                 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1445
1446                 /* if we’re still here, Sone was loaded successfully. */
1447                 synchronized (sone) {
1448                         sone.setTime(soneTime);
1449                         sone.setProfile(profile);
1450                         sone.setPosts(posts);
1451                         sone.setReplies(replies);
1452                         sone.setLikePostIds(likedPostIds);
1453                         sone.setLikeReplyIds(likedReplyIds);
1454                         for (String friendId : friends) {
1455                                 followSone(sone, friendId);
1456                         }
1457                         sone.setAlbums(topLevelAlbums);
1458                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1459                 }
1460                 synchronized (knownSones) {
1461                         for (String friend : friends) {
1462                                 knownSones.add(friend);
1463                         }
1464                 }
1465                 synchronized (knownPosts) {
1466                         for (Post post : posts) {
1467                                 knownPosts.add(post.getId());
1468                         }
1469                 }
1470                 synchronized (knownReplies) {
1471                         for (PostReply reply : replies) {
1472                                 knownReplies.add(reply.getId());
1473                         }
1474                 }
1475         }
1476
1477         /**
1478          * Creates a new post.
1479          *
1480          * @param sone
1481          *            The Sone that creates the post
1482          * @param text
1483          *            The text of the post
1484          * @return The created post
1485          */
1486         public Post createPost(Sone sone, String text) {
1487                 return createPost(sone, System.currentTimeMillis(), text);
1488         }
1489
1490         /**
1491          * Creates a new post.
1492          *
1493          * @param sone
1494          *            The Sone that creates the post
1495          * @param time
1496          *            The time of the post
1497          * @param text
1498          *            The text of the post
1499          * @return The created post
1500          */
1501         public Post createPost(Sone sone, long time, String text) {
1502                 return createPost(sone, null, time, text);
1503         }
1504
1505         /**
1506          * Creates a new post.
1507          *
1508          * @param sone
1509          *            The Sone that creates the post
1510          * @param recipient
1511          *            The recipient Sone, or {@code null} if this post does not have
1512          *            a recipient
1513          * @param text
1514          *            The text of the post
1515          * @return The created post
1516          */
1517         public Post createPost(Sone sone, Sone recipient, String text) {
1518                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1519         }
1520
1521         /**
1522          * Creates a new post.
1523          *
1524          * @param sone
1525          *            The Sone that creates the post
1526          * @param recipient
1527          *            The recipient Sone, or {@code null} if this post does not have
1528          *            a recipient
1529          * @param time
1530          *            The time of the post
1531          * @param text
1532          *            The text of the post
1533          * @return The created post
1534          */
1535         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1536                 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1537                 if (!sone.isLocal()) {
1538                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1539                         return null;
1540                 }
1541                 final Post post = new PostImpl(sone, time, text);
1542                 if (recipient != null) {
1543                         post.setRecipient(recipient);
1544                 }
1545                 synchronized (posts) {
1546                         posts.put(post.getId(), post);
1547                 }
1548                 eventBus.post(new NewPostFoundEvent(post));
1549                 sone.addPost(post);
1550                 touchConfiguration();
1551                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1552
1553                         /**
1554                          * {@inheritDoc}
1555                          */
1556                         @Override
1557                         public void run() {
1558                                 markPostKnown(post);
1559                         }
1560                 }, "Mark " + post + " read.");
1561                 return post;
1562         }
1563
1564         /**
1565          * Deletes the given post.
1566          *
1567          * @param post
1568          *            The post to delete
1569          */
1570         public void deletePost(Post post) {
1571                 if (!post.getSone().isLocal()) {
1572                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1573                         return;
1574                 }
1575                 post.getSone().removePost(post);
1576                 synchronized (posts) {
1577                         posts.remove(post.getId());
1578                 }
1579                 coreListenerManager.firePostRemoved(post);
1580                 markPostKnown(post);
1581                 touchConfiguration();
1582         }
1583
1584         /**
1585          * Marks the given post as known, if it is currently not a known post
1586          * (according to {@link Post#isKnown()}).
1587          *
1588          * @param post
1589          *            The post to mark as known
1590          */
1591         public void markPostKnown(Post post) {
1592                 post.setKnown(true);
1593                 synchronized (knownPosts) {
1594                         coreListenerManager.fireMarkPostKnown(post);
1595                         if (knownPosts.add(post.getId())) {
1596                                 touchConfiguration();
1597                         }
1598                 }
1599                 for (PostReply reply : getReplies(post)) {
1600                         markReplyKnown(reply);
1601                 }
1602         }
1603
1604         /**
1605          * Bookmarks the given post.
1606          *
1607          * @param post
1608          *            The post to bookmark
1609          */
1610         public void bookmark(Post post) {
1611                 bookmarkPost(post.getId());
1612         }
1613
1614         /**
1615          * Bookmarks the post with the given ID.
1616          *
1617          * @param id
1618          *            The ID of the post to bookmark
1619          */
1620         public void bookmarkPost(String id) {
1621                 synchronized (bookmarkedPosts) {
1622                         bookmarkedPosts.add(id);
1623                 }
1624         }
1625
1626         /**
1627          * Removes the given post from the bookmarks.
1628          *
1629          * @param post
1630          *            The post to unbookmark
1631          */
1632         public void unbookmark(Post post) {
1633                 unbookmarkPost(post.getId());
1634         }
1635
1636         /**
1637          * Removes the post with the given ID from the bookmarks.
1638          *
1639          * @param id
1640          *            The ID of the post to unbookmark
1641          */
1642         public void unbookmarkPost(String id) {
1643                 synchronized (bookmarkedPosts) {
1644                         bookmarkedPosts.remove(id);
1645                 }
1646         }
1647
1648         /**
1649          * Creates a new reply.
1650          *
1651          * @param sone
1652          *            The Sone that creates the reply
1653          * @param post
1654          *            The post that this reply refers to
1655          * @param text
1656          *            The text of the reply
1657          * @return The created reply
1658          */
1659         public PostReply createReply(Sone sone, Post post, String text) {
1660                 return createReply(sone, post, System.currentTimeMillis(), text);
1661         }
1662
1663         /**
1664          * Creates a new reply.
1665          *
1666          * @param sone
1667          *            The Sone that creates the reply
1668          * @param post
1669          *            The post that this reply refers to
1670          * @param time
1671          *            The time of the reply
1672          * @param text
1673          *            The text of the reply
1674          * @return The created reply
1675          */
1676         public PostReply createReply(Sone sone, Post post, long time, String text) {
1677                 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1678                 if (!sone.isLocal()) {
1679                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1680                         return null;
1681                 }
1682                 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1683                 synchronized (replies) {
1684                         replies.put(reply.getId(), reply);
1685                 }
1686                 synchronized (knownReplies) {
1687                         eventBus.post(new NewPostReplyFoundEvent(reply));
1688                 }
1689                 sone.addReply(reply);
1690                 touchConfiguration();
1691                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1692
1693                         /**
1694                          * {@inheritDoc}
1695                          */
1696                         @Override
1697                         public void run() {
1698                                 markReplyKnown(reply);
1699                         }
1700                 }, "Mark " + reply + " read.");
1701                 return reply;
1702         }
1703
1704         /**
1705          * Deletes the given reply.
1706          *
1707          * @param reply
1708          *            The reply to delete
1709          */
1710         public void deleteReply(PostReply reply) {
1711                 Sone sone = reply.getSone();
1712                 if (!sone.isLocal()) {
1713                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1714                         return;
1715                 }
1716                 synchronized (replies) {
1717                         replies.remove(reply.getId());
1718                 }
1719                 synchronized (knownReplies) {
1720                         markReplyKnown(reply);
1721                         knownReplies.remove(reply.getId());
1722                 }
1723                 sone.removeReply(reply);
1724                 touchConfiguration();
1725         }
1726
1727         /**
1728          * Marks the given reply as known, if it is currently not a known reply
1729          * (according to {@link Reply#isKnown()}).
1730          *
1731          * @param reply
1732          *            The reply to mark as known
1733          */
1734         public void markReplyKnown(PostReply reply) {
1735                 reply.setKnown(true);
1736                 synchronized (knownReplies) {
1737                         coreListenerManager.fireMarkReplyKnown(reply);
1738                         if (knownReplies.add(reply.getId())) {
1739                                 touchConfiguration();
1740                         }
1741                 }
1742         }
1743
1744         /**
1745          * Creates a new top-level album for the given Sone.
1746          *
1747          * @param sone
1748          *            The Sone to create the album for
1749          * @return The new album
1750          */
1751         public Album createAlbum(Sone sone) {
1752                 return createAlbum(sone, null);
1753         }
1754
1755         /**
1756          * Creates a new album for the given Sone.
1757          *
1758          * @param sone
1759          *            The Sone to create the album for
1760          * @param parent
1761          *            The parent of the album (may be {@code null} to create a
1762          *            top-level album)
1763          * @return The new album
1764          */
1765         public Album createAlbum(Sone sone, Album parent) {
1766                 Album album = new Album();
1767                 synchronized (albums) {
1768                         albums.put(album.getId(), album);
1769                 }
1770                 album.setSone(sone);
1771                 if (parent != null) {
1772                         parent.addAlbum(album);
1773                 } else {
1774                         sone.addAlbum(album);
1775                 }
1776                 return album;
1777         }
1778
1779         /**
1780          * Deletes the given album. The owner of the album has to be a local Sone,
1781          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1782          *
1783          * @param album
1784          *            The album to remove
1785          */
1786         public void deleteAlbum(Album album) {
1787                 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1788                 if (!album.isEmpty()) {
1789                         return;
1790                 }
1791                 if (album.getParent() == null) {
1792                         album.getSone().removeAlbum(album);
1793                 } else {
1794                         album.getParent().removeAlbum(album);
1795                 }
1796                 synchronized (albums) {
1797                         albums.remove(album.getId());
1798                 }
1799                 touchConfiguration();
1800         }
1801
1802         /**
1803          * Creates a new image.
1804          *
1805          * @param sone
1806          *            The Sone creating the image
1807          * @param album
1808          *            The album the image will be inserted into
1809          * @param temporaryImage
1810          *            The temporary image to create the image from
1811          * @return The newly created image
1812          */
1813         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1814                 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", sone.isLocal()).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1815                 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1816                 album.addImage(image);
1817                 synchronized (images) {
1818                         images.put(image.getId(), image);
1819                 }
1820                 imageInserter.insertImage(temporaryImage, image);
1821                 return image;
1822         }
1823
1824         /**
1825          * Deletes the given image. This method will also delete a matching
1826          * temporary image.
1827          *
1828          * @see #deleteTemporaryImage(TemporaryImage)
1829          * @param image
1830          *            The image to delete
1831          */
1832         public void deleteImage(Image image) {
1833                 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1834                 deleteTemporaryImage(image.getId());
1835                 image.getAlbum().removeImage(image);
1836                 synchronized (images) {
1837                         images.remove(image.getId());
1838                 }
1839                 touchConfiguration();
1840         }
1841
1842         /**
1843          * Creates a new temporary image.
1844          *
1845          * @param mimeType
1846          *            The MIME type of the temporary image
1847          * @param imageData
1848          *            The encoded data of the image
1849          * @return The temporary image
1850          */
1851         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1852                 TemporaryImage temporaryImage = new TemporaryImage();
1853                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1854                 synchronized (temporaryImages) {
1855                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1856                 }
1857                 return temporaryImage;
1858         }
1859
1860         /**
1861          * Deletes the given temporary image.
1862          *
1863          * @param temporaryImage
1864          *            The temporary image to delete
1865          */
1866         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1867                 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1868                 deleteTemporaryImage(temporaryImage.getId());
1869         }
1870
1871         /**
1872          * Deletes the temporary image with the given ID.
1873          *
1874          * @param imageId
1875          *            The ID of the temporary image to delete
1876          */
1877         public void deleteTemporaryImage(String imageId) {
1878                 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1879                 synchronized (temporaryImages) {
1880                         temporaryImages.remove(imageId);
1881                 }
1882                 Image image = getImage(imageId, false);
1883                 if (image != null) {
1884                         imageInserter.cancelImageInsert(image);
1885                 }
1886         }
1887
1888         /**
1889          * Notifies the core that the configuration, either of the core or of a
1890          * single local Sone, has changed, and that the configuration should be
1891          * saved.
1892          */
1893         public void touchConfiguration() {
1894                 lastConfigurationUpdate = System.currentTimeMillis();
1895         }
1896
1897         //
1898         // SERVICE METHODS
1899         //
1900
1901         /**
1902          * Starts the core.
1903          */
1904         @Override
1905         public void serviceStart() {
1906                 loadConfiguration();
1907                 updateChecker.addUpdateListener(this);
1908                 updateChecker.start();
1909                 identityManager.addIdentityListener(this);
1910                 identityManager.start();
1911                 webOfTrustUpdater.init();
1912                 webOfTrustUpdater.start();
1913         }
1914
1915         /**
1916          * {@inheritDoc}
1917          */
1918         @Override
1919         public void serviceRun() {
1920                 long lastSaved = System.currentTimeMillis();
1921                 while (!shouldStop()) {
1922                         sleep(1000);
1923                         long now = System.currentTimeMillis();
1924                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1925                                 for (Sone localSone : getLocalSones()) {
1926                                         saveSone(localSone);
1927                                 }
1928                                 saveConfiguration();
1929                                 lastSaved = now;
1930                         }
1931                 }
1932         }
1933
1934         /**
1935          * Stops the core.
1936          */
1937         @Override
1938         public void serviceStop() {
1939                 synchronized (sones) {
1940                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1941                                 soneInserter.getValue().removeSoneInsertListener(this);
1942                                 soneInserter.getValue().stop();
1943                                 saveSone(soneInserter.getKey());
1944                         }
1945                 }
1946                 saveConfiguration();
1947                 webOfTrustUpdater.stop();
1948                 updateChecker.stop();
1949                 updateChecker.removeUpdateListener(this);
1950                 soneDownloader.stop();
1951                 identityManager.removeIdentityListener(this);
1952                 identityManager.stop();
1953         }
1954
1955         //
1956         // PRIVATE METHODS
1957         //
1958
1959         /**
1960          * Saves the given Sone. This will persist all local settings for the given
1961          * Sone, such as the friends list and similar, private options.
1962          *
1963          * @param sone
1964          *            The Sone to save
1965          */
1966         private synchronized void saveSone(Sone sone) {
1967                 if (!sone.isLocal()) {
1968                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1969                         return;
1970                 }
1971                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1972                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1973                         return;
1974                 }
1975
1976                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1977                 try {
1978                         /* save Sone into configuration. */
1979                         String sonePrefix = "Sone/" + sone.getId();
1980                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1981                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1982
1983                         /* save profile. */
1984                         Profile profile = sone.getProfile();
1985                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1986                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1987                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1988                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1989                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1990                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1991                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1992
1993                         /* save profile fields. */
1994                         int fieldCounter = 0;
1995                         for (Field profileField : profile.getFields()) {
1996                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1997                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1998                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1999                         }
2000                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2001
2002                         /* save posts. */
2003                         int postCounter = 0;
2004                         for (Post post : sone.getPosts()) {
2005                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2006                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2007                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2008                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2009                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2010                         }
2011                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2012
2013                         /* save replies. */
2014                         int replyCounter = 0;
2015                         for (PostReply reply : sone.getReplies()) {
2016                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2017                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2018                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2019                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2020                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2021                         }
2022                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2023
2024                         /* save post likes. */
2025                         int postLikeCounter = 0;
2026                         for (String postId : sone.getLikedPostIds()) {
2027                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2028                         }
2029                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2030
2031                         /* save reply likes. */
2032                         int replyLikeCounter = 0;
2033                         for (String replyId : sone.getLikedReplyIds()) {
2034                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2035                         }
2036                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2037
2038                         /* save friends. */
2039                         int friendCounter = 0;
2040                         for (String friendId : sone.getFriends()) {
2041                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2042                         }
2043                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2044
2045                         /* save albums. first, collect in a flat structure, top-level first. */
2046                         List<Album> albums = sone.getAllAlbums();
2047
2048                         int albumCounter = 0;
2049                         for (Album album : albums) {
2050                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2051                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2052                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2053                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2054                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2055                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2056                         }
2057                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2058
2059                         /* save images. */
2060                         int imageCounter = 0;
2061                         for (Album album : albums) {
2062                                 for (Image image : album.getImages()) {
2063                                         if (!image.isInserted()) {
2064                                                 continue;
2065                                         }
2066                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2067                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2068                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2069                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2070                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2071                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2072                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2073                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2074                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2075                                 }
2076                         }
2077                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2078
2079                         /* save options. */
2080                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2081                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2082                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2083                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2084                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2085                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2086
2087                         configuration.save();
2088
2089                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2090
2091                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2092                 } catch (ConfigurationException ce1) {
2093                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2094                 }
2095         }
2096
2097         /**
2098          * Saves the current options.
2099          */
2100         private void saveConfiguration() {
2101                 synchronized (configuration) {
2102                         if (storingConfiguration) {
2103                                 logger.log(Level.FINE, "Already storing configuration…");
2104                                 return;
2105                         }
2106                         storingConfiguration = true;
2107                 }
2108
2109                 /* store the options first. */
2110                 try {
2111                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2112                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2113                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2114                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2115                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2116                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2117                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2118                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2119                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2120                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2121                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2122                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2123
2124                         /* save known Sones. */
2125                         int soneCounter = 0;
2126                         synchronized (knownSones) {
2127                                 for (String knownSoneId : knownSones) {
2128                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2129                                 }
2130                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2131                         }
2132
2133                         /* save Sone following times. */
2134                         soneCounter = 0;
2135                         synchronized (soneFollowingTimes) {
2136                                 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2137                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2138                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2139                                         ++soneCounter;
2140                                 }
2141                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2142                         }
2143
2144                         /* save known posts. */
2145                         int postCounter = 0;
2146                         synchronized (knownPosts) {
2147                                 for (String knownPostId : knownPosts) {
2148                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2149                                 }
2150                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2151                         }
2152
2153                         /* save known replies. */
2154                         int replyCounter = 0;
2155                         synchronized (knownReplies) {
2156                                 for (String knownReplyId : knownReplies) {
2157                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2158                                 }
2159                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2160                         }
2161
2162                         /* save bookmarked posts. */
2163                         int bookmarkedPostCounter = 0;
2164                         synchronized (bookmarkedPosts) {
2165                                 for (String bookmarkedPostId : bookmarkedPosts) {
2166                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2167                                 }
2168                         }
2169                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2170
2171                         /* now save it. */
2172                         configuration.save();
2173
2174                 } catch (ConfigurationException ce1) {
2175                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2176                 } finally {
2177                         synchronized (configuration) {
2178                                 storingConfiguration = false;
2179                         }
2180                 }
2181         }
2182
2183         /**
2184          * Loads the configuration.
2185          */
2186         @SuppressWarnings("unchecked")
2187         private void loadConfiguration() {
2188                 /* create options. */
2189                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2190
2191                         @Override
2192                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2193                                 SoneInserter.setInsertionDelay(newValue);
2194                         }
2195
2196                 }));
2197                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2198                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2199                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2200                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2201                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2202                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2203                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2204                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2205                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2206
2207                         @Override
2208                         @SuppressWarnings("synthetic-access")
2209                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2210                                 fcpInterface.setActive(newValue);
2211                         }
2212                 }));
2213                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2214
2215                         @Override
2216                         @SuppressWarnings("synthetic-access")
2217                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2218                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2219                         }
2220
2221                 }));
2222
2223                 loadConfigurationValue("InsertionDelay");
2224                 loadConfigurationValue("PostsPerPage");
2225                 loadConfigurationValue("ImagesPerPage");
2226                 loadConfigurationValue("CharactersPerPost");
2227                 loadConfigurationValue("PostCutOffLength");
2228                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2229                 loadConfigurationValue("PositiveTrust");
2230                 loadConfigurationValue("NegativeTrust");
2231                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2232                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2233                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2234
2235                 /* load known Sones. */
2236                 int soneCounter = 0;
2237                 while (true) {
2238                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2239                         if (knownSoneId == null) {
2240                                 break;
2241                         }
2242                         synchronized (knownSones) {
2243                                 knownSones.add(knownSoneId);
2244                         }
2245                 }
2246
2247                 /* load Sone following times. */
2248                 soneCounter = 0;
2249                 while (true) {
2250                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2251                         if (soneId == null) {
2252                                 break;
2253                         }
2254                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2255                         Sone followedSone = getSone(soneId);
2256                         if (followedSone == null) {
2257                                 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2258                         } else {
2259                                 synchronized (soneFollowingTimes) {
2260                                         soneFollowingTimes.put(getSone(soneId), time);
2261                                 }
2262                         }
2263                         ++soneCounter;
2264                 }
2265
2266                 /* load known posts. */
2267                 int postCounter = 0;
2268                 while (true) {
2269                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2270                         if (knownPostId == null) {
2271                                 break;
2272                         }
2273                         synchronized (knownPosts) {
2274                                 knownPosts.add(knownPostId);
2275                         }
2276                 }
2277
2278                 /* load known replies. */
2279                 int replyCounter = 0;
2280                 while (true) {
2281                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2282                         if (knownReplyId == null) {
2283                                 break;
2284                         }
2285                         synchronized (knownReplies) {
2286                                 knownReplies.add(knownReplyId);
2287                         }
2288                 }
2289
2290                 /* load bookmarked posts. */
2291                 int bookmarkedPostCounter = 0;
2292                 while (true) {
2293                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2294                         if (bookmarkedPostId == null) {
2295                                 break;
2296                         }
2297                         synchronized (bookmarkedPosts) {
2298                                 bookmarkedPosts.add(bookmarkedPostId);
2299                         }
2300                 }
2301
2302         }
2303
2304         /**
2305          * Loads an {@link Integer} configuration value for the option with the
2306          * given name, logging validation failures.
2307          *
2308          * @param optionName
2309          *            The name of the option to load
2310          */
2311         private void loadConfigurationValue(String optionName) {
2312                 try {
2313                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2314                 } catch (IllegalArgumentException iae1) {
2315                         logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2316                 }
2317         }
2318
2319         /**
2320          * Generate a Sone URI from the given URI and latest edition.
2321          *
2322          * @param uriString
2323          *            The URI to derive the Sone URI from
2324          * @return The derived URI
2325          */
2326         private static FreenetURI getSoneUri(String uriString) {
2327                 try {
2328                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2329                         return uri;
2330                 } catch (MalformedURLException mue1) {
2331                         logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2332                         return null;
2333                 }
2334         }
2335
2336         //
2337         // INTERFACE IdentityListener
2338         //
2339
2340         /**
2341          * {@inheritDoc}
2342          */
2343         @Override
2344         public void ownIdentityAdded(OwnIdentity ownIdentity) {
2345                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2346                 if (ownIdentity.hasContext("Sone")) {
2347                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2348                         addLocalSone(ownIdentity);
2349                 }
2350         }
2351
2352         /**
2353          * {@inheritDoc}
2354          */
2355         @Override
2356         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2357                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2358                 trustedIdentities.remove(ownIdentity);
2359         }
2360
2361         /**
2362          * {@inheritDoc}
2363          */
2364         @Override
2365         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2366                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2367                 trustedIdentities.get(ownIdentity).add(identity);
2368                 addRemoteSone(identity);
2369         }
2370
2371         /**
2372          * {@inheritDoc}
2373          */
2374         @Override
2375         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2376                 soneDownloaders.execute(new Runnable() {
2377
2378                         @Override
2379                         @SuppressWarnings("synthetic-access")
2380                         public void run() {
2381                                 Sone sone = getRemoteSone(identity.getId(), false);
2382                                 sone.setIdentity(identity);
2383                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2384                                 soneDownloader.addSone(sone);
2385                                 soneDownloader.fetchSone(sone);
2386                         }
2387                 });
2388         }
2389
2390         /**
2391          * {@inheritDoc}
2392          */
2393         @Override
2394         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2395                 trustedIdentities.get(ownIdentity).remove(identity);
2396                 boolean foundIdentity = false;
2397                 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2398                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2399                                 continue;
2400                         }
2401                         if (trustedIdentity.getValue().contains(identity)) {
2402                                 foundIdentity = true;
2403                         }
2404                 }
2405                 if (foundIdentity) {
2406                         /* some local identity still trusts this identity, don’t remove. */
2407                         return;
2408                 }
2409                 Sone sone = getSone(identity.getId(), false);
2410                 if (sone == null) {
2411                         /* TODO - we don’t have the Sone anymore. should this happen? */
2412                         return;
2413                 }
2414                 synchronized (posts) {
2415                         synchronized (knownPosts) {
2416                                 for (Post post : sone.getPosts()) {
2417                                         posts.remove(post.getId());
2418                                         coreListenerManager.firePostRemoved(post);
2419                                 }
2420                         }
2421                 }
2422                 synchronized (replies) {
2423                         synchronized (knownReplies) {
2424                                 for (PostReply reply : sone.getReplies()) {
2425                                         replies.remove(reply.getId());
2426                                         coreListenerManager.fireReplyRemoved(reply);
2427                                 }
2428                         }
2429                 }
2430                 synchronized (sones) {
2431                         sones.remove(identity.getId());
2432                 }
2433                 coreListenerManager.fireSoneRemoved(sone);
2434         }
2435
2436         //
2437         // INTERFACE UpdateListener
2438         //
2439
2440         /**
2441          * {@inheritDoc}
2442          */
2443         @Override
2444         public void updateFound(Version version, long releaseTime, long latestEdition) {
2445                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2446         }
2447
2448         //
2449         // INTERFACE ImageInsertListener
2450         //
2451
2452         /**
2453          * {@inheritDoc}
2454          */
2455         @Override
2456         public void insertStarted(Sone sone) {
2457                 coreListenerManager.fireSoneInserting(sone);
2458         }
2459
2460         /**
2461          * {@inheritDoc}
2462          */
2463         @Override
2464         public void insertFinished(Sone sone, long insertDuration) {
2465                 coreListenerManager.fireSoneInserted(sone, insertDuration);
2466         }
2467
2468         /**
2469          * {@inheritDoc}
2470          */
2471         @Override
2472         public void insertAborted(Sone sone, Throwable cause) {
2473                 coreListenerManager.fireSoneInsertAborted(sone, cause);
2474         }
2475
2476         //
2477         // SONEINSERTLISTENER METHODS
2478         //
2479
2480         /**
2481          * {@inheritDoc}
2482          */
2483         @Override
2484         public void imageInsertStarted(Image image) {
2485                 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2486                 coreListenerManager.fireImageInsertStarted(image);
2487         }
2488
2489         /**
2490          * {@inheritDoc}
2491          */
2492         @Override
2493         public void imageInsertAborted(Image image) {
2494                 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2495                 coreListenerManager.fireImageInsertAborted(image);
2496         }
2497
2498         /**
2499          * {@inheritDoc}
2500          */
2501         @Override
2502         public void imageInsertFinished(Image image, FreenetURI key) {
2503                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2504                 image.setKey(key.toString());
2505                 deleteTemporaryImage(image.getId());
2506                 touchConfiguration();
2507                 coreListenerManager.fireImageInsertFinished(image);
2508         }
2509
2510         /**
2511          * {@inheritDoc}
2512          */
2513         @Override
2514         public void imageInsertFailed(Image image, Throwable cause) {
2515                 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2516                 coreListenerManager.fireImageInsertFailed(image, cause);
2517         }
2518
2519         /**
2520          * Convenience interface for external classes that want to access the core’s
2521          * configuration.
2522          *
2523          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2524          */
2525         public static class Preferences {
2526
2527                 /** The wrapped options. */
2528                 private final Options options;
2529
2530                 /**
2531                  * Creates a new preferences object wrapped around the given options.
2532                  *
2533                  * @param options
2534                  *            The options to wrap
2535                  */
2536                 public Preferences(Options options) {
2537                         this.options = options;
2538                 }
2539
2540                 /**
2541                  * Returns the insertion delay.
2542                  *
2543                  * @return The insertion delay
2544                  */
2545                 public int getInsertionDelay() {
2546                         return options.getIntegerOption("InsertionDelay").get();
2547                 }
2548
2549                 /**
2550                  * Validates the given insertion delay.
2551                  *
2552                  * @param insertionDelay
2553                  *            The insertion delay to validate
2554                  * @return {@code true} if the given insertion delay was valid,
2555                  *         {@code false} otherwise
2556                  */
2557                 public boolean validateInsertionDelay(Integer insertionDelay) {
2558                         return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2559                 }
2560
2561                 /**
2562                  * Sets the insertion delay
2563                  *
2564                  * @param insertionDelay
2565                  *            The new insertion delay, or {@code null} to restore it to
2566                  *            the default value
2567                  * @return This preferences
2568                  */
2569                 public Preferences setInsertionDelay(Integer insertionDelay) {
2570                         options.getIntegerOption("InsertionDelay").set(insertionDelay);
2571                         return this;
2572                 }
2573
2574                 /**
2575                  * Returns the number of posts to show per page.
2576                  *
2577                  * @return The number of posts to show per page
2578                  */
2579                 public int getPostsPerPage() {
2580                         return options.getIntegerOption("PostsPerPage").get();
2581                 }
2582
2583                 /**
2584                  * Validates the number of posts per page.
2585                  *
2586                  * @param postsPerPage
2587                  *            The number of posts per page
2588                  * @return {@code true} if the number of posts per page was valid,
2589                  *         {@code false} otherwise
2590                  */
2591                 public boolean validatePostsPerPage(Integer postsPerPage) {
2592                         return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2593                 }
2594
2595                 /**
2596                  * Sets the number of posts to show per page.
2597                  *
2598                  * @param postsPerPage
2599                  *            The number of posts to show per page
2600                  * @return This preferences object
2601                  */
2602                 public Preferences setPostsPerPage(Integer postsPerPage) {
2603                         options.getIntegerOption("PostsPerPage").set(postsPerPage);
2604                         return this;
2605                 }
2606
2607                 /**
2608                  * Returns the number of images to show per page.
2609                  *
2610                  * @return The number of images to show per page
2611                  */
2612                 public int getImagesPerPage() {
2613                         return options.getIntegerOption("ImagesPerPage").get();
2614                 }
2615
2616                 /**
2617                  * Validates the number of images per page.
2618                  *
2619                  * @param imagesPerPage
2620                  *            The number of images per page
2621                  * @return {@code true} if the number of images per page was valid,
2622                  *         {@code false} otherwise
2623                  */
2624                 public boolean validateImagesPerPage(Integer imagesPerPage) {
2625                         return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2626                 }
2627
2628                 /**
2629                  * Sets the number of images per page.
2630                  *
2631                  * @param imagesPerPage
2632                  *            The number of images per page
2633                  * @return This preferences object
2634                  */
2635                 public Preferences setImagesPerPage(Integer imagesPerPage) {
2636                         options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2637                         return this;
2638                 }
2639
2640                 /**
2641                  * Returns the number of characters per post, or <code>-1</code> if the
2642                  * posts should not be cut off.
2643                  *
2644                  * @return The numbers of characters per post
2645                  */
2646                 public int getCharactersPerPost() {
2647                         return options.getIntegerOption("CharactersPerPost").get();
2648                 }
2649
2650                 /**
2651                  * Validates the number of characters per post.
2652                  *
2653                  * @param charactersPerPost
2654                  *            The number of characters per post
2655                  * @return {@code true} if the number of characters per post was valid,
2656                  *         {@code false} otherwise
2657                  */
2658                 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2659                         return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2660                 }
2661
2662                 /**
2663                  * Sets the number of characters per post.
2664                  *
2665                  * @param charactersPerPost
2666                  *            The number of characters per post, or <code>-1</code> to
2667                  *            not cut off the posts
2668                  * @return This preferences objects
2669                  */
2670                 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2671                         options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2672                         return this;
2673                 }
2674
2675                 /**
2676                  * Returns the number of characters the shortened post should have.
2677                  *
2678                  * @return The number of characters of the snippet
2679                  */
2680                 public int getPostCutOffLength() {
2681                         return options.getIntegerOption("PostCutOffLength").get();
2682                 }
2683
2684                 /**
2685                  * Validates the number of characters after which to cut off the post.
2686                  *
2687                  * @param postCutOffLength
2688                  *            The number of characters of the snippet
2689                  * @return {@code true} if the number of characters of the snippet is
2690                  *         valid, {@code false} otherwise
2691                  */
2692                 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2693                         return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2694                 }
2695
2696                 /**
2697                  * Sets the number of characters the shortened post should have.
2698                  *
2699                  * @param postCutOffLength
2700                  *            The number of characters of the snippet
2701                  * @return This preferences
2702                  */
2703                 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2704                         options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2705                         return this;
2706                 }
2707
2708                 /**
2709                  * Returns whether Sone requires full access to be even visible.
2710                  *
2711                  * @return {@code true} if Sone requires full access, {@code false}
2712                  *         otherwise
2713                  */
2714                 public boolean isRequireFullAccess() {
2715                         return options.getBooleanOption("RequireFullAccess").get();
2716                 }
2717
2718                 /**
2719                  * Sets whether Sone requires full access to be even visible.
2720                  *
2721                  * @param requireFullAccess
2722                  *            {@code true} if Sone requires full access, {@code false}
2723                  *            otherwise
2724                  */
2725                 public void setRequireFullAccess(Boolean requireFullAccess) {
2726                         options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2727                 }
2728
2729                 /**
2730                  * Returns the positive trust.
2731                  *
2732                  * @return The positive trust
2733                  */
2734                 public int getPositiveTrust() {
2735                         return options.getIntegerOption("PositiveTrust").get();
2736                 }
2737
2738                 /**
2739                  * Validates the positive trust.
2740                  *
2741                  * @param positiveTrust
2742                  *            The positive trust to validate
2743                  * @return {@code true} if the positive trust was valid, {@code false}
2744                  *         otherwise
2745                  */
2746                 public boolean validatePositiveTrust(Integer positiveTrust) {
2747                         return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2748                 }
2749
2750                 /**
2751                  * Sets the positive trust.
2752                  *
2753                  * @param positiveTrust
2754                  *            The new positive trust, or {@code null} to restore it to
2755                  *            the default vlaue
2756                  * @return This preferences
2757                  */
2758                 public Preferences setPositiveTrust(Integer positiveTrust) {
2759                         options.getIntegerOption("PositiveTrust").set(positiveTrust);
2760                         return this;
2761                 }
2762
2763                 /**
2764                  * Returns the negative trust.
2765                  *
2766                  * @return The negative trust
2767                  */
2768                 public int getNegativeTrust() {
2769                         return options.getIntegerOption("NegativeTrust").get();
2770                 }
2771
2772                 /**
2773                  * Validates the negative trust.
2774                  *
2775                  * @param negativeTrust
2776                  *            The negative trust to validate
2777                  * @return {@code true} if the negative trust was valid, {@code false}
2778                  *         otherwise
2779                  */
2780                 public boolean validateNegativeTrust(Integer negativeTrust) {
2781                         return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2782                 }
2783
2784                 /**
2785                  * Sets the negative trust.
2786                  *
2787                  * @param negativeTrust
2788                  *            The negative trust, or {@code null} to restore it to the
2789                  *            default value
2790                  * @return The preferences
2791                  */
2792                 public Preferences setNegativeTrust(Integer negativeTrust) {
2793                         options.getIntegerOption("NegativeTrust").set(negativeTrust);
2794                         return this;
2795                 }
2796
2797                 /**
2798                  * Returns the trust comment. This is the comment that is set in the web
2799                  * of trust when a trust value is assigned to an identity.
2800                  *
2801                  * @return The trust comment
2802                  */
2803                 public String getTrustComment() {
2804                         return options.getStringOption("TrustComment").get();
2805                 }
2806
2807                 /**
2808                  * Sets the trust comment.
2809                  *
2810                  * @param trustComment
2811                  *            The trust comment, or {@code null} to restore it to the
2812                  *            default value
2813                  * @return This preferences
2814                  */
2815                 public Preferences setTrustComment(String trustComment) {
2816                         options.getStringOption("TrustComment").set(trustComment);
2817                         return this;
2818                 }
2819
2820                 /**
2821                  * Returns whether the {@link FcpInterface FCP interface} is currently
2822                  * active.
2823                  *
2824                  * @see FcpInterface#setActive(boolean)
2825                  * @return {@code true} if the FCP interface is currently active,
2826                  *         {@code false} otherwise
2827                  */
2828                 public boolean isFcpInterfaceActive() {
2829                         return options.getBooleanOption("ActivateFcpInterface").get();
2830                 }
2831
2832                 /**
2833                  * Sets whether the {@link FcpInterface FCP interface} is currently
2834                  * active.
2835                  *
2836                  * @see FcpInterface#setActive(boolean)
2837                  * @param fcpInterfaceActive
2838                  *            {@code true} to activate the FCP interface, {@code false}
2839                  *            to deactivate the FCP interface
2840                  * @return This preferences object
2841                  */
2842                 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2843                         options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2844                         return this;
2845                 }
2846
2847                 /**
2848                  * Returns the action level for which full access to the FCP interface
2849                  * is required.
2850                  *
2851                  * @return The action level for which full access to the FCP interface
2852                  *         is required
2853                  */
2854                 public FullAccessRequired getFcpFullAccessRequired() {
2855                         return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2856                 }
2857
2858                 /**
2859                  * Sets the action level for which full access to the FCP interface is
2860                  * required
2861                  *
2862                  * @param fcpFullAccessRequired
2863                  *            The action level
2864                  * @return This preferences
2865                  */
2866                 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2867                         options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2868                         return this;
2869                 }
2870
2871         }
2872
2873 }