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