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