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