All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.googlecode.gendevcode.common.VelocityFactory Maven / Gradle / Ivy

There is a newer version: 1.0.1
Show newest version
package com.googlecode.gendevcode.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

/**
 * 模板工厂类
 * @author devilishking
 */
public class VelocityFactory {	
	/**
	 * 模版文件编码类型
	 */
	private static final String ENCODING = "UTF-8";
	
	/**
	 * 写入文件
	 * @param dataMap     替换集合<标签名, 值>
	 * @param vmFileUrl   模板路径
	 * @param genFileUrl  生成页面路径
	 * @throws Exception
	 */
	public static void writeFile(Map dataMap, String vmFileUrl, String genFileUrl, String serverAbsolutePath) throws Exception{
		Properties p = new Properties();   
        p.setProperty(Velocity.INPUT_ENCODING, ENCODING);   
        p.setProperty(Velocity.OUTPUT_ENCODING, ENCODING);
        p.setProperty(Velocity.RUNTIME_LOG, (new StringBuffer()).append(serverAbsolutePath)
        													    .append("/velocity.log").toString());
        p.setProperty(Velocity.RESOURCE_LOADER, "class"); 
        p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); 
		        
        Velocity.init(p);        
        VelocityContext context = new VelocityContext();
        Iterator> it = dataMap.entrySet().iterator();
        while(it.hasNext()){
        	Entry entry = it.next();
        	context.put(entry.getKey(), entry.getValue());
        }
        
        StringWriter writer = new StringWriter();
        
        Velocity.mergeTemplate((new StringBuffer()).append("/vm/")
        										   .append(vmFileUrl)
        										   .toString(), 
        					   ENCODING, 
        					   context, 
        					   writer); 
        File file = new File(genFileUrl);
        
        if (!file.exists()){
        	file.createNewFile();
        }
        
        Writer ow = new OutputStreamWriter(new FileOutputStream(genFileUrl),ENCODING);
        ow.write(writer.toString());
        ow.close();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy