1   
2   
3   
4   
5   
6   
7   
8   
9   
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  package net.sf.jameleon.util;
20  
21  import org.apache.velocity.Template;
22  import org.apache.velocity.VelocityContext;
23  import org.apache.velocity.io.VelocityWriter;
24  import org.apache.velocity.app.Velocity;
25  
26  import java.io.*;
27  import java.util.Iterator;
28  import java.util.Map;
29  
30  public class TemplateProcessor {
31  
32      protected Template template;
33      protected String templateName;
34  
35      public TemplateProcessor(String templateName){
36          Velocity.setProperty("resource.loader", "classpath");
37          Velocity.setProperty("classpath.resource.loader.class", "net.sf.jameleon.util.VelocityClasspathResourceLoader");
38          this.templateName = templateName;
39          initVelocity();
40      }
41  
42      private void initVelocity(){
43          try{
44              Velocity.init();
45          }catch(Exception rnfe){
46              
47              System.err.println("Can not write results to file: ");
48              rnfe.printStackTrace();
49          }
50      }
51  
52      public void transform(File toFile, Map params){
53          JameleonUtility.createDirStructure(toFile.getParentFile());
54          VelocityWriter vw = null;
55          try{
56              vw = new VelocityWriter(new FileWriter(toFile));
57              transformToWriter(vw, params);
58          }catch(IOException ioe){ioe.printStackTrace();}finally{
59              if (vw != null){
60                  try {
61                      vw.close();
62                  } catch (IOException e) {e.printStackTrace();}
63              }
64          }
65      }
66  
67      public String transformToString(Map params){
68          StringWriter sw = new StringWriter();
69          transformToWriter(sw, params);
70          return sw.getBuffer().toString();
71      }
72  
73      public void transformToWriter(Writer w, Map params){
74          try{
75              VelocityContext context = new VelocityContext();
76              Iterator it = params.keySet().iterator();
77              String key;
78              while (it.hasNext()) {
79                  key = (String)it.next();
80                  context.put(key, params.get(key));
81              }
82              template = Velocity.getTemplate(templateName);
83              template.merge( context, w );
84          }catch(Exception e){
85              System.err.println("ERROR: Loading Velocity Template: " + templateName);            
86              e.printStackTrace();
87          }
88      }
89  
90  }