Velocity & Google guice(3)

先日のVelocityTemplateModule を利用

Injector injector = Guice.createInjector(
    new VelocityTemplateModule("sample.vm")
);
================
@Inject private Template temp;
// インジェクトされたら、VelocityContext 実行する以下のようなラッパを使う。

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

public final class VelocityHelper{

   private VelocityHelper(){}
   
   public static String mergeString(Template template,Map<String,Object> map) throws Exception{
      VelocityContext context = new VelocityContext();
      for(Iterator<String> it=map.keySet().iterator();it.hasNext();){
         String key = it.next();
         context.put(key,map.get(key));
      }
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      Writer writer = null;
      writer =new OutputStreamWriter(baos);
      template.merge(context,writer);
      baos.close();
      writer.close();
      return baos.toString();
   }
   
   public static void mergeWrite(Writer writer,Template template,Map<String,Object> map)
   throws Exception{

      VelocityContext context = new VelocityContext();
      for(Iterator<String> it=map.keySet().iterator();it.hasNext();){
         String key = it.next();
         context.put(key,map.get(key));
      }
      template.merge(context,writer);
      writer.flush();
   }
   
   public static void mergeFile(String filepath,Template template,Map<String,Object> map)
   throws Exception{

      FileWriter fw = new FileWriter(new File(filepath));
      mergeWrite(fw,template,map);
      fw.close();
   }
   
   public static void mergeFile(String filepath,Template template,Map<String,Object> map,String encoding)
   throws Exception{

      OutputStreamWriter ow = new OutputStreamWriter(
               new FileOutputStream(new File(filepath)),encoding);
      mergeWrite(ow,template,map);
      ow.close();

   }
}