i18n-feature based on kellans proposal implemented. the resource-bundles are located...
[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       if (out==null) throw new HTMLParseException("no outputstream");
199       Template tmpl = getTemplateFor(templateFilename);
200       if (tmpl == null) throw new HTMLParseException("no template: " + templateFilename);
201       if (tmr==null) tmr = new SimpleHash();
202
203       /** @todo  what is this for? (rk) */
204       String session="";
205       if (res!=null) {
206         session=res.encodeURL("");
207       }
208
209       /** @todo why do we double those? should be cleaned up and
210        *  statically initialized, we do not need to assemble a config
211        *  hash everytime we give out a page, only exception is
212        *  date "now" // rk */
213       // put standard configuration into tempalteRootmodel
214       SimpleHash configHash = new SimpleHash();
215       configHash.put("producerDocRoot", new SimpleScalar(producerDocRoot));
216       configHash.put("storageRoot", new SimpleScalar(producerStorageRoot));
217       configHash.put("productionHost", new SimpleScalar(productionHost));
218       configHash.put("openAction", new SimpleScalar(openAction));
219       configHash.put("actionRootLogin",new SimpleScalar(actionRoot));
220       configHash.put("docRoot", new SimpleScalar(docRoot));
221       configHash.put("now", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
222       configHash.put("actionRoot", new SimpleScalar(actionRoot+session));
223       configHash.put("productionHost", new SimpleScalar(productionHost));
224       configHash.put("videoHost", new SimpleScalar(videoHost));
225       configHash.put("audioHost", new SimpleScalar(audioHost));
226       configHash.put("imageHost", new SimpleScalar(imageHost));
227       // this conform to updated freemarker syntax
228       configHash.put("compressWhitespace", new freemarker.template.utility.CompressWhitespace() );
229                         
230                         SimpleHash outPutHash = new SimpleHash();
231                         outPutHash.put("data",tmr);
232       outPutHash.put("config", configHash);
233                                 
234                         MessageResources messages = MessageResources.getMessageResources("admin");
235                         outPutHash.put("message", new MessageMethodModel(locale, messages) );
236                                 
237       tmpl.process(outPutHash,out);
238     }
239
240
241   /**
242    *   Converts Entity-List to SimpleList of SimpleHashes.
243    *   @param aList ist eine Liste von Entity
244    *   @return eine freemarker.template.SimpleList von SimpleHashes.
245    *
246    *    @deprecated EntityLists comply with TemplateListModel now.
247    */
248   public static SimpleList makeSimpleList(EntityList aList) throws StorageObjectException
249   {
250     theLog.printWarning("## using deprecated makeSimpleList(entityList) - a waste of resources");
251     SimpleList  simpleList = new SimpleList();
252     if (aList != null) {
253       for(int i=0;i<aList.size();i++) {
254         simpleList.add(aList.elementAt(i));
255       }
256     }
257     return simpleList;
258   }
259
260   /**
261    *  Konvertiert ein EntityList in ein freemarker.template.SimpleHash-Modell. Im Hash
262    *  sind die einzelnen Entities ueber ihre id zu erreichen.
263    *  @param aList ist die EntityList
264    *  @return SimpleHash mit den entsprechenden freemarker Daten
265    *
266    */
267   public static SimpleHash makeSimpleHash(EntityList aList) throws StorageObjectException
268   {
269     SimpleHash      simpleHash = new SimpleHash();
270     Entity          currentEntity;
271
272     if (aList != null) {
273       for (int i=0;i<aList.size();i++) {
274          currentEntity = (Entity)aList.elementAt(i);
275          simpleHash.put(currentEntity.getId(), currentEntity);
276       }
277     }
278     return simpleHash;
279   }
280
281   /**
282    *  Konvertiert ein Entity in ein freemarker.template.SimpleHash-Modell
283    *  @param entity ist die Entity
284    *  @return SimpleHash mit den entsprechenden freemarker Daten
285    *
286    *  @deprecated This method is deprecated and will be deleted in the next
287    *  release. Entity interfaces freemarker.template.TemplateHashModel now
288    *  and can be used in the same way as SimpleHash. It is not necessary any
289    *  more to make a SimpleHash from an Entity
290    */
291   public static SimpleHash makeSimpleHash(Entity entity) {
292     if (entity != null) {
293       theLog.printWarning("## using deprecated makeSimpleHash(entity) - a waste of resources");
294       return makeSimpleHash(entity.getValues());
295     }
296     else
297       return null;
298   }
299
300   /**
301    *  Konvertiert ein Hashtable mit den keys und values als String
302    *  in ein freemarker.template.SimpleHash-Modell
303    *  @param mergeData der HashMap mit den String / String Daten
304    *  @return SimpleHash mit den entsprechenden freemarker Daten
305    *
306    */
307   public static SimpleHash makeSimpleHash(HashMap mergeData)
308   {
309     SimpleHash modelRoot = new SimpleHash();
310     String aField;
311     if (mergeData != null) {
312       Set set = mergeData.keySet();
313       Iterator it =  set.iterator();
314       for (int i=0; i<set.size();i++)  {
315         aField = (String)it.next();
316         modelRoot.put(aField, (String)mergeData.get(aField));
317       }
318     }
319     return modelRoot;
320   }
321
322
323   /**
324    * Converts EntityList in SimpleHash and adds additional information
325    * to the returned SimpleHash
326    *
327    * @param entList
328    * @return SimpleHash returns SimpleHash with the converted EntityList plus
329    *        additional Data about the list.
330    * @exception StorageObjectException
331    */
332
333   public static SimpleHash makeSimpleHashWithEntitylistInfos(EntityList entList) throws StorageObjectException {
334     SimpleHash modelRoot = new SimpleHash();
335     if (entList!=null) {
336       modelRoot.put("contentlist", entList);
337       modelRoot.put("count", new SimpleScalar((new Integer(entList.getCount())).toString()));
338       if (entList.getWhere()!=null) {
339         modelRoot.put("where", new SimpleScalar(entList.getWhere()));
340         modelRoot.put("where_encoded", new SimpleScalar(URLEncoder.encode(entList.getWhere())));
341       }
342       if(entList.getOrder()!=null) {
343         modelRoot.put("order", new SimpleScalar(entList.getOrder()));
344         modelRoot.put("order_encoded", new SimpleScalar(URLEncoder.encode(entList.getOrder())));
345       }
346       modelRoot.put("from", new SimpleScalar((new Integer(entList.getFrom())).toString()));
347       modelRoot.put("to", new SimpleScalar((new Integer(entList.getTo())).toString()));
348
349       if (entList.hasNextBatch())
350         modelRoot.put("next", new SimpleScalar((new Integer(entList.getNextBatch())).toString()));
351       if (entList.hasPrevBatch())
352         modelRoot.put("prev", new SimpleScalar((new Integer(entList.getPrevBatch())).toString()));
353     }
354     return modelRoot;
355   }
356
357   /**
358    * Private methods to get template from a templateFilename
359    * @param templateFilename
360    * @return Template
361    * @exception HTMLParseException
362    */
363   private static Template getTemplateFor(String templateFilename) throws HTMLParseException
364   {
365     Template returnTemplate = null;
366     if (templateFilename!=null)
367       returnTemplate = (Template)templateCache.getItem(templateFilename,"template");
368
369
370     if (returnTemplate==null) {
371       theLog.printError("CACHE (ERR): Unknown template: " + templateFilename);
372       throw new HTMLParseException("Templatefile: "+ templateFilename + " not found.");
373     }
374
375     return returnTemplate;
376   }
377
378   public static void stopAutoUpdate(){
379     templateCache.stopAutoUpdate();
380     templateCache=null;
381   }
382
383 }