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