
// VTLCatch.java
// Jason van Zyl, Geir Magnusson Jr.
// Modified by Andrew Davison, ad@coe.psu.ac.th, July 2023

/* Most of my examples deal with exceptions by throwing
   Exception. This code uses try-catch blocks
   with the various Velocity methods. Also illustrates
   the use of Velocity initializing properties.

  Usage:
    > compile VTLCatch.java
    > run VTLCatch
*/

import java.io.*;
import java.util.*;

import org.apache.velocity.*;
import org.apache.velocity.app.*;
import org.apache.velocity.exception.*;


public class VTLCatch
{
  private static final String TEMPLATE_FNM = "template1.vm";

  public static void main(String[] args)
  {

    Properties props = new Properties();
    // props.setProperty("runtime.strict_mode.enable", "true");
       /* will trigger an error if any template variables
          aren't set, which is the case for $foo in this template
       */

    try {
      Velocity.init(props);

      VelocityContext vc = new VelocityContext();
      ArrayList<String> names = new ArrayList<>();
      names.add("Jim");
      names.add("Jane");
      names.add("Joan");
      names.add("John");
      vc.put("names", names);

      Template template =  null;
      try {
        System.out.println("Loading template: " + TEMPLATE_FNM);
        template = Velocity.getTemplate(TEMPLATE_FNM);
      }
      catch (ResourceNotFoundException rnfe) {
        System.out.println("Cannot find template");
      }
      catch (ParseErrorException pe) {
        System.out.println("Parsing error:" + pe.getMessage());
      }

      // generate text using template
      StringWriter sw = new StringWriter();
      template.merge(vc, sw);
      System.out.println(sw);
    }
    catch(Exception e) 
    {  System.out.println("Error: " + e.getMessage());  }
  } /* main */

}  // end of VTLCatch class
