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