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