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