
// ObjMacro.java
// Modified by Andrew Davison, ad@coe.psu.ac.th, July 2023

// https://www.knowledgewalls.com/johnpeter/books/java-apache-velocity-examples/how-to-use-java-class-in-apache-velocity-template-engine-with-example

/* Utilizes a simple macro in the prods.vm template.
   For more complex macros, see xml.vm and jsonTool.vm.

   The data is also more complex -- a list of Product objects,
   which requires the use of "." and method calls in the template.

   Usage:
    > compile ObjMacro.java
    > run ObjMacro
*/

import java.io.*;
import java.util.*;

import org.apache.velocity.app.*;
import org.apache.velocity.*;


public class ObjMacro
{
  private static final String TEMPLATE_FNM = "prods.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();

    List<Product> prods =  Arrays.asList(
        new Product("Dell Laptop", 31000.00),
        new Product("Samsung Mobile", 16000.00),
        new Product("Samsung Tablet", 15000.00),
        new Product("Sony Camera", 23000.00));
    vc.put("prods", prods);

    StringWriter sw = new StringWriter();
    template.merge(vc, sw);
    System.out.println(sw);
  } /* main */


}  // end of ObjMacro class
