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.thymeleaf; 018 019import static org.apache.juneau.commons.utils.Shorts.*; 020import static org.apache.juneau.commons.utils.StringUtils.*; 021 022import java.io.*; 023 024import org.apache.juneau.commons.utils.*; 025import org.apache.juneau.http.response.*; 026import org.apache.juneau.rest.server.*; 027import org.apache.juneau.rest.server.view.*; 028import org.thymeleaf.*; 029import org.thymeleaf.templatemode.*; 030import org.thymeleaf.templateresolver.*; 031 032/** 033 * Flavor-neutral worker bean carrying the Thymeleaf raw-template-dispatch logic shared by the 034 * {@link ThymeleafMixin} mixin, the {@link ThymeleafServlet} servlet, and the 035 * {@link ThymeleafResource} child flavors. 036 * 037 * <p> 038 * This is the <i>flavor-neutral worker</i> for the Thymeleaf capability: it is <b>not</b> one 039 * of the three {@code @Rest} flavor classes — it is a plain bean that implements 040 * {@link RawTemplateDispatcher} and holds the capability state ({@code basePath} / 041 * {@code cacheTemplates} / {@code templateMode} / lazy default engine) plus the raw-serve and 042 * engine-resolution logic. Each flavor independently holds an instance of this worker and delegates 043 * to it, so no flavor is another flavor's worker. 044 * 045 * <h2 class='section'>See Also:</h2><ul> 046 * <li class='jc'>{@link ThymeleafMixin} 047 * <li class='jc'>{@link ThymeleafServlet} 048 * <li class='jc'>{@link ThymeleafResource} 049 * <li class='jic'>{@link RawTemplateDispatcher} 050 * </ul> 051 * 052 * @since 10.0.0 053 */ 054@SuppressWarnings({ 055 "java:S1192", // Duplicate string literals are Thymeleaf template attribute keys; intentional 056 "resource" // Closeables here are framework-managed and not owned/closed by this class; not a real leak. 057}) 058public class ThymeleafDispatcher 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-cache flag — production-safe; opt out per-builder for dev. */ 067 public static final boolean DEFAULT_CACHE_TEMPLATES = true; 068 069 /** Default template mode for the bridge's fallback engine. */ 070 public static final TemplateMode DEFAULT_TEMPLATE_MODE = TemplateMode.HTML; 071 072 private final String basePath; 073 private final boolean cacheTemplates; 074 private final TemplateMode templateMode; 075 076 // Lazy bridge-default engine. Built on first call to resolveTemplateEngine(...) when no 077 // TemplateEngine bean is registered in the request's BeanStore. Volatile so the 078 // double-checked-locking idiom is safe under concurrent first-request load. 079 @SuppressWarnings({ 080 "java:S3077" // volatile is required here for correct double-checked-locking safe-publication of the lazily-created defaultEngine in resolveTemplateEngine(); the reference is publish-once and never compound-mutated. 081 }) 082 private volatile TemplateEngine defaultEngine; 083 084 /** 085 * Creates a new builder. 086 * 087 * @return A new builder. 088 */ 089 public static Builder create() { 090 return new Builder(); 091 } 092 093 /** 094 * Builder constructor. 095 * 096 * @param builder The builder. Must not be {@code null}. 097 */ 098 protected ThymeleafDispatcher(Builder builder) { 099 basePath = builder.basePath; 100 cacheTemplates = builder.cacheTemplates; 101 templateMode = builder.templateMode; 102 } 103 104 /** 105 * Returns the base path under which template resources are resolved. 106 * 107 * @return The base path. Never {@code null}. 108 */ 109 public String getBasePath() { 110 return basePath; 111 } 112 113 /** 114 * Returns whether the bridge's default engine caches resolved templates. 115 * 116 * @return The cache flag. Defaults to {@link #DEFAULT_CACHE_TEMPLATES}. 117 */ 118 public boolean isCacheTemplates() { 119 return cacheTemplates; 120 } 121 122 /** 123 * Returns the template mode used by the bridge's default engine. 124 * 125 * @return The template mode. Defaults to {@link #DEFAULT_TEMPLATE_MODE}. 126 */ 127 public TemplateMode getTemplateMode() { 128 return templateMode; 129 } 130 131 /** 132 * Resolves the active {@link TemplateEngine}. 133 * 134 * <p> 135 * Lookup order: 136 * <ol class='spaced-list'> 137 * <li>{@code req.getContext().getBeanStore().getBean(TemplateEngine.class)} — covers 138 * Spring Boot autoconfig (`SpringTemplateEngine` is-a `TemplateEngine`) and any 139 * user-supplied bean. 140 * <li>Lazy bridge default — constructed on first call when no engine bean is 141 * registered. Carries a single {@link ClassLoaderTemplateResolver} keyed off 142 * ({@link #getBasePath() basePath}, {@code .html}, {@link #getTemplateMode() templateMode}, 143 * {@link #isCacheTemplates() cacheTemplates}). 144 * </ol> 145 * 146 * @param req The current REST request. 147 * @return The active template engine. Never {@code null}. 148 */ 149 public TemplateEngine resolveTemplateEngine(RestRequest req) { 150 var bean = req.getContext().getBeanStore().getBean(TemplateEngine.class); 151 if (bean.isPresent()) 152 return bean.get(); 153 var local = defaultEngine; 154 if (local == null) { 155 synchronized (this) { 156 local = defaultEngine; 157 if (local == null) { 158 local = buildDefaultEngine(); 159 defaultEngine = local; 160 } 161 } 162 } 163 return local; 164 } 165 166 /** 167 * Constructs the bridge-default {@link TemplateEngine}. 168 * 169 * <p> 170 * Single {@link ClassLoaderTemplateResolver} with {@code prefix=basePath}, 171 * {@code suffix=".html"}, {@code templateMode=templateMode}, and 172 * {@code cacheable=cacheTemplates}. Subclasses may override to plug in custom resolvers / 173 * dialects without registering a separate {@code @Bean TemplateEngine}. 174 * 175 * @return A new {@link TemplateEngine} instance. 176 */ 177 protected TemplateEngine buildDefaultEngine() { 178 var resolver = new ClassLoaderTemplateResolver(); 179 resolver.setPrefix(basePath); 180 resolver.setSuffix(".html"); 181 resolver.setTemplateMode(templateMode); 182 resolver.setCacheable(cacheTemplates); 183 resolver.setCharacterEncoding("UTF-8"); 184 var engine = new TemplateEngine(); 185 engine.setTemplateResolver(resolver); 186 return engine; 187 } 188 189 /** 190 * Renders a raw template through the Thymeleaf engine onto the response. 191 * 192 * @param path The trailing path segment after the mount prefix (the template name relative to 193 * the configured {@link #getBasePath() base path}; trailing {@code .html} stripped). 194 * @param req The current REST request. 195 * @param res The current REST response. 196 * @throws IOException If the underlying response writer fails. 197 * @throws BasicHttpException On boundary violation (403), missing engine (500), or render 198 * failure (500). 199 */ 200 @Override /* RawTemplateDispatcher */ 201 public void render(String path, RestRequest req, RestResponse res) 202 throws IOException, BasicHttpException { 203 204 // The engine resolver re-adds the .html suffix; strip if present so callers can request 205 // /thymeleaf/hello, /thymeleaf/hello.html, or /thymeleaf/admin/dashboard.html uniformly. 206 var template = (path == null) ? "" : path; 207 if (template.endsWith(".html")) 208 template = template.substring(0, template.length() - ".html".length()); 209 210 // resolveVirtualPathSafely validates that the resolved virtual path stays inside the 211 // configured basePath. The traversal check operates on basePath + template so a template 212 // name like "../../etc/passwd" or "a/b/../../../secret" is rejected before reaching the 213 // engine. We re-derive the engine-relative template name from the safe result by 214 // stripping the (already-normalized) basePath prefix. 215 if (! ViewTemplateNames.isPlainName(template)) 216 throw new NotFound("Template not found."); 217 String safeTemplate; 218 try { 219 var resolved = FileUtils.resolveVirtualPathSafely(basePath, template); 220 safeTemplate = stripBasePath(basePath, resolved); 221 } catch (IllegalArgumentException ex) { 222 throw new Forbidden("Path escapes configured base path."); 223 } 224 225 try { 226 var engine = resolveTemplateEngine(req); 227 var ctx = new org.thymeleaf.context.Context(req.getLocale()); 228 if (! res.containsHeader("Content-Type")) 229 res.setHeader("Content-Type", ThymeleafViewRenderer.DEFAULT_CONTENT_TYPE); 230 engine.process(safeTemplate, ctx, res.getWriter()); 231 } catch (LinkageError ex) { 232 throw new InternalServerError(ex, ThymeleafViewRenderer.NO_ENGINE_DIAGNOSTIC); 233 } catch (IOException | BasicHttpException ex) { 234 throw ex; 235 } catch (Exception ex) { 236 throw new InternalServerError(ex, "Thymeleaf render failed for '%s'", safeTemplate); 237 } 238 } 239 240 /** 241 * Strips the normalized {@code basePath} prefix from a {@code resolveVirtualPathSafely} 242 * result so the leftover string is engine-relative (the resolver re-adds the configured 243 * prefix + suffix). 244 * 245 * <p> 246 * Normalization mirrors {@code FileUtils.resolveVirtualPathSafely}: a {@code null} / empty 247 * base normalizes to {@code "/"}; otherwise the base is guaranteed to start with {@code "/"} 248 * and end with {@code "/"} once the helper has normalized it. 249 * 250 * @param base The configured base path (typically {@code "/templates/"}). 251 * @param resolved The output of {@code resolveVirtualPathSafely} (always starts with the 252 * normalized base). 253 * @return The engine-relative template name (e.g. {@code "hello"} for base 254 * {@code "/templates/"} and resolved {@code "/templates/hello"}). 255 */ 256 static String stripBasePath(String base, String resolved) { 257 var bp = isEmpty(base) ? "/" : base; 258 if (! bp.endsWith("/")) 259 bp = bp + "/"; 260 if (! bp.startsWith("/")) 261 bp = "/" + bp; 262 if (resolved.startsWith(bp)) 263 return resolved.substring(bp.length()); 264 throw iaex("Resolved path '%s' does not start with base '%s'", resolved, bp); 265 } 266 267 /** 268 * Builder for {@link ThymeleafDispatcher}. 269 */ 270 public static class Builder { 271 272 String basePath = DEFAULT_BASE_PATH; 273 boolean cacheTemplates = DEFAULT_CACHE_TEMPLATES; 274 TemplateMode templateMode = DEFAULT_TEMPLATE_MODE; 275 276 /** Constructor — package access for {@link ThymeleafDispatcher#create()}. */ 277 protected Builder() {} 278 279 /** 280 * Sets the classpath base path under which template resources are resolved. 281 * 282 * @param value The base path. {@code null} or blank values reset to the default 283 * {@link ThymeleafDispatcher#DEFAULT_BASE_PATH}. 284 * @return This object. 285 */ 286 public Builder basePath(String value) { 287 basePath = isBlank(value) ? DEFAULT_BASE_PATH : value; 288 return this; 289 } 290 291 /** 292 * Sets whether the bridge's default engine caches resolved templates. 293 * 294 * @param value The new value. 295 * @return This object. 296 */ 297 public Builder cacheTemplates(boolean value) { 298 cacheTemplates = value; 299 return this; 300 } 301 302 /** 303 * Sets the template mode used by the bridge's default engine. 304 * 305 * @param value The new value. {@code null} resets to {@link #DEFAULT_TEMPLATE_MODE}. 306 * @return This object. 307 */ 308 public Builder templateMode(TemplateMode value) { 309 templateMode = (value == null) ? DEFAULT_TEMPLATE_MODE : value; 310 return this; 311 } 312 313 /** 314 * Reads the current base path setting (test/inspection helper). 315 * 316 * @return The base path. Never {@code null}. 317 */ 318 public String getBasePath() { 319 return basePath; 320 } 321 322 /** 323 * Reads the current cache-templates setting (test/inspection helper). 324 * 325 * @return The cache flag. 326 */ 327 public boolean isCacheTemplates() { 328 return cacheTemplates; 329 } 330 331 /** 332 * Reads the current template-mode setting (test/inspection helper). 333 * 334 * @return The template mode. Never {@code null}. 335 */ 336 public TemplateMode getTemplateMode() { 337 return templateMode; 338 } 339 340 /** 341 * Builds the {@link ThymeleafDispatcher}. 342 * 343 * @return A new {@link ThymeleafDispatcher} instance. 344 */ 345 public ThymeleafDispatcher build() { 346 if (basePath == null) 347 throw iaex("basePath must not be null"); 348 return new ThymeleafDispatcher(this); 349 } 350 } 351}