1b45367ad2baaa9ba7b2935506586f8c64d52d8e
[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     /** @todo
49       quickhack: action-root is only for Mir!!!!, idfx
50       actionRoot = docRoot + "/servlet/" + MirConfig.getProp("ServletName");*/
51     actionRoot = docRoot + "/servlet/Mir";
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
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("KEIN OUTPUTSTREAM");
184       Template tmpl = getTemplateFor(templateFilename);
185       if (tmpl == null) throw new HTMLParseException("KEIN TEMPLATE: " + templateFilename);
186       if (tmr==null) tmr = new SimpleHash();
187
188       String session=null;
189       if (res!=null) {
190         session=res.encodeURL("");
191       }
192
193       // put standard configuration into tempalteRootmodel
194       SimpleHash configHash = new SimpleHash();
195       configHash.put("docroot", new SimpleScalar(producerDocRoot));
196       configHash.put("storageroot", new SimpleScalar(producerStorageRoot));
197       configHash.put("productionhost", new SimpleScalar(productionHost));
198       configHash.put("openaction", new SimpleScalar(openAction));
199       configHash.put("actionRootLogin",new SimpleScalar(actionRoot));
200
201
202       tmr.put("docRoot", new SimpleScalar(docRoot));
203       tmr.put("now", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
204       tmr.put("actionRoot", new SimpleScalar(actionRoot+session));
205       tmr.put("openAction", new SimpleScalar(openAction));
206       tmr.put("productionHost", new SimpleScalar(productionHost));
207       tmr.put("videoHost", new SimpleScalar(videoHost));
208       tmr.put("audioHost", new SimpleScalar(audioHost));
209       tmr.put("imageHost", new SimpleScalar(imageHost));
210
211       tmr.put("config", configHash);
212       tmpl.process(tmr, out);
213
214     }
215
216
217   /**
218    *   Wandelt eine Entity-Liste in eine SimpleList von SimpleHashes um.
219    *   @param aList ist eine Liste von Entity
220    *   @return eine freemarker.template.SimpleList von SimpleHashes.
221    */
222   public static SimpleList makeSimpleList(EntityList aList) throws StorageObjectException
223   {
224     SimpleList      simpleList = new SimpleList();
225     if (aList != null) {
226       for(int i=0;i<aList.size();i++){
227         simpleList.add(makeSimpleHash(aList.elementAt(i)));
228       }
229     }
230     return simpleList;
231   }
232
233   /**
234    *  Konvertiert ein EntityList in ein freemarker.template.SimpleHash-Modell. Im Hash
235    *  sind die einzelnen Entities ueber ihre id zu erreichen.
236    *  @param aList ist die EntityList
237    *  @return SimpleHash mit den entsprechenden freemarker Daten
238    *
239    */
240   public static SimpleHash makeSimpleHash(EntityList aList) throws StorageObjectException
241   {
242     SimpleHash      simpleHash = new SimpleHash();
243     Entity          currentEntity;
244
245     if (aList != null) {
246       for (int i=0;i<aList.size();i++) {
247          currentEntity = (Entity)aList.elementAt(i);
248          simpleHash.put(currentEntity.getId(), makeSimpleHash(currentEntity));
249       }
250     }
251     return simpleHash;
252   }
253
254   /**
255    *  Konvertiert ein Entity in ein freemarker.template.SimpleHash-Modell
256    *  @param entity ist die Entity
257    *  @return SimpleHash mit den entsprechenden freemarker Daten
258    *
259    */
260     public static SimpleHash makeSimpleHash(Entity entity) {
261       if (entity != null) {
262         return makeSimpleHash(entity.getValues());
263       }
264       else {
265         //theLog.printWarning("Entity ist <null>");
266         return null;
267       }
268     }
269
270   /**
271    *  Konvertiert ein Hashtable mit den keys und values als String
272    *  in ein freemarker.template.SimpleHash-Modell
273    *  @param mergeData der HashMap mit den String / String Daten
274    *  @return SimpleHash mit den entsprechenden freemarker Daten
275    *
276    */
277   public static SimpleHash makeSimpleHash(HashMap mergeData)
278   {
279     SimpleHash modelRoot = new SimpleHash();
280     String aField;
281     if (mergeData != null) {
282       Set set = mergeData.keySet();
283       Iterator it =  set.iterator();
284       for (int i=0; i<set.size();i++)  {
285         aField = (String)it.next();
286         modelRoot.put(aField, (String)mergeData.get(aField));
287       }
288     }
289     return modelRoot;
290   }
291
292
293   /**
294    * Wandelt EntityListe in SimpleHash um, und versieht die Liste mit StandardInfos,
295    * die aus EntityList kommen.
296    *
297    * @param entList
298    * @return SimpleHash mit Entity-Daten und ZusatzInfos.
299    * @exception StorageObjectException
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
311           if(entList.getOrder()!=null) {
312             modelRoot.put("order", new SimpleScalar(entList.getOrder()));
313             modelRoot.put("order_encoded", new SimpleScalar(URLEncoder.encode(entList.getOrder())));
314           }
315           modelRoot.put("from", new SimpleScalar((new Integer(entList.getFrom())).toString()));
316           modelRoot.put("to", new SimpleScalar((new Integer(entList.getTo())).toString()));
317
318           if (entList.hasNextBatch())
319             modelRoot.put("next", new SimpleScalar((new Integer(entList.getNextBatch())).toString()));
320           if (entList.hasPrevBatch())
321             modelRoot.put("prev", new SimpleScalar((new Integer(entList.getPrevBatch())).toString()));
322       }
323       return modelRoot;
324     }
325
326   /**
327    * Private methods to get template from a templateFilename
328    * @param templateFilename
329    * @return Template
330    * @exception HTMLParseException
331    */
332   private static Template getTemplateFor(String templateFilename) throws HTMLParseException
333   {
334     if (templateFilename!=null) return templateCache.getTemplate(templateFilename);
335     else {
336       theLog.printError("CACHE (ERR): Unknown template: " + templateFilename);
337       throw new HTMLParseException("Templatefile: "+ templateFilename + " not found.");
338     }
339   }
340
341   public static void stopAutoUpdate(){
342     templateCache.stopAutoUpdate();
343     templateCache=null;
344   }
345
346 }