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