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