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