c2bb1c8ebe93f2c015a9596787ba798d701479af
[Sone.git] / src / main / java / net / pterodactylus / sone / web / WebInterface.java
1 /*
2  * Sone - WebInterface.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.web;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.InputStreamReader;
23 import java.io.Reader;
24 import java.io.StringReader;
25 import java.io.UnsupportedEncodingException;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Set;
34 import java.util.UUID;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
37
38 import net.pterodactylus.sone.core.Core;
39 import net.pterodactylus.sone.core.CoreListener;
40 import net.pterodactylus.sone.data.Album;
41 import net.pterodactylus.sone.data.Image;
42 import net.pterodactylus.sone.data.Post;
43 import net.pterodactylus.sone.data.PostReply;
44 import net.pterodactylus.sone.data.Profile;
45 import net.pterodactylus.sone.data.Reply;
46 import net.pterodactylus.sone.data.Sone;
47 import net.pterodactylus.sone.freenet.L10nFilter;
48 import net.pterodactylus.sone.freenet.wot.Identity;
49 import net.pterodactylus.sone.freenet.wot.Trust;
50 import net.pterodactylus.sone.main.SonePlugin;
51 import net.pterodactylus.sone.notify.ListNotification;
52 import net.pterodactylus.sone.template.AlbumAccessor;
53 import net.pterodactylus.sone.template.CollectionAccessor;
54 import net.pterodactylus.sone.template.CssClassNameFilter;
55 import net.pterodactylus.sone.template.HttpRequestAccessor;
56 import net.pterodactylus.sone.template.IdentityAccessor;
57 import net.pterodactylus.sone.template.ImageAccessor;
58 import net.pterodactylus.sone.template.ImageLinkFilter;
59 import net.pterodactylus.sone.template.JavascriptFilter;
60 import net.pterodactylus.sone.template.ParserFilter;
61 import net.pterodactylus.sone.template.PostAccessor;
62 import net.pterodactylus.sone.template.ProfileAccessor;
63 import net.pterodactylus.sone.template.ReplyAccessor;
64 import net.pterodactylus.sone.template.ReplyGroupFilter;
65 import net.pterodactylus.sone.template.RequestChangeFilter;
66 import net.pterodactylus.sone.template.SoneAccessor;
67 import net.pterodactylus.sone.template.SubstringFilter;
68 import net.pterodactylus.sone.template.TrustAccessor;
69 import net.pterodactylus.sone.template.UniqueElementFilter;
70 import net.pterodactylus.sone.template.UnknownDateFilter;
71 import net.pterodactylus.sone.text.Part;
72 import net.pterodactylus.sone.text.SonePart;
73 import net.pterodactylus.sone.text.SoneTextParser;
74 import net.pterodactylus.sone.web.ajax.BookmarkAjaxPage;
75 import net.pterodactylus.sone.web.ajax.CreatePostAjaxPage;
76 import net.pterodactylus.sone.web.ajax.CreateReplyAjaxPage;
77 import net.pterodactylus.sone.web.ajax.DeletePostAjaxPage;
78 import net.pterodactylus.sone.web.ajax.DeleteProfileFieldAjaxPage;
79 import net.pterodactylus.sone.web.ajax.DeleteReplyAjaxPage;
80 import net.pterodactylus.sone.web.ajax.DismissNotificationAjaxPage;
81 import net.pterodactylus.sone.web.ajax.DistrustAjaxPage;
82 import net.pterodactylus.sone.web.ajax.EditAlbumAjaxPage;
83 import net.pterodactylus.sone.web.ajax.EditImageAjaxPage;
84 import net.pterodactylus.sone.web.ajax.EditProfileFieldAjaxPage;
85 import net.pterodactylus.sone.web.ajax.FollowSoneAjaxPage;
86 import net.pterodactylus.sone.web.ajax.GetLikesAjaxPage;
87 import net.pterodactylus.sone.web.ajax.GetNotificationsAjaxPage;
88 import net.pterodactylus.sone.web.ajax.GetPostAjaxPage;
89 import net.pterodactylus.sone.web.ajax.GetReplyAjaxPage;
90 import net.pterodactylus.sone.web.ajax.GetStatusAjaxPage;
91 import net.pterodactylus.sone.web.ajax.GetTimesAjaxPage;
92 import net.pterodactylus.sone.web.ajax.GetTranslationPage;
93 import net.pterodactylus.sone.web.ajax.LikeAjaxPage;
94 import net.pterodactylus.sone.web.ajax.LockSoneAjaxPage;
95 import net.pterodactylus.sone.web.ajax.MarkAsKnownAjaxPage;
96 import net.pterodactylus.sone.web.ajax.MoveProfileFieldAjaxPage;
97 import net.pterodactylus.sone.web.ajax.TrustAjaxPage;
98 import net.pterodactylus.sone.web.ajax.UnbookmarkAjaxPage;
99 import net.pterodactylus.sone.web.ajax.UnfollowSoneAjaxPage;
100 import net.pterodactylus.sone.web.ajax.UnlikeAjaxPage;
101 import net.pterodactylus.sone.web.ajax.UnlockSoneAjaxPage;
102 import net.pterodactylus.sone.web.ajax.UntrustAjaxPage;
103 import net.pterodactylus.sone.web.page.FreenetRequest;
104 import net.pterodactylus.sone.web.page.PageToadlet;
105 import net.pterodactylus.sone.web.page.PageToadletFactory;
106 import net.pterodactylus.util.cache.Cache;
107 import net.pterodactylus.util.cache.CacheException;
108 import net.pterodactylus.util.cache.CacheItem;
109 import net.pterodactylus.util.cache.DefaultCacheItem;
110 import net.pterodactylus.util.cache.MemoryCache;
111 import net.pterodactylus.util.cache.ValueRetriever;
112 import net.pterodactylus.util.collection.SetBuilder;
113 import net.pterodactylus.util.collection.filter.Filters;
114 import net.pterodactylus.util.logging.Logging;
115 import net.pterodactylus.util.notify.Notification;
116 import net.pterodactylus.util.notify.NotificationManager;
117 import net.pterodactylus.util.notify.TemplateNotification;
118 import net.pterodactylus.util.template.CollectionSortFilter;
119 import net.pterodactylus.util.template.ContainsFilter;
120 import net.pterodactylus.util.template.DateFilter;
121 import net.pterodactylus.util.template.FormatFilter;
122 import net.pterodactylus.util.template.HtmlFilter;
123 import net.pterodactylus.util.template.MatchFilter;
124 import net.pterodactylus.util.template.ModFilter;
125 import net.pterodactylus.util.template.PaginationFilter;
126 import net.pterodactylus.util.template.Provider;
127 import net.pterodactylus.util.template.ReflectionAccessor;
128 import net.pterodactylus.util.template.ReplaceFilter;
129 import net.pterodactylus.util.template.StoreFilter;
130 import net.pterodactylus.util.template.Template;
131 import net.pterodactylus.util.template.TemplateContext;
132 import net.pterodactylus.util.template.TemplateContextFactory;
133 import net.pterodactylus.util.template.TemplateException;
134 import net.pterodactylus.util.template.TemplateParser;
135 import net.pterodactylus.util.template.XmlFilter;
136 import net.pterodactylus.util.thread.Ticker;
137 import net.pterodactylus.util.version.Version;
138 import net.pterodactylus.util.web.RedirectPage;
139 import net.pterodactylus.util.web.StaticPage;
140 import net.pterodactylus.util.web.TemplatePage;
141 import freenet.clients.http.SessionManager;
142 import freenet.clients.http.SessionManager.Session;
143 import freenet.clients.http.ToadletContainer;
144 import freenet.clients.http.ToadletContext;
145 import freenet.l10n.BaseL10n;
146 import freenet.support.api.HTTPRequest;
147
148 /**
149  * Bundles functionality that a web interface of a Freenet plugin needs, e.g.
150  * references to l10n helpers.
151  *
152  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
153  */
154 public class WebInterface implements CoreListener {
155
156         /** The logger. */
157         private static final Logger logger = Logging.getLogger(WebInterface.class);
158
159         /** The notification manager. */
160         private final NotificationManager notificationManager = new NotificationManager();
161
162         /** The Sone plugin. */
163         private final SonePlugin sonePlugin;
164
165         /** The registered toadlets. */
166         private final List<PageToadlet> pageToadlets = new ArrayList<PageToadlet>();
167
168         /** The form password. */
169         private final String formPassword;
170
171         /** The template context factory. */
172         private final TemplateContextFactory templateContextFactory;
173
174         /** The Sone text parser. */
175         private final SoneTextParser soneTextParser;
176
177         /** The parser filter. */
178         private final ParserFilter parserFilter;
179
180         /** The “new Sone” notification. */
181         private final ListNotification<Sone> newSoneNotification;
182
183         /** The “new post” notification. */
184         private final ListNotification<Post> newPostNotification;
185
186         /** The “new reply” notification. */
187         private final ListNotification<PostReply> newReplyNotification;
188
189         /** The invisible “local post” notification. */
190         private final ListNotification<Post> localPostNotification;
191
192         /** The invisible “local reply” notification. */
193         private final ListNotification<PostReply> localReplyNotification;
194
195         /** The “you have been mentioned” notification. */
196         private final ListNotification<Post> mentionNotification;
197
198         /** Notifications for sone inserts. */
199         private final Map<Sone, TemplateNotification> soneInsertNotifications = new HashMap<Sone, TemplateNotification>();
200
201         /** Sone locked notification ticker objects. */
202         private final Map<Sone, Object> lockedSonesTickerObjects = Collections.synchronizedMap(new HashMap<Sone, Object>());
203
204         /** The “Sone locked” notification. */
205         private final ListNotification<Sone> lockedSonesNotification;
206
207         /** The “new version” notification. */
208         private final TemplateNotification newVersionNotification;
209
210         /** The “inserting images” notification. */
211         private final ListNotification<Image> insertingImagesNotification;
212
213         /** The “inserted images” notification. */
214         private final ListNotification<Image> insertedImagesNotification;
215
216         /** The “image insert failed” notification. */
217         private final ListNotification<Image> imageInsertFailedNotification;
218
219         /**
220          * Creates a new web interface.
221          *
222          * @param sonePlugin
223          *            The Sone plugin
224          */
225         @SuppressWarnings("synthetic-access")
226         public WebInterface(SonePlugin sonePlugin) {
227                 this.sonePlugin = sonePlugin;
228                 formPassword = sonePlugin.pluginRespirator().getToadletContainer().getFormPassword();
229                 soneTextParser = new SoneTextParser(getCore(), getCore());
230
231                 templateContextFactory = new TemplateContextFactory();
232                 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
233                 templateContextFactory.addAccessor(Collection.class, new CollectionAccessor());
234                 templateContextFactory.addAccessor(Sone.class, new SoneAccessor(getCore()));
235                 templateContextFactory.addAccessor(Post.class, new PostAccessor(getCore()));
236                 templateContextFactory.addAccessor(Reply.class, new ReplyAccessor(getCore()));
237                 templateContextFactory.addAccessor(Album.class, new AlbumAccessor());
238                 templateContextFactory.addAccessor(Image.class, new ImageAccessor());
239                 templateContextFactory.addAccessor(Identity.class, new IdentityAccessor(getCore()));
240                 templateContextFactory.addAccessor(Trust.class, new TrustAccessor());
241                 templateContextFactory.addAccessor(HTTPRequest.class, new HttpRequestAccessor());
242                 templateContextFactory.addAccessor(Profile.class, new ProfileAccessor(getCore()));
243                 templateContextFactory.addFilter("date", new DateFilter());
244                 templateContextFactory.addFilter("html", new HtmlFilter());
245                 templateContextFactory.addFilter("replace", new ReplaceFilter());
246                 templateContextFactory.addFilter("store", new StoreFilter());
247                 templateContextFactory.addFilter("l10n", new L10nFilter(this));
248                 templateContextFactory.addFilter("substring", new SubstringFilter());
249                 templateContextFactory.addFilter("xml", new XmlFilter());
250                 templateContextFactory.addFilter("change", new RequestChangeFilter());
251                 templateContextFactory.addFilter("match", new MatchFilter());
252                 templateContextFactory.addFilter("css", new CssClassNameFilter());
253                 templateContextFactory.addFilter("js", new JavascriptFilter());
254                 templateContextFactory.addFilter("parse", parserFilter = new ParserFilter(getCore(), templateContextFactory, soneTextParser));
255                 templateContextFactory.addFilter("unknown", new UnknownDateFilter(getL10n(), "View.Sone.Text.UnknownDate"));
256                 templateContextFactory.addFilter("format", new FormatFilter());
257                 templateContextFactory.addFilter("sort", new CollectionSortFilter());
258                 templateContextFactory.addFilter("image-link", new ImageLinkFilter(getCore(), templateContextFactory));
259                 templateContextFactory.addFilter("replyGroup", new ReplyGroupFilter());
260                 templateContextFactory.addFilter("in", new ContainsFilter());
261                 templateContextFactory.addFilter("unique", new UniqueElementFilter());
262                 templateContextFactory.addFilter("mod", new ModFilter());
263                 templateContextFactory.addFilter("paginate", new PaginationFilter());
264                 templateContextFactory.addProvider(Provider.TEMPLATE_CONTEXT_PROVIDER);
265                 templateContextFactory.addProvider(new ClassPathTemplateProvider());
266                 templateContextFactory.addTemplateObject("webInterface", this);
267                 templateContextFactory.addTemplateObject("formPassword", formPassword);
268
269                 /* create notifications. */
270                 Template newSoneNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newSoneNotification.html"));
271                 newSoneNotification = new ListNotification<Sone>("new-sone-notification", "sones", newSoneNotificationTemplate, false);
272
273                 Template newPostNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newPostNotification.html"));
274                 newPostNotification = new ListNotification<Post>("new-post-notification", "posts", newPostNotificationTemplate, false);
275
276                 Template localPostNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newPostNotification.html"));
277                 localPostNotification = new ListNotification<Post>("local-post-notification", "posts", localPostNotificationTemplate, false);
278
279                 Template newReplyNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newReplyNotification.html"));
280                 newReplyNotification = new ListNotification<PostReply>("new-reply-notification", "replies", newReplyNotificationTemplate, false);
281
282                 Template localReplyNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newReplyNotification.html"));
283                 localReplyNotification = new ListNotification<PostReply>("local-reply-notification", "replies", localReplyNotificationTemplate, false);
284
285                 Template mentionNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/mentionNotification.html"));
286                 mentionNotification = new ListNotification<Post>("mention-notification", "posts", mentionNotificationTemplate, false);
287
288                 Template lockedSonesTemplate = TemplateParser.parse(createReader("/templates/notify/lockedSonesNotification.html"));
289                 lockedSonesNotification = new ListNotification<Sone>("sones-locked-notification", "sones", lockedSonesTemplate);
290
291                 Template newVersionTemplate = TemplateParser.parse(createReader("/templates/notify/newVersionNotification.html"));
292                 newVersionNotification = new TemplateNotification("new-version-notification", newVersionTemplate);
293
294                 Template insertingImagesTemplate = TemplateParser.parse(createReader("/templates/notify/inserting-images-notification.html"));
295                 insertingImagesNotification = new ListNotification<Image>("inserting-images-notification", "images", insertingImagesTemplate);
296
297                 Template insertedImagesTemplate = TemplateParser.parse(createReader("/templates/notify/inserted-images-notification.html"));
298                 insertedImagesNotification = new ListNotification<Image>("inserted-images-notification", "images", insertedImagesTemplate);
299
300                 Template imageInsertFailedTemplate = TemplateParser.parse(createReader("/templates/notify/image-insert-failed-notification.html"));
301                 imageInsertFailedNotification = new ListNotification<Image>("image-insert-failed-notification", "images", imageInsertFailedTemplate);
302         }
303
304         //
305         // ACCESSORS
306         //
307
308         /**
309          * Returns the Sone core used by the Sone plugin.
310          *
311          * @return The Sone core
312          */
313         public Core getCore() {
314                 return sonePlugin.core();
315         }
316
317         /**
318          * Returns the template context factory of the web interface.
319          *
320          * @return The template context factory
321          */
322         public TemplateContextFactory getTemplateContextFactory() {
323                 return templateContextFactory;
324         }
325
326         /**
327          * Returns the current session, creating a new session if there is no
328          * current session.
329          *
330          * @param toadletContenxt
331          *            The toadlet context
332          * @return The current session, or {@code null} if there is no current
333          *         session
334          */
335         public Session getCurrentSession(ToadletContext toadletContenxt) {
336                 return getCurrentSession(toadletContenxt, true);
337         }
338
339         /**
340          * Returns the current session, creating a new session if there is no
341          * current session and {@code create} is {@code true}.
342          *
343          * @param toadletContenxt
344          *            The toadlet context
345          * @param create
346          *            {@code true} to create a new session if there is no current
347          *            session, {@code false} otherwise
348          * @return The current session, or {@code null} if there is no current
349          *         session
350          */
351         public Session getCurrentSession(ToadletContext toadletContenxt, boolean create) {
352                 Session session = getSessionManager().useSession(toadletContenxt);
353                 if (create && (session == null)) {
354                         session = getSessionManager().createSession(UUID.randomUUID().toString(), toadletContenxt);
355                 }
356                 return session;
357         }
358
359         /**
360          * Returns the currently logged in Sone.
361          *
362          * @param toadletContext
363          *            The toadlet context
364          * @return The currently logged in Sone, or {@code null} if no Sone is
365          *         currently logged in
366          */
367         public Sone getCurrentSone(ToadletContext toadletContext) {
368                 return getCurrentSone(toadletContext, true);
369         }
370
371         /**
372          * Returns the currently logged in Sone.
373          *
374          * @param toadletContext
375          *            The toadlet context
376          * @param create
377          *            {@code true} to create a new session if no session exists,
378          *            {@code false} to not create a new session
379          * @return The currently logged in Sone, or {@code null} if no Sone is
380          *         currently logged in
381          */
382         public Sone getCurrentSone(ToadletContext toadletContext, boolean create) {
383                 Set<Sone> localSones = getCore().getLocalSones();
384                 if (localSones.size() == 1) {
385                         return localSones.iterator().next();
386                 }
387                 return getCurrentSone(getCurrentSession(toadletContext, create));
388         }
389
390         /**
391          * Returns the currently logged in Sone.
392          *
393          * @param session
394          *            The session
395          * @return The currently logged in Sone, or {@code null} if no Sone is
396          *         currently logged in
397          */
398         public Sone getCurrentSone(Session session) {
399                 if (session == null) {
400                         return null;
401                 }
402                 String soneId = (String) session.getAttribute("Sone.CurrentSone");
403                 if (soneId == null) {
404                         return null;
405                 }
406                 return getCore().getLocalSone(soneId, false);
407         }
408
409         /**
410          * Sets the currently logged in Sone.
411          *
412          * @param toadletContext
413          *            The toadlet context
414          * @param sone
415          *            The Sone to set as currently logged in
416          */
417         public void setCurrentSone(ToadletContext toadletContext, Sone sone) {
418                 Session session = getCurrentSession(toadletContext);
419                 if (sone == null) {
420                         session.removeAttribute("Sone.CurrentSone");
421                 } else {
422                         session.setAttribute("Sone.CurrentSone", sone.getId());
423                 }
424         }
425
426         /**
427          * Returns the notification manager.
428          *
429          * @return The notification manager
430          */
431         public NotificationManager getNotifications() {
432                 return notificationManager;
433         }
434
435         /**
436          * Returns the l10n helper of the node.
437          *
438          * @return The node’s l10n helper
439          */
440         public BaseL10n getL10n() {
441                 return sonePlugin.l10n().getBase();
442         }
443
444         /**
445          * Returns the session manager of the node.
446          *
447          * @return The node’s session manager
448          */
449         public SessionManager getSessionManager() {
450                 return sonePlugin.pluginRespirator().getSessionManager("Sone");
451         }
452
453         /**
454          * Returns the node’s form password.
455          *
456          * @return The form password
457          */
458         public String getFormPassword() {
459                 return formPassword;
460         }
461
462         /**
463          * Returns the posts that have been announced as new in the
464          * {@link #newPostNotification}.
465          *
466          * @return The new posts
467          */
468         public Set<Post> getNewPosts() {
469                 return new SetBuilder<Post>().addAll(newPostNotification.getElements()).addAll(localPostNotification.getElements()).get();
470         }
471
472         /**
473          * Returns the replies that have been announced as new in the
474          * {@link #newReplyNotification}.
475          *
476          * @return The new replies
477          */
478         public Set<PostReply> getNewReplies() {
479                 return new SetBuilder<PostReply>().addAll(newReplyNotification.getElements()).addAll(localReplyNotification.getElements()).get();
480         }
481
482         /**
483          * Sets whether the current start of the plugin is the first start. It is
484          * considered a first start if the configuration file does not exist.
485          *
486          * @param firstStart
487          *            {@code true} if no configuration file existed when Sone was
488          *            loaded, {@code false} otherwise
489          */
490         public void setFirstStart(boolean firstStart) {
491                 if (firstStart) {
492                         Template firstStartNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/firstStartNotification.html"));
493                         Notification firstStartNotification = new TemplateNotification("first-start-notification", firstStartNotificationTemplate);
494                         notificationManager.addNotification(firstStartNotification);
495                 }
496         }
497
498         /**
499          * Sets whether Sone was started with a fresh configuration file.
500          *
501          * @param newConfig
502          *            {@code true} if Sone was started with a fresh configuration,
503          *            {@code false} if the existing configuration could be read
504          */
505         public void setNewConfig(boolean newConfig) {
506                 if (newConfig && !hasFirstStartNotification()) {
507                         Template configNotReadNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/configNotReadNotification.html"));
508                         Notification configNotReadNotification = new TemplateNotification("config-not-read-notification", configNotReadNotificationTemplate);
509                         notificationManager.addNotification(configNotReadNotification);
510                 }
511         }
512
513         //
514         // PRIVATE ACCESSORS
515         //
516
517         /**
518          * Returns whether the first start notification is currently displayed.
519          *
520          * @return {@code true} if the first-start notification is currently
521          *         displayed, {@code false} otherwise
522          */
523         private boolean hasFirstStartNotification() {
524                 return notificationManager.getNotification("first-start-notification") != null;
525         }
526
527         //
528         // ACTIONS
529         //
530
531         /**
532          * Starts the web interface and registers all toadlets.
533          */
534         public void start() {
535                 registerToadlets();
536
537                 /* notification templates. */
538                 Template startupNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/startupNotification.html"));
539
540                 final TemplateNotification startupNotification = new TemplateNotification("startup-notification", startupNotificationTemplate);
541                 notificationManager.addNotification(startupNotification);
542
543                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (120 * 1000), new Runnable() {
544
545                         @Override
546                         public void run() {
547                                 startupNotification.dismiss();
548                         }
549                 }, "Sone Startup Notification Remover");
550
551                 Template wotMissingNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/wotMissingNotification.html"));
552                 final TemplateNotification wotMissingNotification = new TemplateNotification("wot-missing-notification", wotMissingNotificationTemplate);
553                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (15 * 1000), new Runnable() {
554
555                         @Override
556                         @SuppressWarnings("synthetic-access")
557                         public void run() {
558                                 if (getCore().getIdentityManager().isConnected()) {
559                                         wotMissingNotification.dismiss();
560                                 } else {
561                                         notificationManager.addNotification(wotMissingNotification);
562                                 }
563                                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (15 * 1000), this, "Sone WoT Connector Checker");
564                         }
565
566                 }, "Sone WoT Connector Checker");
567         }
568
569         /**
570          * Stops the web interface and unregisters all toadlets.
571          */
572         public void stop() {
573                 unregisterToadlets();
574                 Ticker.getInstance().stop();
575         }
576
577         //
578         // PRIVATE METHODS
579         //
580
581         /**
582          * Register all toadlets.
583          */
584         private void registerToadlets() {
585                 Template emptyTemplate = TemplateParser.parse(new StringReader(""));
586                 Template loginTemplate = TemplateParser.parse(createReader("/templates/login.html"));
587                 Template indexTemplate = TemplateParser.parse(createReader("/templates/index.html"));
588                 Template newTemplate = TemplateParser.parse(createReader("/templates/new.html"));
589                 Template knownSonesTemplate = TemplateParser.parse(createReader("/templates/knownSones.html"));
590                 Template createSoneTemplate = TemplateParser.parse(createReader("/templates/createSone.html"));
591                 Template createPostTemplate = TemplateParser.parse(createReader("/templates/createPost.html"));
592                 Template createReplyTemplate = TemplateParser.parse(createReader("/templates/createReply.html"));
593                 Template bookmarksTemplate = TemplateParser.parse(createReader("/templates/bookmarks.html"));
594                 Template searchTemplate = TemplateParser.parse(createReader("/templates/search.html"));
595                 Template editProfileTemplate = TemplateParser.parse(createReader("/templates/editProfile.html"));
596                 Template editProfileFieldTemplate = TemplateParser.parse(createReader("/templates/editProfileField.html"));
597                 Template deleteProfileFieldTemplate = TemplateParser.parse(createReader("/templates/deleteProfileField.html"));
598                 Template viewSoneTemplate = TemplateParser.parse(createReader("/templates/viewSone.html"));
599                 Template viewPostTemplate = TemplateParser.parse(createReader("/templates/viewPost.html"));
600                 Template deletePostTemplate = TemplateParser.parse(createReader("/templates/deletePost.html"));
601                 Template deleteReplyTemplate = TemplateParser.parse(createReader("/templates/deleteReply.html"));
602                 Template deleteSoneTemplate = TemplateParser.parse(createReader("/templates/deleteSone.html"));
603                 Template imageBrowserTemplate = TemplateParser.parse(createReader("/templates/imageBrowser.html"));
604                 Template createAlbumTemplate = TemplateParser.parse(createReader("/templates/createAlbum.html"));
605                 Template deleteAlbumTemplate = TemplateParser.parse(createReader("/templates/deleteAlbum.html"));
606                 Template deleteImageTemplate = TemplateParser.parse(createReader("/templates/deleteImage.html"));
607                 Template noPermissionTemplate = TemplateParser.parse(createReader("/templates/noPermission.html"));
608                 Template optionsTemplate = TemplateParser.parse(createReader("/templates/options.html"));
609                 Template rescueTemplate = TemplateParser.parse(createReader("/templates/rescue.html"));
610                 Template aboutTemplate = TemplateParser.parse(createReader("/templates/about.html"));
611                 Template invalidTemplate = TemplateParser.parse(createReader("/templates/invalid.html"));
612                 Template postTemplate = TemplateParser.parse(createReader("/templates/include/viewPost.html"));
613                 Template replyTemplate = TemplateParser.parse(createReader("/templates/include/viewReply.html"));
614                 Template openSearchTemplate = TemplateParser.parse(createReader("/templates/xml/OpenSearch.xml"));
615
616                 PageToadletFactory pageToadletFactory = new PageToadletFactory(sonePlugin.pluginRespirator().getHLSimpleClient(), "/Sone/");
617                 pageToadlets.add(pageToadletFactory.createPageToadlet(new RedirectPage<FreenetRequest>("", "index.html")));
618                 pageToadlets.add(pageToadletFactory.createPageToadlet(new IndexPage(indexTemplate, this), "Index"));
619                 pageToadlets.add(pageToadletFactory.createPageToadlet(new NewPage(newTemplate, this), "New"));
620                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateSonePage(createSoneTemplate, this), "CreateSone"));
621                 pageToadlets.add(pageToadletFactory.createPageToadlet(new KnownSonesPage(knownSonesTemplate, this), "KnownSones"));
622                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfilePage(editProfileTemplate, this), "EditProfile"));
623                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfileFieldPage(editProfileFieldTemplate, this)));
624                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteProfileFieldPage(deleteProfileFieldTemplate, this)));
625                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreatePostPage(createPostTemplate, this)));
626                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyPage(createReplyTemplate, this)));
627                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewSonePage(viewSoneTemplate, this)));
628                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewPostPage(viewPostTemplate, this)));
629                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LikePage(emptyTemplate, this)));
630                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlikePage(emptyTemplate, this)));
631                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostPage(deletePostTemplate, this)));
632                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyPage(deleteReplyTemplate, this)));
633                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LockSonePage(emptyTemplate, this)));
634                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlockSonePage(emptyTemplate, this)));
635                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSonePage(emptyTemplate, this)));
636                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSonePage(emptyTemplate, this)));
637                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ImageBrowserPage(imageBrowserTemplate, this), "ImageBrowser"));
638                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateAlbumPage(createAlbumTemplate, this)));
639                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditAlbumPage(emptyTemplate, this)));
640                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteAlbumPage(deleteAlbumTemplate, this)));
641                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UploadImagePage(invalidTemplate, this)));
642                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditImagePage(emptyTemplate, this)));
643                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteImagePage(deleteImageTemplate, this)));
644                 pageToadlets.add(pageToadletFactory.createPageToadlet(new TrustPage(emptyTemplate, this)));
645                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DistrustPage(emptyTemplate, this)));
646                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UntrustPage(emptyTemplate, this)));
647                 pageToadlets.add(pageToadletFactory.createPageToadlet(new MarkAsKnownPage(emptyTemplate, this)));
648                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarkPage(emptyTemplate, this)));
649                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnbookmarkPage(emptyTemplate, this)));
650                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarksPage(bookmarksTemplate, this), "Bookmarks"));
651                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SearchPage(searchTemplate, this)));
652                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteSonePage(deleteSoneTemplate, this), "DeleteSone"));
653                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LoginPage(loginTemplate, this), "Login"));
654                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LogoutPage(emptyTemplate, this), "Logout"));
655                 pageToadlets.add(pageToadletFactory.createPageToadlet(new OptionsPage(optionsTemplate, this), "Options"));
656                 pageToadlets.add(pageToadletFactory.createPageToadlet(new RescuePage(rescueTemplate, this), "Rescue"));
657                 pageToadlets.add(pageToadletFactory.createPageToadlet(new AboutPage(aboutTemplate, this, SonePlugin.VERSION), "About"));
658                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("noPermission.html", noPermissionTemplate, "Page.NoPermission.Title", this)));
659                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DismissNotificationPage(emptyTemplate, this)));
660                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("invalid.html", invalidTemplate, "Page.Invalid.Title", this)));
661                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage<FreenetRequest>("css/", "/static/css/", "text/css")));
662                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage<FreenetRequest>("javascript/", "/static/javascript/", "text/javascript")));
663                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage<FreenetRequest>("images/", "/static/images/", "image/png")));
664                 pageToadlets.add(pageToadletFactory.createPageToadlet(new TemplatePage<FreenetRequest>("OpenSearch.xml", "application/opensearchdescription+xml", templateContextFactory, openSearchTemplate)));
665                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetImagePage(this)));
666                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetTranslationPage(this)));
667                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetStatusAjaxPage(this)));
668                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetNotificationsAjaxPage(this)));
669                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DismissNotificationAjaxPage(this)));
670                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreatePostAjaxPage(this)));
671                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyAjaxPage(this)));
672                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetReplyAjaxPage(this, replyTemplate)));
673                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetPostAjaxPage(this, postTemplate)));
674                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetTimesAjaxPage(this)));
675                 pageToadlets.add(pageToadletFactory.createPageToadlet(new MarkAsKnownAjaxPage(this)));
676                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostAjaxPage(this)));
677                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyAjaxPage(this)));
678                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LockSoneAjaxPage(this)));
679                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlockSoneAjaxPage(this)));
680                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSoneAjaxPage(this)));
681                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSoneAjaxPage(this)));
682                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditAlbumAjaxPage(this)));
683                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditImageAjaxPage(this, parserFilter)));
684                 pageToadlets.add(pageToadletFactory.createPageToadlet(new TrustAjaxPage(this)));
685                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DistrustAjaxPage(this)));
686                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UntrustAjaxPage(this)));
687                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LikeAjaxPage(this)));
688                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlikeAjaxPage(this)));
689                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetLikesAjaxPage(this)));
690                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarkAjaxPage(this)));
691                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnbookmarkAjaxPage(this)));
692                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfileFieldAjaxPage(this)));
693                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteProfileFieldAjaxPage(this)));
694                 pageToadlets.add(pageToadletFactory.createPageToadlet(new MoveProfileFieldAjaxPage(this)));
695
696                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
697                 toadletContainer.getPageMaker().addNavigationCategory("/Sone/index.html", "Navigation.Menu.Sone.Name", "Navigation.Menu.Sone.Tooltip", sonePlugin);
698                 for (PageToadlet toadlet : pageToadlets) {
699                         String menuName = toadlet.getMenuName();
700                         if (menuName != null) {
701                                 toadletContainer.register(toadlet, "Navigation.Menu.Sone.Name", toadlet.path(), true, "Navigation.Menu.Sone.Item." + menuName + ".Name", "Navigation.Menu.Sone.Item." + menuName + ".Tooltip", false, toadlet);
702                         } else {
703                                 toadletContainer.register(toadlet, null, toadlet.path(), true, false);
704                         }
705                 }
706         }
707
708         /**
709          * Unregisters all toadlets.
710          */
711         private void unregisterToadlets() {
712                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
713                 for (PageToadlet pageToadlet : pageToadlets) {
714                         toadletContainer.unregister(pageToadlet);
715                 }
716                 toadletContainer.getPageMaker().removeNavigationCategory("Navigation.Menu.Sone.Name");
717         }
718
719         /**
720          * Creates a {@link Reader} from the {@link InputStream} for the resource
721          * with the given name.
722          *
723          * @param resourceName
724          *            The name of the resource
725          * @return A {@link Reader} for the resource
726          */
727         private Reader createReader(String resourceName) {
728                 try {
729                         return new InputStreamReader(getClass().getResourceAsStream(resourceName), "UTF-8");
730                 } catch (UnsupportedEncodingException uee1) {
731                         return null;
732                 }
733         }
734
735         /**
736          * Returns all {@link Core#isLocalSone(Sone) local Sone}s that are
737          * referenced by {@link SonePart}s in the given text (after parsing it using
738          * {@link SoneTextParser}).
739          *
740          * @param text
741          *            The text to parse
742          * @return All mentioned local Sones
743          */
744         private Set<Sone> getMentionedSones(String text) {
745                 /* we need no context to find mentioned Sones. */
746                 Set<Sone> mentionedSones = new HashSet<Sone>();
747                 try {
748                         for (Part part : soneTextParser.parse(null, new StringReader(text))) {
749                                 if (part instanceof SonePart) {
750                                         mentionedSones.add(((SonePart) part).getSone());
751                                 }
752                         }
753                 } catch (IOException ioe1) {
754                         logger.log(Level.WARNING, String.format("Could not parse post text: %s", text), ioe1);
755                 }
756                 return Filters.filteredSet(mentionedSones, Sone.LOCAL_SONE_FILTER);
757         }
758
759         /**
760          * Returns the Sone insert notification for the given Sone. If no
761          * notification for the given Sone exists, a new notification is created and
762          * cached.
763          *
764          * @param sone
765          *            The Sone to get the insert notification for
766          * @return The Sone insert notification
767          */
768         private TemplateNotification getSoneInsertNotification(Sone sone) {
769                 synchronized (soneInsertNotifications) {
770                         TemplateNotification templateNotification = soneInsertNotifications.get(sone);
771                         if (templateNotification == null) {
772                                 templateNotification = new TemplateNotification(TemplateParser.parse(createReader("/templates/notify/soneInsertNotification.html")));
773                                 templateNotification.set("insertSone", sone);
774                                 soneInsertNotifications.put(sone, templateNotification);
775                         }
776                         return templateNotification;
777                 }
778         }
779
780         //
781         // CORELISTENER METHODS
782         //
783
784         /**
785          * {@inheritDoc}
786          */
787         @Override
788         public void newSoneFound(Sone sone) {
789                 newSoneNotification.add(sone);
790                 if (!hasFirstStartNotification()) {
791                         notificationManager.addNotification(newSoneNotification);
792                 }
793         }
794
795         /**
796          * {@inheritDoc}
797          */
798         @Override
799         public void newPostFound(Post post) {
800                 boolean isLocal = getCore().isLocalSone(post.getSone());
801                 if (isLocal) {
802                         localPostNotification.add(post);
803                 } else {
804                         newPostNotification.add(post);
805                 }
806                 if (!hasFirstStartNotification()) {
807                         notificationManager.addNotification(isLocal ? localPostNotification : newPostNotification);
808                         if (!getMentionedSones(post.getText()).isEmpty() && !isLocal) {
809                                 mentionNotification.add(post);
810                                 notificationManager.addNotification(mentionNotification);
811                         }
812                 } else {
813                         getCore().markPostKnown(post);
814                 }
815         }
816
817         /**
818          * {@inheritDoc}
819          */
820         @Override
821         public void newReplyFound(PostReply reply) {
822                 boolean isLocal = getCore().isLocalSone(reply.getSone());
823                 if (isLocal) {
824                         localReplyNotification.add(reply);
825                 } else {
826                         newReplyNotification.add(reply);
827                 }
828                 if (!hasFirstStartNotification()) {
829                         notificationManager.addNotification(isLocal ? localReplyNotification : newReplyNotification);
830                         if (!getMentionedSones(reply.getText()).isEmpty() && !isLocal && (reply.getPost().getSone() != null) && (reply.getTime() <= System.currentTimeMillis())) {
831                                 mentionNotification.add(reply.getPost());
832                                 notificationManager.addNotification(mentionNotification);
833                         }
834                 } else {
835                         getCore().markReplyKnown(reply);
836                 }
837         }
838
839         /**
840          * {@inheritDoc}
841          */
842         @Override
843         public void markSoneKnown(Sone sone) {
844                 newSoneNotification.remove(sone);
845         }
846
847         /**
848          * {@inheritDoc}
849          */
850         @Override
851         public void markPostKnown(Post post) {
852                 newPostNotification.remove(post);
853                 localPostNotification.remove(post);
854                 mentionNotification.remove(post);
855         }
856
857         /**
858          * {@inheritDoc}
859          */
860         @Override
861         public void markReplyKnown(PostReply reply) {
862                 newReplyNotification.remove(reply);
863                 localReplyNotification.remove(reply);
864                 mentionNotification.remove(reply.getPost());
865         }
866
867         /**
868          * {@inheritDoc}
869          */
870         @Override
871         public void soneRemoved(Sone sone) {
872                 newSoneNotification.remove(sone);
873         }
874
875         /**
876          * {@inheritDoc}
877          */
878         @Override
879         public void postRemoved(Post post) {
880                 newPostNotification.remove(post);
881                 localPostNotification.remove(post);
882                 mentionNotification.remove(post);
883         }
884
885         /**
886          * {@inheritDoc}
887          */
888         @Override
889         public void replyRemoved(PostReply reply) {
890                 newReplyNotification.remove(reply);
891                 localReplyNotification.remove(reply);
892                 if (!getMentionedSones(reply.getText()).isEmpty()) {
893                         boolean isMentioned = false;
894                         for (PostReply existingReply : getCore().getReplies(reply.getPost())) {
895                                 isMentioned |= !reply.isKnown() && !getMentionedSones(existingReply.getText()).isEmpty();
896                         }
897                         if (!isMentioned) {
898                                 mentionNotification.remove(reply.getPost());
899                         }
900                 }
901         }
902
903         /**
904          * {@inheritDoc}
905          */
906         @Override
907         public void soneLocked(final Sone sone) {
908                 Object tickerObject = Ticker.getInstance().registerEvent(System.currentTimeMillis() + (5 * 60) * 1000, new Runnable() {
909
910                         @Override
911                         @SuppressWarnings("synthetic-access")
912                         public void run() {
913                                 lockedSonesNotification.add(sone);
914                                 lockedSonesTickerObjects.remove(sone);
915                                 notificationManager.addNotification(lockedSonesNotification);
916                         }
917                 }, "Sone Locked Notification");
918                 lockedSonesTickerObjects.put(sone, tickerObject);
919         }
920
921         /**
922          * {@inheritDoc}
923          */
924         @Override
925         public void soneUnlocked(Sone sone) {
926                 lockedSonesNotification.remove(sone);
927                 Ticker.getInstance().deregisterEvent(lockedSonesTickerObjects.remove(sone));
928         }
929
930         /**
931          * {@inheritDoc}
932          */
933         @Override
934         public void soneInserting(Sone sone) {
935                 TemplateNotification soneInsertNotification = getSoneInsertNotification(sone);
936                 soneInsertNotification.set("soneStatus", "inserting");
937                 if (sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").get()) {
938                         notificationManager.addNotification(soneInsertNotification);
939                 }
940         }
941
942         /**
943          * {@inheritDoc}
944          */
945         @Override
946         public void soneInserted(Sone sone, long insertDuration) {
947                 TemplateNotification soneInsertNotification = getSoneInsertNotification(sone);
948                 soneInsertNotification.set("soneStatus", "inserted");
949                 soneInsertNotification.set("insertDuration", insertDuration / 1000);
950                 if (sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").get()) {
951                         notificationManager.addNotification(soneInsertNotification);
952                 }
953         }
954
955         /**
956          * {@inheritDoc}
957          */
958         @Override
959         public void soneInsertAborted(Sone sone, Throwable cause) {
960                 TemplateNotification soneInsertNotification = getSoneInsertNotification(sone);
961                 soneInsertNotification.set("soneStatus", "insert-aborted");
962                 soneInsertNotification.set("insert-error", cause);
963                 if (sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").get()) {
964                         notificationManager.addNotification(soneInsertNotification);
965                 }
966         }
967
968         /**
969          * {@inheritDoc}
970          */
971         @Override
972         public void updateFound(Version version, long releaseTime, long latestEdition) {
973                 newVersionNotification.getTemplateContext().set("latestVersion", version);
974                 newVersionNotification.getTemplateContext().set("latestEdition", latestEdition);
975                 newVersionNotification.getTemplateContext().set("releaseTime", releaseTime);
976                 notificationManager.addNotification(newVersionNotification);
977         }
978
979         /**
980          * {@inheritDoc}
981          */
982         @Override
983         public void imageInsertStarted(Image image) {
984                 insertingImagesNotification.add(image);
985                 notificationManager.addNotification(insertingImagesNotification);
986         }
987
988         /**
989          * {@inheritDoc}
990          */
991         @Override
992         public void imageInsertAborted(Image image) {
993                 insertingImagesNotification.remove(image);
994         }
995
996         /**
997          * {@inheritDoc}
998          */
999         @Override
1000         public void imageInsertFinished(Image image) {
1001                 insertingImagesNotification.remove(image);
1002                 insertedImagesNotification.add(image);
1003                 notificationManager.addNotification(insertedImagesNotification);
1004         }
1005
1006         /**
1007          * {@inheritDoc}
1008          */
1009         @Override
1010         public void imageInsertFailed(Image image, Throwable cause) {
1011                 insertingImagesNotification.remove(image);
1012                 imageInsertFailedNotification.add(image);
1013                 notificationManager.addNotification(imageInsertFailedNotification);
1014         }
1015
1016         /**
1017          * Template provider implementation that uses
1018          * {@link WebInterface#createReader(String)} to load templates for
1019          * inclusion.
1020          *
1021          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
1022          */
1023         private class ClassPathTemplateProvider implements Provider {
1024
1025                 /** Cache for templates. */
1026                 private final Cache<String, Template> templateCache = new MemoryCache<String, Template>(new ValueRetriever<String, Template>() {
1027
1028                         @Override
1029                         @SuppressWarnings("synthetic-access")
1030                         public CacheItem<Template> retrieve(String key) throws CacheException {
1031                                 Template template = findTemplate(key);
1032                                 if (template != null) {
1033                                         return new DefaultCacheItem<Template>(template);
1034                                 }
1035                                 return null;
1036                         }
1037                 });
1038
1039                 /**
1040                  * {@inheritDoc}
1041                  */
1042                 @Override
1043                 @SuppressWarnings("synthetic-access")
1044                 public Template getTemplate(TemplateContext templateContext, String templateName) {
1045                         try {
1046                                 return templateCache.get(templateName);
1047                         } catch (CacheException ce1) {
1048                                 logger.log(Level.WARNING, String.format("Could not get template for %s!", templateName), ce1);
1049                                 return null;
1050                         }
1051                 }
1052
1053                 /**
1054                  * Locates a template in the class path.
1055                  *
1056                  * @param templateName
1057                  *            The name of the template to load
1058                  * @return The loaded template, or {@code null} if no template could be
1059                  *         found
1060                  */
1061                 @SuppressWarnings("synthetic-access")
1062                 private Template findTemplate(String templateName) {
1063                         Reader templateReader = createReader("/templates/" + templateName);
1064                         if (templateReader == null) {
1065                                 return null;
1066                         }
1067                         Template template = null;
1068                         try {
1069                                 template = TemplateParser.parse(templateReader);
1070                         } catch (TemplateException te1) {
1071                                 logger.log(Level.WARNING, String.format("Could not parse template “%s” for inclusion!", templateName), te1);
1072                         }
1073                         return template;
1074                 }
1075
1076         }
1077
1078 }