package com.javahonk;

import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;

public class FreeMarkerGenrateXMLFromObject {
	
	private static Configuration cfg = null;
	
	static{		
		// Freemarker below configuration object deprecated
		//Configuration cfg = new Configuration();
		//Please use this. To make it backward compatible. Please visit here for more info: 
		//http://freemarker.org/docs/api/freemarker/template/Configuration.html
		cfg = new Configuration(new Version("2.3.0"));
	}
	
	public static void main(String[] args) {

		try {
			// Load template
			Template template = cfg.getTemplate("resources/BuildXMLTemplate.ftl");

			// Create data for template
			Map<String, Object> templateData = new HashMap<String, Object>();
			templateData.put("name", "Java Honk");
			
			List<Person> personDetails = Arrays.asList(
				       new Person( "Java Honk", "USA" ), 
				       new Person( "Java Monk", "France" ) );

			templateData.put("personDetails", personDetails);

			// Write output on console example 1
			StringWriter out = new StringWriter();
			template.process(templateData, out);
			System.out.println( out.getBuffer().toString() );
			out.flush();
			
			// Write output on console example 2
			/*Writer out = new OutputStreamWriter(System.out);
			template.process(templateData, out);
			out.flush();*/

			// Write data to the file
			Writer file = new FileWriter(new File("C:\\JavaHonk\\BuildXMLTemplateXML.xml"));
			template.process(templateData, file);
			file.flush();
			file.close();

		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}
