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