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