001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2018 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.http.freemarker;
020
021import freemarker.template.Configuration;
022import freemarker.template.SimpleScalar;
023import freemarker.template.Template;
024import freemarker.template.TemplateException;
025import freemarker.template.TemplateExceptionHandler;
026import freemarker.template.TemplateMethodModelEx;
027import freemarker.template.TemplateModel;
028import freemarker.template.TemplateModelException;
029import java.io.IOException;
030import java.io.Writer;
031import java.net.URI;
032import java.text.ParseException;
033import java.time.Instant;
034import java.util.HashMap;
035import java.util.List;
036import java.util.Locale;
037import java.util.Map;
038import java.util.MissingResourceException;
039import java.util.Optional;
040import java.util.ResourceBundle;
041import java.util.regex.Pattern;
042import org.jdrupes.httpcodec.protocols.http.HttpConstants.HttpStatus;
043import org.jdrupes.httpcodec.protocols.http.HttpField;
044import org.jdrupes.httpcodec.protocols.http.HttpRequest;
045import org.jdrupes.httpcodec.protocols.http.HttpResponse;
046import org.jdrupes.httpcodec.types.MediaType;
047import org.jgrapes.core.Channel;
048import org.jgrapes.core.Component;
049import org.jgrapes.core.annotation.Handler;
050import org.jgrapes.core.annotation.HandlerDefinition.ChannelReplacements;
051import org.jgrapes.core.events.Error;
052import org.jgrapes.http.ResourcePattern;
053import org.jgrapes.http.ResponseCreationSupport;
054import org.jgrapes.http.ResponseCreationSupport.MaxAgeCalculator;
055import org.jgrapes.http.Session;
056import org.jgrapes.http.events.Request;
057import org.jgrapes.http.events.Response;
058import org.jgrapes.io.IOSubchannel;
059import org.jgrapes.io.events.Close;
060import org.jgrapes.io.events.Output;
061import org.jgrapes.io.util.ByteBufferWriter;
062
063/**
064 * A base class for components that generate responses to
065 * HTTP requests which are based on a FreeMarker template.
066 */
067public class FreeMarkerRequestHandler extends Component {
068    public static final Pattern TEMPLATE_PATTERN
069        = Pattern.compile(".*\\.ftl\\.[a-z]+$");
070
071    private ClassLoader contentLoader;
072    private String contentPath;
073    private URI prefix;
074    private ResourcePattern prefixPattern;
075    private Configuration fmConfig;
076    private MaxAgeCalculator maxAgeCalculator;
077
078    /**
079     * Instantiates a new free marker request handler.
080     * 
081     * The prefix path is removed from the request paths before resolving
082     * them against the content root. A prefix path must start with a
083     * slash and must end with a slash. If the request handler
084     * should respond to top-level requests, the prefix must be
085     * a single slash.
086     *
087     * @param componentChannel the component channel
088     * @param channelReplacements the channel replacements to apply
089     * to the `channels` elements of the {@link Handler} annotations
090     * @param contentLoader the content loader
091     * @param contentPath the content path
092     * @param prefix the prefix used in requests
093     */
094    @SuppressWarnings("PMD.LooseCoupling")
095    public FreeMarkerRequestHandler(Channel componentChannel,
096            ChannelReplacements channelReplacements,
097            ClassLoader contentLoader, String contentPath, URI prefix) {
098        super(componentChannel, channelReplacements);
099        String prefixPath = prefix.getPath();
100        if (!prefixPath.startsWith("/") || !prefixPath.endsWith("/")) {
101            throw new IllegalArgumentException("Illegal prefix: " + prefix);
102        }
103        this.prefix = prefix;
104        this.contentLoader = contentLoader;
105        if (contentPath.startsWith("/")) {
106            contentPath = contentPath.substring(1);
107        }
108        if (contentPath.endsWith("/")) {
109            contentPath = contentPath.substring(0, contentPath.length() - 1);
110        }
111        this.contentPath = contentPath;
112        try {
113            this.prefixPattern = new ResourcePattern(
114                prefixPath.substring(0, prefixPath.length() - 1) + "|**");
115        } catch (ParseException e) {
116            throw new IllegalArgumentException(e);
117        }
118    }
119
120    /**
121     * Instantiates a new free marker request handler.
122     * 
123     * The prefix path is removed from the request paths before resolving
124     * them against the content root. A prefix path must start with a
125     * slash and must end with a slash. If the request handler
126     * should respond to top-level requests, the prefix must be
127     * a single slash.
128     *
129     * @param componentChannel the component channel
130     * @param contentLoader the content loader
131     * @param contentPath the content path
132     * @param prefix the prefix used in requests
133     */
134    public FreeMarkerRequestHandler(Channel componentChannel,
135            ClassLoader contentLoader, String contentPath, URI prefix) {
136        this(componentChannel, null, contentLoader, contentPath, prefix);
137    }
138
139    /**
140     * Returns the prefix passed to the constructor.
141     *
142     * @return the prefix
143     */
144    public URI prefix() {
145        return prefix;
146    }
147
148    /**
149     * Gets the prefix pattern. 
150     *
151     * @return the prefixPattern
152     */
153    public ResourcePattern prefixPattern() {
154        return prefixPattern;
155    }
156
157    /**
158     * Updates the prefix pattern. The contructor initializes the
159     * prefix pattern to the prefix with "|**" appended
160     * (see {@link ResourcePattern}.
161     *
162     * @param prefixPattern the prefixPattern to set
163     */
164    protected void updatePrefixPattern(ResourcePattern prefixPattern) {
165        this.prefixPattern = prefixPattern;
166    }
167
168    /**
169     * @return the maxAgeCalculator
170     */
171    public MaxAgeCalculator maxAgeCalculator() {
172        return maxAgeCalculator;
173    }
174
175    /**
176     * Sets the {@link MaxAgeCalculator} for generating the `Cache-Control` 
177     * (`max-age`) header of the response. The default is `null`. This
178     * causes 0 to be provided for responses generated from templates and the 
179     * {@link ResponseCreationSupport#DEFAULT_MAX_AGE_CALCULATOR} to be
180     * used for static content.
181     * 
182     * @param maxAgeCalculator the maxAgeCalculator to set
183     */
184    public void setMaxAgeCalculator(MaxAgeCalculator maxAgeCalculator) {
185        this.maxAgeCalculator = maxAgeCalculator;
186    }
187
188    /**
189     * Removes the prefix specified in the constructor from the
190     * path in the request. Checks if the resulting path  
191     * ends with `*.ftl.*`. If so, processes the template with the
192     * {@link #sendProcessedTemplate(Request.In, IOSubchannel, String)} (which 
193     * uses {@link #fmSessionModel(Optional)}) and sends the result. 
194     * Else, tries to serve static content with the optionally 
195     * shortened path.
196     * 
197     * @param event the event
198     * @param channel the channel
199     * @throws ParseException the parse exception
200     */
201    protected void doRespond(Request.In event, IOSubchannel channel)
202            throws ParseException {
203        final HttpRequest request = event.httpRequest();
204        prefixPattern.pathRemainder(request.requestUri()).ifPresent(path -> {
205            boolean success;
206            if (TEMPLATE_PATTERN.matcher(path).matches()) {
207                success = sendProcessedTemplate(event, channel, path);
208            } else {
209                success = ResponseCreationSupport.sendStaticContent(
210                    request, channel, requestPath -> contentLoader
211                        .getResource(contentPath + "/" + path),
212                    maxAgeCalculator);
213            }
214            event.setResult(true);
215            event.stop();
216            if (!success) {
217                channel.respond(new Close());
218            }
219        });
220    }
221
222    /**
223     * Render a response using the given template. Send the 
224     * {@link Response} and at least one {@link Output} event.
225     *
226     * If the method does not return `true`, the invoker should close
227     * the connection because it is most likely in an undefined state.
228     *
229     * @param event the request event
230     * @param channel the channel
231     * @param tpl the template
232     * @return false if an error occurred
233     */
234    protected boolean sendProcessedTemplate(
235            Request.In event, IOSubchannel channel, Template tpl) {
236        // Prepare response
237        HttpResponse response = event.httpRequest().response().get();
238        MediaType mediaType = contentType(
239            ResponseCreationSupport.uriFromPath(tpl.getSourceName()));
240        response.setContentType(mediaType);
241
242        // Send response
243        response.setStatus(HttpStatus.OK);
244        response.setField(HttpField.LAST_MODIFIED, Instant.now());
245        if (maxAgeCalculator == null) {
246            ResponseCreationSupport.setMaxAge(response, 0);
247        } else {
248            ResponseCreationSupport.setMaxAge(response,
249                maxAgeCalculator.maxAge(event.httpRequest(), mediaType));
250        }
251        channel.respond(new Response(response));
252
253        // Send content
254        try (@SuppressWarnings("resource")
255        Writer out = new ByteBufferWriter(channel).suppressClose()) {
256            Map<String, Object> model
257                = fmSessionModel(event.associatedGet(Session.class));
258            tpl.setLocale((Locale) model.get("locale"));
259            tpl.process(model, out);
260            return true;
261        } catch (IOException | TemplateException e) {
262            // Too late to do anything about this (header was sent).
263            fire(new Error(event, e), channel);
264        }
265        return false;
266    }
267
268    /**
269     * Render a response using the template obtained from the config with
270     * {@link Configuration#getTemplate(String)} and the given path.
271     *
272     * @param event
273     *            the event
274     * @param channel
275     *            the channel
276     * @param path
277     *            the path
278     */
279    protected boolean sendProcessedTemplate(
280            Request.In event, IOSubchannel channel, String path) {
281        try {
282            // Get template (no need to continue if this fails).
283            Template tpl = freemarkerConfig().getTemplate(path);
284            return sendProcessedTemplate(event, channel, tpl);
285        } catch (IOException e) {
286            fire(new Error(event, e), channel);
287            return false;
288        }
289    }
290
291    /**
292     * Creates the configuration for freemarker template processing.
293     * 
294     * @return the configuration
295     */
296    protected Configuration freemarkerConfig() {
297        if (fmConfig == null) {
298            fmConfig = new Configuration(Configuration.VERSION_2_3_26);
299            fmConfig.setClassLoaderForTemplateLoading(
300                contentLoader, contentPath);
301            fmConfig.setDefaultEncoding("utf-8");
302            fmConfig.setTemplateExceptionHandler(
303                TemplateExceptionHandler.RETHROW_HANDLER);
304            fmConfig.setLogTemplateExceptions(false);
305        }
306        return fmConfig;
307    }
308
309    /**
310     * Build a freemarker model holding the information usually found in the
311     * session. Provides fallbacks in case no session is available.
312     * 
313     * This model provides: 
314     * 
315     * * The `locale` (of type {@link Locale}) (falls back to 
316     *   {@link Locale#getDefault()}. 
317     * 
318     * * The `resourceBundle` (of type {@link ResourceBundle})
319     *   obtained by calling {@link #resourceBundle(Locale)}. 
320     * 
321     * * A function "`_`" that looks up the given key in the 
322     *   resource bundle.
323     * 
324     * @param session
325     *            the session
326     * @return the model
327     */
328    protected Map<String, Object> fmSessionModel(Optional<Session> session) {
329        @SuppressWarnings("PMD.UseConcurrentHashMap")
330        final Map<String, Object> model = new HashMap<>();
331        Locale locale
332            = session.map(Session::locale).orElse(Locale.getDefault());
333        model.put("locale", locale);
334        final ResourceBundle resourceBundle = resourceBundle(locale);
335        model.put("resourceBundle", resourceBundle);
336        model.put("_", new TemplateMethodModelEx() {
337            @Override
338            @SuppressWarnings("PMD.EmptyCatchBlock")
339            public Object exec(@SuppressWarnings("rawtypes") List arguments)
340                    throws TemplateModelException {
341                @SuppressWarnings("unchecked")
342                List<TemplateModel> args = (List<TemplateModel>) arguments;
343                if (!(args.get(0) instanceof SimpleScalar)) {
344                    throw new TemplateModelException("Not a string.");
345                }
346                String key = ((SimpleScalar) args.get(0)).getAsString();
347                try {
348                    return resourceBundle.getString(key);
349                } catch (MissingResourceException e) {
350                    // no luck
351                }
352                return key;
353            }
354        });
355        return model;
356    }
357
358    /**
359     * Used to get the content type when generating a response with
360     * {@link #sendProcessedTemplate(Request.In, IOSubchannel, Template)}. 
361     * May be overridden by derived classes. This implementation simply invokes
362     * {@link HttpResponse#contentType(URI)}.
363     *
364     * @param request the request
365     * @return the content type
366     */
367    protected MediaType contentType(URI request) {
368        return HttpResponse.contentType(request);
369    }
370
371    /**
372     * Provides a resource bundle for localization.
373     * The default implementation looks up a bundle using the
374     * package name plus "l10n" as base name.
375     * 
376     * @return the resource bundle
377     */
378    protected ResourceBundle resourceBundle(Locale locale) {
379        return ResourceBundle.getBundle(
380            contentPath.replace('/', '.') + ".l10n", locale,
381            contentLoader, ResourceBundle.Control.getNoFallbackControl(
382                ResourceBundle.Control.FORMAT_DEFAULT));
383    }
384}