001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.rest.server.view.freemarker; 018 019import static org.apache.juneau.commons.utils.Shorts.*; 020import static org.apache.juneau.commons.utils.StringUtils.*; 021 022import java.io.*; 023import java.util.*; 024 025import org.apache.juneau.commons.utils.*; 026import org.apache.juneau.http.response.*; 027import org.apache.juneau.rest.server.*; 028import org.apache.juneau.rest.server.view.*; 029 030import freemarker.core.*; 031import freemarker.template.*; 032 033/** 034 * Flavor-neutral worker bean carrying the FreeMarker raw-template-dispatch logic shared by the 035 * {@link FreemarkerMixin} mixin, the {@link FreemarkerServlet} servlet, and the 036 * {@link FreemarkerResource} child flavors. 037 * 038 * <p> 039 * This is the <i>flavor-neutral worker</i> for the FreeMarker capability: it is <b>not</b> one 040 * of the three {@code @Rest} flavor classes — it is a plain bean that implements 041 * {@link RawTemplateDispatcher} and holds the capability state ({@code basePath} / 042 * {@code templateSuffix} / {@code cacheTemplates} / lazy default configuration) plus the raw-serve 043 * and configuration-resolution logic. Each flavor independently holds an instance of this worker and 044 * delegates to it, so no flavor is another flavor's worker. 045 * 046 * <h2 class='section'>See Also:</h2><ul> 047 * <li class='jc'>{@link FreemarkerMixin} 048 * <li class='jc'>{@link FreemarkerServlet} 049 * <li class='jc'>{@link FreemarkerResource} 050 * <li class='jic'>{@link RawTemplateDispatcher} 051 * </ul> 052 * 053 * @since 10.0.0 054 */ 055@SuppressWarnings({ 056 "resource" // Closeables here are framework-managed and not owned/closed by this class; not a real leak. 057}) 058public class FreemarkerDispatcher implements RawTemplateDispatcher { 059 060 /** Default base path applied when no {@link Builder#basePath(String)} call has been made. */ 061 @SuppressWarnings({ 062 "java:S1075" // Default for the configurable basePath setting, not a hardcoded location. 063 }) 064 public static final String DEFAULT_BASE_PATH = "/templates/"; 065 066 /** Default template suffix — empty (literal template names, no implicit suffix). */ 067 public static final String DEFAULT_TEMPLATE_SUFFIX = ""; 068 069 /** Default template-cache flag — {@code true} (production-safe). */ 070 public static final boolean DEFAULT_CACHE_TEMPLATES = true; 071 072 /** Default field-exposure flag — {@code true} (public-field DTOs render out of the box). */ 073 public static final boolean DEFAULT_EXPOSE_FIELDS = true; 074 075 private final String basePath; 076 private final String templateSuffix; 077 private final boolean cacheTemplates; 078 private final boolean exposeFields; 079 private final ObjectWrapper objectWrapper; 080 081 // Lazy bridge-default configuration. Built on first call to resolveConfiguration(...) when 082 // no Configuration bean is registered in the request's BeanStore. Volatile so the 083 // double-checked-locking idiom is safe under concurrent first-request load. 084 @SuppressWarnings({ 085 "java:S3077" // volatile is required here for correct double-checked-locking safe-publication of the lazily-built default Configuration in resolveConfiguration(); the reference is publish-once (fully constructed before assignment) and never compound-mutated. 086 }) 087 private volatile Configuration defaultConfiguration; 088 089 /** 090 * Creates a new builder. 091 * 092 * @return A new builder. 093 */ 094 public static Builder create() { 095 return new Builder(); 096 } 097 098 /** 099 * Builder constructor. 100 * 101 * @param builder The builder. Must not be {@code null}. 102 */ 103 protected FreemarkerDispatcher(Builder builder) { 104 basePath = builder.basePath; 105 templateSuffix = builder.templateSuffix; 106 cacheTemplates = builder.cacheTemplates; 107 exposeFields = builder.exposeFields; 108 objectWrapper = builder.objectWrapper; 109 } 110 111 /** 112 * Returns the base path under which template resources are resolved. 113 * 114 * @return The base path. Never {@code null}. 115 */ 116 public String getBasePath() { 117 return basePath; 118 } 119 120 /** 121 * Returns the configured template-name suffix. 122 * 123 * @return The template suffix. Never {@code null}. 124 */ 125 public String getTemplateSuffix() { 126 return templateSuffix; 127 } 128 129 /** 130 * Returns the template-cache flag. 131 * 132 * @return The cache flag. 133 */ 134 public boolean isCacheTemplates() { 135 return cacheTemplates; 136 } 137 138 /** 139 * Returns the field-exposure flag applied to the bridge-default object wrapper. 140 * 141 * @return The field-exposure flag. Ignored once {@link #getObjectWrapper()} returns non-{@code null}. 142 */ 143 public boolean isExposeFields() { 144 return exposeFields; 145 } 146 147 /** 148 * Returns the user-supplied {@link ObjectWrapper} override, if any. 149 * 150 * @return The object wrapper override, or {@code null} if the bridge builds its own default 151 * (a {@link DefaultObjectWrapper} configured per {@link #isExposeFields() isExposeFields()}). 152 */ 153 public ObjectWrapper getObjectWrapper() { 154 return objectWrapper; 155 } 156 157 /** 158 * Appends {@link #getTemplateSuffix()} to {@code name} if not already present (idempotent). 159 * 160 * @param name The template name. Must not be {@code null}. 161 * @return The template name with the configured suffix appended (if applicable). 162 */ 163 public String applyTemplateSuffix(String name) { 164 if (isEmpty(templateSuffix)) 165 return name; 166 if (name.endsWith(templateSuffix)) 167 return name; 168 return name + templateSuffix; 169 } 170 171 /** 172 * Resolves the active {@link Configuration}. 173 * 174 * <p> 175 * Lookup order: 176 * <ol class='spaced-list'> 177 * <li>{@code req.getContext().getBeanStore().getBean(Configuration.class)} — any 178 * user-supplied bean (Spring {@code @Bean} including Spring Boot autoconfig, microservice 179 * {@code BasicBeanStore.put}, etc.). 180 * <li>Lazy bridge default — constructed on first call when no configuration bean is 181 * registered. Anchored on a classpath resource root derived from 182 * {@link #getBasePath() basePath}, with {@code IncompatibleImprovements} pinned to the 183 * bridge-tested minor version. 184 * </ol> 185 * 186 * @param req The current REST request. 187 * @return The active FreeMarker configuration. Never {@code null}. 188 */ 189 public Configuration resolveConfiguration(RestRequest req) { 190 var bean = req.getContext().getBeanStore().getBean(Configuration.class); 191 if (bean.isPresent()) 192 return bean.get(); 193 var local = defaultConfiguration; 194 if (local == null) { 195 synchronized (this) { 196 local = defaultConfiguration; 197 if (local == null) { 198 local = buildDefaultConfiguration(); 199 defaultConfiguration = local; 200 } 201 } 202 } 203 return local; 204 } 205 206 /** 207 * Constructs the bridge-default {@link Configuration}. 208 * 209 * <p> 210 * Anchored on a classpath resource root derived from {@link #getBasePath() basePath} (leading + 211 * trailing slashes trimmed). The default 212 * pins {@code IncompatibleImprovements} to {@link Configuration#VERSION_2_3_34} so behavior is 213 * stable across consumer upgrades of {@code org.freemarker:freemarker}; sets 214 * {@code DefaultEncoding} to {@code UTF-8} and {@code OutputFormat} to 215 * {@link HTMLOutputFormat#INSTANCE} so HTML escaping is the natural target; applies 216 * {@code TemplateUpdateDelayMilliseconds} per the configured 217 * {@link #isCacheTemplates() cacheTemplates} flag; and sets an {@code ObjectWrapper} — 218 * either the user-supplied {@link #getObjectWrapper() objectWrapper} override, or (by default) 219 * a {@link DefaultObjectWrapper} built with {@code exposeFields} set to 220 * {@link #isExposeFields() isExposeFields()}. Field exposure defaults to {@code true} (unlike 221 * FreeMarker's own version-default wrapper, which is getter-only): Juneau's own marshalling is 222 * comfortable with public-field beans elsewhere, so a view-model DTO written with public fields 223 * and no getters renders its field values here too, instead of silently resolving to 224 * {@code null}/missing. 225 * 226 * <p> 227 * Template exceptions are not logged by FreeMarker ({@code LogTemplateExceptions} is {@code false}): 228 * every caller rethrows them as an {@code InternalServerError} carrying the cause, so logging them 229 * as well would only duplicate the stack trace. 230 * 231 * <p> 232 * Subclasses may override to plug in custom loaders / encodings / output formats without 233 * registering a separate {@code @Bean Configuration}. 234 * 235 * @return A new {@link Configuration} instance. 236 */ 237 protected Configuration buildDefaultConfiguration() { 238 var cfg = new Configuration(Configuration.VERSION_2_3_34); 239 cfg.setClassLoaderForTemplateLoading(FreemarkerDispatcher.class.getClassLoader(), toResourceRoot(basePath)); 240 cfg.setDefaultEncoding("UTF-8"); 241 cfg.setLogTemplateExceptions(false); 242 cfg.setOutputFormat(HTMLOutputFormat.INSTANCE); 243 cfg.setTemplateUpdateDelayMilliseconds(cacheTemplates ? Long.MAX_VALUE : 0L); 244 cfg.setNewBuiltinClassResolver(TemplateClassResolver.ALLOWS_NOTHING_RESOLVER); 245 cfg.setAPIBuiltinEnabled(false); 246 cfg.setObjectWrapper(objectWrapper != null ? objectWrapper : buildDefaultObjectWrapper()); 247 return cfg; 248 } 249 250 /** 251 * Builds the bridge-default {@link ObjectWrapper} — a {@link DefaultObjectWrapper} with 252 * {@code exposeFields} set per {@link #isExposeFields() isExposeFields()}. Only called when no 253 * {@link #getObjectWrapper() objectWrapper} override has been supplied. 254 * 255 * @return A new {@link DefaultObjectWrapper} instance. 256 */ 257 private ObjectWrapper buildDefaultObjectWrapper() { 258 var b = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_34); 259 b.setExposeFields(exposeFields); 260 return b.build(); 261 } 262 263 /** 264 * Translates a virtual base path (e.g. {@code "/templates/"}) into a FreeMarker 265 * {@code ClassLoaderTemplateLoader} resource root (e.g. {@code "/templates"}). 266 * 267 * <p> 268 * FreeMarker's 269 * {@link Configuration#setClassLoaderForTemplateLoading(ClassLoader, String) 270 * setClassLoaderForTemplateLoading(ClassLoader, String basePackagePath)} expects a 271 * classpath-relative root with a leading {@code "/"}. We trim any trailing slash and ensure a 272 * single leading slash; a {@code null} / blank / {@code "/"} base yields {@code "/"} (root of 273 * classpath). 274 * 275 * @param base The virtual base path. 276 * @return The FreeMarker classloader resource root (never {@code null}; always starts with 277 * {@code "/"}). 278 */ 279 static String toResourceRoot(String base) { 280 if (isBlank(base)) 281 return "/"; 282 var s = base; 283 while (s.endsWith("/") && s.length() > 1) 284 s = s.substring(0, s.length() - 1); 285 if (! s.startsWith("/")) 286 s = "/" + s; 287 return s; 288 } 289 290 /** 291 * Renders a raw template through the FreeMarker engine onto the response. 292 * 293 * @param path The trailing path segment after the mount prefix (the template name relative to 294 * the configured {@link #getBasePath() base path}; configured suffix appended if missing). 295 * @param req The current REST request. 296 * @param res The current REST response. 297 * @throws IOException If the underlying response writer fails. 298 * @throws BasicHttpException On boundary violation (403), missing engine (500), or render 299 * failure (500). 300 */ 301 @Override /* RawTemplateDispatcher */ 302 public void render(String path, RestRequest req, RestResponse res) 303 throws IOException, BasicHttpException { 304 305 var template = (path == null) ? "" : path; 306 307 // resolveVirtualPathSafely validates that the resolved virtual path stays inside the 308 // configured basePath. The traversal check operates on basePath + template so a template 309 // name like "../../etc/passwd" or "a/b/../../../secret" is rejected before reaching the 310 // engine. We re-derive the configuration-relative template name from the safe result by 311 // stripping the (already-normalized) basePath prefix. 312 String safeTemplate; 313 try { 314 var resolved = FileUtils.resolveVirtualPathSafely(basePath, template); 315 safeTemplate = stripBasePath(basePath, resolved); 316 } catch (IllegalArgumentException ex) { 317 throw new Forbidden("Path escapes configured base path."); 318 } 319 320 // Apply suffix idempotently so /freemarker/about resolves to about.ftlh (when 321 // templateSuffix is configured), while /freemarker/about.ftlh stays as-is. 322 safeTemplate = applyTemplateSuffix(safeTemplate); 323 324 // Only template-extension names are served, and names carrying a scheme or backslash never are. 325 if (! ViewTemplateNames.isPlainName(safeTemplate) || ! ViewTemplateNames.hasAllowedExtension(safeTemplate, ".ftlh", ".ftl")) 326 throw new NotFound("Template not found."); 327 328 try { 329 var cfg = resolveConfiguration(req); 330 if (! res.containsHeader("Content-Type")) 331 res.setHeader("Content-Type", FreemarkerViewRenderer.DEFAULT_CONTENT_TYPE); 332 var tpl = cfg.getTemplate(safeTemplate); 333 tpl.process(Map.of(), res.getWriter()); 334 res.getWriter().flush(); 335 } catch (LinkageError ex) { 336 throw new InternalServerError(ex, FreemarkerViewRenderer.NO_ENGINE_DIAGNOSTIC); 337 } catch (IOException | BasicHttpException ex) { 338 throw ex; 339 } catch (TemplateException | RuntimeException ex) { 340 throw new InternalServerError(ex, "FreeMarker render failed for '%s'", safeTemplate); 341 } 342 } 343 344 /** 345 * Strips the normalized {@code basePath} prefix from a {@code resolveVirtualPathSafely} 346 * result so the leftover string is configuration-relative (the bridge's default configuration 347 * re-adds the configured resource-root prefix via its template loader). 348 * 349 * <p> 350 * Normalization mirrors {@code FileUtils.resolveVirtualPathSafely}: a {@code null} / empty 351 * base normalizes to {@code "/"}; otherwise the base is guaranteed to start with {@code "/"} 352 * and end with {@code "/"} once the helper has normalized it. 353 * 354 * @param base The configured base path (typically {@code "/templates/"}). 355 * @param resolved The output of {@code resolveVirtualPathSafely} (always starts with the 356 * normalized base). 357 * @return The configuration-relative template name (e.g. {@code "hello.ftlh"} for base 358 * {@code "/templates/"} and resolved {@code "/templates/hello.ftlh"}). 359 */ 360 static String stripBasePath(String base, String resolved) { 361 var bp = isEmpty(base) ? "/" : base; 362 if (! bp.endsWith("/")) 363 bp = bp + "/"; 364 if (! bp.startsWith("/")) 365 bp = "/" + bp; 366 if (resolved.startsWith(bp)) 367 return resolved.substring(bp.length()); 368 throw iaex("Resolved path '%s' does not start with base '%s'", resolved, bp); 369 } 370 371 /** 372 * Builder for {@link FreemarkerDispatcher}. 373 */ 374 public static class Builder { 375 376 String basePath = DEFAULT_BASE_PATH; 377 String templateSuffix = DEFAULT_TEMPLATE_SUFFIX; 378 boolean cacheTemplates = DEFAULT_CACHE_TEMPLATES; 379 boolean exposeFields = DEFAULT_EXPOSE_FIELDS; 380 ObjectWrapper objectWrapper; 381 382 /** Constructor — package access for {@link FreemarkerDispatcher#create()}. */ 383 protected Builder() {} 384 385 /** 386 * Sets the classpath base path under which template resources are resolved. 387 * 388 * @param value The base path. {@code null} or blank values reset to the default 389 * {@link FreemarkerDispatcher#DEFAULT_BASE_PATH}. 390 * @return This object. 391 */ 392 public Builder basePath(String value) { 393 basePath = isBlank(value) ? DEFAULT_BASE_PATH : value; 394 return this; 395 } 396 397 /** 398 * Sets the suffix to append to template names that don't already end with it 399 * (idempotent). 400 * 401 * @param value The new suffix. {@code null} resets to 402 * {@link FreemarkerDispatcher#DEFAULT_TEMPLATE_SUFFIX}. 403 * @return This object. 404 */ 405 public Builder templateSuffix(String value) { 406 templateSuffix = (value == null) ? DEFAULT_TEMPLATE_SUFFIX : value; 407 return this; 408 } 409 410 /** 411 * Sets the template-cache flag for the bridge-default configuration. 412 * 413 * @param value The cache flag. 414 * @return This object. 415 */ 416 public Builder cacheTemplates(boolean value) { 417 cacheTemplates = value; 418 return this; 419 } 420 421 /** 422 * Sets whether the bridge-default {@code ObjectWrapper} exposes public fields (not just 423 * JavaBean getters) to templates. 424 * 425 * <p> 426 * Defaults to {@link FreemarkerDispatcher#DEFAULT_EXPOSE_FIELDS true} so simple view-model 427 * DTOs written with public fields and no getters render their field values instead of 428 * silently resolving to {@code null}/missing. Has no effect once {@link #objectWrapper} 429 * has been called with a non-{@code null} value — the explicit wrapper always wins. 430 * 431 * @param value The field-exposure flag. 432 * @return This object. 433 */ 434 public Builder exposeFields(boolean value) { 435 exposeFields = value; 436 return this; 437 } 438 439 /** 440 * Sets a fully custom {@code ObjectWrapper} for the bridge-default configuration, 441 * overriding {@link #exposeFields(boolean)} entirely. 442 * 443 * <p> 444 * Escape hatch for consumers who need full control (e.g. a {@code BeansWrapper} with 445 * custom method/property exposure, or a third-party wrapper) without hand-rolling and 446 * registering a whole replacement {@code Configuration} bean. 447 * 448 * @param value The object wrapper. {@code null} reverts to the bridge-built 449 * {@link DefaultObjectWrapper} (per {@link #exposeFields(boolean)}). 450 * @return This object. 451 */ 452 public Builder objectWrapper(ObjectWrapper value) { 453 objectWrapper = value; 454 return this; 455 } 456 457 /** 458 * Reads the current base path setting (test/inspection helper). 459 * 460 * @return The base path. Never {@code null}. 461 */ 462 public String getBasePath() { 463 return basePath; 464 } 465 466 /** 467 * Reads the current template-suffix setting (test/inspection helper). 468 * 469 * @return The template suffix. Never {@code null}. 470 */ 471 public String getTemplateSuffix() { 472 return templateSuffix; 473 } 474 475 /** 476 * Reads the current cache-templates setting (test/inspection helper). 477 * 478 * @return The cache flag. 479 */ 480 public boolean isCacheTemplates() { 481 return cacheTemplates; 482 } 483 484 /** 485 * Reads the current field-exposure setting (test/inspection helper). 486 * 487 * @return The field-exposure flag. 488 */ 489 public boolean isExposeFields() { 490 return exposeFields; 491 } 492 493 /** 494 * Reads the current object-wrapper override (test/inspection helper). 495 * 496 * @return The object wrapper override, or {@code null} if none has been set. 497 */ 498 public ObjectWrapper getObjectWrapper() { 499 return objectWrapper; 500 } 501 502 /** 503 * Builds the {@link FreemarkerDispatcher}. 504 * 505 * @return A new {@link FreemarkerDispatcher} instance. 506 */ 507 public FreemarkerDispatcher build() { 508 if (basePath == null) 509 throw iaex("basePath must not be null"); 510 return new FreemarkerDispatcher(this); 511 } 512 } 513}