View Javadoc
1   package org.argeo.support.freemarker;
2   
3   import java.io.File;
4   import java.io.FileWriter;
5   import java.io.IOException;
6   import java.io.Writer;
7   import java.util.HashMap;
8   import java.util.Map;
9   
10  import freemarker.template.Configuration;
11  import freemarker.template.Template;
12  import freemarker.template.TemplateExceptionHandler;
13  
14  public class TestFreeMarker {
15  	static String base = System.getProperty("user.home") + File.separator + "dev" + File.separator + "work"
16  			+ File.separator + "ftl";
17  	static Configuration cfg;
18  	static {
19  		try {
20  			cfg = new Configuration(Configuration.VERSION_2_3_28);
21  			cfg.setDirectoryForTemplateLoading(new File(base));
22  			cfg.setDefaultEncoding("UTF-8");
23  			cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
24  			cfg.setLogTemplateExceptions(false);
25  			cfg.setWrapUncheckedExceptions(true);
26  		} catch (IOException e) {
27  			// TODO Auto-generated catch block
28  			e.printStackTrace();
29  		}
30  	}
31  
32  	public static void main(String[] args) {
33  		if (args.length == 0) {
34  			System.err.println("Usage: <template name> (in " + base + ")");
35  		}
36  		String template = args[0];
37  		try {
38  			/* Create a data-model */
39  			Map<String, Object> root = new HashMap<>();
40  			root.put("user", "Big Joe");
41  			Product latest = new Product();
42  			latest.setUrl("products/greenmouse.html");
43  			latest.setName("green mouse");
44  			root.put("latestProduct", latest);
45  
46  			root.put("message", "It's a test");
47  
48  			Map<String, Animal> animals = new HashMap<>();
49  			animals.put("mouse", new Animal("small", 50));
50  			animals.put("elephant", new Animal("big", 2000));
51  			animals.put("dog", new Animal("medium", 150));
52  			root.put("animals", animals);
53  
54  			/* Get the template (uses cache internally) */
55  			Template temp = cfg.getTemplate(template);
56  
57  			/* Merge data-model with template */
58  			String target = base + File.separator + template + ".html";
59  			Writer out = new FileWriter(target);
60  			temp.process(root, out);
61  			out.flush();
62  			System.out.println("Wrote " + target);
63  		} catch (Exception e) {
64  			e.printStackTrace();
65  		}
66  	}
67  
68  }