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