d9ed5bb22d45975cb0d33b95ec55c753e1bb233c
[mir.git] / source / mir / misc / HTMLTemplateProcessor.java
1 /*
2  * put your module comment here
3  */
4
5
6 package mir.misc;
7
8 import  java.lang.*;
9 import  java.util.*;
10 import  java.io.*;
11 import  java.net.*;
12 import  freemarker.template.*;
13 import  mir.entity.*;
14 import  mir.storage.*;
15 import javax.servlet.http.*;
16
17
18 /**
19  * Hilfsklasse zum Mergen von Template und Daten
20  */
21 public final class HTMLTemplateProcessor {
22
23   public static String                templateDir;
24   private static FileTemplateCache    templateCache;
25   private static Logfile              theLog;
26   private static String               docRoot;
27   private static String               actionRoot;
28   private static String               productionHost;
29   private static String               audioHost;
30   private static String               videoHost;
31   private static String               imageHost;
32   private static String               openAction;
33   protected static String producerDocRoot = MirConfig.getProp("Producer.DocRoot");
34   protected static String producerStorageRoot = MirConfig.getProp("Producer.StorageRoot");
35
36
37   //
38   // init
39
40   static {
41
42     templateDir = MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");
43     templateCache = new FileTemplateCache(templateDir);
44     templateCache.setLoadingPolicy(templateCache.LOAD_ON_DEMAND);
45     templateCache.startAutoUpdate();
46     theLog = Logfile.getInstance(MirConfig.getPropWithHome("HTMLTemplateProcessor.Logfile"));
47     docRoot = MirConfig.getProp("RootUri");
48     //small quickhack, idfx
49     //actionRoot = docRoot + "/servlet/" + MirConfig.getProp("ServletName");
50     actionRoot = docRoot + "/servlet/Mir";
51
52     openAction = MirConfig.getProp("Producer.OpenAction");
53     productionHost = MirConfig.getProp("Producer.ProductionHost");
54     videoHost = MirConfig.getProp("Producer.VideoHost");
55     audioHost = MirConfig.getProp("Producer.AudioHost");
56     imageHost = MirConfig.getProp("Producer.Image.Host");
57     producerDocRoot = MirConfig.getProp("Producer.DocRoot");
58     producerStorageRoot = MirConfig.getProp("Producer.StorageRoot");
59
60   }
61
62   /**
63    * empty private constructor, to avoid instantiation
64    */
65   private HTMLTemplateProcessor () { }
66
67
68   // process-methods to merge different datastructures
69   // with freemarker templates
70
71
72   /**
73    * Wandelt <code>anEntity</code> in freemarker-Struktur um, mischt die Daten mit
74    * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
75    * <code>out</code>
76    *
77    * @param templateFilename
78    * @param anEntity
79    * @param out
80    * @exception HTMLParseException
81    */
82
83     public static void process(String templateFilename, Entity anEntity, PrintWriter out)
84       throws HTMLParseException {
85         if (anEntity == null)  throw new HTMLParseException("entity is empty!");
86         else process(templateFilename, anEntity, out);
87     }
88
89
90   /**
91    * Wandelt Liste mit Entities <code>entList</code> in freemarker-Struktur um, mischt die Daten mit
92    * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
93    * <code>out</code>
94    *
95    * @param templateFilename
96    * @param entList
97    * @param out
98    * @exception HTMLParseException
99    */
100   public static void process(HttpServletResponse res,String templateFilename, EntityList entList, PrintWriter out)
101       throws HTMLParseException {
102     process(res, templateFilename,  entList,  (String)null, (TemplateModelRoot)null,  out);
103   }
104
105   /**
106    * Wandelt Entitylist in freemarker-Struktur um, fügt <code>additionalModel</code>
107    * unter dem Namen <code>additionalModelName</code> ein und mischt die Daten mit
108    * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
109    * <code>out</code>
110    *
111    * @param templateFilename
112    * @param entList
113    * @param additionalModelName
114    * @param additionalModel
115    * @param out
116    * @exception HTMLParseException
117    */
118     public static void process(HttpServletResponse res,String templateFilename, EntityList entList, String additionalModelName,
119              TemplateModelRoot additionalModel, PrintWriter out)
120       throws HTMLParseException {
121
122       SimpleHash modelRoot = new SimpleHash();
123
124       if (entList == null) {
125          process(null,templateFilename, modelRoot, out);
126       } else {
127         try {
128           modelRoot = makeSimpleHashWithEntitylistInfos(entList);
129
130           // Quickhack um mal ein Popup mit reinzunhemen ..
131           if (additionalModelName != null && additionalModel != null)
132               modelRoot.put(additionalModelName, additionalModel);
133
134           process(res,templateFilename, modelRoot, out);
135         } catch (StorageObjectException e) {
136           throw new HTMLParseException(e.toString());
137         }
138       }
139     }
140
141   /**
142    * Wandelt HashMap <code>mergeData</code> in freemarker-Struktur und mischt diese mit
143    * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
144    * <code>out</code>
145    *
146    * @param templateFilename
147    * @param mergeData - a HashMap with mergeData to be converted in SimpleHash
148    * @param out
149    * @exception HTMLParseException
150    */
151     public static void process(HttpServletResponse res,String templateFilename, HashMap mergeData, PrintWriter out)
152       throws HTMLParseException {
153       process(res,templateFilename, makeSimpleHash(mergeData), out);
154     }
155
156   /**
157    * Gibt Template <code>templateFilename</code> an den PrintWriter
158    * <code>out</code>
159    *
160    * @param templateFilename
161    * @param mergeData
162    * @param out
163    * @exception HTMLParseException
164    */
165     public static void process(String templateFilename, PrintWriter out)
166       throws HTMLParseException {
167       process(null,templateFilename, (TemplateModelRoot)null, out);
168     }
169
170
171   /**
172    * Mischt die freemarker-Struktur <code>tmr</code> mit
173    * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
174    * <code>out</code>
175    *
176    * @param templateFilename
177    * @param mergeData
178    * @param out
179    * @exception HTMLParseException
180    */
181     public static void process(HttpServletResponse res,String templateFilename, TemplateModelRoot tmr, PrintWriter out)
182       throws HTMLParseException {
183       if (out==null) throw new HTMLParseException("no outputstream");
184       Template tmpl = getTemplateFor(templateFilename);
185       if (tmpl == null) throw new HTMLParseException("no template: " + templateFilename);
186       if (tmr==null) tmr = new SimpleHash();
187
188       /** @todo  what is this for? (rk) */
189       String session="";
190       if (res!=null) {
191         session=res.encodeURL("");
192       }
193
194       // put standard configuration into tempalteRootmodel
195       SimpleHash configHash = new SimpleHash();
196       configHash.put("docroot", new SimpleScalar(producerDocRoot));
197       configHash.put("storageroot", new SimpleScalar(producerStorageRoot));
198       configHash.put("productionhost", new SimpleScalar(productionHost));
199       configHash.put("openaction", new SimpleScalar(openAction));
200       configHash.put("actionRootLogin",new SimpleScalar(actionRoot));
201
202
203       tmr.put("docRoot", new SimpleScalar(docRoot));
204       tmr.put("now", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
205       tmr.put("actionRoot", new SimpleScalar(actionRoot+session));
206       tmr.put("openAction", new SimpleScalar(openAction));
207       tmr.put("productionHost", new SimpleScalar(productionHost));
208       tmr.put("videoHost", new SimpleScalar(videoHost));
209       tmr.put("audioHost", new SimpleScalar(audioHost));
210       tmr.put("imageHost", new SimpleScalar(imageHost));
211
212       tmr.put("config", configHash);
213       tmpl.process(tmr, out);
214
215     }
216
217
218   /**
219    *   Converts Entity-List to SimpleList of SimpleHashes.
220    *   @param aList ist eine Liste von Entity
221    *   @return eine freemarker.template.SimpleList von SimpleHashes.
222    */
223   public static SimpleList makeSimpleList(EntityList aList) throws StorageObjectException
224   {
225     SimpleList  simpleList = new SimpleList();
226     if (aList != null) {
227       for(int i=0;i<aList.size();i++) {
228         simpleList.add(makeSimpleHash(aList.elementAt(i)));
229       }
230     }
231     return simpleList;
232   }
233
234   /**
235    *  Konvertiert ein EntityList in ein freemarker.template.SimpleHash-Modell. Im Hash
236    *  sind die einzelnen Entities ueber ihre id zu erreichen.
237    *  @param aList ist die EntityList
238    *  @return SimpleHash mit den entsprechenden freemarker Daten
239    *
240    */
241   public static SimpleHash makeSimpleHash(EntityList aList) throws StorageObjectException
242   {
243     SimpleHash      simpleHash = new SimpleHash();
244     Entity          currentEntity;
245
246     if (aList != null) {
247       for (int i=0;i<aList.size();i++) {
248          currentEntity = (Entity)aList.elementAt(i);
249          simpleHash.put(currentEntity.getId(), makeSimpleHash(currentEntity));
250       }
251     }
252     return simpleHash;
253   }
254
255   /**
256    *  Konvertiert ein Entity in ein freemarker.template.SimpleHash-Modell
257    *  @param entity ist die Entity
258    *  @return SimpleHash mit den entsprechenden freemarker Daten
259    *
260    */
261   public static SimpleHash makeSimpleHash(Entity entity) {
262     if (entity != null)
263       return makeSimpleHash(entity.getValues());
264     else
265       return null;
266   }
267
268   /**
269    *  Konvertiert ein Hashtable mit den keys und values als String
270    *  in ein freemarker.template.SimpleHash-Modell
271    *  @param mergeData der HashMap mit den String / String Daten
272    *  @return SimpleHash mit den entsprechenden freemarker Daten
273    *
274    */
275   public static SimpleHash makeSimpleHash(HashMap mergeData)
276   {
277     SimpleHash modelRoot = new SimpleHash();
278     String aField;
279     if (mergeData != null) {
280       Set set = mergeData.keySet();
281       Iterator it =  set.iterator();
282       for (int i=0; i<set.size();i++)  {
283         aField = (String)it.next();
284         modelRoot.put(aField, (String)mergeData.get(aField));
285       }
286     }
287     return modelRoot;
288   }
289
290
291   /**
292    * Converts EntityList in SimpleHash and adds additional information
293    * to the returned SimpleHash
294    *
295    * @param entList
296    * @return SimpleHash returns SimpleHash with the converted EntityList plus
297    *        additional Data about the list.
298    * @exception StorageObjectException
299    */
300
301   public static SimpleHash makeSimpleHashWithEntitylistInfos(EntityList entList) throws StorageObjectException {
302     SimpleHash modelRoot = new SimpleHash();
303     if (entList!=null) {
304       modelRoot.put("contentlist", makeSimpleList(entList));
305       modelRoot.put("count", new SimpleScalar((new Integer(entList.getCount())).toString()));
306       if (entList.getWhere()!=null) {
307         modelRoot.put("where", new SimpleScalar(entList.getWhere()));
308         modelRoot.put("where_encoded", new SimpleScalar(URLEncoder.encode(entList.getWhere())));
309       }
310       if(entList.getOrder()!=null) {
311         modelRoot.put("order", new SimpleScalar(entList.getOrder()));
312         modelRoot.put("order_encoded", new SimpleScalar(URLEncoder.encode(entList.getOrder())));
313       }
314       modelRoot.put("from", new SimpleScalar((new Integer(entList.getFrom())).toString()));
315       modelRoot.put("to", new SimpleScalar((new Integer(entList.getTo())).toString()));
316
317       if (entList.hasNextBatch())
318         modelRoot.put("next", new SimpleScalar((new Integer(entList.getNextBatch())).toString()));
319       if (entList.hasPrevBatch())
320         modelRoot.put("prev", new SimpleScalar((new Integer(entList.getPrevBatch())).toString()));
321     }
322     return modelRoot;
323   }
324
325   /**
326    * Private methods to get template from a templateFilename
327    * @param templateFilename
328    * @return Template
329    * @exception HTMLParseException
330    */
331   private static Template getTemplateFor(String templateFilename) throws HTMLParseException
332   {
333     if (templateFilename!=null) return templateCache.getTemplate(templateFilename);
334     else {
335       theLog.printError("CACHE (ERR): Unknown template: " + templateFilename);
336       throw new HTMLParseException("Templatefile: "+ templateFilename + " not found.");
337     }
338   }
339
340   public static void stopAutoUpdate(){
341     templateCache.stopAutoUpdate();
342     templateCache=null;
343   }
344
345 }