1   package net.sourceforge.blogentis.storage;
2   
3   
4   
5   
6   
7   
8   
9   
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  import java.io.StringWriter;
26  
27  import net.sourceforge.blogentis.om.Blog;
28  
29  import org.apache.turbine.services.velocity.TurbineVelocity;
30  import org.apache.turbine.util.RunData;
31  import org.apache.velocity.Template;
32  import org.apache.velocity.app.Velocity;
33  import org.apache.velocity.context.Context;
34  
35  /***
36   * @author abas
37   *  
38   */
39  public class VelocityFragment {
40      protected int blogID = -1;
41  
42      protected String templateName = null;
43  
44      protected Template template = null;
45  
46      public Object getName() {
47          return templateName;
48      }
49  
50      public VelocityFragment() {}
51  
52      public void init(Blog blog, String name)
53              throws Exception {
54          if (blog != null)
55              blogID = blog.getBlogId();
56          templateName = name;
57          loadTemplate();
58      }
59  
60      protected void loadTemplate()
61              throws Exception {
62          template = Velocity.getTemplate(templateName + ".vm");
63      }
64  
65      public String build(RunData data)
66              throws Exception {
67          if (template.isSourceModified())
68              loadTemplate();
69          Context context = TurbineVelocity.getContext(data);
70          doBuildTemplate(data, context);
71          StringWriter temp = new StringWriter();
72          template.merge(context, temp);
73          return temp.toString();
74      }
75  
76      protected void doBuildTemplate(RunData data, Context context)
77              throws Exception {}
78  
79      public VelocityFragment invoke(Context context)
80              throws Exception {
81          return this;
82      }
83  
84      public VelocityFragment invoke(Context context, Object param)
85              throws Exception {
86          context.put("param",param);
87          return this;
88      }
89  
90      public VelocityFragment invoke(Context context, Object param1, Object param2)
91              throws Exception {
92          context.put("param",param1);
93          context.put("param2",param2);
94          return this;
95      }
96  
97      public VelocityFragment invoke(RunData data)
98              throws Exception {
99          return invoke(TurbineVelocity.getContext(data));
100     }
101 
102     public VelocityFragment invoke(RunData data, Object param)
103             throws Exception {
104         return invoke(TurbineVelocity.getContext(data), param);
105     }
106 
107     public VelocityFragment invoke(RunData data, Object param1, Object param2)
108             throws Exception {
109         return invoke(TurbineVelocity.getContext(data), param1, param2);
110     }
111 }