
// VTLTests.java
// Modified by Andrew Davison, ad@coe.psu.ac.th, July 2023

// Based on examples by John Peter at https://www.knowledgewalls.com/johnpeter/books/java-apache-velocity-examples/how-to-use-java-class-in-apache-velocity-template-engine-with-example

/* Various Velocity Template Language (VTL) features:
   variables, set, lists, maps, if, foreach;
   see https://velocity.apache.org/engine/2.3/user-guide.html
   and https://velocity.apache.org/engine/2.3/vtl-reference.html

  Usage:
    > compile VTLTests.java
    > run VTLTests
*/

import java.io.*;
import java.util.*;

import org.apache.velocity.app.*;
import org.apache.velocity.*;


public class VTLTests
{
  private static final String TEMPLATE_FNM = "vtl.vm";

  public static void main(String args[]) 
                            throws Exception
  {
    Velocity.init();
    System.out.println("Loading template: " + TEMPLATE_FNM);
    Template template = Velocity.getTemplate(TEMPLATE_FNM);
     
    VelocityContext vc = new VelocityContext();
     
    // build a list
    List<String> users = new ArrayList<String>();
    users.add("Bala");
    users.add("Arun");
    users.add("Chinna");
    users.add("Vijay");
    vc.put("users", users);

    // build a map
    Map<String,String> usersMap = new HashMap<String,String>();
    usersMap.put("1001", "Sarathy");
    usersMap.put("1002", "Kumar");
    usersMap.put("1003", "Raja");
    usersMap.put("1004", "Gopal");
    vc.put("usersMap", usersMap);

    // use #if
    vc.put("choice", 4);

    // use #foreach
    vc.put("maxNum", 10);

    // maths and #set
    vc.put("num1", 20);
    vc.put("num2", 40);

    // nested #foreach
    Map<String,List<String>> namesByCompany = new HashMap<>();
    List<String> names = new ArrayList<>();
    names.add("Raja");
    names.add("Roja");
    namesByCompany.put("android", names);

    names = new ArrayList<>();
    names.add("Peter");
    names.add("John");
    namesByCompany.put("microsoft", names);

    vc.put("namesByCompany", namesByCompany);

    // generate all the text using template
    StringWriter sw = new StringWriter();
    template.merge(vc, sw);
    System.out.println(sw);
  } /* main */

}  // end of VTLTests class
