App.java

/*
 Copyright (C) 2025 Steve Flasby

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package org.flasby.thymeleaf;

import java.io.IOException;
import java.time.LocalDateTime;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

/** 
 * runs the demo app.
 */
public class App {

  TemplateEngine templateEngine;

  /**
   * prints the result of handling index.html to the console.
   *
   * @param args the usual commandline arguments, which are ignored in this case.
   */
  public static void main(String[] args) throws IOException {
    App app = new App();
    Context ctx = new Context();
    ctx.setVariable("name", "foo");
    ctx.setVariable("date", LocalDateTime.now().toString());
    ctx.setVariable("goat", "It's a goat");
    if ( args.length > 0 ) {
      new WebServer(app, ctx, Integer.parseInt(args[0])) {
      }.start();
    } else {
      System.err.println("====================================================");
      System.err.println(app.process("index.html", ctx));
      System.err.println("====================================================");
    }
  }

  /**
   * creates a configured App complete with a default TemplateEngine.
   */
  public App() {
    buildDefaultTemplateEngine();
  }

  /**
   * builds the page content returning it as a String ready to be sent to a browser.
   * 
   * @param page the page to be rendered.
   * @param ctx a Thymeleaf Context object used for the rendering process.
   * @return String with the page content.
   */
  public String process(String page, Context ctx) {
    return templateEngine.process(page, ctx);
  }

  /**
   * builds a default TemplateEngine with the usual setup of template locations and file types.
   * Importantly, this can't serve raw binary files as it will try to encode it using UTF-8.
   * Icons don't like this...
   */
  protected void buildDefaultTemplateEngine() {
    templateEngine = new TemplateEngine();
    ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
    resolver.setPrefix("/templates/");
    // resolver.setSuffix(".html");
    resolver.setCharacterEncoding("UTF-8");
    resolver.setTemplateMode(TemplateMode.HTML); // HTML5 option was deprecated in 3.0.0
    templateEngine.addTemplateResolver(resolver);
  }
}