language bundles are now in a directory bundles/ in WEB-INF classes in order to keep...
[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 import org.apache.struts.util.MessageResources;
17
18
19 /**
20  * Hilfsklasse zum Mergen von Template und Daten
21  */
22 public final class HTMLTemplateProcessor {
23
24   public static String                templateDir;
25   private static FileTemplateCache    templateCache;
26   private static Logfile              theLog;
27   private static String               docRoot;
28   private static String               actionRoot;
29   private static String               productionHost;
30   private static String               audioHost;
31   private static String               videoHost;
32   private static String               imageHost;
33   private static String               openAction;
34   protected static String producerDocRoot =
35                 MirConfig.getProp("Producer.DocRoot");
36   protected static String producerStorageRoot =
37                 MirConfig.getProp("Producer.StorageRoot");
38
39   //
40   // init
41
42   static {
43     /** @todo either in the above block or here :) //rk */
44     templateDir = MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");
45     templateCache = new FileTemplateCache(templateDir);
46     templateCache.setLoadingPolicy(templateCache.LOAD_ON_DEMAND);
47     // gone in freemarker 1.7.1
48     // templateCache.startAutoUpdate();
49     theLog = Logfile.getInstance(MirConfig.getPropWithHome("HTMLTemplateProcessor.Logfile"));
50     docRoot = MirConfig.getProp("RootUri");
51     //the quick hack is back in effect as it was more broken than ever before
52     // -mh
53     // sorry: nadir back in town, i have to debug the mirbase.jar in the
54     // nadir evironment. from my point of coding, this needs an urgent
55     // fixxx.
56     // yeah, from my point too - tob.
57           //actionRoot = docRoot + "/servlet/" + MirConfig.getProp("ServletName");
58     //actionRoot = docRoot + "/servlet/NadirAktuell";
59
60     actionRoot = docRoot + "/servlet/Mir";
61
62     openAction = MirConfig.getProp("Producer.OpenAction");
63     productionHost = MirConfig.getProp("Producer.ProductionHost");
64     videoHost = MirConfig.getProp("Producer.VideoHost");
65     audioHost = MirConfig.getProp("Producer.AudioHost");
66     imageHost = MirConfig.getProp("Producer.Image.Host");
67     producerDocRoot = MirConfig.getProp("Producer.DocRoot");
68     producerStorageRoot = MirConfig.getProp("Producer.StorageRoot");
69   }
70
71   /**
72    * empty private constructor, to avoid instantiation
73    */
74   private HTMLTemplateProcessor () { }
75
76
77   // process-methods to merge different datastructures
78   // with freemarker templates
79
80
81   /**
82    * Wandelt <code>anEntity</code> in freemarker-Struktur um, mischt die Daten mit
83    * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
84    * <code>out</code>
85    *
86    * @param templateFilename
87    * @param anEntity
88    * @param out
89    * @exception HTMLParseException
90    */
91
92     public static void process(String templateFilename, Entity anEntity, PrintWriter out)
93       throws HTMLParseException {
94         if (anEntity == null)  throw new HTMLParseException("entity is empty!");
95         else process(templateFilename, anEntity, out);
96     }
97
98
99   /**
100    * Wandelt Liste mit Entities <code>entList</code> in freemarker-Struktur um, mischt die Daten mit
101    * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
102    * <code>out</code>
103    *
104    * @param templateFilename
105    * @param entList
106    * @param out
107    * @exception HTMLParseException
108    */
109   public static void process(HttpServletResponse res,String templateFilename,
110                                                                                                                  EntityList entList, PrintWriter out, Locale locale)
111     throws HTMLParseException {
112     process(res, templateFilename, entList, (String)null, (TemplateModelRoot)null, out, locale);
113   }
114
115   /**
116    * Wandelt Entitylist in freemarker-Struktur um, fügt <code>additionalModel</code>
117    * unter dem Namen <code>additionalModelName</code> ein und mischt die Daten mit
118    * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
119    * <code>out</code>
120    *
121    * @param templateFilename
122    * @param entList
123    * @param additionalModelName
124    * @param additionalModel
125    * @param out
126    * @exception HTMLParseException
127    */
128     public static void process(HttpServletResponse res,String templateFilename,
129                                                                                                                          EntityList entList, String additionalModelName,
130                                TemplateModelRoot additionalModel, PrintWriter out,
131                                                                                                                          Locale locale)
132       throws HTMLParseException {
133
134       SimpleHash modelRoot = new SimpleHash();
135
136       if (entList == null) {
137          process(null,templateFilename, modelRoot, out, locale);
138       } else {
139         try {
140           modelRoot = makeSimpleHashWithEntitylistInfos(entList);
141
142           // Quickhack um mal ein Popup mit reinzunhemen ..
143           if (additionalModelName != null && additionalModel != null)
144               modelRoot.put(additionalModelName, additionalModel);
145
146           process(res,templateFilename, modelRoot, out, locale);
147         } catch (StorageObjectException e) {
148           throw new HTMLParseException(e.toString());
149         }
150       }
151     }
152
153   /**
154    * Wandelt HashMap <code>mergeData</code> in freemarker-Struktur und mischt diese mit
155    * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
156    * <code>out</code>
157    *
158    * @param templateFilename
159    * @param mergeData - a HashMap with mergeData to be converted in SimpleHash
160    * @param out
161    * @exception HTMLParseException
162    */
163     public static void process(HttpServletResponse res,String templateFilename,
164                                                                                                                          HashMap mergeData, PrintWriter out, Locale locale)
165       throws HTMLParseException {
166       process(res,templateFilename, makeSimpleHash(mergeData), out, locale);
167     }
168
169   /**
170    * Gibt Template <code>templateFilename</code> an den PrintWriter
171    * <code>out</code>
172    *
173    * @param templateFilename
174    * @param mergeData
175    * @param out
176    * @exception HTMLParseException
177    */
178     public static void process(String templateFilename, PrintWriter out,
179                                                                                                                          Locale locale)
180       throws HTMLParseException {
181       process(null,templateFilename, (TemplateModelRoot)null, out, locale);
182     }
183
184         
185         /**
186    * Mischt die freemarker-Struktur <code>tmr</code> mit
187    * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
188    * <code>out</code>
189    *
190    * @param templateFilename
191    * @param mergeData
192    * @param out
193    * @exception HTMLParseException
194    */
195         public static void process(HttpServletResponse res,String templateFilename,
196                                                                                                                  TemplateModelRoot tmr, PrintWriter out, Locale locale)
197         throws HTMLParseException {
198                 process(res,templateFilename,tmr,null,out,locale);
199                                                                                                                          
200         }
201
202   /**
203    * Mischt die freemarker-Struktur <code>tmr</code> mit
204    * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
205    * <code>out</code>
206    *
207    * @param templateFilename
208    * @param mergeData
209    * @param out
210    * @exception HTMLParseException
211    */
212         public static void process(HttpServletResponse res,String templateFilename,
213                                                                                                                  TemplateModelRoot tmr, TemplateModelRoot popups,
214                                                                                                                  PrintWriter out, Locale locale)
215                 throws HTMLParseException {
216                 if (out==null) throw new HTMLParseException("no outputstream");
217                 Template tmpl = getTemplateFor(templateFilename);
218                 if (tmpl == null) throw new HTMLParseException("no template: " + templateFilename);
219                 if (tmr==null) tmr = new SimpleHash();
220         
221                 /** @todo  what is this for? (rk) */
222                 String session="";
223                 if (res!=null) {
224                         session=res.encodeURL("");
225                 }
226
227                 // put standard configuration into tempalteRootmodel
228                 SimpleHash configHash = new SimpleHash();
229                 configHash.put("producerDocRoot", new SimpleScalar(producerDocRoot));
230                 configHash.put("storageRoot", new SimpleScalar(producerStorageRoot));
231                 configHash.put("productionHost", new SimpleScalar(productionHost));
232                 configHash.put("openAction", new SimpleScalar(openAction));
233                 configHash.put("actionRootLogin",new SimpleScalar(actionRoot));
234                 configHash.put("docRoot", new SimpleScalar(docRoot));
235                 configHash.put("now", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
236                 configHash.put("actionRoot", new SimpleScalar(actionRoot+session));
237                 configHash.put("productionHost", new SimpleScalar(productionHost));
238                 configHash.put("videoHost", new SimpleScalar(videoHost));
239                 configHash.put("audioHost", new SimpleScalar(audioHost));
240                 configHash.put("imageHost", new SimpleScalar(imageHost));
241                 configHash.put("mirVersion", new SimpleScalar(MirConfig.getProp("Mir.Version")));
242                 // this conform to updated freemarker syntax
243                 configHash.put("compressWhitespace", new freemarker.template.utility.CompressWhitespace() );
244                 
245                 SimpleHash outPutHash = new SimpleHash();
246                         
247                 if(popups!=null){
248                         outPutHash.put("popups",popups);
249                         try{
250                         while(((SimpleList)popups).hasNext()){
251                                 theLog.printDebugInfo(((SimpleList)popups).next().toString());
252                         }
253                         }catch(Exception e){}
254                 }
255                 outPutHash.put("data",tmr);
256                 outPutHash.put("config", configHash);
257                         
258                 MessageResources messages = MessageResources.getMessageResources("bundles.admin");
259                 outPutHash.put("lang", new MessageMethodModel(locale, messages) );
260                         
261                 tmpl.process(outPutHash,out);
262         }
263
264
265   /**
266    *   Converts Entity-List to SimpleList of SimpleHashes.
267    *   @param aList ist eine Liste von Entity
268    *   @return eine freemarker.template.SimpleList von SimpleHashes.
269    *
270    *    @deprecated EntityLists comply with TemplateListModel now.
271    */
272   public static SimpleList makeSimpleList(EntityList aList) throws StorageObjectException
273   {
274     theLog.printWarning("## using deprecated makeSimpleList(entityList) - a waste of resources");
275     SimpleList  simpleList = new SimpleList();
276     if (aList != null) {
277       for(int i=0;i<aList.size();i++) {
278         simpleList.add(aList.elementAt(i));
279       }
280     }
281     return simpleList;
282   }
283
284   /**
285    *  Konvertiert ein EntityList in ein freemarker.template.SimpleHash-Modell. Im Hash
286    *  sind die einzelnen Entities ueber ihre id zu erreichen.
287    *  @param aList ist die EntityList
288    *  @return SimpleHash mit den entsprechenden freemarker Daten
289    *
290    */
291   public static SimpleHash makeSimpleHash(EntityList aList) throws StorageObjectException
292   {
293     SimpleHash      simpleHash = new SimpleHash();
294     Entity          currentEntity;
295
296     if (aList != null) {
297       for (int i=0;i<aList.size();i++) {
298          currentEntity = (Entity)aList.elementAt(i);
299          simpleHash.put(currentEntity.getId(), currentEntity);
300       }
301     }
302     return simpleHash;
303   }
304
305   /**
306    *  Konvertiert ein Entity in ein freemarker.template.SimpleHash-Modell
307    *  @param entity ist die Entity
308    *  @return SimpleHash mit den entsprechenden freemarker Daten
309    *
310    *  @deprecated This method is deprecated and will be deleted in the next
311    *  release. Entity interfaces freemarker.template.TemplateHashModel now
312    *  and can be used in the same way as SimpleHash. It is not necessary any
313    *  more to make a SimpleHash from an Entity
314    */
315   public static SimpleHash makeSimpleHash(Entity entity) {
316     if (entity != null) {
317       theLog.printWarning("## using deprecated makeSimpleHash(entity) - a waste of resources");
318       return makeSimpleHash(entity.getValues());
319     }
320     else
321       return null;
322   }
323
324   /**
325    *  Konvertiert ein Hashtable mit den keys und values als String
326    *  in ein freemarker.template.SimpleHash-Modell
327    *  @param mergeData der HashMap mit den String / String Daten
328    *  @return SimpleHash mit den entsprechenden freemarker Daten
329    *
330    */
331   public static SimpleHash makeSimpleHash(HashMap mergeData)
332   {
333     SimpleHash modelRoot = new SimpleHash();
334     String aField;
335     if (mergeData != null) {
336       Set set = mergeData.keySet();
337       Iterator it =  set.iterator();
338       for (int i=0; i<set.size();i++)  {
339         aField = (String)it.next();
340         modelRoot.put(aField, (String)mergeData.get(aField));
341       }
342     }
343     return modelRoot;
344   }
345
346
347   /**
348    * Converts EntityList in SimpleHash and adds additional information
349    * to the returned SimpleHash
350    *
351    * @param entList
352    * @return SimpleHash returns SimpleHash with the converted EntityList plus
353    *        additional Data about the list.
354    * @exception StorageObjectException
355    */
356
357   public static SimpleHash makeSimpleHashWithEntitylistInfos(EntityList entList) throws StorageObjectException {
358     SimpleHash modelRoot = new SimpleHash();
359     if (entList!=null) {
360       modelRoot.put("contentlist", entList);
361       modelRoot.put("count", new SimpleScalar((new Integer(entList.getCount())).toString()));
362       if (entList.getWhere()!=null) {
363         modelRoot.put("where", new SimpleScalar(entList.getWhere()));
364         modelRoot.put("where_encoded", new SimpleScalar(URLEncoder.encode(entList.getWhere())));
365       }
366       if(entList.getOrder()!=null) {
367         modelRoot.put("order", new SimpleScalar(entList.getOrder()));
368         modelRoot.put("order_encoded", new SimpleScalar(URLEncoder.encode(entList.getOrder())));
369       }
370       modelRoot.put("from", new SimpleScalar((new Integer(entList.getFrom())).toString()));
371       modelRoot.put("to", new SimpleScalar((new Integer(entList.getTo())).toString()));
372
373       if (entList.hasNextBatch())
374         modelRoot.put("next", new SimpleScalar((new Integer(entList.getNextBatch())).toString()));
375       if (entList.hasPrevBatch())
376         modelRoot.put("prev", new SimpleScalar((new Integer(entList.getPrevBatch())).toString()));
377     }
378     return modelRoot;
379   }
380
381   /**
382    * Private methods to get template from a templateFilename
383    * @param templateFilename
384    * @return Template
385    * @exception HTMLParseException
386    */
387   private static Template getTemplateFor(String templateFilename) throws HTMLParseException
388   {
389     Template returnTemplate = null;
390     if (templateFilename!=null)
391       returnTemplate = (Template)templateCache.getItem(templateFilename,"template");
392
393
394     if (returnTemplate==null) {
395       theLog.printError("CACHE (ERR): Unknown template: " + templateFilename);
396       throw new HTMLParseException("Templatefile: "+ templateFilename + " not found.");
397     }
398
399     return returnTemplate;
400   }
401
402   public static void stopAutoUpdate(){
403     templateCache.stopAutoUpdate();
404     templateCache=null;
405   }
406
407 }