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