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