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